From 6b3c3c95c2544c75c4a29d3962c31fda3ee41f4b Mon Sep 17 00:00:00 2001 From: Kmadhav824 Date: Fri, 15 May 2026 00:38:51 +0530 Subject: [PATCH 1/2] Fixes seed admin issues, model imports and createProblem route --- Frontend/src/App.jsx | 6 +- backend/dist/index.js | 97839 ++++++++++----------- backend/src/api/contest/contest.route.ts | 2 +- backend/src/config/index.ts | 28 +- backend/src/scripts/seed-admin.js | 14 +- backend/tsconfig.json | 4 +- 6 files changed, 47069 insertions(+), 50824 deletions(-) diff --git a/Frontend/src/App.jsx b/Frontend/src/App.jsx index c6c5900..59c1a51 100644 --- a/Frontend/src/App.jsx +++ b/Frontend/src/App.jsx @@ -7,7 +7,7 @@ import ProblemPage from "./views/problemPage/ProblemPage"; import Dashboard from "./views/dashboard/DashBoard"; import UserDashboard from "./views/dashboard/UserDashboard"; import Problems from "./views/problems/problems"; -import NewProblem from "./views/newProblem/NewProblem"; +import CreateProblem from "./views/newProblem/NewProblem"; import ContestListPage from "./views/contest/ContestListPage"; import ContestCreatePage from "./views/contest/ContestCreatePage"; import ContestLobbyAndRun from "./views/contest/ContestLobbyAndRun"; @@ -50,11 +50,11 @@ export default function App() { } /> } /> - + } diff --git a/backend/dist/index.js b/backend/dist/index.js index 9336372..1cae9f7 100644 --- a/backend/dist/index.js +++ b/backend/dist/index.js @@ -3,7 +3,6 @@ var __create = Object.create; var __getProtoOf = Object.getPrototypeOf; var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __hasOwnProp = Object.prototype.hasOwnProperty; function __accessProp(key) { return this[key]; @@ -30,23 +29,6 @@ var __toESM = (mod, isNodeMode, target) => { cache.set(mod, to); return to; }; -var __toCommonJS = (from) => { - var entry = (__moduleCache ??= new WeakMap).get(from), desc; - if (entry) - return entry; - entry = __defProp({}, "__esModule", { value: true }); - if (from && typeof from === "object" || typeof from === "function") { - for (var key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(entry, key)) - __defProp(entry, key, { - get: __accessProp.bind(from, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - __moduleCache.set(from, entry); - return entry; -}; -var __moduleCache; var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); var __returnValue = (v) => v; function __exportSetter(name, newValue) { @@ -28284,11 +28266,11 @@ var require_binaryParsers = __commonJS((exports, module) => { var array2 = []; var i2; if (dimension.length > 1) { - var count = dimension.shift(); - for (i2 = 0;i2 < count; i2++) { + var count2 = dimension.shift(); + for (i2 = 0;i2 < count2; i2++) { array2[i2] = parse(dimension, elementType2); } - dimension.unshift(count); + dimension.unshift(count2); } else { for (i2 = 0;i2 < dimension[0]; i2++) { array2[i2] = parseElement(elementType2); @@ -37096,14 +37078,14 @@ var require__stream_writable = __commonJS((exports, module) => { var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; - var count = 0; + var count2 = 0; var allBuffers = true; while (entry) { - buffer[count] = entry; + buffer[count2] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; - count += 1; + count2 += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, "", holder.finish); @@ -62073,10 +62055,10 @@ var require_dist3 = __commonJS((exports) => { } exports.generateUniqueAsync = generateUniqueAsync; function generateMany(options) { - const { count, unique = false } = options, rest = __rest(options, ["count", "unique"]); + const { count: count2, unique = false } = options, rest = __rest(options, ["count", "unique"]); const results = []; const seen = new Set; - for (let i = 0;i < count; i++) { + for (let i = 0;i < count2; i++) { let candidate = uniqueUsernameGenerator(rest); if (unique) { let spins = 0; @@ -62678,10922 +62660,3312 @@ var require_main = __commonJS((exports, module) => { module.exports = DotenvModule; }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/entity.cjs -var require_entity = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); +// node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js +var require_extend = __commonJS((exports, module) => { + var hasOwn = Object.prototype.hasOwnProperty; + var toStr = Object.prototype.toString; + var defineProperty = Object.defineProperty; + var gOPD = Object.getOwnPropertyDescriptor; + var isArray = function isArray2(arr) { + if (typeof Array.isArray === "function") { + return Array.isArray(arr); } - return to; + return toStr.call(arr) === "[object Array]"; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var entity_exports = {}; - __export2(entity_exports, { - entityKind: () => entityKind2, - hasOwnEntityKind: () => hasOwnEntityKind2, - is: () => is2 - }); - module.exports = __toCommonJS2(entity_exports); - var entityKind2 = Symbol.for("drizzle:entityKind"); - var hasOwnEntityKind2 = Symbol.for("drizzle:hasOwnEntityKind"); - function is2(value, type) { - if (!value || typeof value !== "object") { + var isPlainObject = function isPlainObject2(obj) { + if (!obj || toStr.call(obj) !== "[object Object]") { return false; } - if (value instanceof type) { - return true; - } - if (!Object.prototype.hasOwnProperty.call(type, entityKind2)) { - throw new Error(`Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`); - } - let cls = Object.getPrototypeOf(value).constructor; - if (cls) { - while (cls) { - if (entityKind2 in cls && cls[entityKind2] === type[entityKind2]) { - return true; - } - cls = Object.getPrototypeOf(cls); - } - } - return false; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/column.cjs -var require_column = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var column_exports = {}; - __export2(column_exports, { - Column: () => Column2 - }); - module.exports = __toCommonJS2(column_exports); - var import_entity73 = require_entity(); - - class Column2 { - constructor(table, config) { - this.table = table; - this.config = config; - this.name = config.name; - this.keyAsName = config.keyAsName; - this.notNull = config.notNull; - this.default = config.default; - this.defaultFn = config.defaultFn; - this.onUpdateFn = config.onUpdateFn; - this.hasDefault = config.hasDefault; - this.primary = config.primaryKey; - this.isUnique = config.isUnique; - this.uniqueName = config.uniqueName; - this.uniqueType = config.uniqueType; - this.dataType = config.dataType; - this.columnType = config.columnType; - this.generated = config.generated; - this.generatedIdentity = config.generatedIdentity; - } - static [import_entity73.entityKind] = "Column"; - name; - keyAsName; - primary; - notNull; - default; - defaultFn; - onUpdateFn; - hasDefault; - isUnique; - uniqueName; - uniqueType; - dataType; - columnType; - enumValues = undefined; - generated = undefined; - generatedIdentity = undefined; - config; - mapFromDriverValue(value) { - return value; - } - mapToDriverValue(value) { - return value; - } - shouldDisableInsert() { - return this.config.generated !== undefined && this.config.generated.type !== "byDefault"; + var hasOwnConstructor = hasOwn.call(obj, "constructor"); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf"); + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/column-builder.cjs -var require_column_builder = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); + var key; + for (key in obj) {} + return typeof key === "undefined" || hasOwn.call(obj, key); }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); + var setProperty = function setProperty2(target, options) { + if (defineProperty && options.name === "__proto__") { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; } - return to; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var column_builder_exports = {}; - __export2(column_builder_exports, { - ColumnBuilder: () => ColumnBuilder2 - }); - module.exports = __toCommonJS2(column_builder_exports); - var import_entity73 = require_entity(); - - class ColumnBuilder2 { - static [import_entity73.entityKind] = "ColumnBuilder"; - config; - constructor(name, dataType, columnType) { - this.config = { - name, - keyAsName: name === "", - notNull: false, - default: undefined, - hasDefault: false, - primaryKey: false, - isUnique: false, - uniqueName: undefined, - uniqueType: undefined, - dataType, - columnType, - generated: undefined - }; - } - $type() { - return this; - } - notNull() { - this.config.notNull = true; - return this; - } - default(value) { - this.config.default = value; - this.config.hasDefault = true; - return this; - } - $defaultFn(fn) { - this.config.defaultFn = fn; - this.config.hasDefault = true; - return this; - } - $default = this.$defaultFn; - $onUpdateFn(fn) { - this.config.onUpdateFn = fn; - this.config.hasDefault = true; - return this; - } - $onUpdate = this.$onUpdateFn; - primaryKey() { - this.config.primaryKey = true; - this.config.notNull = true; - return this; - } - setName(name) { - if (this.config.name !== "") + var getProperty = function getProperty2(obj, name) { + if (name === "__proto__") { + if (!hasOwn.call(obj, name)) { return; - this.config.name = name; + } else if (gOPD) { + return gOPD(obj, name).value; + } } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/table.utils.cjs -var require_table_utils = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); + return obj[name]; }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); + module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone4; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + if (typeof target === "boolean") { + deep = target; + target = arguments[1] || {}; + i = 2; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var table_utils_exports = {}; - __export2(table_utils_exports, { - TableName: () => TableName2 - }); - module.exports = __toCommonJS2(table_utils_exports); - var TableName2 = Symbol.for("drizzle:Name"); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/foreign-keys.cjs -var require_foreign_keys = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); + if (target == null || typeof target !== "object" && typeof target !== "function") { + target = {}; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var foreign_keys_exports = {}; - __export2(foreign_keys_exports, { - ForeignKey: () => ForeignKey2, - ForeignKeyBuilder: () => ForeignKeyBuilder2, - foreignKey: () => foreignKey2 - }); - module.exports = __toCommonJS2(foreign_keys_exports); - var import_entity73 = require_entity(); - var import_table_utils4 = require_table_utils(); - - class ForeignKeyBuilder2 { - static [import_entity73.entityKind] = "PgForeignKeyBuilder"; - reference; - _onUpdate = "no action"; - _onDelete = "no action"; - constructor(config, actions) { - this.reference = () => { - const { name, columns, foreignColumns } = config(); - return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; - }; - if (actions) { - this._onUpdate = actions.onUpdate; - this._onDelete = actions.onDelete; + for (;i < length; ++i) { + options = arguments[i]; + if (options != null) { + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + if (target !== copy) { + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone4 = src && isArray(src) ? src : []; + } else { + clone4 = src && isPlainObject(src) ? src : {}; + } + setProperty(target, { name, newValue: extend(deep, clone4, copy) }); + } else if (typeof copy !== "undefined") { + setProperty(target, { name, newValue: copy }); + } + } + } } } - onUpdate(action) { - this._onUpdate = action === undefined ? "no action" : action; - return this; - } - onDelete(action) { - this._onDelete = action === undefined ? "no action" : action; - return this; - } - build(table) { - return new ForeignKey2(table, this); - } - } - - class ForeignKey2 { - constructor(table, builder) { - this.table = table; - this.reference = builder.reference; - this.onUpdate = builder._onUpdate; - this.onDelete = builder._onDelete; - } - static [import_entity73.entityKind] = "PgForeignKey"; - reference; - onUpdate; - onDelete; - getName() { - const { name, columns, foreignColumns } = this.reference(); - const columnNames = columns.map((column) => column.name); - const foreignColumnNames = foreignColumns.map((column) => column.name); - const chunks = [ - this.table[import_table_utils4.TableName], - ...columnNames, - foreignColumns[0].table[import_table_utils4.TableName], - ...foreignColumnNames - ]; - return name ?? `${chunks.join("_")}_fk`; - } - } - function foreignKey2(config) { - function mappedConfig() { - const { name, columns, foreignColumns } = config; - return { - name, - columns, - foreignColumns - }; - } - return new ForeignKeyBuilder2(mappedConfig); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/tracing-utils.cjs -var require_tracing_utils = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; + return target; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var tracing_utils_exports = {}; - __export2(tracing_utils_exports, { - iife: () => iife2 - }); - module.exports = __toCommonJS2(tracing_utils_exports); - function iife2(fn, ...args) { - return fn(...args); - } }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/unique-constraint.cjs -var require_unique_constraint = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/package.json +var require_package3 = __commonJS((exports, module) => { + module.exports = { + name: "gaxios", + version: "7.1.4", + description: "A simple common HTTP client specifically for Google APIs and services.", + main: "build/cjs/src/index.js", + types: "build/cjs/src/index.d.ts", + files: [ + "build/" + ], + exports: { + ".": { + import: { + types: "./build/esm/src/index.d.ts", + default: "./build/esm/src/index.js" + }, + require: { + types: "./build/cjs/src/index.d.ts", + default: "./build/cjs/src/index.js" + } + } + }, + scripts: { + lint: "gts check --no-inline-config", + test: "c8 mocha build/esm/test", + "presystem-test": "npm run compile", + "system-test": "mocha build/esm/system-test --timeout 80000", + compile: "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs", + fix: "gts fix", + prepare: "npm run compile", + pretest: "npm run compile", + webpack: "webpack", + "prebrowser-test": "npm run compile", + "browser-test": "node build/browser-test/browser-test-runner.js", + docs: "jsdoc -c .jsdoc.js", + "docs-test": "linkinator docs", + "predocs-test": "npm run docs", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + prelint: "cd samples; npm link ../; npm install", + clean: "gts clean" + }, + repository: { + type: "git", + directory: "packages/gaxios", + url: "https://github.com/googleapis/google-cloud-node-core.git" + }, + keywords: [ + "google" + ], + engines: { + node: ">=18" + }, + author: "Google, LLC", + license: "Apache-2.0", + devDependencies: { + "@babel/plugin-proposal-private-methods": "^7.18.6", + "@types/cors": "^2.8.6", + "@types/express": "^5.0.0", + "@types/extend": "^3.0.1", + "@types/mocha": "^10.0.10", + "@types/multiparty": "4.2.1", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.8", + "@types/node": "^22.13.1", + "@types/sinon": "^17.0.3", + "@types/tmp": "^0.2.6", + assert: "^2.0.0", + browserify: "^17.0.0", + c8: "^10.1.3", + cors: "^2.8.5", + express: "^5.0.0", + gts: "^6.0.2", + "is-docker": "^3.0.0", + jsdoc: "^4.0.4", + "jsdoc-fresh": "^5.0.0", + "jsdoc-region-tag": "^4.0.0", + karma: "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "^5.0.1", + linkinator: "^6.1.2", + mocha: "^11.1.0", + multiparty: "^4.2.1", + mv: "^2.1.1", + ncp: "^2.0.0", + nock: "^14.0.5", + "null-loader": "^4.0.1", + "pack-n-play": "^4.0.0", + puppeteer: "^24.0.0", + sinon: "^21.0.0", + "stream-browserify": "^3.0.0", + tmp: "0.2.5", + "ts-loader": "^9.5.2", + typescript: "5.8.3", + webpack: "^5.97.1", + "webpack-cli": "^6.0.1" + }, + dependencies: { + extend: "^3.0.2", + "https-proxy-agent": "^7.0.1", + "node-fetch": "^3.3.2" + }, + homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios" }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var unique_constraint_exports = {}; - __export2(unique_constraint_exports, { - UniqueConstraint: () => UniqueConstraint, - UniqueConstraintBuilder: () => UniqueConstraintBuilder, - UniqueOnConstraintBuilder: () => UniqueOnConstraintBuilder, - unique: () => unique, - uniqueKeyName: () => uniqueKeyName2 - }); - module.exports = __toCommonJS2(unique_constraint_exports); - var import_entity73 = require_entity(); - var import_table_utils4 = require_table_utils(); - function unique(name) { - return new UniqueOnConstraintBuilder(name); - } - function uniqueKeyName2(table, columns) { - return `${table[import_table_utils4.TableName]}_${columns.join("_")}_unique`; - } - - class UniqueConstraintBuilder { - constructor(columns, name) { - this.name = name; - this.columns = columns; - } - static [import_entity73.entityKind] = "PgUniqueConstraintBuilder"; - columns; - nullsNotDistinctConfig = false; - nullsNotDistinct() { - this.nullsNotDistinctConfig = true; - return this; - } - build(table) { - return new UniqueConstraint(table, this.columns, this.nullsNotDistinctConfig, this.name); - } - } - - class UniqueOnConstraintBuilder { - static [import_entity73.entityKind] = "PgUniqueOnConstraintBuilder"; - name; - constructor(name) { - this.name = name; - } - on(...columns) { - return new UniqueConstraintBuilder(columns, this.name); - } - } +}); - class UniqueConstraint { - constructor(table, columns, nullsNotDistinct, name) { - this.table = table; - this.columns = columns; - this.name = name ?? uniqueKeyName2(this.table, this.columns.map((column) => column.name)); - this.nullsNotDistinct = nullsNotDistinct; - } - static [import_entity73.entityKind] = "PgUniqueConstraint"; - columns; - name; - nullsNotDistinct = false; - getName() { - return this.name; - } - } +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/util.cjs +var require_util = __commonJS((exports, module) => { + var pkg = require_package3(); + module.exports = { pkg }; }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/utils/array.cjs -var require_array = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/common.js +var require_common3 = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var array_exports = {}; - __export2(array_exports, { - makePgArray: () => makePgArray2, - parsePgArray: () => parsePgArray2, - parsePgNestedArray: () => parsePgNestedArray2 - }); - module.exports = __toCommonJS2(array_exports); - function parsePgArrayValue2(arrayString, startFrom, inQuotes) { - for (let i = startFrom;i < arrayString.length; i++) { - const char2 = arrayString[i]; - if (char2 === "\\") { - i++; - continue; - } - if (char2 === '"') { - return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; - } - if (inQuotes) { - continue; - } - if (char2 === "," || char2 === "}") { - return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = undefined; + exports.defaultErrorRedactor = defaultErrorRedactor; + var extend_1 = __importDefault(require_extend()); + var util_cjs_1 = __importDefault(require_util()); + var pkg = util_cjs_1.default.pkg; + exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`); + + class GaxiosError extends Error { + config; + response; + code; + status; + error; + [exports.GAXIOS_ERROR_SYMBOL] = pkg.version; + static [Symbol.hasInstance](instance) { + if (instance && typeof instance === "object" && exports.GAXIOS_ERROR_SYMBOL in instance && instance[exports.GAXIOS_ERROR_SYMBOL] === pkg.version) { + return true; } + return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); } - return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; - } - function parsePgNestedArray2(arrayString, startFrom = 0) { - const result = []; - let i = startFrom; - let lastCharIsComma = false; - while (i < arrayString.length) { - const char2 = arrayString[i]; - if (char2 === ",") { - if (lastCharIsComma || i === startFrom) { - result.push(""); - } - lastCharIsComma = true; - i++; - continue; - } - lastCharIsComma = false; - if (char2 === "\\") { - i += 2; - continue; - } - if (char2 === '"') { - const [value2, startFrom2] = parsePgArrayValue2(arrayString, i + 1, true); - result.push(value2); - i = startFrom2; - continue; + constructor(message, config, response, cause) { + super(message, { cause }); + this.config = config; + this.response = response; + this.error = cause instanceof Error ? cause : undefined; + this.config = (0, extend_1.default)(true, {}, config); + if (this.response) { + this.response.config = (0, extend_1.default)(true, {}, this.response.config); } - if (char2 === "}") { - return [result, i + 1]; + if (this.response) { + try { + this.response.data = translateData(this.config.responseType, this.response?.bodyUsed ? this.response?.data : undefined); + } catch {} + this.status = this.response.status; } - if (char2 === "{") { - const [value2, startFrom2] = parsePgNestedArray2(arrayString, i + 1); - result.push(value2); - i = startFrom2; - continue; + if (cause instanceof DOMException) { + this.code = cause.name; + } else if (cause && typeof cause === "object" && "code" in cause && (typeof cause.code === "string" || typeof cause.code === "number")) { + this.code = cause.code; } - const [value, newStartFrom] = parsePgArrayValue2(arrayString, i, false); - result.push(value); - i = newStartFrom; } - return [result, i]; - } - function parsePgArray2(arrayString) { - const [result] = parsePgNestedArray2(arrayString, 1); - return result; - } - function makePgArray2(array2) { - return `{${array2.map((item) => { - if (Array.isArray(item)) { - return makePgArray2(item); - } - if (typeof item === "string") { - return `"${item.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`; + static extractAPIErrorFromResponse(res, defaultErrorMessage = "The request failed") { + let message = defaultErrorMessage; + if (typeof res.data === "string") { + message = res.data; } - return `${item}`; - }).join(",")}}`; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/common.cjs -var require_common3 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var common_exports = {}; - __export2(common_exports, { - ExtraConfigColumn: () => ExtraConfigColumn2, - IndexedColumn: () => IndexedColumn2, - PgArray: () => PgArray2, - PgArrayBuilder: () => PgArrayBuilder2, - PgColumn: () => PgColumn2, - PgColumnBuilder: () => PgColumnBuilder2 - }); - module.exports = __toCommonJS2(common_exports); - var import_column_builder2 = require_column_builder(); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_foreign_keys2 = require_foreign_keys(); - var import_tracing_utils3 = require_tracing_utils(); - var import_unique_constraint2 = require_unique_constraint(); - var import_array2 = require_array(); - - class PgColumnBuilder2 extends import_column_builder2.ColumnBuilder { - foreignKeyConfigs = []; - static [import_entity73.entityKind] = "PgColumnBuilder"; - array(size) { - return new PgArrayBuilder2(this.config.name, this, size); - } - references(ref, actions = {}) { - this.foreignKeyConfigs.push({ ref, actions }); - return this; - } - unique(name, config) { - this.config.isUnique = true; - this.config.uniqueName = name; - this.config.uniqueType = config?.nulls; - return this; - } - generatedAlwaysAs(as) { - this.config.generated = { - as, - type: "always", - mode: "stored" - }; - return this; - } - buildForeignKeys(column, table) { - return this.foreignKeyConfigs.map(({ ref, actions }) => { - return (0, import_tracing_utils3.iife)((ref2, actions2) => { - const builder = new import_foreign_keys2.ForeignKeyBuilder(() => { - const foreignColumn = ref2(); - return { columns: [column], foreignColumns: [foreignColumn] }; - }); - if (actions2.onUpdate) { - builder.onUpdate(actions2.onUpdate); - } - if (actions2.onDelete) { - builder.onDelete(actions2.onDelete); + if (res.data && typeof res.data === "object" && "error" in res.data && res.data.error && !res.ok) { + if (typeof res.data.error === "string") { + return { + message: res.data.error, + code: res.status, + status: res.statusText + }; + } + if (typeof res.data.error === "object") { + message = "message" in res.data.error && typeof res.data.error.message === "string" ? res.data.error.message : message; + const status = "status" in res.data.error && typeof res.data.error.status === "string" ? res.data.error.status : res.statusText; + const code = "code" in res.data.error && typeof res.data.error.code === "number" ? res.data.error.code : res.status; + if ("errors" in res.data.error && Array.isArray(res.data.error.errors)) { + const errorMessages = []; + for (const e2 of res.data.error.errors) { + if (typeof e2 === "object" && "message" in e2 && typeof e2.message === "string") { + errorMessages.push(e2.message); + } + } + return Object.assign({ + message: errorMessages.join(` +`) || message, + code, + status + }, res.data.error); } - return builder.build(table); - }, ref, actions); - }); - } - buildExtraConfigColumn(table) { - return new ExtraConfigColumn2(table, this.config); - } - } - - class PgColumn2 extends import_column9.Column { - constructor(table, config) { - if (!config.uniqueName) { - config.uniqueName = (0, import_unique_constraint2.uniqueKeyName)(table, [config.name]); + return Object.assign({ + message, + code, + status + }, res.data.error); + } } - super(table, config); - this.table = table; - } - static [import_entity73.entityKind] = "PgColumn"; - } - - class ExtraConfigColumn2 extends PgColumn2 { - static [import_entity73.entityKind] = "ExtraConfigColumn"; - getSQLType() { - return this.getSQLType(); - } - indexConfig = { - order: this.config.order ?? "asc", - nulls: this.config.nulls ?? "last", - opClass: this.config.opClass - }; - defaultConfig = { - order: "asc", - nulls: "last", - opClass: undefined - }; - asc() { - this.indexConfig.order = "asc"; - return this; - } - desc() { - this.indexConfig.order = "desc"; - return this; - } - nullsFirst() { - this.indexConfig.nulls = "first"; - return this; - } - nullsLast() { - this.indexConfig.nulls = "last"; - return this; - } - op(opClass) { - this.indexConfig.opClass = opClass; - return this; + return { + message, + code: res.status, + status: res.statusText + }; } } - - class IndexedColumn2 { - static [import_entity73.entityKind] = "IndexedColumn"; - constructor(name, keyAsName, type, indexConfig) { - this.name = name; - this.keyAsName = keyAsName; - this.type = type; - this.indexConfig = indexConfig; + exports.GaxiosError = GaxiosError; + function translateData(responseType, data) { + switch (responseType) { + case "stream": + return data; + case "json": + return JSON.parse(JSON.stringify(data)); + case "arraybuffer": + return JSON.parse(Buffer.from(data).toString("utf8")); + case "blob": + return JSON.parse(data.text()); + default: + return data; } - name; - keyAsName; - type; - indexConfig; } - - class PgArrayBuilder2 extends PgColumnBuilder2 { - static [import_entity73.entityKind] = "PgArrayBuilder"; - constructor(name, baseBuilder, size) { - super(name, "array", "PgArray"); - this.config.baseBuilder = baseBuilder; - this.config.size = size; - } - build(table) { - const baseColumn = this.config.baseBuilder.build(table); - return new PgArray2(table, this.config, baseColumn); + function defaultErrorRedactor(data) { + const REDACT = "< - See `errorRedactor` option in `gaxios` for configuration>."; + function redactHeaders(headers) { + if (!headers) + return; + headers.forEach((_, key) => { + if (/^authentication$/i.test(key) || /^authorization$/i.test(key) || /secret/i.test(key)) + headers.set(key, REDACT); + }); } - } - - class PgArray2 extends PgColumn2 { - constructor(table, config, baseColumn, range) { - super(table, config); - this.baseColumn = baseColumn; - this.range = range; - this.size = config.size; + function redactString(obj, key) { + if (typeof obj === "object" && obj !== null && typeof obj[key] === "string") { + const text3 = obj[key]; + if (/grant_type=/i.test(text3) || /assertion=/i.test(text3) || /secret/i.test(text3)) { + obj[key] = REDACT; + } + } } - size; - static [import_entity73.entityKind] = "PgArray"; - getSQLType() { - return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; + function redactObject(obj) { + if (!obj || typeof obj !== "object") { + return; + } else if (obj instanceof FormData || obj instanceof URLSearchParams || "forEach" in obj && "set" in obj) { + obj.forEach((_, key) => { + if (["grant_type", "assertion"].includes(key) || /secret/.test(key)) { + obj.set(key, REDACT); + } + }); + } else { + if ("grant_type" in obj) { + obj["grant_type"] = REDACT; + } + if ("assertion" in obj) { + obj["assertion"] = REDACT; + } + if ("client_secret" in obj) { + obj["client_secret"] = REDACT; + } + } } - mapFromDriverValue(value) { - if (typeof value === "string") { - value = (0, import_array2.parsePgArray)(value); + if (data.config) { + redactHeaders(data.config.headers); + redactString(data.config, "data"); + redactObject(data.config.data); + redactString(data.config, "body"); + redactObject(data.config.body); + if (data.config.url.searchParams.has("token")) { + data.config.url.searchParams.set("token", REDACT); + } + if (data.config.url.searchParams.has("client_secret")) { + data.config.url.searchParams.set("client_secret", REDACT); } - return value.map((v) => this.baseColumn.mapFromDriverValue(v)); } - mapToDriverValue(value, isNestedArray = false) { - const a = value.map((v) => v === null ? null : (0, import_entity73.is)(this.baseColumn, PgArray2) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)); - if (isNestedArray) - return a; - return (0, import_array2.makePgArray)(a); + if (data.response) { + defaultErrorRedactor({ config: data.response.config }); + redactHeaders(data.response.headers); + if (data.response.bodyUsed) { + redactString(data.response, "data"); + redactObject(data.response.data); + } } + return data; } }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/enum.cjs -var require_enum = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/retry.js +var require_retry = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRetryConfig = getRetryConfig; + async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || !config && !err.config.retry) { + return { shouldRetry: false }; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var enum_exports = {}; - __export2(enum_exports, { - PgEnumColumn: () => PgEnumColumn2, - PgEnumColumnBuilder: () => PgEnumColumnBuilder2, - PgEnumObjectColumn: () => PgEnumObjectColumn2, - PgEnumObjectColumnBuilder: () => PgEnumObjectColumnBuilder2, - isPgEnum: () => isPgEnum2, - pgEnum: () => pgEnum2, - pgEnumObjectWithSchema: () => pgEnumObjectWithSchema2, - pgEnumWithSchema: () => pgEnumWithSchema2 - }); - module.exports = __toCommonJS2(enum_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgEnumObjectColumnBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgEnumObjectColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumObjectColumn"); - this.config.enum = enumInstance; + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + "GET", + "HEAD", + "PUT", + "OPTIONS", + "DELETE" + ]; + config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null ? 2 : config.noResponseRetries; + config.retryDelayMultiplier = config.retryDelayMultiplier ? config.retryDelayMultiplier : 2; + config.timeOfFirstRequest = config.timeOfFirstRequest ? config.timeOfFirstRequest : Date.now(); + config.totalTimeout = config.totalTimeout ? config.totalTimeout : Number.MAX_SAFE_INTEGER; + config.maxRetryDelay = config.maxRetryDelay ? config.maxRetryDelay : Number.MAX_SAFE_INTEGER; + const retryRanges = [ + [100, 199], + [408, 408], + [429, 429], + [500, 599] + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + err.config.retryConfig = config; + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!await shouldRetryFn(err)) { + return { shouldRetry: false, config: err.config }; } - build(table) { - return new PgEnumObjectColumn2(table, this.config); + const delay = getNextRetryDelay(config); + err.config.retryConfig.currentRetryAttempt += 1; + const backoff = config.retryBackoff ? config.retryBackoff(err, delay) : new Promise((resolve) => { + setTimeout(resolve, delay); + }); + if (config.onRetryAttempt) { + await config.onRetryAttempt(err); } + await backoff; + return { shouldRetry: true, config: err.config }; } - - class PgEnumObjectColumn2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgEnumObjectColumn"; - enum; - enumValues = this.config.enum.enumValues; - constructor(table, config) { - super(table, config); - this.enum = config.enum; + function shouldRetryRequest(err) { + const config = getConfig(err); + if (err.config.signal?.aborted && err.code !== "TimeoutError" || err.code === "AbortError") { + return false; } - getSQLType() { - return this.enum.enumName; + if (!config || config.retry === 0) { + return false; } - } - var isPgEnumSym2 = Symbol.for("drizzle:isPgEnum"); - function isPgEnum2(obj) { - return !!obj && typeof obj === "function" && isPgEnumSym2 in obj && obj[isPgEnumSym2] === true; - } - - class PgEnumColumnBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgEnumColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumColumn"); - this.config.enum = enumInstance; + if (!err.response && (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; } - build(table) { - return new PgEnumColumn2(table, this.config); + if (!config.httpMethodsToRetry || !config.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || "GET")) { + return false; } - } - - class PgEnumColumn2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgEnumColumn"; - enum = this.config.enum; - enumValues = this.config.enum.enumValues; - constructor(table, config) { - super(table, config); - this.enum = config.enum; + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } } - getSQLType() { - return this.enum.enumName; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; } + return true; } - function pgEnum2(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema2(enumName, [...input], undefined) : pgEnumObjectWithSchema2(enumName, input, undefined); - } - function pgEnumWithSchema2(enumName, values, schema) { - const enumInstance = Object.assign((name) => new PgEnumColumnBuilder2(name ?? "", enumInstance), { - enumName, - enumValues: values, - schema, - [isPgEnumSym2]: true - }); - return enumInstance; + function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; } - function pgEnumObjectWithSchema2(enumName, values, schema) { - const enumInstance = Object.assign((name) => new PgEnumObjectColumnBuilder2(name ?? "", enumInstance), { - enumName, - enumValues: Object.values(values), - schema, - [isPgEnumSym2]: true - }); - return enumInstance; + function getNextRetryDelay(config) { + const retryDelay = config.currentRetryAttempt ? 0 : config.retryDelay ?? 100; + const calculatedDelay = retryDelay + (Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / 2 * 1000; + const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); + return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); } }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/subquery.cjs -var require_subquery = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var subquery_exports = {}; - __export2(subquery_exports, { - Subquery: () => Subquery2, - WithSubquery: () => WithSubquery2 - }); - module.exports = __toCommonJS2(subquery_exports); - var import_entity73 = require_entity(); - - class Subquery2 { - static [import_entity73.entityKind] = "Subquery"; - constructor(sql2, fields, alias, isWith = false, usedTables = []) { - this._ = { - brand: "Subquery", - sql: sql2, - selectedFields: fields, - alias, - isWith, - usedTables - }; - } - } +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/interceptor.js +var require_interceptor = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GaxiosInterceptorManager = undefined; - class WithSubquery2 extends Subquery2 { - static [import_entity73.entityKind] = "WithSubquery"; + class GaxiosInterceptorManager extends Set { } + exports.GaxiosInterceptorManager = GaxiosInterceptorManager; }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/version.cjs -var require_version = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); +// node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/helpers.js +var require_helpers = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var version_exports = {}; - __export2(version_exports, { - compatibilityVersion: () => compatibilityVersion, - npmVersion: () => version2 + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; }); - module.exports = __toCommonJS2(version_exports); - var version2 = "0.44.0"; - var compatibilityVersion = 10; -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/tracing.cjs -var require_tracing = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var tracing_exports = {}; - __export2(tracing_exports, { - tracer: () => tracer2 + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; }); - module.exports = __toCommonJS2(tracing_exports); - var import_tracing_utils3 = require_tracing_utils(); - var import_version2 = require_version(); - var otel2; - var rawTracer2; - var tracer2 = { - startActiveSpan(name, fn) { - if (!otel2) { - return fn(); - } - if (!rawTracer2) { - rawTracer2 = otel2.trace.getTracer("drizzle-orm", import_version2.npmVersion); - } - return (0, import_tracing_utils3.iife)((otel22, rawTracer22) => rawTracer22.startActiveSpan(name, (span) => { - try { - return fn(span); - } catch (e2) { - span.setStatus({ - code: otel22.SpanStatusCode.ERROR, - message: e2 instanceof Error ? e2.message : "Unknown error" - }); - throw e2; - } finally { - span.end(); - } - }), otel2, rawTracer2); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); } + __setModuleDefault(result, mod); + return result; }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.req = exports.json = exports.toBuffer = undefined; + var http = __importStar(__require("http")); + var https = __importStar(__require("https")); + async function toBuffer(stream) { + let length = 0; + const chunks = []; + for await (const chunk of stream) { + length += chunk.length; + chunks.push(chunk); + } + return Buffer.concat(chunks, length); + } + exports.toBuffer = toBuffer; + async function json3(stream) { + const buf = await toBuffer(stream); + const str = buf.toString("utf8"); + try { + return JSON.parse(str); + } catch (_err) { + const err = _err; + err.message += ` (input: ${str})`; + throw err; + } + } + exports.json = json3; + function req(url, opts = {}) { + const href = typeof url === "string" ? url : url.href; + const req2 = (href.startsWith("https:") ? https : http).request(url, opts); + const promise = new Promise((resolve, reject) => { + req2.once("response", resolve).once("error", reject).end(); + }); + req2.then = promise.then.bind(promise); + return req2; + } + exports.req = req; }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/view-common.cjs -var require_view_common = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); +// node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/index.js +var require_dist4 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var view_common_exports = {}; - __export2(view_common_exports, { - ViewBaseConfig: () => ViewBaseConfig2 + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; }); - module.exports = __toCommonJS2(view_common_exports); - var ViewBaseConfig2 = Symbol.for("drizzle:ViewBaseConfig"); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/table.cjs -var require_table = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var table_exports = {}; - __export2(table_exports, { - BaseName: () => BaseName2, - Columns: () => Columns2, - ExtraConfigBuilder: () => ExtraConfigBuilder2, - ExtraConfigColumns: () => ExtraConfigColumns2, - IsAlias: () => IsAlias2, - OriginalName: () => OriginalName2, - Schema: () => Schema3, - Table: () => Table2, - getTableName: () => getTableName2, - getTableUniqueName: () => getTableUniqueName2, - isTable: () => isTable + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; }); - module.exports = __toCommonJS2(table_exports); - var import_entity73 = require_entity(); - var import_table_utils4 = require_table_utils(); - var Schema3 = Symbol.for("drizzle:Schema"); - var Columns2 = Symbol.for("drizzle:Columns"); - var ExtraConfigColumns2 = Symbol.for("drizzle:ExtraConfigColumns"); - var OriginalName2 = Symbol.for("drizzle:OriginalName"); - var BaseName2 = Symbol.for("drizzle:BaseName"); - var IsAlias2 = Symbol.for("drizzle:IsAlias"); - var ExtraConfigBuilder2 = Symbol.for("drizzle:ExtraConfigBuilder"); - var IsDrizzleTable2 = Symbol.for("drizzle:IsDrizzleTable"); - - class Table2 { - static [import_entity73.entityKind] = "Table"; - static Symbol = { - Name: import_table_utils4.TableName, - Schema: Schema3, - OriginalName: OriginalName2, - Columns: Columns2, - ExtraConfigColumns: ExtraConfigColumns2, - BaseName: BaseName2, - IsAlias: IsAlias2, - ExtraConfigBuilder: ExtraConfigBuilder2 - }; - [import_table_utils4.TableName]; - [OriginalName2]; - [Schema3]; - [Columns2]; - [ExtraConfigColumns2]; - [BaseName2]; - [IsAlias2] = false; - [IsDrizzleTable2] = true; - [ExtraConfigBuilder2] = undefined; - constructor(name, schema, baseName) { - this[import_table_utils4.TableName] = this[OriginalName2] = name; - this[Schema3] = schema; - this[BaseName2] = baseName; - } - } - function isTable(table) { - return typeof table === "object" && table !== null && IsDrizzleTable2 in table; - } - function getTableName2(table) { - return table[import_table_utils4.TableName]; - } - function getTableUniqueName2(table) { - return `${table[Schema3] ?? "public"}.${table[import_table_utils4.TableName]}`; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/sql.cjs -var require_sql = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name2 in all) - __defProp2(target, name2, { get: all[name2], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); } - return to; + __setModuleDefault(result, mod); + return result; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var sql_exports = {}; - __export2(sql_exports, { - FakePrimitiveParam: () => FakePrimitiveParam, - Name: () => Name2, - Param: () => Param2, - Placeholder: () => Placeholder2, - SQL: () => SQL2, - StringChunk: () => StringChunk2, - View: () => View2, - fillPlaceholders: () => fillPlaceholders2, - getViewName: () => getViewName, - isDriverValueEncoder: () => isDriverValueEncoder2, - isSQLWrapper: () => isSQLWrapper2, - isView: () => isView, - name: () => name, - noopDecoder: () => noopDecoder2, - noopEncoder: () => noopEncoder2, - noopMapper: () => noopMapper2, - param: () => param, - placeholder: () => placeholder, - sql: () => sql2 - }); - module.exports = __toCommonJS2(sql_exports); - var import_entity73 = require_entity(); - var import_enum2 = require_enum(); - var import_subquery10 = require_subquery(); - var import_tracing9 = require_tracing(); - var import_view_common8 = require_view_common(); - var import_column9 = require_column(); - var import_table18 = require_table(); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Agent = undefined; + var net = __importStar(__require("net")); + var http = __importStar(__require("http")); + var https_1 = __require("https"); + __exportStar(require_helpers(), exports); + var INTERNAL = Symbol("AgentBaseInternalState"); - class FakePrimitiveParam { - static [import_entity73.entityKind] = "FakePrimitiveParam"; - } - function isSQLWrapper2(value) { - return value !== null && value !== undefined && typeof value.getSQL === "function"; - } - function mergeQueries2(queries) { - const result = { sql: "", params: [] }; - for (const query of queries) { - result.sql += query.sql; - result.params.push(...query.params); - if (query.typings?.length) { - if (!result.typings) { - result.typings = []; + class Agent extends http.Agent { + constructor(opts) { + super(opts); + this[INTERNAL] = {}; + } + isSecureEndpoint(options) { + if (options) { + if (typeof options.secureEndpoint === "boolean") { + return options.secureEndpoint; + } + if (typeof options.protocol === "string") { + return options.protocol === "https:"; } - result.typings.push(...query.typings); } + const { stack } = new Error; + if (typeof stack !== "string") + return false; + return stack.split(` +`).some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); } - return result; - } - - class StringChunk2 { - static [import_entity73.entityKind] = "StringChunk"; - value; - constructor(value) { - this.value = Array.isArray(value) ? value : [value]; - } - getSQL() { - return new SQL2([this]); + incrementSockets(name) { + if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { + return null; + } + if (!this.sockets[name]) { + this.sockets[name] = []; + } + const fakeSocket = new net.Socket({ writable: false }); + this.sockets[name].push(fakeSocket); + this.totalSocketCount++; + return fakeSocket; } - } - - class SQL2 { - constructor(queryChunks) { - this.queryChunks = queryChunks; - for (const chunk of queryChunks) { - if ((0, import_entity73.is)(chunk, import_table18.Table)) { - const schemaName = chunk[import_table18.Table.Symbol.Schema]; - this.usedTables.push(schemaName === undefined ? chunk[import_table18.Table.Symbol.Name] : schemaName + "." + chunk[import_table18.Table.Symbol.Name]); + decrementSockets(name, socket) { + if (!this.sockets[name] || socket === null) { + return; + } + const sockets = this.sockets[name]; + const index3 = sockets.indexOf(socket); + if (index3 !== -1) { + sockets.splice(index3, 1); + this.totalSocketCount--; + if (sockets.length === 0) { + delete this.sockets[name]; } } } - static [import_entity73.entityKind] = "SQL"; - decoder = noopDecoder2; - shouldInlineParams = false; - usedTables = []; - append(query) { - this.queryChunks.push(...query.queryChunks); - return this; - } - toQuery(config) { - return import_tracing9.tracer.startActiveSpan("drizzle.buildSQL", (span) => { - const query = this.buildQueryFromSourceParams(this.queryChunks, config); - span?.setAttributes({ - "drizzle.query.text": query.sql, - "drizzle.query.params": JSON.stringify(query.params) - }); - return query; - }); + getName(options) { + const secureEndpoint = this.isSecureEndpoint(options); + if (secureEndpoint) { + return https_1.Agent.prototype.getName.call(this, options); + } + return super.getName(options); } - buildQueryFromSourceParams(chunks, _config) { - const config = Object.assign({}, _config, { - inlineParams: _config.inlineParams || this.shouldInlineParams, - paramStartIndex: _config.paramStartIndex || { value: 0 } - }); - const { - casing, - escapeName, - escapeParam, - prepareTyping, - inlineParams, - paramStartIndex - } = config; - return mergeQueries2(chunks.map((chunk) => { - if ((0, import_entity73.is)(chunk, StringChunk2)) { - return { sql: chunk.value.join(""), params: [] }; - } - if ((0, import_entity73.is)(chunk, Name2)) { - return { sql: escapeName(chunk.value), params: [] }; - } - if (chunk === undefined) { - return { sql: "", params: [] }; - } - if (Array.isArray(chunk)) { - const result = [new StringChunk2("(")]; - for (const [i, p] of chunk.entries()) { - result.push(p); - if (i < chunk.length - 1) { - result.push(new StringChunk2(", ")); - } - } - result.push(new StringChunk2(")")); - return this.buildQueryFromSourceParams(result, config); - } - if ((0, import_entity73.is)(chunk, SQL2)) { - return this.buildQueryFromSourceParams(chunk.queryChunks, { - ...config, - inlineParams: inlineParams || chunk.shouldInlineParams - }); - } - if ((0, import_entity73.is)(chunk, import_table18.Table)) { - const schemaName = chunk[import_table18.Table.Symbol.Schema]; - const tableName = chunk[import_table18.Table.Symbol.Name]; - return { - sql: schemaName === undefined || chunk[import_table18.IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), - params: [] - }; - } - if ((0, import_entity73.is)(chunk, import_column9.Column)) { - const columnName = casing.getColumnCasing(chunk); - if (_config.invokeSource === "indexes") { - return { sql: escapeName(columnName), params: [] }; - } - const schemaName = chunk.table[import_table18.Table.Symbol.Schema]; - return { - sql: chunk.table[import_table18.IsAlias] || schemaName === undefined ? escapeName(chunk.table[import_table18.Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[import_table18.Table.Symbol.Name]) + "." + escapeName(columnName), - params: [] - }; - } - if ((0, import_entity73.is)(chunk, View2)) { - const schemaName = chunk[import_view_common8.ViewBaseConfig].schema; - const viewName = chunk[import_view_common8.ViewBaseConfig].name; - return { - sql: schemaName === undefined || chunk[import_view_common8.ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), - params: [] - }; - } - if ((0, import_entity73.is)(chunk, Param2)) { - if ((0, import_entity73.is)(chunk.value, Placeholder2)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); - if ((0, import_entity73.is)(mappedValue, SQL2)) { - return this.buildQueryFromSourceParams([mappedValue], config); - } - if (inlineParams) { - return { sql: this.mapInlineParam(mappedValue, config), params: [] }; - } - let typings = ["none"]; - if (prepareTyping) { - typings = [prepareTyping(chunk.encoder)]; - } - return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; - } - if ((0, import_entity73.is)(chunk, Placeholder2)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - if ((0, import_entity73.is)(chunk, SQL2.Aliased) && chunk.fieldAlias !== undefined) { - return { sql: escapeName(chunk.fieldAlias), params: [] }; - } - if ((0, import_entity73.is)(chunk, import_subquery10.Subquery)) { - if (chunk._.isWith) { - return { sql: escapeName(chunk._.alias), params: [] }; - } - return this.buildQueryFromSourceParams([ - new StringChunk2("("), - chunk._.sql, - new StringChunk2(") "), - new Name2(chunk._.alias) - ], config); - } - if ((0, import_enum2.isPgEnum)(chunk)) { - if (chunk.schema) { - return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; - } - return { sql: escapeName(chunk.enumName), params: [] }; - } - if (isSQLWrapper2(chunk)) { - if (chunk.shouldOmitSQLParens?.()) { - return this.buildQueryFromSourceParams([chunk.getSQL()], config); + createSocket(req, options, cb) { + const connectOpts = { + ...options, + secureEndpoint: this.isSecureEndpoint(options) + }; + const name = this.getName(connectOpts); + const fakeSocket = this.incrementSockets(name); + Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { + this.decrementSockets(name, fakeSocket); + if (socket instanceof http.Agent) { + try { + return socket.addRequest(req, connectOpts); + } catch (err) { + return cb(err); } - return this.buildQueryFromSourceParams([ - new StringChunk2("("), - chunk.getSQL(), - new StringChunk2(")") - ], config); - } - if (inlineParams) { - return { sql: this.mapInlineParam(chunk, config), params: [] }; } - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - })); + this[INTERNAL].currentSocket = socket; + super.createSocket(req, options, cb); + }, (err) => { + this.decrementSockets(name, fakeSocket); + cb(err); + }); } - mapInlineParam(chunk, { escapeString }) { - if (chunk === null) { - return "null"; - } - if (typeof chunk === "number" || typeof chunk === "boolean") { - return chunk.toString(); - } - if (typeof chunk === "string") { - return escapeString(chunk); - } - if (typeof chunk === "object") { - const mappedValueAsString = chunk.toString(); - if (mappedValueAsString === "[object Object]") { - return escapeString(JSON.stringify(chunk)); - } - return escapeString(mappedValueAsString); + createConnection() { + const socket = this[INTERNAL].currentSocket; + this[INTERNAL].currentSocket = undefined; + if (!socket) { + throw new Error("No socket was returned in the `connect()` function"); } - throw new Error("Unexpected param value: " + chunk); + return socket; } - getSQL() { - return this; + get defaultPort() { + return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); } - as(alias) { - if (alias === undefined) { - return this; + set defaultPort(v) { + if (this[INTERNAL]) { + this[INTERNAL].defaultPort = v; } - return new SQL2.Aliased(this, alias); - } - mapWith(decoder) { - this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder; - return this; } - inlineParams() { - this.shouldInlineParams = true; - return this; + get protocol() { + return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); } - if(condition) { - return condition ? this : undefined; + set protocol(v) { + if (this[INTERNAL]) { + this[INTERNAL].protocol = v; + } } } + exports.Agent = Agent; +}); - class Name2 { - constructor(value) { - this.value = value; - } - static [import_entity73.entityKind] = "Name"; - brand; - getSQL() { - return new SQL2([this]); - } - } - function name(value) { - return new Name2(value); - } - function isDriverValueEncoder2(value) { - return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; - } - var noopDecoder2 = { - mapFromDriverValue: (value) => value - }; - var noopEncoder2 = { - mapToDriverValue: (value) => value - }; - var noopMapper2 = { - ...noopDecoder2, - ...noopEncoder2 +// node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/parse-proxy-response.js +var require_parse_proxy_response = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; }; - - class Param2 { - constructor(value, encoder = noopEncoder2) { - this.value = value; - this.encoder = encoder; - } - static [import_entity73.entityKind] = "Param"; - brand; - getSQL() { - return new SQL2([this]); - } - } - function param(value, encoder) { - return new Param2(value, encoder); - } - function sql2(strings, ...params) { - const queryChunks = []; - if (params.length > 0 || strings.length > 0 && strings[0] !== "") { - queryChunks.push(new StringChunk2(strings[0])); - } - for (const [paramIndex, param2] of params.entries()) { - queryChunks.push(param2, new StringChunk2(strings[paramIndex + 1])); - } - return new SQL2(queryChunks); - } - ((sql22) => { - function empty() { - return new SQL2([]); - } - sql22.empty = empty; - function fromList(list) { - return new SQL2(list); - } - sql22.fromList = fromList; - function raw(str) { - return new SQL2([new StringChunk2(str)]); - } - sql22.raw = raw; - function join2(chunks, separator) { - const result = []; - for (const [i, chunk] of chunks.entries()) { - if (i > 0 && separator !== undefined) { - result.push(separator); - } - result.push(chunk); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.parseProxyResponse = undefined; + var debug_1 = __importDefault(require_src()); + var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); + function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once("readable", read); } - return new SQL2(result); - } - sql22.join = join2; - function identifier(value) { - return new Name2(value); - } - sql22.identifier = identifier; - function placeholder2(name2) { - return new Placeholder2(name2); - } - sql22.placeholder = placeholder2; - function param2(value, encoder) { - return new Param2(value, encoder); - } - sql22.param = param2; - })(sql2 || (sql2 = {})); - ((SQL22) => { - - class Aliased { - constructor(sql22, fieldAlias) { - this.sql = sql22; - this.fieldAlias = fieldAlias; + function cleanup() { + socket.removeListener("end", onend); + socket.removeListener("error", onerror); + socket.removeListener("readable", read); } - static [import_entity73.entityKind] = "SQL.Aliased"; - isSelectionField = false; - getSQL() { - return this.sql; + function onend() { + cleanup(); + debug("onend"); + reject(new Error("Proxy connection ended before receiving CONNECT response")); } - clone() { - return new Aliased(this.sql, this.fieldAlias); + function onerror(err) { + cleanup(); + debug("onerror %o", err); + reject(err); } - } - SQL22.Aliased = Aliased; - })(SQL2 || (SQL2 = {})); - - class Placeholder2 { - constructor(name2) { - this.name = name2; - } - static [import_entity73.entityKind] = "Placeholder"; - getSQL() { - return new SQL2([this]); - } - } - function placeholder(name2) { - return new Placeholder2(name2); - } - function fillPlaceholders2(params, values) { - return params.map((p) => { - if ((0, import_entity73.is)(p, Placeholder2)) { - if (!(p.name in values)) { - throw new Error(`No value for placeholder "${p.name}" was provided`); + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf(`\r +\r +`); + if (endOfHeaders === -1) { + debug("have not received end of HTTP headers yet..."); + read(); + return; } - return values[p.name]; - } - if ((0, import_entity73.is)(p, Param2) && (0, import_entity73.is)(p.value, Placeholder2)) { - if (!(p.value.name in values)) { - throw new Error(`No value for placeholder "${p.value.name}" was provided`); + const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split(`\r +`); + const firstLine = headerParts.shift(); + if (!firstLine) { + socket.destroy(); + return reject(new Error("No header received from proxy CONNECT response")); + } + const firstLineParts = firstLine.split(" "); + const statusCode = +firstLineParts[1]; + const statusText = firstLineParts.slice(2).join(" "); + const headers = {}; + for (const header of headerParts) { + if (!header) + continue; + const firstColon = header.indexOf(":"); + if (firstColon === -1) { + socket.destroy(); + return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); + } + const key = header.slice(0, firstColon).toLowerCase(); + const value = header.slice(firstColon + 1).trimStart(); + const current = headers[key]; + if (typeof current === "string") { + headers[key] = [current, value]; + } else if (Array.isArray(current)) { + current.push(value); + } else { + headers[key] = value; + } } - return p.encoder.mapToDriverValue(values[p.value.name]); + debug("got proxy server response: %o %o", firstLine, headers); + cleanup(); + resolve({ + connect: { + statusCode, + statusText, + headers + }, + buffered + }); } - return p; + socket.on("error", onerror); + socket.on("end", onend); + read(); }); } - var IsDrizzleView2 = Symbol.for("drizzle:IsDrizzleView"); + exports.parseProxyResponse = parseProxyResponse; +}); - class View2 { - static [import_entity73.entityKind] = "View"; - [import_view_common8.ViewBaseConfig]; - [IsDrizzleView2] = true; - constructor({ name: name2, schema, selectedFields, query }) { - this[import_view_common8.ViewBaseConfig] = { - name: name2, - originalName: name2, - schema, - selectedFields, - query, - isExisting: !query, - isAlias: false - }; - } - getSQL() { - return new SQL2([this]); - } - } - function isView(view) { - return typeof view === "object" && view !== null && IsDrizzleView2 in view; - } - function getViewName(view) { - return view[import_view_common8.ViewBaseConfig].name; - } - import_column9.Column.prototype.getSQL = function() { - return new SQL2([this]); - }; - import_table18.Table.prototype.getSQL = function() { - return new SQL2([this]); - }; - import_subquery10.Subquery.prototype.getSQL = function() { - return new SQL2([this]); +// node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/index.js +var require_dist5 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + } : function(o, v) { + o["default"] = v; + }); + var __importStar = exports && exports.__importStar || function(mod) { + if (mod && mod.__esModule) + return mod; + var result = {}; + if (mod != null) { + for (var k in mod) + if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) + __createBinding(result, mod, k); + } + __setModuleDefault(result, mod); + return result; }; -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/alias.cjs -var require_alias = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); + Object.defineProperty(exports, "__esModule", { value: true }); + exports.HttpsProxyAgent = undefined; + var net = __importStar(__require("net")); + var tls = __importStar(__require("tls")); + var assert_1 = __importDefault(__require("assert")); + var debug_1 = __importDefault(require_src()); + var agent_base_1 = require_dist4(); + var url_1 = __require("url"); + var parse_proxy_response_1 = require_parse_proxy_response(); + var debug = (0, debug_1.default)("https-proxy-agent"); + var setServernameFromNonIpHost = (options) => { + if (options.servername === undefined && options.host && !net.isIP(options.host)) { + return { + ...options, + servername: options.host + }; } - return to; + return options; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var alias_exports = {}; - __export2(alias_exports, { - ColumnAliasProxyHandler: () => ColumnAliasProxyHandler2, - RelationTableAliasProxyHandler: () => RelationTableAliasProxyHandler, - TableAliasProxyHandler: () => TableAliasProxyHandler2, - aliasedRelation: () => aliasedRelation, - aliasedTable: () => aliasedTable2, - aliasedTableColumn: () => aliasedTableColumn2, - mapColumnsInAliasedSQLToAlias: () => mapColumnsInAliasedSQLToAlias2, - mapColumnsInSQLToAlias: () => mapColumnsInSQLToAlias2 - }); - module.exports = __toCommonJS2(alias_exports); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - var import_table18 = require_table(); - var import_view_common8 = require_view_common(); - class ColumnAliasProxyHandler2 { - constructor(table) { - this.table = table; + class HttpsProxyAgent extends agent_base_1.Agent { + constructor(proxy, opts) { + super(opts); + this.options = { path: undefined }; + this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; + this.proxyHeaders = opts?.headers ?? {}; + debug("Creating new HttpsProxyAgent instance: %o", this.proxy.href); + const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); + const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; + this.connectOpts = { + ALPNProtocols: ["http/1.1"], + ...opts ? omit(opts, "headers") : null, + host, + port + }; } - static [import_entity73.entityKind] = "ColumnAliasProxyHandler"; - get(columnObj, prop) { - if (prop === "table") { - return this.table; + async connect(req, opts) { + const { proxy } = this; + if (!opts.host) { + throw new TypeError('No "host" provided'); } - return columnObj[prop]; - } - } - - class TableAliasProxyHandler2 { - constructor(alias, replaceOriginalName) { - this.alias = alias; - this.replaceOriginalName = replaceOriginalName; - } - static [import_entity73.entityKind] = "TableAliasProxyHandler"; - get(target, prop) { - if (prop === import_table18.Table.Symbol.IsAlias) { - return true; + let socket; + if (proxy.protocol === "https:") { + debug("Creating `tls.Socket`: %o", this.connectOpts); + socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); + } else { + debug("Creating `net.Socket`: %o", this.connectOpts); + socket = net.connect(this.connectOpts); } - if (prop === import_table18.Table.Symbol.Name) { - return this.alias; + const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; + const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; + let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r +`; + if (proxy.username || proxy.password) { + const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; + headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; } - if (this.replaceOriginalName && prop === import_table18.Table.Symbol.OriginalName) { - return this.alias; + headers.Host = `${host}:${opts.port}`; + if (!headers["Proxy-Connection"]) { + headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; } - if (prop === import_view_common8.ViewBaseConfig) { - return { - ...target[import_view_common8.ViewBaseConfig], - name: this.alias, - isAlias: true - }; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r +`; } - if (prop === import_table18.Table.Symbol.Columns) { - const columns = target[import_table18.Table.Symbol.Columns]; - if (!columns) { - return columns; + const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); + socket.write(`${payload}\r +`); + const { connect, buffered } = await proxyResponsePromise; + req.emit("proxyConnect", connect); + this.emit("proxyConnect", connect, req); + if (connect.statusCode === 200) { + req.once("socket", resume); + if (opts.secureEndpoint) { + debug("Upgrading socket connection to TLS"); + return tls.connect({ + ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), + socket + }); } - const proxiedColumns = {}; - Object.keys(columns).map((key) => { - proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler2(new Proxy(target, this))); - }); - return proxiedColumns; - } - const value = target[prop]; - if ((0, import_entity73.is)(value, import_column9.Column)) { - return new Proxy(value, new ColumnAliasProxyHandler2(new Proxy(target, this))); - } - return value; - } - } - - class RelationTableAliasProxyHandler { - constructor(alias) { - this.alias = alias; - } - static [import_entity73.entityKind] = "RelationTableAliasProxyHandler"; - get(target, prop) { - if (prop === "sourceTable") { - return aliasedTable2(target.sourceTable, this.alias); + return socket; } - return target[prop]; + socket.destroy(); + const fakeSocket = new net.Socket({ writable: false }); + fakeSocket.readable = true; + req.once("socket", (s) => { + debug("Replaying proxy buffer for failed request"); + (0, assert_1.default)(s.listenerCount("data") > 0); + s.push(buffered); + s.push(null); + }); + return fakeSocket; } } - function aliasedTable2(table, tableAlias) { - return new Proxy(table, new TableAliasProxyHandler2(tableAlias, false)); - } - function aliasedRelation(relation, tableAlias) { - return new Proxy(relation, new RelationTableAliasProxyHandler(tableAlias)); - } - function aliasedTableColumn2(column, tableAlias) { - return new Proxy(column, new ColumnAliasProxyHandler2(new Proxy(column.table, new TableAliasProxyHandler2(tableAlias, false)))); - } - function mapColumnsInAliasedSQLToAlias2(query, alias) { - return new import_sql21.SQL.Aliased(mapColumnsInSQLToAlias2(query.sql, alias), query.fieldAlias); + HttpsProxyAgent.protocols = ["http", "https"]; + exports.HttpsProxyAgent = HttpsProxyAgent; + function resume(socket) { + socket.resume(); } - function mapColumnsInSQLToAlias2(query, alias) { - return import_sql21.sql.join(query.queryChunks.map((c) => { - if ((0, import_entity73.is)(c, import_column9.Column)) { - return aliasedTableColumn2(c, alias); - } - if ((0, import_entity73.is)(c, import_sql21.SQL)) { - return mapColumnsInSQLToAlias2(c, alias); - } - if ((0, import_entity73.is)(c, import_sql21.SQL.Aliased)) { - return mapColumnsInAliasedSQLToAlias2(c, alias); + function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; } - return c; - })); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/alias.cjs -var require_alias2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var alias_exports = {}; - __export2(alias_exports, { - alias: () => alias - }); - module.exports = __toCommonJS2(alias_exports); - var import_alias3 = require_alias(); - function alias(table, alias2) { - return new Proxy(table, new import_alias3.TableAliasProxyHandler(alias2, false)); + return ret; } }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/checks.cjs -var require_checks = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/gaxios.js +var require_gaxios = __commonJS((exports) => { + var __importDefault = exports && exports.__importDefault || function(mod) { + return mod && mod.__esModule ? mod : { default: mod }; }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var checks_exports = {}; - __export2(checks_exports, { - Check: () => Check, - CheckBuilder: () => CheckBuilder, - check: () => check - }); - module.exports = __toCommonJS2(checks_exports); - var import_entity73 = require_entity(); - - class CheckBuilder { - constructor(name, value) { - this.name = name; - this.value = value; - } - static [import_entity73.entityKind] = "PgCheckBuilder"; - brand; - build(table) { - return new Check(table, this); - } - } - - class Check { - constructor(table, builder) { - this.table = table; - this.name = builder.name; - this.value = builder.value; - } - static [import_entity73.entityKind] = "PgCheck"; - name; - value; - } - function check(name, value) { - return new CheckBuilder(name, value); - } -}); + var _a; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Gaxios = undefined; + var extend_1 = __importDefault(require_extend()); + var https_1 = __require("https"); + var common_js_1 = require_common3(); + var retry_js_1 = require_retry(); + var stream_1 = __require("stream"); + var interceptor_js_1 = require_interceptor(); + var randomUUID = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID(); + var HTTP_STATUS_NO_CONTENT = 204; -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/utils.cjs -var require_utils6 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); + class Gaxios { + agentCache = new Map; + defaults; + interceptors; + constructor(defaults2) { + this.defaults = defaults2 || {}; + this.interceptors = { + request: new interceptor_js_1.GaxiosInterceptorManager, + response: new interceptor_js_1.GaxiosInterceptorManager + }; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var utils_exports = {}; - __export2(utils_exports, { - applyMixins: () => applyMixins2, - getColumnNameAndConfig: () => getColumnNameAndConfig2, - getTableColumns: () => getTableColumns2, - getTableLikeName: () => getTableLikeName2, - getViewSelectedFields: () => getViewSelectedFields, - haveSameKeys: () => haveSameKeys2, - isConfig: () => isConfig2, - mapResultRow: () => mapResultRow2, - mapUpdateSet: () => mapUpdateSet2, - orderSelectedFields: () => orderSelectedFields2 - }); - module.exports = __toCommonJS2(utils_exports); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - var import_subquery10 = require_subquery(); - var import_table18 = require_table(); - var import_view_common8 = require_view_common(); - function mapResultRow2(columns, row, joinsNotNullableMap) { - const nullifyMap = {}; - const result = columns.reduce((result2, { path: path2, field }, columnIndex) => { - let decoder; - if ((0, import_entity73.is)(field, import_column9.Column)) { - decoder = field; - } else if ((0, import_entity73.is)(field, import_sql21.SQL)) { - decoder = field.decoder; + fetch(...args) { + const input = args[0]; + const init3 = args[1]; + let url = undefined; + const headers = new Headers; + if (typeof input === "string") { + url = new URL(input); + } else if (input instanceof URL) { + url = input; + } else if (input && input.url) { + url = new URL(input.url); + } + if (input && typeof input === "object" && "headers" in input) { + _a.mergeHeaders(headers, input.headers); + } + if (init3) { + _a.mergeHeaders(headers, new Headers(init3.headers)); + } + if (typeof input === "object" && !(input instanceof URL)) { + return this.request({ ...init3, ...input, headers, url }); } else { - decoder = field.sql.decoder; + return this.request({ ...init3, headers, url }); } - let node = result2; - for (const [pathChunkIndex, pathChunk] of path2.entries()) { - if (pathChunkIndex < path2.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; + } + async request(opts = {}) { + let prepared = await this.#prepareRequest(opts); + prepared = await this.#applyRequestInterceptors(prepared); + return this.#applyResponseInterceptors(this._request(prepared)); + } + async _defaultAdapter(config) { + const fetchImpl = config.fetchImplementation || this.defaults.fetchImplementation || await _a.#getFetch(); + const preparedOpts = { ...config }; + delete preparedOpts.data; + const res = await fetchImpl(config.url, preparedOpts); + const data = await this.getResponseData(config, res); + if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) { + Object.defineProperties(res, { + data: { + configurable: true, + writable: true, + enumerable: true, + value: data } - node = node[pathChunk]; + }); + } + return Object.assign(res, { config, data }); + } + async _request(opts) { + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); } else { - const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); - if (joinsNotNullableMap && (0, import_entity73.is)(field, import_column9.Column) && path2.length === 2) { - const objectName = path2[0]; - if (!(objectName in nullifyMap)) { - nullifyMap[objectName] = value === null ? (0, import_table18.getTableName)(field.table) : false; - } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== (0, import_table18.getTableName)(field.table)) { - nullifyMap[objectName] = false; + translatedResponse = await this._defaultAdapter(opts); + } + if (!opts.validateStatus(translatedResponse.status)) { + if (opts.responseType === "stream") { + const response = []; + for await (const chunk of translatedResponse.data) { + response.push(chunk); } + translatedResponse.data = response.toString(); } + const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`); + throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo); } - } - return result2; - }, {}); - if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { - for (const [objectName, tableName] of Object.entries(nullifyMap)) { - if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { - result[objectName] = null; + return translatedResponse; + } catch (e2) { + let err; + if (e2 instanceof common_js_1.GaxiosError) { + err = e2; + } else if (e2 instanceof Error) { + err = new common_js_1.GaxiosError(e2.message, opts, undefined, e2); + } else { + err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, undefined, e2); + } + const { shouldRetry, config } = await (0, retry_js_1.getRetryConfig)(err); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; + opts.retryConfig = err.config?.retryConfig; + this.#appendTimeoutToSignal(opts); + return this._request(opts); + } + if (opts.errorRedactor) { + opts.errorRedactor(err); } + throw err; } } - return result; - } - function orderSelectedFields2(fields, pathPrefix) { - return Object.entries(fields).reduce((result, [name, field]) => { - if (typeof name !== "string") { - return result; + async getResponseData(opts, res) { + if (res.status === HTTP_STATUS_NO_CONTENT) { + return ""; } - const newPath = pathPrefix ? [...pathPrefix, name] : [name]; - if ((0, import_entity73.is)(field, import_column9.Column) || (0, import_entity73.is)(field, import_sql21.SQL) || (0, import_entity73.is)(field, import_sql21.SQL.Aliased)) { - result.push({ path: newPath, field }); - } else if ((0, import_entity73.is)(field, import_table18.Table)) { - result.push(...orderSelectedFields2(field[import_table18.Table.Symbol.Columns], newPath)); - } else { - result.push(...orderSelectedFields2(field, newPath)); + if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) { + throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts })); } - return result; - }, []); - } - function haveSameKeys2(left, right) { - const leftKeys = Object.keys(left); - const rightKeys = Object.keys(right); - if (leftKeys.length !== rightKeys.length) { - return false; - } - for (const [index2, key] of leftKeys.entries()) { - if (key !== rightKeys[index2]) { - return false; + switch (opts.responseType) { + case "stream": + return res.body; + case "json": { + const data = await res.text(); + try { + return JSON.parse(data); + } catch { + return data; + } + } + case "arraybuffer": + return res.arrayBuffer(); + case "blob": + return res.blob(); + case "text": + return res.text(); + default: + return this.getResponseDataFromContentType(res); } } - return true; - } - function mapUpdateSet2(table, values) { - const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => { - if ((0, import_entity73.is)(value, import_sql21.SQL) || (0, import_entity73.is)(value, import_column9.Column)) { - return [key, value]; - } else { - return [key, new import_sql21.Param(value, table[import_table18.Table.Symbol.Columns][key])]; + #urlMayUseProxy(url, noProxy = []) { + const candidate = new URL(url); + const noProxyList = [...noProxy]; + const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(",") || []; + for (const rule of noProxyEnvList) { + noProxyList.push(rule.trim()); } - }); - if (entries.length === 0) { - throw new Error("No values to set"); - } - return Object.fromEntries(entries); - } - function applyMixins2(baseClass, extendedClasses) { - for (const extendedClass of extendedClasses) { - for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { - if (name === "constructor") - continue; - Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)); + for (const rule of noProxyList) { + if (rule instanceof RegExp) { + if (rule.test(candidate.toString())) { + return false; + } + } else if (rule instanceof URL) { + if (rule.origin === candidate.origin) { + return false; + } + } else if (rule.startsWith("*.") || rule.startsWith(".")) { + const cleanedRule = rule.replace(/^\*\./, "."); + if (candidate.hostname.endsWith(cleanedRule)) { + return false; + } + } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) { + return false; + } } - } - } - function getTableColumns2(table) { - return table[import_table18.Table.Symbol.Columns]; - } - function getViewSelectedFields(view) { - return view[import_view_common8.ViewBaseConfig].selectedFields; - } - function getTableLikeName2(table) { - return (0, import_entity73.is)(table, import_subquery10.Subquery) ? table._.alias : (0, import_entity73.is)(table, import_sql21.View) ? table[import_view_common8.ViewBaseConfig].name : (0, import_entity73.is)(table, import_sql21.SQL) ? undefined : table[import_table18.Table.Symbol.IsAlias] ? table[import_table18.Table.Symbol.Name] : table[import_table18.Table.Symbol.BaseName]; - } - function getColumnNameAndConfig2(a, b) { - return { - name: typeof a === "string" && a.length > 0 ? a : "", - config: typeof a === "object" ? a : b - }; - } - function isConfig2(data) { - if (typeof data !== "object" || data === null) - return false; - if (data.constructor.name !== "Object") - return false; - if ("logger" in data) { - const type = typeof data["logger"]; - if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") - return false; - return true; - } - if ("schema" in data) { - const type = typeof data["schema"]; - if (type !== "object" && type !== "undefined") - return false; - return true; - } - if ("casing" in data) { - const type = typeof data["casing"]; - if (type !== "string" && type !== "undefined") - return false; - return true; - } - if ("mode" in data) { - if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined) - return false; - return true; - } - if ("connection" in data) { - const type = typeof data["connection"]; - if (type !== "string" && type !== "object" && type !== "undefined") - return false; - return true; - } - if ("client" in data) { - const type = typeof data["client"]; - if (type !== "object" && type !== "function" && type !== "undefined") - return false; return true; } - if (Object.keys(data).length === 0) - return true; - return false; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/int.common.cjs -var require_int_common = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var int_common_exports = {}; - __export2(int_common_exports, { - PgIntColumnBaseBuilder: () => PgIntColumnBaseBuilder2 - }); - module.exports = __toCommonJS2(int_common_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgIntColumnBaseBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgIntColumnBaseBuilder"; - generatedAlwaysAsIdentity(sequence) { - if (sequence) { - const { name, ...options } = sequence; - this.config.generatedIdentity = { - type: "always", - sequenceName: name, - sequenceOptions: options - }; - } else { - this.config.generatedIdentity = { - type: "always" - }; + async#applyRequestInterceptors(options) { + let promiseChain = Promise.resolve(options); + for (const interceptor of this.interceptors.request.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } } - this.config.hasDefault = true; - this.config.notNull = true; - return this; + return promiseChain; } - generatedByDefaultAsIdentity(sequence) { - if (sequence) { - const { name, ...options } = sequence; - this.config.generatedIdentity = { - type: "byDefault", - sequenceName: name, - sequenceOptions: options - }; - } else { - this.config.generatedIdentity = { - type: "byDefault" - }; + async#applyResponseInterceptors(response) { + let promiseChain = Promise.resolve(response); + for (const interceptor of this.interceptors.response.values()) { + if (interceptor) { + promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + } } - this.config.hasDefault = true; - this.config.notNull = true; - return this; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/bigint.cjs -var require_bigint = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var bigint_exports = {}; - __export2(bigint_exports, { - PgBigInt53: () => PgBigInt532, - PgBigInt53Builder: () => PgBigInt53Builder2, - PgBigInt64: () => PgBigInt642, - PgBigInt64Builder: () => PgBigInt64Builder2, - bigint: () => bigint2 - }); - module.exports = __toCommonJS2(bigint_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - var import_int_common4 = require_int_common(); - - class PgBigInt53Builder2 extends import_int_common4.PgIntColumnBaseBuilder { - static [import_entity73.entityKind] = "PgBigInt53Builder"; - constructor(name) { - super(name, "number", "PgBigInt53"); - } - build(table) { - return new PgBigInt532(table, this.config); - } - } - - class PgBigInt532 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgBigInt53"; - getSQLType() { - return "bigint"; + return promiseChain; } - mapFromDriverValue(value) { - if (typeof value === "number") { - return value; + async#prepareRequest(options) { + const preparedHeaders = new Headers(this.defaults.headers); + _a.mergeHeaders(preparedHeaders, options.headers); + const opts = (0, extend_1.default)(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error("URL is required."); } - return Number(value); - } - } - - class PgBigInt64Builder2 extends import_int_common4.PgIntColumnBaseBuilder { - static [import_entity73.entityKind] = "PgBigInt64Builder"; - constructor(name) { - super(name, "bigint", "PgBigInt64"); - } - build(table) { - return new PgBigInt642(table, this.config); - } - } - - class PgBigInt642 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgBigInt64"; - getSQLType() { - return "bigint"; - } - mapFromDriverValue(value) { - return BigInt(value); - } - } - function bigint2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (config.mode === "number") { - return new PgBigInt53Builder2(name); - } - return new PgBigInt64Builder2(name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/bigserial.cjs -var require_bigserial = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var bigserial_exports = {}; - __export2(bigserial_exports, { - PgBigSerial53: () => PgBigSerial532, - PgBigSerial53Builder: () => PgBigSerial53Builder2, - PgBigSerial64: () => PgBigSerial642, - PgBigSerial64Builder: () => PgBigSerial64Builder2, - bigserial: () => bigserial2 - }); - module.exports = __toCommonJS2(bigserial_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgBigSerial53Builder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgBigSerial53Builder"; - constructor(name) { - super(name, "number", "PgBigSerial53"); - this.config.hasDefault = true; - this.config.notNull = true; - } - build(table) { - return new PgBigSerial532(table, this.config); - } - } - - class PgBigSerial532 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgBigSerial53"; - getSQLType() { - return "bigserial"; - } - mapFromDriverValue(value) { - if (typeof value === "number") { - return value; + if (opts.baseURL) { + opts.url = new URL(opts.url, opts.baseURL); } - return Number(value); - } - } - - class PgBigSerial64Builder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgBigSerial64Builder"; - constructor(name) { - super(name, "bigint", "PgBigSerial64"); - this.config.hasDefault = true; - } - build(table) { - return new PgBigSerial642(table, this.config); - } - } - - class PgBigSerial642 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgBigSerial64"; - getSQLType() { - return "bigserial"; - } - mapFromDriverValue(value) { - return BigInt(value); - } - } - function bigserial2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (config.mode === "number") { - return new PgBigSerial53Builder2(name); - } - return new PgBigSerial64Builder2(name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/boolean.cjs -var require_boolean = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var boolean_exports = {}; - __export2(boolean_exports, { - PgBoolean: () => PgBoolean2, - PgBooleanBuilder: () => PgBooleanBuilder2, - boolean: () => boolean3 - }); - module.exports = __toCommonJS2(boolean_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgBooleanBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgBooleanBuilder"; - constructor(name) { - super(name, "boolean", "PgBoolean"); - } - build(table) { - return new PgBoolean2(table, this.config); - } - } - - class PgBoolean2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgBoolean"; - getSQLType() { - return "boolean"; - } - } - function boolean3(name) { - return new PgBooleanBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/char.cjs -var require_char = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var char_exports = {}; - __export2(char_exports, { - PgChar: () => PgChar2, - PgCharBuilder: () => PgCharBuilder2, - char: () => char2 - }); - module.exports = __toCommonJS2(char_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgCharBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgCharBuilder"; - constructor(name, config) { - super(name, "string", "PgChar"); - this.config.length = config.length; - this.config.enumValues = config.enum; - } - build(table) { - return new PgChar2(table, this.config); - } - } - - class PgChar2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgChar"; - length = this.config.length; - enumValues = this.config.enumValues; - getSQLType() { - return this.length === undefined ? `char` : `char(${this.length})`; - } - } - function char2(a, b = {}) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgCharBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/cidr.cjs -var require_cidr = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var cidr_exports = {}; - __export2(cidr_exports, { - PgCidr: () => PgCidr2, - PgCidrBuilder: () => PgCidrBuilder2, - cidr: () => cidr2 - }); - module.exports = __toCommonJS2(cidr_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgCidrBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgCidrBuilder"; - constructor(name) { - super(name, "string", "PgCidr"); - } - build(table) { - return new PgCidr2(table, this.config); - } - } - - class PgCidr2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgCidr"; - getSQLType() { - return "cidr"; - } - } - function cidr2(name) { - return new PgCidrBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/custom.cjs -var require_custom = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var custom_exports = {}; - __export2(custom_exports, { - PgCustomColumn: () => PgCustomColumn2, - PgCustomColumnBuilder: () => PgCustomColumnBuilder2, - customType: () => customType2 - }); - module.exports = __toCommonJS2(custom_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgCustomColumnBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgCustomColumnBuilder"; - constructor(name, fieldConfig, customTypeParams) { - super(name, "custom", "PgCustomColumn"); - this.config.fieldConfig = fieldConfig; - this.config.customTypeParams = customTypeParams; - } - build(table) { - return new PgCustomColumn2(table, this.config); - } - } - - class PgCustomColumn2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgCustomColumn"; - sqlName; - mapTo; - mapFrom; - constructor(table, config) { - super(table, config); - this.sqlName = config.customTypeParams.dataType(config.fieldConfig); - this.mapTo = config.customTypeParams.toDriver; - this.mapFrom = config.customTypeParams.fromDriver; - } - getSQLType() { - return this.sqlName; - } - mapFromDriverValue(value) { - return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; - } - mapToDriverValue(value) { - return typeof this.mapTo === "function" ? this.mapTo(value) : value; - } - } - function customType2(customTypeParams) { - return (a, b) => { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgCustomColumnBuilder2(name, config, customTypeParams); - }; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/date.common.cjs -var require_date_common = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var date_common_exports = {}; - __export2(date_common_exports, { - PgDateColumnBaseBuilder: () => PgDateColumnBaseBuilder2 - }); - module.exports = __toCommonJS2(date_common_exports); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - var import_common36 = require_common3(); - - class PgDateColumnBaseBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgDateColumnBaseBuilder"; - defaultNow() { - return this.default(import_sql21.sql`now()`); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/date.cjs -var require_date = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var date_exports = {}; - __export2(date_exports, { - PgDate: () => PgDate2, - PgDateBuilder: () => PgDateBuilder2, - PgDateString: () => PgDateString2, - PgDateStringBuilder: () => PgDateStringBuilder2, - date: () => date3 - }); - module.exports = __toCommonJS2(date_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - var import_date_common4 = require_date_common(); - - class PgDateBuilder2 extends import_date_common4.PgDateColumnBaseBuilder { - static [import_entity73.entityKind] = "PgDateBuilder"; - constructor(name) { - super(name, "date", "PgDate"); - } - build(table) { - return new PgDate2(table, this.config); - } - } - - class PgDate2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgDate"; - getSQLType() { - return "date"; - } - mapFromDriverValue(value) { - return new Date(value); - } - mapToDriverValue(value) { - return value.toISOString(); - } - } - - class PgDateStringBuilder2 extends import_date_common4.PgDateColumnBaseBuilder { - static [import_entity73.entityKind] = "PgDateStringBuilder"; - constructor(name) { - super(name, "string", "PgDateString"); - } - build(table) { - return new PgDateString2(table, this.config); - } - } - - class PgDateString2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgDateString"; - getSQLType() { - return "date"; - } - } - function date3(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (config?.mode === "date") { - return new PgDateBuilder2(name); - } - return new PgDateStringBuilder2(name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/double-precision.cjs -var require_double_precision = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var double_precision_exports = {}; - __export2(double_precision_exports, { - PgDoublePrecision: () => PgDoublePrecision2, - PgDoublePrecisionBuilder: () => PgDoublePrecisionBuilder2, - doublePrecision: () => doublePrecision2 - }); - module.exports = __toCommonJS2(double_precision_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgDoublePrecisionBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgDoublePrecisionBuilder"; - constructor(name) { - super(name, "number", "PgDoublePrecision"); - } - build(table) { - return new PgDoublePrecision2(table, this.config); - } - } - - class PgDoublePrecision2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgDoublePrecision"; - getSQLType() { - return "double precision"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - return Number.parseFloat(value); + opts.url = new URL(opts.url); + if (opts.params) { + if (opts.paramsSerializer) { + let additionalQueryParams = opts.paramsSerializer(opts.params); + if (additionalQueryParams.startsWith("?")) { + additionalQueryParams = additionalQueryParams.slice(1); + } + const prefix = opts.url.toString().includes("?") ? "&" : "?"; + opts.url = opts.url + prefix + additionalQueryParams; + } else { + const url = opts.url instanceof URL ? opts.url : new URL(opts.url); + for (const [key, value] of new URLSearchParams(opts.params)) { + url.searchParams.append(key, value); + } + opts.url = url; + } } - return value; - } - } - function doublePrecision2(name) { - return new PgDoublePrecisionBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/inet.cjs -var require_inet = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var inet_exports = {}; - __export2(inet_exports, { - PgInet: () => PgInet2, - PgInetBuilder: () => PgInetBuilder2, - inet: () => inet2 - }); - module.exports = __toCommonJS2(inet_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgInetBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgInetBuilder"; - constructor(name) { - super(name, "string", "PgInet"); - } - build(table) { - return new PgInet2(table, this.config); - } - } - - class PgInet2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgInet"; - getSQLType() { - return "inet"; - } - } - function inet2(name) { - return new PgInetBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/integer.cjs -var require_integer = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var integer_exports = {}; - __export2(integer_exports, { - PgInteger: () => PgInteger2, - PgIntegerBuilder: () => PgIntegerBuilder2, - integer: () => integer2 - }); - module.exports = __toCommonJS2(integer_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - var import_int_common4 = require_int_common(); - - class PgIntegerBuilder2 extends import_int_common4.PgIntColumnBaseBuilder { - static [import_entity73.entityKind] = "PgIntegerBuilder"; - constructor(name) { - super(name, "number", "PgInteger"); - } - build(table) { - return new PgInteger2(table, this.config); - } - } - - class PgInteger2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgInteger"; - getSQLType() { - return "integer"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - return Number.parseInt(value); + if (typeof options.maxContentLength === "number") { + opts.size = options.maxContentLength; } - return value; - } - } - function integer2(name) { - return new PgIntegerBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/interval.cjs -var require_interval = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var interval_exports = {}; - __export2(interval_exports, { - PgInterval: () => PgInterval2, - PgIntervalBuilder: () => PgIntervalBuilder2, - interval: () => interval2 - }); - module.exports = __toCommonJS2(interval_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgIntervalBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgIntervalBuilder"; - constructor(name, intervalConfig) { - super(name, "string", "PgInterval"); - this.config.intervalConfig = intervalConfig; - } - build(table) { - return new PgInterval2(table, this.config); - } - } - - class PgInterval2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgInterval"; - fields = this.config.intervalConfig.fields; - precision = this.config.intervalConfig.precision; - getSQLType() { - const fields = this.fields ? ` ${this.fields}` : ""; - const precision = this.precision ? `(${this.precision})` : ""; - return `interval${fields}${precision}`; - } - } - function interval2(a, b = {}) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgIntervalBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/json.cjs -var require_json3 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var json_exports = {}; - __export2(json_exports, { - PgJson: () => PgJson2, - PgJsonBuilder: () => PgJsonBuilder2, - json: () => json2 - }); - module.exports = __toCommonJS2(json_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgJsonBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgJsonBuilder"; - constructor(name) { - super(name, "json", "PgJson"); - } - build(table) { - return new PgJson2(table, this.config); - } - } - - class PgJson2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgJson"; - constructor(table, config) { - super(table, config); - } - getSQLType() { - return "json"; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return value; + if (typeof options.maxRedirects === "number") { + opts.follow = options.maxRedirects; + } + const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || ""); + if (opts.multipart?.length) { + const boundary = await randomUUID(); + preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`); + opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary)); + } else if (shouldDirectlyPassData) { + opts.body = opts.data; + } else if (typeof opts.data === "object") { + if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") { + opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data); + } else { + if (!preparedHeaders.has("content-type")) { + preparedHeaders.set("content-type", "application/json"); + } + opts.body = JSON.stringify(opts.data); } + } else if (opts.data) { + opts.body = opts.data; } - return value; - } - } - function json2(name) { - return new PgJsonBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/jsonb.cjs -var require_jsonb = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var jsonb_exports = {}; - __export2(jsonb_exports, { - PgJsonb: () => PgJsonb2, - PgJsonbBuilder: () => PgJsonbBuilder2, - jsonb: () => jsonb2 - }); - module.exports = __toCommonJS2(jsonb_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgJsonbBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgJsonbBuilder"; - constructor(name) { - super(name, "json", "PgJsonb"); - } - build(table) { - return new PgJsonb2(table, this.config); - } - } - - class PgJsonb2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgJsonb"; - constructor(table, config) { - super(table, config); - } - getSQLType() { - return "jsonb"; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return value; + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || "unknown"; + if (!preparedHeaders.has("accept") && opts.responseType === "json") { + preparedHeaders.set("accept", "application/json"); + } + const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy; + if (opts.agent) {} else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) { + const HttpsProxyAgent = await _a.#getProxyAgent(); + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } else { + opts.agent = new HttpsProxyAgent(proxy, { + cert: opts.cert, + key: opts.key + }); + this.agentCache.set(proxy, opts.agent); + } + } else if (opts.cert && opts.key) { + if (this.agentCache.has(opts.key)) { + opts.agent = this.agentCache.get(opts.key); + } else { + opts.agent = new https_1.Agent({ + cert: opts.cert, + key: opts.key + }); + this.agentCache.set(opts.key, opts.agent); } } - return value; - } - } - function jsonb2(name) { - return new PgJsonbBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/line.cjs -var require_line = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var line_exports = {}; - __export2(line_exports, { - PgLineABC: () => PgLineABC2, - PgLineABCBuilder: () => PgLineABCBuilder2, - PgLineBuilder: () => PgLineBuilder2, - PgLineTuple: () => PgLineTuple2, - line: () => line2 - }); - module.exports = __toCommonJS2(line_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgLineBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgLineBuilder"; - constructor(name) { - super(name, "array", "PgLine"); - } - build(table) { - return new PgLineTuple2(table, this.config); - } - } - - class PgLineTuple2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgLine"; - getSQLType() { - return "line"; - } - mapFromDriverValue(value) { - const [a, b, c] = value.slice(1, -1).split(","); - return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)]; - } - mapToDriverValue(value) { - return `{${value[0]},${value[1]},${value[2]}}`; - } - } - - class PgLineABCBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgLineABCBuilder"; - constructor(name) { - super(name, "json", "PgLineABC"); - } - build(table) { - return new PgLineABC2(table, this.config); - } - } - - class PgLineABC2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgLineABC"; - getSQLType() { - return "line"; - } - mapFromDriverValue(value) { - const [a, b, c] = value.slice(1, -1).split(","); - return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) }; - } - mapToDriverValue(value) { - return `{${value.a},${value.b},${value.c}}`; - } - } - function line2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (!config?.mode || config.mode === "tuple") { - return new PgLineBuilder2(name); - } - return new PgLineABCBuilder2(name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/macaddr.cjs -var require_macaddr = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var macaddr_exports = {}; - __export2(macaddr_exports, { - PgMacaddr: () => PgMacaddr2, - PgMacaddrBuilder: () => PgMacaddrBuilder2, - macaddr: () => macaddr2 - }); - module.exports = __toCommonJS2(macaddr_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgMacaddrBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgMacaddrBuilder"; - constructor(name) { - super(name, "string", "PgMacaddr"); - } - build(table) { - return new PgMacaddr2(table, this.config); - } - } - - class PgMacaddr2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgMacaddr"; - getSQLType() { - return "macaddr"; - } - } - function macaddr2(name) { - return new PgMacaddrBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/macaddr8.cjs -var require_macaddr8 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var macaddr8_exports = {}; - __export2(macaddr8_exports, { - PgMacaddr8: () => PgMacaddr82, - PgMacaddr8Builder: () => PgMacaddr8Builder2, - macaddr8: () => macaddr82 - }); - module.exports = __toCommonJS2(macaddr8_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgMacaddr8Builder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgMacaddr8Builder"; - constructor(name) { - super(name, "string", "PgMacaddr8"); - } - build(table) { - return new PgMacaddr82(table, this.config); - } - } - - class PgMacaddr82 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgMacaddr8"; - getSQLType() { - return "macaddr8"; - } - } - function macaddr82(name) { - return new PgMacaddr8Builder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/numeric.cjs -var require_numeric = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var numeric_exports = {}; - __export2(numeric_exports, { - PgNumeric: () => PgNumeric2, - PgNumericBigInt: () => PgNumericBigInt2, - PgNumericBigIntBuilder: () => PgNumericBigIntBuilder2, - PgNumericBuilder: () => PgNumericBuilder2, - PgNumericNumber: () => PgNumericNumber2, - PgNumericNumberBuilder: () => PgNumericNumberBuilder2, - decimal: () => decimal, - numeric: () => numeric2 - }); - module.exports = __toCommonJS2(numeric_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgNumericBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgNumericBuilder"; - constructor(name, precision, scale) { - super(name, "string", "PgNumeric"); - this.config.precision = precision; - this.config.scale = scale; - } - build(table) { - return new PgNumeric2(table, this.config); - } - } - - class PgNumeric2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgNumeric"; - precision; - scale; - constructor(table, config) { - super(table, config); - this.precision = config.precision; - this.scale = config.scale; - } - mapFromDriverValue(value) { - if (typeof value === "string") - return value; - return String(value); - } - getSQLType() { - if (this.precision !== undefined && this.scale !== undefined) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === undefined) { - return "numeric"; - } else { - return `numeric(${this.precision})`; + if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) { + opts.errorRedactor = common_js_1.defaultErrorRedactor; } - } - } - - class PgNumericNumberBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgNumericNumberBuilder"; - constructor(name, precision, scale) { - super(name, "number", "PgNumericNumber"); - this.config.precision = precision; - this.config.scale = scale; - } - build(table) { - return new PgNumericNumber2(table, this.config); - } - } - - class PgNumericNumber2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgNumericNumber"; - precision; - scale; - constructor(table, config) { - super(table, config); - this.precision = config.precision; - this.scale = config.scale; - } - mapFromDriverValue(value) { - if (typeof value === "number") - return value; - return Number(value); - } - mapToDriverValue = String; - getSQLType() { - if (this.precision !== undefined && this.scale !== undefined) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === undefined) { - return "numeric"; - } else { - return `numeric(${this.precision})`; + if (opts.body && !("duplex" in opts)) { + opts.duplex = "half"; } + this.#appendTimeoutToSignal(opts); + return Object.assign(opts, { + headers: preparedHeaders, + url: opts.url instanceof URL ? opts.url : new URL(opts.url) + }); } - } - - class PgNumericBigIntBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgNumericBigIntBuilder"; - constructor(name, precision, scale) { - super(name, "bigint", "PgNumericBigInt"); - this.config.precision = precision; - this.config.scale = scale; - } - build(table) { - return new PgNumericBigInt2(table, this.config); + #appendTimeoutToSignal(opts) { + if (opts.timeout) { + const timeoutSignal = AbortSignal.timeout(opts.timeout); + if (opts.signal && !opts.signal.aborted) { + opts.signal = AbortSignal.any([opts.signal, timeoutSignal]); + } else { + opts.signal = timeoutSignal; + } + } } - } - - class PgNumericBigInt2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgNumericBigInt"; - precision; - scale; - constructor(table, config) { - super(table, config); - this.precision = config.precision; - this.scale = config.scale; + validateStatus(status) { + return status >= 200 && status < 300; } - mapFromDriverValue = BigInt; - mapToDriverValue = String; - getSQLType() { - if (this.precision !== undefined && this.scale !== undefined) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === undefined) { - return "numeric"; + async getResponseDataFromContentType(response) { + let contentType = response.headers.get("Content-Type"); + if (contentType === null) { + return response.text(); + } + contentType = contentType.toLowerCase(); + if (contentType.includes("application/json")) { + let data = await response.text(); + try { + data = JSON.parse(data); + } catch {} + return data; + } else if (contentType.match(/^text\//)) { + return response.text(); } else { - return `numeric(${this.precision})`; + return response.blob(); } } - } - function numeric2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - const mode = config?.mode; - return mode === "number" ? new PgNumericNumberBuilder2(name, config?.precision, config?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder2(name, config?.precision, config?.scale) : new PgNumericBuilder2(name, config?.precision, config?.scale); - } - var decimal = numeric2; -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/point.cjs -var require_point = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var point_exports = {}; - __export2(point_exports, { - PgPointObject: () => PgPointObject2, - PgPointObjectBuilder: () => PgPointObjectBuilder2, - PgPointTuple: () => PgPointTuple2, - PgPointTupleBuilder: () => PgPointTupleBuilder2, - point: () => point2 - }); - module.exports = __toCommonJS2(point_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgPointTupleBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgPointTupleBuilder"; - constructor(name) { - super(name, "array", "PgPointTuple"); - } - build(table) { - return new PgPointTuple2(table, this.config); - } - } - - class PgPointTuple2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgPointTuple"; - getSQLType() { - return "point"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - const [x, y] = value.slice(1, -1).split(","); - return [Number.parseFloat(x), Number.parseFloat(y)]; + async* getMultipartRequest(multipartOptions, boundary) { + const finale = `--${boundary}--`; + for (const currentPart of multipartOptions) { + const partContentType = currentPart.headers.get("Content-Type") || "application/octet-stream"; + const preamble = `--${boundary}\r +Content-Type: ${partContentType}\r +\r +`; + yield preamble; + if (typeof currentPart.content === "string") { + yield currentPart.content; + } else { + yield* currentPart.content; + } + yield `\r +`; } - return [value.x, value.y]; - } - mapToDriverValue(value) { - return `(${value[0]},${value[1]})`; - } - } - - class PgPointObjectBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgPointObjectBuilder"; - constructor(name) { - super(name, "json", "PgPointObject"); + yield finale; } - build(table) { - return new PgPointObject2(table, this.config); + static #proxyAgent; + static #fetch; + static async#getProxyAgent() { + this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist5()))).HttpsProxyAgent; + return this.#proxyAgent; } - } - - class PgPointObject2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgPointObject"; - getSQLType() { - return "point"; + static async#getFetch() { + const hasWindow = typeof window !== "undefined" && !!window; + this.#fetch ||= hasWindow ? window.fetch : (await import("node-fetch")).default; + return this.#fetch; } - mapFromDriverValue(value) { - if (typeof value === "string") { - const [x, y] = value.slice(1, -1).split(","); - return { x: Number.parseFloat(x), y: Number.parseFloat(y) }; + static mergeHeaders(base, ...append) { + base = base instanceof Headers ? base : new Headers(base); + for (const headers of append) { + const add = headers instanceof Headers ? headers : new Headers(headers); + add.forEach((value, key) => { + key === "set-cookie" ? base.append(key, value) : base.set(key, value); + }); } - return value; - } - mapToDriverValue(value) { - return `(${value.x},${value.y})`; - } - } - function point2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (!config?.mode || config.mode === "tuple") { - return new PgPointTupleBuilder2(name); + return base; } - return new PgPointObjectBuilder2(name); } + exports.Gaxios = Gaxios; + _a = Gaxios; }); -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.cjs -var require_utils7 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); +// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/index.js +var require_src2 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var utils_exports = {}; - __export2(utils_exports, { - parseEWKB: () => parseEWKB2 + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; }); - module.exports = __toCommonJS2(utils_exports); - function hexToBytes2(hex) { - const bytes = []; - for (let c = 0;c < hex.length; c += 2) { - bytes.push(Number.parseInt(hex.slice(c, c + 2), 16)); - } - return new Uint8Array(bytes); - } - function bytesToFloat642(bytes, offset) { - const buffer = new ArrayBuffer(8); - const view = new DataView(buffer); - for (let i = 0;i < 8; i++) { - view.setUint8(i, bytes[offset + i]); - } - return view.getFloat64(0, true); - } - function parseEWKB2(hex) { - const bytes = hexToBytes2(hex); - let offset = 0; - const byteOrder = bytes[offset]; - offset += 1; - const view = new DataView(bytes.buffer); - const geomType = view.getUint32(offset, byteOrder === 1); - offset += 4; - let _srid; - if (geomType & 536870912) { - _srid = view.getUint32(offset, byteOrder === 1); - offset += 4; - } - if ((geomType & 65535) === 1) { - const x = bytesToFloat642(bytes, offset); - offset += 8; - const y = bytesToFloat642(bytes, offset); - offset += 8; - return [x, y]; - } - throw new Error("Unsupported geometry type"); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.cjs -var require_geometry = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var geometry_exports = {}; - __export2(geometry_exports, { - PgGeometry: () => PgGeometry2, - PgGeometryBuilder: () => PgGeometryBuilder2, - PgGeometryObject: () => PgGeometryObject2, - PgGeometryObjectBuilder: () => PgGeometryObjectBuilder2, - geometry: () => geometry2 - }); - module.exports = __toCommonJS2(geometry_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - var import_utils210 = require_utils7(); - - class PgGeometryBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgGeometryBuilder"; - constructor(name) { - super(name, "array", "PgGeometry"); - } - build(table) { - return new PgGeometry2(table, this.config); - } - } - - class PgGeometry2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgGeometry"; - getSQLType() { - return "geometry(point)"; - } - mapFromDriverValue(value) { - return (0, import_utils210.parseEWKB)(value); - } - mapToDriverValue(value) { - return `point(${value[0]} ${value[1]})`; - } - } - - class PgGeometryObjectBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgGeometryObjectBuilder"; - constructor(name) { - super(name, "json", "PgGeometryObject"); - } - build(table) { - return new PgGeometryObject2(table, this.config); - } + Object.defineProperty(exports, "__esModule", { value: true }); + exports.instance = exports.Gaxios = exports.GaxiosError = undefined; + exports.request = request; + var gaxios_js_1 = require_gaxios(); + Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function() { + return gaxios_js_1.Gaxios; + } }); + var common_js_1 = require_common3(); + Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function() { + return common_js_1.GaxiosError; + } }); + __exportStar(require_interceptor(), exports); + exports.instance = new gaxios_js_1.Gaxios; + async function request(opts) { + return exports.instance.request(opts); } +}); - class PgGeometryObject2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgGeometryObject"; - getSQLType() { - return "geometry(point)"; - } - mapFromDriverValue(value) { - const parsed = (0, import_utils210.parseEWKB)(value); - return { x: parsed[0], y: parsed[1] }; - } - mapToDriverValue(value) { - return `point(${value.x} ${value.y})`; - } - } - function geometry2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (!config?.mode || config.mode === "tuple") { - return new PgGeometryBuilder2(name); - } - return new PgGeometryObjectBuilder2(name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/real.cjs -var require_real = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var real_exports = {}; - __export2(real_exports, { - PgReal: () => PgReal2, - PgRealBuilder: () => PgRealBuilder2, - real: () => real2 - }); - module.exports = __toCommonJS2(real_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgRealBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgRealBuilder"; - constructor(name, length) { - super(name, "number", "PgReal"); - this.config.length = length; - } - build(table) { - return new PgReal2(table, this.config); - } - } - - class PgReal2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgReal"; - constructor(table, config) { - super(table, config); - } - getSQLType() { - return "real"; - } - mapFromDriverValue = (value) => { - if (typeof value === "string") { - return Number.parseFloat(value); - } - return value; - }; - } - function real2(name) { - return new PgRealBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/serial.cjs -var require_serial = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var serial_exports = {}; - __export2(serial_exports, { - PgSerial: () => PgSerial2, - PgSerialBuilder: () => PgSerialBuilder2, - serial: () => serial2 - }); - module.exports = __toCommonJS2(serial_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgSerialBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgSerialBuilder"; - constructor(name) { - super(name, "number", "PgSerial"); - this.config.hasDefault = true; - this.config.notNull = true; - } - build(table) { - return new PgSerial2(table, this.config); - } - } - - class PgSerial2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgSerial"; - getSQLType() { - return "serial"; - } - } - function serial2(name) { - return new PgSerialBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/smallint.cjs -var require_smallint = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var smallint_exports = {}; - __export2(smallint_exports, { - PgSmallInt: () => PgSmallInt2, - PgSmallIntBuilder: () => PgSmallIntBuilder2, - smallint: () => smallint2 - }); - module.exports = __toCommonJS2(smallint_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - var import_int_common4 = require_int_common(); - - class PgSmallIntBuilder2 extends import_int_common4.PgIntColumnBaseBuilder { - static [import_entity73.entityKind] = "PgSmallIntBuilder"; - constructor(name) { - super(name, "number", "PgSmallInt"); - } - build(table) { - return new PgSmallInt2(table, this.config); - } - } - - class PgSmallInt2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgSmallInt"; - getSQLType() { - return "smallint"; - } - mapFromDriverValue = (value) => { - if (typeof value === "string") { - return Number(value); - } - return value; - }; - } - function smallint2(name) { - return new PgSmallIntBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/smallserial.cjs -var require_smallserial = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var smallserial_exports = {}; - __export2(smallserial_exports, { - PgSmallSerial: () => PgSmallSerial2, - PgSmallSerialBuilder: () => PgSmallSerialBuilder2, - smallserial: () => smallserial2 - }); - module.exports = __toCommonJS2(smallserial_exports); - var import_entity73 = require_entity(); - var import_common36 = require_common3(); - - class PgSmallSerialBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgSmallSerialBuilder"; - constructor(name) { - super(name, "number", "PgSmallSerial"); - this.config.hasDefault = true; - this.config.notNull = true; - } - build(table) { - return new PgSmallSerial2(table, this.config); - } - } - - class PgSmallSerial2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgSmallSerial"; - getSQLType() { - return "smallserial"; - } - } - function smallserial2(name) { - return new PgSmallSerialBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/text.cjs -var require_text2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var text_exports = {}; - __export2(text_exports, { - PgText: () => PgText2, - PgTextBuilder: () => PgTextBuilder2, - text: () => text2 - }); - module.exports = __toCommonJS2(text_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgTextBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgTextBuilder"; - constructor(name, config) { - super(name, "string", "PgText"); - this.config.enumValues = config.enum; - } - build(table) { - return new PgText2(table, this.config); - } - } - - class PgText2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgText"; - enumValues = this.config.enumValues; - getSQLType() { - return "text"; - } - } - function text2(a, b = {}) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgTextBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/time.cjs -var require_time = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var time_exports = {}; - __export2(time_exports, { - PgTime: () => PgTime2, - PgTimeBuilder: () => PgTimeBuilder2, - time: () => time2 - }); - module.exports = __toCommonJS2(time_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - var import_date_common4 = require_date_common(); - - class PgTimeBuilder2 extends import_date_common4.PgDateColumnBaseBuilder { - constructor(name, withTimezone, precision) { - super(name, "string", "PgTime"); - this.withTimezone = withTimezone; - this.precision = precision; - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - static [import_entity73.entityKind] = "PgTimeBuilder"; - build(table) { - return new PgTime2(table, this.config); - } - } - - class PgTime2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgTime"; - withTimezone; - precision; - constructor(table, config) { - super(table, config); - this.withTimezone = config.withTimezone; - this.precision = config.precision; - } - getSQLType() { - const precision = this.precision === undefined ? "" : `(${this.precision})`; - return `time${precision}${this.withTimezone ? " with time zone" : ""}`; - } - } - function time2(a, b = {}) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgTimeBuilder2(name, config.withTimezone ?? false, config.precision); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/timestamp.cjs -var require_timestamp2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var timestamp_exports = {}; - __export2(timestamp_exports, { - PgTimestamp: () => PgTimestamp2, - PgTimestampBuilder: () => PgTimestampBuilder2, - PgTimestampString: () => PgTimestampString2, - PgTimestampStringBuilder: () => PgTimestampStringBuilder2, - timestamp: () => timestamp2 - }); - module.exports = __toCommonJS2(timestamp_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - var import_date_common4 = require_date_common(); - - class PgTimestampBuilder2 extends import_date_common4.PgDateColumnBaseBuilder { - static [import_entity73.entityKind] = "PgTimestampBuilder"; - constructor(name, withTimezone, precision) { - super(name, "date", "PgTimestamp"); - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - build(table) { - return new PgTimestamp2(table, this.config); - } - } - - class PgTimestamp2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgTimestamp"; - withTimezone; - precision; - constructor(table, config) { - super(table, config); - this.withTimezone = config.withTimezone; - this.precision = config.precision; - } - getSQLType() { - const precision = this.precision === undefined ? "" : ` (${this.precision})`; - return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; - } - mapFromDriverValue = (value) => { - return new Date(this.withTimezone ? value : value + "+0000"); - }; - mapToDriverValue = (value) => { - return value.toISOString(); - }; - } - - class PgTimestampStringBuilder2 extends import_date_common4.PgDateColumnBaseBuilder { - static [import_entity73.entityKind] = "PgTimestampStringBuilder"; - constructor(name, withTimezone, precision) { - super(name, "string", "PgTimestampString"); - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - build(table) { - return new PgTimestampString2(table, this.config); - } - } - - class PgTimestampString2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgTimestampString"; - withTimezone; - precision; - constructor(table, config) { - super(table, config); - this.withTimezone = config.withTimezone; - this.precision = config.precision; - } - getSQLType() { - const precision = this.precision === undefined ? "" : `(${this.precision})`; - return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; - } - } - function timestamp2(a, b = {}) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - if (config?.mode === "string") { - return new PgTimestampStringBuilder2(name, config.withTimezone ?? false, config.precision); - } - return new PgTimestampBuilder2(name, config?.withTimezone ?? false, config?.precision); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/uuid.cjs -var require_uuid = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var uuid_exports = {}; - __export2(uuid_exports, { - PgUUID: () => PgUUID2, - PgUUIDBuilder: () => PgUUIDBuilder2, - uuid: () => uuid2 - }); - module.exports = __toCommonJS2(uuid_exports); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - var import_common36 = require_common3(); - - class PgUUIDBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgUUIDBuilder"; - constructor(name) { - super(name, "string", "PgUUID"); - } - defaultRandom() { - return this.default(import_sql21.sql`gen_random_uuid()`); - } - build(table) { - return new PgUUID2(table, this.config); - } - } - - class PgUUID2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgUUID"; - getSQLType() { - return "uuid"; - } - } - function uuid2(name) { - return new PgUUIDBuilder2(name ?? ""); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/varchar.cjs -var require_varchar = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var varchar_exports = {}; - __export2(varchar_exports, { - PgVarchar: () => PgVarchar2, - PgVarcharBuilder: () => PgVarcharBuilder2, - varchar: () => varchar2 - }); - module.exports = __toCommonJS2(varchar_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgVarcharBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgVarcharBuilder"; - constructor(name, config) { - super(name, "string", "PgVarchar"); - this.config.length = config.length; - this.config.enumValues = config.enum; - } - build(table) { - return new PgVarchar2(table, this.config); - } - } - - class PgVarchar2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgVarchar"; - length = this.config.length; - enumValues = this.config.enumValues; - getSQLType() { - return this.length === undefined ? `varchar` : `varchar(${this.length})`; - } - } - function varchar2(a, b = {}) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgVarcharBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.cjs -var require_bit = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var bit_exports = {}; - __export2(bit_exports, { - PgBinaryVector: () => PgBinaryVector2, - PgBinaryVectorBuilder: () => PgBinaryVectorBuilder2, - bit: () => bit2 - }); - module.exports = __toCommonJS2(bit_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgBinaryVectorBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgBinaryVectorBuilder"; - constructor(name, config) { - super(name, "string", "PgBinaryVector"); - this.config.dimensions = config.dimensions; - } - build(table) { - return new PgBinaryVector2(table, this.config); - } - } - - class PgBinaryVector2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgBinaryVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `bit(${this.dimensions})`; - } - } - function bit2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgBinaryVectorBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.cjs -var require_halfvec = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var halfvec_exports = {}; - __export2(halfvec_exports, { - PgHalfVector: () => PgHalfVector2, - PgHalfVectorBuilder: () => PgHalfVectorBuilder2, - halfvec: () => halfvec2 - }); - module.exports = __toCommonJS2(halfvec_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgHalfVectorBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgHalfVectorBuilder"; - constructor(name, config) { - super(name, "array", "PgHalfVector"); - this.config.dimensions = config.dimensions; - } - build(table) { - return new PgHalfVector2(table, this.config); - } - } - - class PgHalfVector2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgHalfVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `halfvec(${this.dimensions})`; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); - } - } - function halfvec2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgHalfVectorBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.cjs -var require_sparsevec = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var sparsevec_exports = {}; - __export2(sparsevec_exports, { - PgSparseVector: () => PgSparseVector2, - PgSparseVectorBuilder: () => PgSparseVectorBuilder2, - sparsevec: () => sparsevec2 - }); - module.exports = __toCommonJS2(sparsevec_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgSparseVectorBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgSparseVectorBuilder"; - constructor(name, config) { - super(name, "string", "PgSparseVector"); - this.config.dimensions = config.dimensions; - } - build(table) { - return new PgSparseVector2(table, this.config); - } - } - - class PgSparseVector2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgSparseVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `sparsevec(${this.dimensions})`; - } - } - function sparsevec2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgSparseVectorBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.cjs -var require_vector = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var vector_exports = {}; - __export2(vector_exports, { - PgVector: () => PgVector2, - PgVectorBuilder: () => PgVectorBuilder2, - vector: () => vector2 - }); - module.exports = __toCommonJS2(vector_exports); - var import_entity73 = require_entity(); - var import_utils33 = require_utils6(); - var import_common36 = require_common3(); - - class PgVectorBuilder2 extends import_common36.PgColumnBuilder { - static [import_entity73.entityKind] = "PgVectorBuilder"; - constructor(name, config) { - super(name, "array", "PgVector"); - this.config.dimensions = config.dimensions; - } - build(table) { - return new PgVector2(table, this.config); - } - } - - class PgVector2 extends import_common36.PgColumn { - static [import_entity73.entityKind] = "PgVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `vector(${this.dimensions})`; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); - } - } - function vector2(a, b) { - const { name, config } = (0, import_utils33.getColumnNameAndConfig)(a, b); - return new PgVectorBuilder2(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/index.cjs -var require_columns = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var columns_exports = {}; - module.exports = __toCommonJS2(columns_exports); - __reExport(columns_exports, require_bigint(), module.exports); - __reExport(columns_exports, require_bigserial(), module.exports); - __reExport(columns_exports, require_boolean(), module.exports); - __reExport(columns_exports, require_char(), module.exports); - __reExport(columns_exports, require_cidr(), module.exports); - __reExport(columns_exports, require_common3(), module.exports); - __reExport(columns_exports, require_custom(), module.exports); - __reExport(columns_exports, require_date(), module.exports); - __reExport(columns_exports, require_double_precision(), module.exports); - __reExport(columns_exports, require_enum(), module.exports); - __reExport(columns_exports, require_inet(), module.exports); - __reExport(columns_exports, require_int_common(), module.exports); - __reExport(columns_exports, require_integer(), module.exports); - __reExport(columns_exports, require_interval(), module.exports); - __reExport(columns_exports, require_json3(), module.exports); - __reExport(columns_exports, require_jsonb(), module.exports); - __reExport(columns_exports, require_line(), module.exports); - __reExport(columns_exports, require_macaddr(), module.exports); - __reExport(columns_exports, require_macaddr8(), module.exports); - __reExport(columns_exports, require_numeric(), module.exports); - __reExport(columns_exports, require_point(), module.exports); - __reExport(columns_exports, require_geometry(), module.exports); - __reExport(columns_exports, require_real(), module.exports); - __reExport(columns_exports, require_serial(), module.exports); - __reExport(columns_exports, require_smallint(), module.exports); - __reExport(columns_exports, require_smallserial(), module.exports); - __reExport(columns_exports, require_text2(), module.exports); - __reExport(columns_exports, require_time(), module.exports); - __reExport(columns_exports, require_timestamp2(), module.exports); - __reExport(columns_exports, require_uuid(), module.exports); - __reExport(columns_exports, require_varchar(), module.exports); - __reExport(columns_exports, require_bit(), module.exports); - __reExport(columns_exports, require_halfvec(), module.exports); - __reExport(columns_exports, require_sparsevec(), module.exports); - __reExport(columns_exports, require_vector(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/query-promise.cjs -var require_query_promise = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var query_promise_exports = {}; - __export2(query_promise_exports, { - QueryPromise: () => QueryPromise2 - }); - module.exports = __toCommonJS2(query_promise_exports); - var import_entity73 = require_entity(); - - class QueryPromise2 { - static [import_entity73.entityKind] = "QueryPromise"; - [Symbol.toStringTag] = "QueryPromise"; - catch(onRejected) { - return this.then(undefined, onRejected); - } - finally(onFinally) { - return this.then((value) => { - onFinally?.(); - return value; - }, (reason) => { - onFinally?.(); - throw reason; - }); - } - then(onFulfilled, onRejected) { - return this.execute().then(onFulfilled, onRejected); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/selection-proxy.cjs -var require_selection_proxy = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var selection_proxy_exports = {}; - __export2(selection_proxy_exports, { - SelectionProxyHandler: () => SelectionProxyHandler2 - }); - module.exports = __toCommonJS2(selection_proxy_exports); - var import_alias3 = require_alias(); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - var import_subquery10 = require_subquery(); - var import_view_common8 = require_view_common(); - - class SelectionProxyHandler2 { - static [import_entity73.entityKind] = "SelectionProxyHandler"; - config; - constructor(config) { - this.config = { ...config }; - } - get(subquery, prop) { - if (prop === "_") { - return { - ...subquery["_"], - selectedFields: new Proxy(subquery._.selectedFields, this) - }; - } - if (prop === import_view_common8.ViewBaseConfig) { - return { - ...subquery[import_view_common8.ViewBaseConfig], - selectedFields: new Proxy(subquery[import_view_common8.ViewBaseConfig].selectedFields, this) - }; - } - if (typeof prop === "symbol") { - return subquery[prop]; - } - const columns = (0, import_entity73.is)(subquery, import_subquery10.Subquery) ? subquery._.selectedFields : (0, import_entity73.is)(subquery, import_sql21.View) ? subquery[import_view_common8.ViewBaseConfig].selectedFields : subquery; - const value = columns[prop]; - if ((0, import_entity73.is)(value, import_sql21.SQL.Aliased)) { - if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { - return value.sql; - } - const newValue = value.clone(); - newValue.isSelectionField = true; - return newValue; - } - if ((0, import_entity73.is)(value, import_sql21.SQL)) { - if (this.config.sqlBehavior === "sql") { - return value; - } - throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`); - } - if ((0, import_entity73.is)(value, import_column9.Column)) { - if (this.config.alias) { - return new Proxy(value, new import_alias3.ColumnAliasProxyHandler(new Proxy(value.table, new import_alias3.TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)))); - } - return value; - } - if (typeof value !== "object" || value === null) { - return value; - } - return new Proxy(value, new SelectionProxyHandler2(this.config)); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/all.cjs -var require_all = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var all_exports = {}; - __export2(all_exports, { - getPgColumnBuilders: () => getPgColumnBuilders2 - }); - module.exports = __toCommonJS2(all_exports); - var import_bigint2 = require_bigint(); - var import_bigserial2 = require_bigserial(); - var import_boolean2 = require_boolean(); - var import_char2 = require_char(); - var import_cidr2 = require_cidr(); - var import_custom2 = require_custom(); - var import_date2 = require_date(); - var import_double_precision2 = require_double_precision(); - var import_inet2 = require_inet(); - var import_integer2 = require_integer(); - var import_interval2 = require_interval(); - var import_json2 = require_json3(); - var import_jsonb2 = require_jsonb(); - var import_line2 = require_line(); - var import_macaddr2 = require_macaddr(); - var import_macaddr82 = require_macaddr8(); - var import_numeric2 = require_numeric(); - var import_point2 = require_point(); - var import_geometry2 = require_geometry(); - var import_real2 = require_real(); - var import_serial2 = require_serial(); - var import_smallint2 = require_smallint(); - var import_smallserial2 = require_smallserial(); - var import_text2 = require_text2(); - var import_time2 = require_time(); - var import_timestamp2 = require_timestamp2(); - var import_uuid2 = require_uuid(); - var import_varchar2 = require_varchar(); - var import_bit2 = require_bit(); - var import_halfvec2 = require_halfvec(); - var import_sparsevec2 = require_sparsevec(); - var import_vector2 = require_vector(); - function getPgColumnBuilders2() { - return { - bigint: import_bigint2.bigint, - bigserial: import_bigserial2.bigserial, - boolean: import_boolean2.boolean, - char: import_char2.char, - cidr: import_cidr2.cidr, - customType: import_custom2.customType, - date: import_date2.date, - doublePrecision: import_double_precision2.doublePrecision, - inet: import_inet2.inet, - integer: import_integer2.integer, - interval: import_interval2.interval, - json: import_json2.json, - jsonb: import_jsonb2.jsonb, - line: import_line2.line, - macaddr: import_macaddr2.macaddr, - macaddr8: import_macaddr82.macaddr8, - numeric: import_numeric2.numeric, - point: import_point2.point, - geometry: import_geometry2.geometry, - real: import_real2.real, - serial: import_serial2.serial, - smallint: import_smallint2.smallint, - smallserial: import_smallserial2.smallserial, - text: import_text2.text, - time: import_time2.time, - timestamp: import_timestamp2.timestamp, - uuid: import_uuid2.uuid, - varchar: import_varchar2.varchar, - bit: import_bit2.bit, - halfvec: import_halfvec2.halfvec, - sparsevec: import_sparsevec2.sparsevec, - vector: import_vector2.vector - }; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/table.cjs -var require_table2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var table_exports = {}; - __export2(table_exports, { - EnableRLS: () => EnableRLS2, - InlineForeignKeys: () => InlineForeignKeys2, - PgTable: () => PgTable2, - pgTable: () => pgTable2, - pgTableCreator: () => pgTableCreator, - pgTableWithSchema: () => pgTableWithSchema2 - }); - module.exports = __toCommonJS2(table_exports); - var import_entity73 = require_entity(); - var import_table18 = require_table(); - var import_all2 = require_all(); - var InlineForeignKeys2 = Symbol.for("drizzle:PgInlineForeignKeys"); - var EnableRLS2 = Symbol.for("drizzle:EnableRLS"); - - class PgTable2 extends import_table18.Table { - static [import_entity73.entityKind] = "PgTable"; - static Symbol = Object.assign({}, import_table18.Table.Symbol, { - InlineForeignKeys: InlineForeignKeys2, - EnableRLS: EnableRLS2 - }); - [InlineForeignKeys2] = []; - [EnableRLS2] = false; - [import_table18.Table.Symbol.ExtraConfigBuilder] = undefined; - [import_table18.Table.Symbol.ExtraConfigColumns] = {}; - } - function pgTableWithSchema2(name, columns, extraConfig, schema, baseName = name) { - const rawTable = new PgTable2(name, schema, baseName); - const parsedColumns = typeof columns === "function" ? columns((0, import_all2.getPgColumnBuilders)()) : columns; - const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.build(rawTable); - rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable)); - return [name2, column]; - })); - const builtColumnsForExtraConfig = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.buildExtraConfigColumn(rawTable); - return [name2, column]; - })); - const table = Object.assign(rawTable, builtColumns); - table[import_table18.Table.Symbol.Columns] = builtColumns; - table[import_table18.Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; - if (extraConfig) { - table[PgTable2.Symbol.ExtraConfigBuilder] = extraConfig; - } - return Object.assign(table, { - enableRLS: () => { - table[PgTable2.Symbol.EnableRLS] = true; - return table; - } - }); - } - var pgTable2 = (name, columns, extraConfig) => { - return pgTableWithSchema2(name, columns, extraConfig, undefined); - }; - function pgTableCreator(customizeTableName) { - return (name, columns, extraConfig) => { - return pgTableWithSchema2(customizeTableName(name), columns, extraConfig, undefined, name); - }; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/indexes.cjs -var require_indexes = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var indexes_exports = {}; - __export2(indexes_exports, { - Index: () => Index2, - IndexBuilder: () => IndexBuilder2, - IndexBuilderOn: () => IndexBuilderOn2, - index: () => index2, - uniqueIndex: () => uniqueIndex2 - }); - module.exports = __toCommonJS2(indexes_exports); - var import_sql21 = require_sql(); - var import_entity73 = require_entity(); - var import_columns3 = require_columns(); - - class IndexBuilderOn2 { - constructor(unique, name) { - this.unique = unique; - this.name = name; - } - static [import_entity73.entityKind] = "PgIndexBuilderOn"; - on(...columns) { - return new IndexBuilder2(columns.map((it) => { - if ((0, import_entity73.is)(it, import_sql21.SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new import_columns3.IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); - return clonedIndexedColumn; - }), this.unique, false, this.name); - } - onOnly(...columns) { - return new IndexBuilder2(columns.map((it) => { - if ((0, import_entity73.is)(it, import_sql21.SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new import_columns3.IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = it.defaultConfig; - return clonedIndexedColumn; - }), this.unique, true, this.name); - } - using(method, ...columns) { - return new IndexBuilder2(columns.map((it) => { - if ((0, import_entity73.is)(it, import_sql21.SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new import_columns3.IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); - return clonedIndexedColumn; - }), this.unique, true, this.name, method); - } - } - - class IndexBuilder2 { - static [import_entity73.entityKind] = "PgIndexBuilder"; - config; - constructor(columns, unique, only, name, method = "btree") { - this.config = { - name, - columns, - unique, - only, - method - }; - } - concurrently() { - this.config.concurrently = true; - return this; - } - with(obj) { - this.config.with = obj; - return this; - } - where(condition) { - this.config.where = condition; - return this; - } - build(table) { - return new Index2(this.config, table); - } - } - - class Index2 { - static [import_entity73.entityKind] = "PgIndex"; - config; - constructor(config, table) { - this.config = { ...config, table }; - } - } - function index2(name) { - return new IndexBuilderOn2(false, name); - } - function uniqueIndex2(name) { - return new IndexBuilderOn2(true, name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/policies.cjs -var require_policies = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var policies_exports = {}; - __export2(policies_exports, { - PgPolicy: () => PgPolicy, - pgPolicy: () => pgPolicy - }); - module.exports = __toCommonJS2(policies_exports); - var import_entity73 = require_entity(); - - class PgPolicy { - constructor(name, config) { - this.name = name; - if (config) { - this.as = config.as; - this.for = config.for; - this.to = config.to; - this.using = config.using; - this.withCheck = config.withCheck; - } - } - static [import_entity73.entityKind] = "PgPolicy"; - as; - for; - to; - using; - withCheck; - _linkedTable; - link(table) { - this._linkedTable = table; - return this; - } - } - function pgPolicy(name, config) { - return new PgPolicy(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/primary-keys.cjs -var require_primary_keys = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var primary_keys_exports = {}; - __export2(primary_keys_exports, { - PrimaryKey: () => PrimaryKey2, - PrimaryKeyBuilder: () => PrimaryKeyBuilder2, - primaryKey: () => primaryKey2 - }); - module.exports = __toCommonJS2(primary_keys_exports); - var import_entity73 = require_entity(); - var import_table18 = require_table2(); - function primaryKey2(...config) { - if (config[0].columns) { - return new PrimaryKeyBuilder2(config[0].columns, config[0].name); - } - return new PrimaryKeyBuilder2(config); - } - - class PrimaryKeyBuilder2 { - static [import_entity73.entityKind] = "PgPrimaryKeyBuilder"; - columns; - name; - constructor(columns, name) { - this.columns = columns; - this.name = name; - } - build(table) { - return new PrimaryKey2(table, this.columns, this.name); - } - } - - class PrimaryKey2 { - constructor(table, columns, name) { - this.table = table; - this.columns = columns; - this.name = name; - } - static [import_entity73.entityKind] = "PgPrimaryKey"; - columns; - name; - getName() { - return this.name ?? `${this.table[import_table18.PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/view-common.cjs -var require_view_common2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var view_common_exports = {}; - __export2(view_common_exports, { - PgViewConfig: () => PgViewConfig - }); - module.exports = __toCommonJS2(view_common_exports); - var PgViewConfig = Symbol.for("drizzle:PgViewConfig"); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/casing.cjs -var require_casing = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var casing_exports = {}; - __export2(casing_exports, { - CasingCache: () => CasingCache2, - toCamelCase: () => toCamelCase2, - toSnakeCase: () => toSnakeCase2 - }); - module.exports = __toCommonJS2(casing_exports); - var import_entity73 = require_entity(); - var import_table18 = require_table(); - function toSnakeCase2(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.map((word) => word.toLowerCase()).join("_"); - } - function toCamelCase2(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.reduce((acc, word, i) => { - const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; - return acc + formattedWord; - }, ""); - } - function noopCase2(input) { - return input; - } - - class CasingCache2 { - static [import_entity73.entityKind] = "CasingCache"; - cache = {}; - cachedTables = {}; - convert; - constructor(casing) { - this.convert = casing === "snake_case" ? toSnakeCase2 : casing === "camelCase" ? toCamelCase2 : noopCase2; - } - getColumnCasing(column) { - if (!column.keyAsName) - return column.name; - const schema = column.table[import_table18.Table.Symbol.Schema] ?? "public"; - const tableName = column.table[import_table18.Table.Symbol.OriginalName]; - const key = `${schema}.${tableName}.${column.name}`; - if (!this.cache[key]) { - this.cacheTable(column.table); - } - return this.cache[key]; - } - cacheTable(table) { - const schema = table[import_table18.Table.Symbol.Schema] ?? "public"; - const tableName = table[import_table18.Table.Symbol.OriginalName]; - const tableKey = `${schema}.${tableName}`; - if (!this.cachedTables[tableKey]) { - for (const column of Object.values(table[import_table18.Table.Symbol.Columns])) { - const columnKey = `${tableKey}.${column.name}`; - this.cache[columnKey] = this.convert(column.name); - } - this.cachedTables[tableKey] = true; - } - } - clearCache() { - this.cache = {}; - this.cachedTables = {}; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/errors.cjs -var require_errors3 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var errors_exports = {}; - __export2(errors_exports, { - DrizzleError: () => DrizzleError2, - TransactionRollbackError: () => TransactionRollbackError2 - }); - module.exports = __toCommonJS2(errors_exports); - var import_entity73 = require_entity(); - - class DrizzleError2 extends Error { - static [import_entity73.entityKind] = "DrizzleError"; - constructor({ message, cause }) { - super(message); - this.name = "DrizzleError"; - this.cause = cause; - } - } - - class TransactionRollbackError2 extends DrizzleError2 { - static [import_entity73.entityKind] = "TransactionRollbackError"; - constructor() { - super({ message: "Rollback" }); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/expressions/conditions.cjs -var require_conditions = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var conditions_exports = {}; - __export2(conditions_exports, { - and: () => and2, - arrayContained: () => arrayContained, - arrayContains: () => arrayContains, - arrayOverlaps: () => arrayOverlaps, - between: () => between2, - bindIfParam: () => bindIfParam2, - eq: () => eq2, - exists: () => exists2, - gt: () => gt2, - gte: () => gte2, - ilike: () => ilike2, - inArray: () => inArray2, - isNotNull: () => isNotNull2, - isNull: () => isNull2, - like: () => like2, - lt: () => lt2, - lte: () => lte2, - ne: () => ne2, - not: () => not2, - notBetween: () => notBetween2, - notExists: () => notExists2, - notIlike: () => notIlike2, - notInArray: () => notInArray2, - notLike: () => notLike2, - or: () => or2 - }); - module.exports = __toCommonJS2(conditions_exports); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_table18 = require_table(); - var import_sql21 = require_sql(); - function bindIfParam2(value, column) { - if ((0, import_sql21.isDriverValueEncoder)(column) && !(0, import_sql21.isSQLWrapper)(value) && !(0, import_entity73.is)(value, import_sql21.Param) && !(0, import_entity73.is)(value, import_sql21.Placeholder) && !(0, import_entity73.is)(value, import_column9.Column) && !(0, import_entity73.is)(value, import_table18.Table) && !(0, import_entity73.is)(value, import_sql21.View)) { - return new import_sql21.Param(value, column); - } - return value; - } - var eq2 = (left, right) => { - return import_sql21.sql`${left} = ${bindIfParam2(right, left)}`; - }; - var ne2 = (left, right) => { - return import_sql21.sql`${left} <> ${bindIfParam2(right, left)}`; - }; - function and2(...unfilteredConditions) { - const conditions = unfilteredConditions.filter((c) => c !== undefined); - if (conditions.length === 0) { - return; - } - if (conditions.length === 1) { - return new import_sql21.SQL(conditions); - } - return new import_sql21.SQL([ - new import_sql21.StringChunk("("), - import_sql21.sql.join(conditions, new import_sql21.StringChunk(" and ")), - new import_sql21.StringChunk(")") - ]); - } - function or2(...unfilteredConditions) { - const conditions = unfilteredConditions.filter((c) => c !== undefined); - if (conditions.length === 0) { - return; - } - if (conditions.length === 1) { - return new import_sql21.SQL(conditions); - } - return new import_sql21.SQL([ - new import_sql21.StringChunk("("), - import_sql21.sql.join(conditions, new import_sql21.StringChunk(" or ")), - new import_sql21.StringChunk(")") - ]); - } - function not2(condition) { - return import_sql21.sql`not ${condition}`; - } - var gt2 = (left, right) => { - return import_sql21.sql`${left} > ${bindIfParam2(right, left)}`; - }; - var gte2 = (left, right) => { - return import_sql21.sql`${left} >= ${bindIfParam2(right, left)}`; - }; - var lt2 = (left, right) => { - return import_sql21.sql`${left} < ${bindIfParam2(right, left)}`; - }; - var lte2 = (left, right) => { - return import_sql21.sql`${left} <= ${bindIfParam2(right, left)}`; - }; - function inArray2(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - return import_sql21.sql`false`; - } - return import_sql21.sql`${column} in ${values.map((v) => bindIfParam2(v, column))}`; - } - return import_sql21.sql`${column} in ${bindIfParam2(values, column)}`; - } - function notInArray2(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - return import_sql21.sql`true`; - } - return import_sql21.sql`${column} not in ${values.map((v) => bindIfParam2(v, column))}`; - } - return import_sql21.sql`${column} not in ${bindIfParam2(values, column)}`; - } - function isNull2(value) { - return import_sql21.sql`${value} is null`; - } - function isNotNull2(value) { - return import_sql21.sql`${value} is not null`; - } - function exists2(subquery) { - return import_sql21.sql`exists ${subquery}`; - } - function notExists2(subquery) { - return import_sql21.sql`not exists ${subquery}`; - } - function between2(column, min, max) { - return import_sql21.sql`${column} between ${bindIfParam2(min, column)} and ${bindIfParam2(max, column)}`; - } - function notBetween2(column, min, max) { - return import_sql21.sql`${column} not between ${bindIfParam2(min, column)} and ${bindIfParam2(max, column)}`; - } - function like2(column, value) { - return import_sql21.sql`${column} like ${value}`; - } - function notLike2(column, value) { - return import_sql21.sql`${column} not like ${value}`; - } - function ilike2(column, value) { - return import_sql21.sql`${column} ilike ${value}`; - } - function notIlike2(column, value) { - return import_sql21.sql`${column} not ilike ${value}`; - } - function arrayContains(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - throw new Error("arrayContains requires at least one value"); - } - const array2 = import_sql21.sql`${bindIfParam2(values, column)}`; - return import_sql21.sql`${column} @> ${array2}`; - } - return import_sql21.sql`${column} @> ${bindIfParam2(values, column)}`; - } - function arrayContained(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - throw new Error("arrayContained requires at least one value"); - } - const array2 = import_sql21.sql`${bindIfParam2(values, column)}`; - return import_sql21.sql`${column} <@ ${array2}`; - } - return import_sql21.sql`${column} <@ ${bindIfParam2(values, column)}`; - } - function arrayOverlaps(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - throw new Error("arrayOverlaps requires at least one value"); - } - const array2 = import_sql21.sql`${bindIfParam2(values, column)}`; - return import_sql21.sql`${column} && ${array2}`; - } - return import_sql21.sql`${column} && ${bindIfParam2(values, column)}`; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/expressions/select.cjs -var require_select = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc22) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc22 = __getOwnPropDesc2(from, key)) || desc22.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var select_exports = {}; - __export2(select_exports, { - asc: () => asc2, - desc: () => desc2 - }); - module.exports = __toCommonJS2(select_exports); - var import_sql21 = require_sql(); - function asc2(column) { - return import_sql21.sql`${column} asc`; - } - function desc2(column) { - return import_sql21.sql`${column} desc`; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/expressions/index.cjs -var require_expressions = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var expressions_exports = {}; - module.exports = __toCommonJS2(expressions_exports); - __reExport(expressions_exports, require_conditions(), module.exports); - __reExport(expressions_exports, require_select(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/relations.cjs -var require_relations = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var relations_exports = {}; - __export2(relations_exports, { - Many: () => Many2, - One: () => One2, - Relation: () => Relation2, - Relations: () => Relations2, - createMany: () => createMany2, - createOne: () => createOne2, - createTableRelationsHelpers: () => createTableRelationsHelpers2, - extractTablesRelationalConfig: () => extractTablesRelationalConfig2, - getOperators: () => getOperators2, - getOrderByOperators: () => getOrderByOperators2, - mapRelationalRow: () => mapRelationalRow2, - normalizeRelation: () => normalizeRelation2, - relations: () => relations - }); - module.exports = __toCommonJS2(relations_exports); - var import_table18 = require_table(); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_primary_keys2 = require_primary_keys(); - var import_expressions2 = require_expressions(); - var import_sql21 = require_sql(); - - class Relation2 { - constructor(sourceTable, referencedTable, relationName) { - this.sourceTable = sourceTable; - this.referencedTable = referencedTable; - this.relationName = relationName; - this.referencedTableName = referencedTable[import_table18.Table.Symbol.Name]; - } - static [import_entity73.entityKind] = "Relation"; - referencedTableName; - fieldName; - } - - class Relations2 { - constructor(table, config) { - this.table = table; - this.config = config; - } - static [import_entity73.entityKind] = "Relations"; - } - - class One2 extends Relation2 { - constructor(sourceTable, referencedTable, config, isNullable) { - super(sourceTable, referencedTable, config?.relationName); - this.config = config; - this.isNullable = isNullable; - } - static [import_entity73.entityKind] = "One"; - withFieldName(fieldName) { - const relation = new One2(this.sourceTable, this.referencedTable, this.config, this.isNullable); - relation.fieldName = fieldName; - return relation; - } - } - - class Many2 extends Relation2 { - constructor(sourceTable, referencedTable, config) { - super(sourceTable, referencedTable, config?.relationName); - this.config = config; - } - static [import_entity73.entityKind] = "Many"; - withFieldName(fieldName) { - const relation = new Many2(this.sourceTable, this.referencedTable, this.config); - relation.fieldName = fieldName; - return relation; - } - } - function getOperators2() { - return { - and: import_expressions2.and, - between: import_expressions2.between, - eq: import_expressions2.eq, - exists: import_expressions2.exists, - gt: import_expressions2.gt, - gte: import_expressions2.gte, - ilike: import_expressions2.ilike, - inArray: import_expressions2.inArray, - isNull: import_expressions2.isNull, - isNotNull: import_expressions2.isNotNull, - like: import_expressions2.like, - lt: import_expressions2.lt, - lte: import_expressions2.lte, - ne: import_expressions2.ne, - not: import_expressions2.not, - notBetween: import_expressions2.notBetween, - notExists: import_expressions2.notExists, - notLike: import_expressions2.notLike, - notIlike: import_expressions2.notIlike, - notInArray: import_expressions2.notInArray, - or: import_expressions2.or, - sql: import_sql21.sql - }; - } - function getOrderByOperators2() { - return { - sql: import_sql21.sql, - asc: import_expressions2.asc, - desc: import_expressions2.desc - }; - } - function extractTablesRelationalConfig2(schema, configHelpers) { - if (Object.keys(schema).length === 1 && "default" in schema && !(0, import_entity73.is)(schema["default"], import_table18.Table)) { - schema = schema["default"]; - } - const tableNamesMap = {}; - const relationsBuffer = {}; - const tablesConfig = {}; - for (const [key, value] of Object.entries(schema)) { - if ((0, import_entity73.is)(value, import_table18.Table)) { - const dbName = (0, import_table18.getTableUniqueName)(value); - const bufferedRelations = relationsBuffer[dbName]; - tableNamesMap[dbName] = key; - tablesConfig[key] = { - tsName: key, - dbName: value[import_table18.Table.Symbol.Name], - schema: value[import_table18.Table.Symbol.Schema], - columns: value[import_table18.Table.Symbol.Columns], - relations: bufferedRelations?.relations ?? {}, - primaryKey: bufferedRelations?.primaryKey ?? [] - }; - for (const column of Object.values(value[import_table18.Table.Symbol.Columns])) { - if (column.primary) { - tablesConfig[key].primaryKey.push(column); - } - } - const extraConfig = value[import_table18.Table.Symbol.ExtraConfigBuilder]?.(value[import_table18.Table.Symbol.ExtraConfigColumns]); - if (extraConfig) { - for (const configEntry of Object.values(extraConfig)) { - if ((0, import_entity73.is)(configEntry, import_primary_keys2.PrimaryKeyBuilder)) { - tablesConfig[key].primaryKey.push(...configEntry.columns); +// node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js +var require_bignumber = __commonJS((exports, module) => { + (function(globalObject) { + var BigNumber3, isNumeric3 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil3 = Math.ceil, mathfloor3 = Math.floor, bignumberError3 = "[BigNumber Error] ", tooManyDigits3 = bignumberError3 + "Number primitive has more than 15 significant digits: ", BASE3 = 100000000000000, LOG_BASE3 = 14, MAX_SAFE_INTEGER3 = 9007199254740991, POWS_TEN3 = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000], SQRT_BASE3 = 1e7, MAX3 = 1e9; + function clone4(configObject) { + var div, convertBase, parseNumeric, P = BigNumber4.prototype = { constructor: BigNumber4, toString: null, valueOf: null }, ONE = new BigNumber4(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber4(v, b) { + var alphabet3, c, caseChanged, e2, i, isNum, len, str, x = this; + if (!(x instanceof BigNumber4)) + return new BigNumber4(v, b); + if (b == null) { + if (v && v._isBigNumber === true) { + x.s = v.s; + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); } + return; } - } - } else if ((0, import_entity73.is)(value, Relations2)) { - const dbName = (0, import_table18.getTableUniqueName)(value.table); - const tableName = tableNamesMap[dbName]; - const relations2 = value.config(configHelpers(value.table)); - let primaryKey2; - for (const [relationName, relation] of Object.entries(relations2)) { - if (tableName) { - const tableConfig = tablesConfig[tableName]; - tableConfig.relations[relationName] = relation; - if (primaryKey2) { - tableConfig.primaryKey.push(...primaryKey2); + if ((isNum = typeof v == "number") && v * 0 == 0) { + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + if (v === ~~v) { + for (e2 = 0, i = v;i >= 10; i /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e2; + x.c = [v]; + } + return; } + str = String(v); } else { - if (!(dbName in relationsBuffer)) { - relationsBuffer[dbName] = { - relations: {}, - primaryKey: primaryKey2 - }; - } - relationsBuffer[dbName].relations[relationName] = relation; + if (!isNumeric3.test(str = String(v))) + return parseNumeric(x, str, isNum); + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i; + e2 += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e2 < 0) { + e2 = str.length; } - } - } - } - return { tables: tablesConfig, tableNamesMap }; - } - function relations(table, relations2) { - return new Relations2(table, (helpers) => Object.fromEntries(Object.entries(relations2(helpers)).map(([key, value]) => [ - key, - value.withFieldName(key) - ]))); - } - function createOne2(sourceTable) { - return function one(table, config) { - return new One2(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false); - }; - } - function createMany2(sourceTable) { - return function many(referencedTable, config) { - return new Many2(sourceTable, referencedTable, config); - }; - } - function normalizeRelation2(schema, tableNamesMap, relation) { - if ((0, import_entity73.is)(relation, One2) && relation.config) { - return { - fields: relation.config.fields, - references: relation.config.references - }; - } - const referencedTableTsName = tableNamesMap[(0, import_table18.getTableUniqueName)(relation.referencedTable)]; - if (!referencedTableTsName) { - throw new Error(`Table "${relation.referencedTable[import_table18.Table.Symbol.Name]}" not found in schema`); - } - const referencedTableConfig = schema[referencedTableTsName]; - if (!referencedTableConfig) { - throw new Error(`Table "${referencedTableTsName}" not found in schema`); - } - const sourceTable = relation.sourceTable; - const sourceTableTsName = tableNamesMap[(0, import_table18.getTableUniqueName)(sourceTable)]; - if (!sourceTableTsName) { - throw new Error(`Table "${sourceTable[import_table18.Table.Symbol.Name]}" not found in schema`); - } - const reverseRelations = []; - for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) { - if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { - reverseRelations.push(referencedTableRelation); - } - } - if (reverseRelations.length > 1) { - throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[import_table18.Table.Symbol.Name]}". Please specify relation name`); - } - if (reverseRelations[0] && (0, import_entity73.is)(reverseRelations[0], One2) && reverseRelations[0].config) { - return { - fields: reverseRelations[0].config.references, - references: reverseRelations[0].config.fields - }; - } - throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`); - } - function createTableRelationsHelpers2(sourceTable) { - return { - one: createOne2(sourceTable), - many: createMany2(sourceTable) - }; - } - function mapRelationalRow2(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { - const result = {}; - for (const [ - selectionItemIndex, - selectionItem - ] of buildQueryResultSelection.entries()) { - if (selectionItem.isJson) { - const relation = tableConfig.relations[selectionItem.tsKey]; - const rawSubRows = row[selectionItemIndex]; - const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; - result[selectionItem.tsKey] = (0, import_entity73.is)(relation, One2) ? subRows && mapRelationalRow2(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow2(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue)); - } else { - const value = mapColumnValue(row[selectionItemIndex]); - const field = selectionItem.field; - let decoder; - if ((0, import_entity73.is)(field, import_column9.Column)) { - decoder = field; - } else if ((0, import_entity73.is)(field, import_sql21.SQL)) { - decoder = field.decoder; } else { - decoder = field.sql.decoder; - } - result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value); - } - } - return result; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/functions/aggregate.cjs -var require_aggregate = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var aggregate_exports = {}; - __export2(aggregate_exports, { - avg: () => avg, - avgDistinct: () => avgDistinct, - count: () => count, - countDistinct: () => countDistinct, - max: () => max, - min: () => min, - sum: () => sum, - sumDistinct: () => sumDistinct - }); - module.exports = __toCommonJS2(aggregate_exports); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - function count(expression) { - return import_sql21.sql`count(${expression || import_sql21.sql.raw("*")})`.mapWith(Number); - } - function countDistinct(expression) { - return import_sql21.sql`count(distinct ${expression})`.mapWith(Number); - } - function avg(expression) { - return import_sql21.sql`avg(${expression})`.mapWith(String); - } - function avgDistinct(expression) { - return import_sql21.sql`avg(distinct ${expression})`.mapWith(String); - } - function sum(expression) { - return import_sql21.sql`sum(${expression})`.mapWith(String); - } - function sumDistinct(expression) { - return import_sql21.sql`sum(distinct ${expression})`.mapWith(String); - } - function max(expression) { - return import_sql21.sql`max(${expression})`.mapWith((0, import_entity73.is)(expression, import_column9.Column) ? expression : String); - } - function min(expression) { - return import_sql21.sql`min(${expression})`.mapWith((0, import_entity73.is)(expression, import_column9.Column) ? expression : String); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/functions/vector.cjs -var require_vector2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var vector_exports = {}; - __export2(vector_exports, { - cosineDistance: () => cosineDistance, - hammingDistance: () => hammingDistance, - innerProduct: () => innerProduct, - jaccardDistance: () => jaccardDistance, - l1Distance: () => l1Distance, - l2Distance: () => l2Distance - }); - module.exports = __toCommonJS2(vector_exports); - var import_sql21 = require_sql(); - function toSql(value) { - return JSON.stringify(value); - } - function l2Distance(column, value) { - if (Array.isArray(value)) { - return import_sql21.sql`${column} <-> ${toSql(value)}`; - } - return import_sql21.sql`${column} <-> ${value}`; - } - function l1Distance(column, value) { - if (Array.isArray(value)) { - return import_sql21.sql`${column} <+> ${toSql(value)}`; - } - return import_sql21.sql`${column} <+> ${value}`; - } - function innerProduct(column, value) { - if (Array.isArray(value)) { - return import_sql21.sql`${column} <#> ${toSql(value)}`; - } - return import_sql21.sql`${column} <#> ${value}`; - } - function cosineDistance(column, value) { - if (Array.isArray(value)) { - return import_sql21.sql`${column} <=> ${toSql(value)}`; - } - return import_sql21.sql`${column} <=> ${value}`; - } - function hammingDistance(column, value) { - if (Array.isArray(value)) { - return import_sql21.sql`${column} <~> ${toSql(value)}`; - } - return import_sql21.sql`${column} <~> ${value}`; - } - function jaccardDistance(column, value) { - if (Array.isArray(value)) { - return import_sql21.sql`${column} <%> ${toSql(value)}`; - } - return import_sql21.sql`${column} <%> ${value}`; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/functions/index.cjs -var require_functions = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var functions_exports = {}; - module.exports = __toCommonJS2(functions_exports); - __reExport(functions_exports, require_aggregate(), module.exports); - __reExport(functions_exports, require_vector2(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/index.cjs -var require_sql2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var sql_exports = {}; - module.exports = __toCommonJS2(sql_exports); - __reExport(sql_exports, require_expressions(), module.exports); - __reExport(sql_exports, require_functions(), module.exports); - __reExport(sql_exports, require_sql(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/view-base.cjs -var require_view_base = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var view_base_exports = {}; - __export2(view_base_exports, { - PgViewBase: () => PgViewBase2 - }); - module.exports = __toCommonJS2(view_base_exports); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - - class PgViewBase2 extends import_sql21.View { - static [import_entity73.entityKind] = "PgViewBase"; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/dialect.cjs -var require_dialect = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var dialect_exports = {}; - __export2(dialect_exports, { - PgDialect: () => PgDialect2 - }); - module.exports = __toCommonJS2(dialect_exports); - var import_alias3 = require_alias(); - var import_casing2 = require_casing(); - var import_column9 = require_column(); - var import_entity73 = require_entity(); - var import_errors3 = require_errors3(); - var import_columns3 = require_columns(); - var import_table18 = require_table2(); - var import_relations4 = require_relations(); - var import_sql21 = require_sql2(); - var import_sql22 = require_sql(); - var import_subquery10 = require_subquery(); - var import_table22 = require_table(); - var import_utils33 = require_utils6(); - var import_view_common8 = require_view_common(); - var import_view_base3 = require_view_base(); - - class PgDialect2 { - static [import_entity73.entityKind] = "PgDialect"; - casing; - constructor(config) { - this.casing = new import_casing2.CasingCache(config?.casing); - } - async migrate(migrations, session2, config) { - const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations"; - const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle"; - const migrationTableCreate = import_sql22.sql` - CREATE TABLE IF NOT EXISTS ${import_sql22.sql.identifier(migrationsSchema)}.${import_sql22.sql.identifier(migrationsTable)} ( - id SERIAL PRIMARY KEY, - hash text NOT NULL, - created_at bigint - ) - `; - await session2.execute(import_sql22.sql`CREATE SCHEMA IF NOT EXISTS ${import_sql22.sql.identifier(migrationsSchema)}`); - await session2.execute(migrationTableCreate); - const dbMigrations = await session2.all(import_sql22.sql`select id, hash, created_at from ${import_sql22.sql.identifier(migrationsSchema)}.${import_sql22.sql.identifier(migrationsTable)} order by created_at desc limit 1`); - const lastDbMigration = dbMigrations[0]; - await session2.transaction(async (tx) => { - for await (const migration of migrations) { - if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) { - for (const stmt of migration.sql) { - await tx.execute(import_sql22.sql.raw(stmt)); + intCheck3(b, 2, ALPHABET.length, "Base"); + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber4(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + str = String(v); + if (isNum = typeof v == "number") { + if (v * 0 != 0) + return parseNumeric(x, str, isNum, b); + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber4.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits3 + v); } - await tx.execute(import_sql22.sql`insert into ${import_sql22.sql.identifier(migrationsSchema)}.${import_sql22.sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`); + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; } - } - }); - } - escapeName(name) { - return `"${name}"`; - } - escapeParam(num) { - return `$${num + 1}`; - } - escapeString(str) { - return `'${str.replace(/'/g, "''")}'`; - } - buildWithCTE(queries) { - if (!queries?.length) - return; - const withSqlChunks = [import_sql22.sql`with `]; - for (const [i, w] of queries.entries()) { - withSqlChunks.push(import_sql22.sql`${import_sql22.sql.identifier(w._.alias)} as (${w._.sql})`); - if (i < queries.length - 1) { - withSqlChunks.push(import_sql22.sql`, `); - } - } - withSqlChunks.push(import_sql22.sql` `); - return import_sql22.sql.join(withSqlChunks); - } - buildDeleteQuery({ table, where, returning, withList }) { - const withSql = this.buildWithCTE(withList); - const returningSql = returning ? import_sql22.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined; - const whereSql = where ? import_sql22.sql` where ${where}` : undefined; - return import_sql22.sql`${withSql}delete from ${table}${whereSql}${returningSql}`; - } - buildUpdateSet(table, set) { - const tableColumns = table[import_table22.Table.Symbol.Columns]; - const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined); - const setSize = columnNames.length; - return import_sql22.sql.join(columnNames.flatMap((colName, i) => { - const col = tableColumns[colName]; - const value = set[colName] ?? import_sql22.sql.param(col.onUpdateFn(), col); - const res = import_sql22.sql`${import_sql22.sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { - return [res, import_sql22.sql.raw(", ")]; - } - return [res]; - })); - } - buildUpdateQuery({ table, set, where, returning, withList, from, joins }) { - const withSql = this.buildWithCTE(withList); - const tableName = table[import_table18.PgTable.Symbol.Name]; - const tableSchema = table[import_table18.PgTable.Symbol.Schema]; - const origTableName = table[import_table18.PgTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? undefined : tableName; - const tableSql = import_sql22.sql`${tableSchema ? import_sql22.sql`${import_sql22.sql.identifier(tableSchema)}.` : undefined}${import_sql22.sql.identifier(origTableName)}${alias && import_sql22.sql` ${import_sql22.sql.identifier(alias)}`}`; - const setSql = this.buildUpdateSet(table, set); - const fromSql = from && import_sql22.sql.join([import_sql22.sql.raw(" from "), this.buildFromTable(from)]); - const joinsSql = this.buildJoins(joins); - const returningSql = returning ? import_sql22.sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : undefined; - const whereSql = where ? import_sql22.sql` where ${where}` : undefined; - return import_sql22.sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`; - } - buildSelection(fields, { isSingleTable = false } = {}) { - const columnsLen = fields.length; - const chunks = fields.flatMap(({ field }, i) => { - const chunk = []; - if ((0, import_entity73.is)(field, import_sql22.SQL.Aliased) && field.isSelectionField) { - chunk.push(import_sql22.sql.identifier(field.fieldAlias)); - } else if ((0, import_entity73.is)(field, import_sql22.SQL.Aliased) || (0, import_entity73.is)(field, import_sql22.SQL)) { - const query = (0, import_entity73.is)(field, import_sql22.SQL.Aliased) ? field.sql : field; - if (isSingleTable) { - chunk.push(new import_sql22.SQL(query.queryChunks.map((c) => { - if ((0, import_entity73.is)(c, import_columns3.PgColumn)) { - return import_sql22.sql.identifier(this.casing.getColumnCasing(c)); + alphabet3 = ALPHABET.slice(0, b); + e2 = i = 0; + for (len = str.length;i < len; i++) { + if (alphabet3.indexOf(c = str.charAt(i)) < 0) { + if (c == ".") { + if (i > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e2 = 0; + continue; + } } - return c; - }))); - } else { - chunk.push(query); + return parseNumeric(x, String(v), isNum, b); + } } - if ((0, import_entity73.is)(field, import_sql22.SQL.Aliased)) { - chunk.push(import_sql22.sql` as ${import_sql22.sql.identifier(field.fieldAlias)}`); + isNum = false; + str = convertBase(str, b, 10, x.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i = 0;str.charCodeAt(i) === 48; i++) + ; + for (len = str.length;str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i, ++len)) { + len -= i; + if (isNum && BigNumber4.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER3 || v !== mathfloor3(v))) { + throw Error(tooManyDigits3 + x.s * v); } - } else if ((0, import_entity73.is)(field, import_column9.Column)) { - if (isSingleTable) { - chunk.push(import_sql22.sql.identifier(this.casing.getColumnCasing(field))); + if ((e2 = e2 - i - 1) > MAX_EXP) { + x.c = x.e = null; + } else if (e2 < MIN_EXP) { + x.c = [x.e = 0]; } else { - chunk.push(field); - } - } - if (i < columnsLen - 1) { - chunk.push(import_sql22.sql`, `); - } - return chunk; - }); - return import_sql22.sql.join(chunks); - } - buildJoins(joins) { - if (!joins || joins.length === 0) { - return; - } - const joinsArray = []; - for (const [index2, joinMeta] of joins.entries()) { - if (index2 === 0) { - joinsArray.push(import_sql22.sql` `); - } - const table = joinMeta.table; - const lateralSql = joinMeta.lateral ? import_sql22.sql` lateral` : undefined; - const onSql = joinMeta.on ? import_sql22.sql` on ${joinMeta.on}` : undefined; - if ((0, import_entity73.is)(table, import_table18.PgTable)) { - const tableName = table[import_table18.PgTable.Symbol.Name]; - const tableSchema = table[import_table18.PgTable.Symbol.Schema]; - const origTableName = table[import_table18.PgTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? undefined : joinMeta.alias; - joinsArray.push(import_sql22.sql`${import_sql22.sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? import_sql22.sql`${import_sql22.sql.identifier(tableSchema)}.` : undefined}${import_sql22.sql.identifier(origTableName)}${alias && import_sql22.sql` ${import_sql22.sql.identifier(alias)}`}${onSql}`); - } else if ((0, import_entity73.is)(table, import_sql21.View)) { - const viewName = table[import_view_common8.ViewBaseConfig].name; - const viewSchema = table[import_view_common8.ViewBaseConfig].schema; - const origViewName = table[import_view_common8.ViewBaseConfig].originalName; - const alias = viewName === origViewName ? undefined : joinMeta.alias; - joinsArray.push(import_sql22.sql`${import_sql22.sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? import_sql22.sql`${import_sql22.sql.identifier(viewSchema)}.` : undefined}${import_sql22.sql.identifier(origViewName)}${alias && import_sql22.sql` ${import_sql22.sql.identifier(alias)}`}${onSql}`); - } else { - joinsArray.push(import_sql22.sql`${import_sql22.sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`); - } - if (index2 < joins.length - 1) { - joinsArray.push(import_sql22.sql` `); - } - } - return import_sql22.sql.join(joinsArray); - } - buildFromTable(table) { - if ((0, import_entity73.is)(table, import_table22.Table) && table[import_table22.Table.Symbol.IsAlias]) { - let fullName = import_sql22.sql`${import_sql22.sql.identifier(table[import_table22.Table.Symbol.OriginalName])}`; - if (table[import_table22.Table.Symbol.Schema]) { - fullName = import_sql22.sql`${import_sql22.sql.identifier(table[import_table22.Table.Symbol.Schema])}.${fullName}`; - } - return import_sql22.sql`${fullName} ${import_sql22.sql.identifier(table[import_table22.Table.Symbol.Name])}`; - } - return table; - } - buildSelectQuery({ - withList, - fields, - fieldsFlat, - where, - having, - table, - joins, - orderBy, - groupBy, - limit, - offset, - lockingClause, - distinct, - setOperators - }) { - const fieldsList = fieldsFlat ?? (0, import_utils33.orderSelectedFields)(fields); - for (const f of fieldsList) { - if ((0, import_entity73.is)(f.field, import_column9.Column) && (0, import_table22.getTableName)(f.field.table) !== ((0, import_entity73.is)(table, import_subquery10.Subquery) ? table._.alias : (0, import_entity73.is)(table, import_view_base3.PgViewBase) ? table[import_view_common8.ViewBaseConfig].name : (0, import_entity73.is)(table, import_sql22.SQL) ? undefined : (0, import_table22.getTableName)(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[import_table22.Table.Symbol.IsAlias] ? (0, import_table22.getTableName)(table2) : table2[import_table22.Table.Symbol.BaseName])))(f.field.table)) { - const tableName = (0, import_table22.getTableName)(f.field.table); - throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`); - } - } - const isSingleTable = !joins || joins.length === 0; - const withSql = this.buildWithCTE(withList); - let distinctSql; - if (distinct) { - distinctSql = distinct === true ? import_sql22.sql` distinct` : import_sql22.sql` distinct on (${import_sql22.sql.join(distinct.on, import_sql22.sql`, `)})`; - } - const selection = this.buildSelection(fieldsList, { isSingleTable }); - const tableSql = this.buildFromTable(table); - const joinsSql = this.buildJoins(joins); - const whereSql = where ? import_sql22.sql` where ${where}` : undefined; - const havingSql = having ? import_sql22.sql` having ${having}` : undefined; - let orderBySql; - if (orderBy && orderBy.length > 0) { - orderBySql = import_sql22.sql` order by ${import_sql22.sql.join(orderBy, import_sql22.sql`, `)}`; - } - let groupBySql; - if (groupBy && groupBy.length > 0) { - groupBySql = import_sql22.sql` group by ${import_sql22.sql.join(groupBy, import_sql22.sql`, `)}`; - } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql22.sql` limit ${limit}` : undefined; - const offsetSql = offset ? import_sql22.sql` offset ${offset}` : undefined; - const lockingClauseSql = import_sql22.sql.empty(); - if (lockingClause) { - const clauseSql = import_sql22.sql` for ${import_sql22.sql.raw(lockingClause.strength)}`; - if (lockingClause.config.of) { - clauseSql.append(import_sql22.sql` of ${import_sql22.sql.join(Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], import_sql22.sql`, `)}`); - } - if (lockingClause.config.noWait) { - clauseSql.append(import_sql22.sql` nowait`); - } else if (lockingClause.config.skipLocked) { - clauseSql.append(import_sql22.sql` skip locked`); - } - lockingClauseSql.append(clauseSql); - } - const finalQuery = import_sql22.sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`; - if (setOperators.length > 0) { - return this.buildSetOperations(finalQuery, setOperators); - } - return finalQuery; - } - buildSetOperations(leftSelect, setOperators) { - const [setOperator, ...rest] = setOperators; - if (!setOperator) { - throw new Error("Cannot pass undefined values to any set operator"); - } - if (rest.length === 0) { - return this.buildSetOperationQuery({ leftSelect, setOperator }); - } - return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest); - } - buildSetOperationQuery({ - leftSelect, - setOperator: { type, isAll, rightSelect, limit, orderBy, offset } - }) { - const leftChunk = import_sql22.sql`(${leftSelect.getSQL()}) `; - const rightChunk = import_sql22.sql`(${rightSelect.getSQL()})`; - let orderBySql; - if (orderBy && orderBy.length > 0) { - const orderByValues = []; - for (const singleOrderBy of orderBy) { - if ((0, import_entity73.is)(singleOrderBy, import_columns3.PgColumn)) { - orderByValues.push(import_sql22.sql.identifier(singleOrderBy.name)); - } else if ((0, import_entity73.is)(singleOrderBy, import_sql22.SQL)) { - for (let i = 0;i < singleOrderBy.queryChunks.length; i++) { - const chunk = singleOrderBy.queryChunks[i]; - if ((0, import_entity73.is)(chunk, import_columns3.PgColumn)) { - singleOrderBy.queryChunks[i] = import_sql22.sql.identifier(chunk.name); + x.e = e2; + x.c = []; + i = (e2 + 1) % LOG_BASE3; + if (e2 < 0) + i += LOG_BASE3; + if (i < len) { + if (i) + x.c.push(+str.slice(0, i)); + for (len -= LOG_BASE3;i < len; ) { + x.c.push(+str.slice(i, i += LOG_BASE3)); } + i = LOG_BASE3 - (str = str.slice(i)).length; + } else { + i -= len; } - orderByValues.push(import_sql22.sql`${singleOrderBy}`); - } else { - orderByValues.push(import_sql22.sql`${singleOrderBy}`); + for (;i--; str += "0") + ; + x.c.push(+str); } - } - orderBySql = import_sql22.sql` order by ${import_sql22.sql.join(orderByValues, import_sql22.sql`, `)} `; - } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? import_sql22.sql` limit ${limit}` : undefined; - const operatorChunk = import_sql22.sql.raw(`${type} ${isAll ? "all " : ""}`); - const offsetSql = offset ? import_sql22.sql` offset ${offset}` : undefined; - return import_sql22.sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; - } - buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) { - const valuesSqlList = []; - const columns = table[import_table22.Table.Symbol.Columns]; - const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert()); - const insertOrder = colEntries.map(([, column]) => import_sql22.sql.identifier(this.casing.getColumnCasing(column))); - if (select) { - const select2 = valuesOrSelect; - if ((0, import_entity73.is)(select2, import_sql22.SQL)) { - valuesSqlList.push(select2); } else { - valuesSqlList.push(select2.getSQL()); + x.c = [x.e = 0]; } - } else { - const values = valuesOrSelect; - valuesSqlList.push(import_sql22.sql.raw("values ")); - for (const [valueIndex, value] of values.entries()) { - const valueList = []; - for (const [fieldName, col] of colEntries) { - const colValue = value[fieldName]; - if (colValue === undefined || (0, import_entity73.is)(colValue, import_sql22.Param) && colValue.value === undefined) { - if (col.defaultFn !== undefined) { - const defaultFnResult = col.defaultFn(); - const defaultValue = (0, import_entity73.is)(defaultFnResult, import_sql22.SQL) ? defaultFnResult : import_sql22.sql.param(defaultFnResult, col); - valueList.push(defaultValue); - } else if (!col.default && col.onUpdateFn !== undefined) { - const onUpdateFnResult = col.onUpdateFn(); - const newValue = (0, import_entity73.is)(onUpdateFnResult, import_sql22.SQL) ? onUpdateFnResult : import_sql22.sql.param(onUpdateFnResult, col); - valueList.push(newValue); + } + BigNumber4.clone = clone4; + BigNumber4.ROUND_UP = 0; + BigNumber4.ROUND_DOWN = 1; + BigNumber4.ROUND_CEIL = 2; + BigNumber4.ROUND_FLOOR = 3; + BigNumber4.ROUND_HALF_UP = 4; + BigNumber4.ROUND_HALF_DOWN = 5; + BigNumber4.ROUND_HALF_EVEN = 6; + BigNumber4.ROUND_HALF_CEIL = 7; + BigNumber4.ROUND_HALF_FLOOR = 8; + BigNumber4.EUCLID = 9; + BigNumber4.config = BigNumber4.set = function(obj) { + var p, v; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) { + v = obj[p]; + intCheck3(v, 0, MAX3, p); + DECIMAL_PLACES = v; + } + if (obj.hasOwnProperty(p = "ROUNDING_MODE")) { + v = obj[p]; + intCheck3(v, 0, 8, p); + ROUNDING_MODE = v; + } + if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) { + v = obj[p]; + if (v && v.pop) { + intCheck3(v[0], -MAX3, 0, p); + intCheck3(v[1], 0, MAX3, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; } else { - valueList.push(import_sql22.sql`default`); + intCheck3(v, -MAX3, MAX3, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); } - } else { - valueList.push(colValue); } - } - valuesSqlList.push(valueList); - if (valueIndex < values.length - 1) { - valuesSqlList.push(import_sql22.sql`, `); - } - } - } - const withSql = this.buildWithCTE(withList); - const valuesSql = import_sql22.sql.join(valuesSqlList); - const returningSql = returning ? import_sql22.sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined; - const onConflictSql = onConflict ? import_sql22.sql` on conflict ${onConflict}` : undefined; - const overridingSql = overridingSystemValue_ === true ? import_sql22.sql`overriding system value ` : undefined; - return import_sql22.sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`; - } - buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) { - const concurrentlySql = concurrently ? import_sql22.sql` concurrently` : undefined; - const withNoDataSql = withNoData ? import_sql22.sql` with no data` : undefined; - return import_sql22.sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`; - } - prepareTyping(encoder) { - if ((0, import_entity73.is)(encoder, import_columns3.PgJsonb) || (0, import_entity73.is)(encoder, import_columns3.PgJson)) { - return "json"; - } else if ((0, import_entity73.is)(encoder, import_columns3.PgNumeric)) { - return "decimal"; - } else if ((0, import_entity73.is)(encoder, import_columns3.PgTime)) { - return "time"; - } else if ((0, import_entity73.is)(encoder, import_columns3.PgTimestamp) || (0, import_entity73.is)(encoder, import_columns3.PgTimestampString)) { - return "timestamp"; - } else if ((0, import_entity73.is)(encoder, import_columns3.PgDate) || (0, import_entity73.is)(encoder, import_columns3.PgDateString)) { - return "date"; - } else if ((0, import_entity73.is)(encoder, import_columns3.PgUUID)) { - return "uuid"; - } else { - return "none"; - } - } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ - casing: this.casing, - escapeName: this.escapeName, - escapeParam: this.escapeParam, - escapeString: this.escapeString, - prepareTyping: this.prepareTyping, - invokeSource - }); - } - buildRelationalQueryWithoutPK({ - fullSchema, - schema, - tableNamesMap, - table, - tableConfig, - queryConfig: config, - tableAlias, - nestedQueryRelation, - joinOn - }) { - let selection = []; - let limit, offset, orderBy = [], where; - const joins = []; - if (config === true) { - const selectionEntries = Object.entries(tableConfig.columns); - selection = selectionEntries.map(([key, value]) => ({ - dbKey: value.name, - tsKey: key, - field: (0, import_alias3.aliasedTableColumn)(value, tableAlias), - relationTableTsKey: undefined, - isJson: false, - selection: [] - })); - } else { - const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, (0, import_alias3.aliasedTableColumn)(value, tableAlias)])); - if (config.where) { - const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, (0, import_relations4.getOperators)()) : config.where; - where = whereSql && (0, import_alias3.mapColumnsInSQLToAlias)(whereSql, tableAlias); - } - const fieldsSelection = []; - let selectedColumns = []; - if (config.columns) { - let isIncludeMode = false; - for (const [field, value] of Object.entries(config.columns)) { - if (value === undefined) { - continue; + if (obj.hasOwnProperty(p = "RANGE")) { + v = obj[p]; + if (v && v.pop) { + intCheck3(v[0], -MAX3, -1, p); + intCheck3(v[1], 1, MAX3, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck3(v, -MAX3, MAX3, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error(bignumberError3 + p + " cannot be zero: " + v); + } + } } - if (field in tableConfig.columns) { - if (!isIncludeMode && value === true) { - isIncludeMode = true; + if (obj.hasOwnProperty(p = "CRYPTO")) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error(bignumberError3 + "crypto unavailable"); + } + } else { + CRYPTO = v; + } + } else { + throw Error(bignumberError3 + p + " not true or false: " + v); } - selectedColumns.push(field); } - } - if (selectedColumns.length > 0) { - selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); - } - } else { - selectedColumns = Object.keys(tableConfig.columns); - } - for (const field of selectedColumns) { - const column = tableConfig.columns[field]; - fieldsSelection.push({ tsKey: field, value: column }); - } - let selectedRelations = []; - if (config.with) { - selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); - } - let extras; - if (config.extras) { - extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql: import_sql22.sql }) : config.extras; - for (const [tsKey, value] of Object.entries(extras)) { - fieldsSelection.push({ - tsKey, - value: (0, import_alias3.mapColumnsInAliasedSQLToAlias)(value, tableAlias) - }); - } - } - for (const { tsKey, value } of fieldsSelection) { - selection.push({ - dbKey: (0, import_entity73.is)(value, import_sql22.SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, - tsKey, - field: (0, import_entity73.is)(value, import_column9.Column) ? (0, import_alias3.aliasedTableColumn)(value, tableAlias) : value, - relationTableTsKey: undefined, - isJson: false, - selection: [] - }); - } - let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, (0, import_relations4.getOrderByOperators)()) : config.orderBy ?? []; - if (!Array.isArray(orderByOrig)) { - orderByOrig = [orderByOrig]; - } - orderBy = orderByOrig.map((orderByValue) => { - if ((0, import_entity73.is)(orderByValue, import_column9.Column)) { - return (0, import_alias3.aliasedTableColumn)(orderByValue, tableAlias); - } - return (0, import_alias3.mapColumnsInSQLToAlias)(orderByValue, tableAlias); - }); - limit = config.limit; - offset = config.offset; - for (const { - tsKey: selectedRelationTsKey, - queryConfig: selectedRelationConfigValue, - relation - } of selectedRelations) { - const normalizedRelation = (0, import_relations4.normalizeRelation)(schema, tableNamesMap, relation); - const relationTableName = (0, import_table22.getTableUniqueName)(relation.referencedTable); - const relationTableTsName = tableNamesMap[relationTableName]; - const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - const joinOn2 = (0, import_sql21.and)(...normalizedRelation.fields.map((field2, i) => (0, import_sql21.eq)((0, import_alias3.aliasedTableColumn)(normalizedRelation.references[i], relationTableAlias), (0, import_alias3.aliasedTableColumn)(field2, tableAlias)))); - const builtRelation = this.buildRelationalQueryWithoutPK({ - fullSchema, - schema, - tableNamesMap, - table: fullSchema[relationTableTsName], - tableConfig: schema[relationTableTsName], - queryConfig: (0, import_entity73.is)(relation, import_relations4.One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, - tableAlias: relationTableAlias, - joinOn: joinOn2, - nestedQueryRelation: relation - }); - const field = import_sql22.sql`${import_sql22.sql.identifier(relationTableAlias)}.${import_sql22.sql.identifier("data")}`.as(selectedRelationTsKey); - joins.push({ - on: import_sql22.sql`true`, - table: new import_subquery10.Subquery(builtRelation.sql, {}, relationTableAlias), - alias: relationTableAlias, - joinType: "left", - lateral: true - }); - selection.push({ - dbKey: selectedRelationTsKey, - tsKey: selectedRelationTsKey, - field, - relationTableTsKey: relationTableTsName, - isJson: true, - selection: builtRelation.selection - }); - } - } - if (selection.length === 0) { - throw new import_errors3.DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` }); - } - let result; - where = (0, import_sql21.and)(joinOn, where); - if (nestedQueryRelation) { - let field = import_sql22.sql`json_build_array(${import_sql22.sql.join(selection.map(({ field: field2, tsKey, isJson }) => isJson ? import_sql22.sql`${import_sql22.sql.identifier(`${tableAlias}_${tsKey}`)}.${import_sql22.sql.identifier("data")}` : (0, import_entity73.is)(field2, import_sql22.SQL.Aliased) ? field2.sql : field2), import_sql22.sql`, `)})`; - if ((0, import_entity73.is)(nestedQueryRelation, import_relations4.Many)) { - field = import_sql22.sql`coalesce(json_agg(${field}${orderBy.length > 0 ? import_sql22.sql` order by ${import_sql22.sql.join(orderBy, import_sql22.sql`, `)}` : undefined}), '[]'::json)`; - } - const nestedSelection = [{ - dbKey: "data", - tsKey: "data", - field: field.as("data"), - isJson: true, - relationTableTsKey: tableConfig.tsName, - selection - }]; - const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0; - if (needsSubquery) { - result = this.buildSelectQuery({ - table: (0, import_alias3.aliasedTable)(table, tableAlias), - fields: {}, - fieldsFlat: [{ - path: [], - field: import_sql22.sql.raw("*") - }], - where, - limit, - offset, - orderBy, - setOperators: [] - }); - where = undefined; - limit = undefined; - offset = undefined; - orderBy = []; - } else { - result = (0, import_alias3.aliasedTable)(table, tableAlias); - } - result = this.buildSelectQuery({ - table: (0, import_entity73.is)(result, import_table18.PgTable) ? result : new import_subquery10.Subquery(result, {}, tableAlias), - fields: {}, - fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ - path: [], - field: (0, import_entity73.is)(field2, import_column9.Column) ? (0, import_alias3.aliasedTableColumn)(field2, tableAlias) : field2 - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } else { - result = this.buildSelectQuery({ - table: (0, import_alias3.aliasedTable)(table, tableAlias), - fields: {}, - fieldsFlat: selection.map(({ field }) => ({ - path: [], - field: (0, import_entity73.is)(field, import_column9.Column) ? (0, import_alias3.aliasedTableColumn)(field, tableAlias) : field - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } - return { - tableTsKey: tableConfig.tsName, - sql: result, - selection - }; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/query-builders/query-builder.cjs -var require_query_builder = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var query_builder_exports = {}; - __export2(query_builder_exports, { - TypedQueryBuilder: () => TypedQueryBuilder2 - }); - module.exports = __toCommonJS2(query_builder_exports); - var import_entity73 = require_entity(); - - class TypedQueryBuilder2 { - static [import_entity73.entityKind] = "TypedQueryBuilder"; - getSelectedFields() { - return this._.selectedFields; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/select.cjs -var require_select2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except22, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except22) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var select_exports = {}; - __export2(select_exports, { - PgSelectBase: () => PgSelectBase2, - PgSelectBuilder: () => PgSelectBuilder2, - PgSelectQueryBuilderBase: () => PgSelectQueryBuilderBase2, - except: () => except2, - exceptAll: () => exceptAll2, - intersect: () => intersect2, - intersectAll: () => intersectAll2, - union: () => union2, - unionAll: () => unionAll2 - }); - module.exports = __toCommonJS2(select_exports); - var import_entity73 = require_entity(); - var import_view_base3 = require_view_base(); - var import_query_builder3 = require_query_builder(); - var import_query_promise8 = require_query_promise(); - var import_selection_proxy7 = require_selection_proxy(); - var import_sql21 = require_sql(); - var import_subquery10 = require_subquery(); - var import_table18 = require_table(); - var import_tracing9 = require_tracing(); - var import_utils33 = require_utils6(); - var import_utils210 = require_utils6(); - var import_view_common8 = require_view_common(); - var import_utils34 = require_utils8(); - - class PgSelectBuilder2 { - static [import_entity73.entityKind] = "PgSelectBuilder"; - fields; - session; - dialect; - withList = []; - distinct; - constructor(config) { - this.fields = config.fields; - this.session = config.session; - this.dialect = config.dialect; - if (config.withList) { - this.withList = config.withList; - } - this.distinct = config.distinct; - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - from(source) { - const isPartialSelect = !!this.fields; - const src = source; - let fields; - if (this.fields) { - fields = this.fields; - } else if ((0, import_entity73.is)(src, import_subquery10.Subquery)) { - fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [key, src[key]])); - } else if ((0, import_entity73.is)(src, import_view_base3.PgViewBase)) { - fields = src[import_view_common8.ViewBaseConfig].selectedFields; - } else if ((0, import_entity73.is)(src, import_sql21.SQL)) { - fields = {}; - } else { - fields = (0, import_utils33.getTableColumns)(src); - } - return new PgSelectBase2({ - table: src, - fields, - isPartialSelect, - session: this.session, - dialect: this.dialect, - withList: this.withList, - distinct: this.distinct - }).setToken(this.authToken); - } - } - - class PgSelectQueryBuilderBase2 extends import_query_builder3.TypedQueryBuilder { - static [import_entity73.entityKind] = "PgSelectQueryBuilder"; - _; - config; - joinsNotNullableMap; - tableName; - isPartialSelect; - session; - dialect; - cacheConfig = undefined; - usedTables = /* @__PURE__ */ new Set; - constructor({ table, fields, isPartialSelect, session: session2, dialect, withList, distinct }) { - super(); - this.config = { - withList, - table, - fields: { ...fields }, - distinct, - setOperators: [] - }; - this.isPartialSelect = isPartialSelect; - this.session = session2; - this.dialect = dialect; - this._ = { - selectedFields: fields, - config: this.config - }; - this.tableName = (0, import_utils33.getTableLikeName)(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; - for (const item of (0, import_utils34.extractUsedTable)(table)) - this.usedTables.add(item); - } - getUsedTables() { - return [...this.usedTables]; - } - createJoin(joinType, lateral) { - return (table, on) => { - const baseTableName = this.tableName; - const tableName = (0, import_utils33.getTableLikeName)(table); - for (const item of (0, import_utils34.extractUsedTable)(table)) - this.usedTables.add(item); - if (typeof tableName === "string" && this.config.joins?.some((join2) => join2.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (!this.isPartialSelect) { - if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { - this.config.fields = { - [baseTableName]: this.config.fields - }; - } - if (typeof tableName === "string" && !(0, import_entity73.is)(table, import_sql21.SQL)) { - const selection = (0, import_entity73.is)(table, import_subquery10.Subquery) ? table._.selectedFields : (0, import_entity73.is)(table, import_sql21.View) ? table[import_view_common8.ViewBaseConfig].selectedFields : table[import_table18.Table.Symbol.Columns]; - this.config.fields[tableName] = selection; - } - } - if (typeof on === "function") { - on = on(new Proxy(this.config.fields, new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); - } - if (!this.config.joins) { - this.config.joins = []; - } - this.config.joins.push({ on, table, joinType, alias: tableName, lateral }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; + if (obj.hasOwnProperty(p = "MODULO_MODE")) { + v = obj[p]; + intCheck3(v, 0, 9, p); + MODULO_MODE = v; } - case "right": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = true; - break; + if (obj.hasOwnProperty(p = "POW_PRECISION")) { + v = obj[p]; + intCheck3(v, 0, MAX3, p); + POW_PRECISION = v; } - case "cross": - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; + if (obj.hasOwnProperty(p = "FORMAT")) { + v = obj[p]; + if (typeof v == "object") + FORMAT = v; + else + throw Error(bignumberError3 + p + " not an object: " + v); } - case "full": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = false; - break; + if (obj.hasOwnProperty(p = "ALPHABET")) { + v = obj[p]; + if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; + ALPHABET = v; + } else { + throw Error(bignumberError3 + p + " invalid: " + v); + } } + } else { + throw Error(bignumberError3 + "Object expected: " + obj); } } - return this; + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; }; - } - leftJoin = this.createJoin("left", false); - leftJoinLateral = this.createJoin("left", true); - rightJoin = this.createJoin("right", false); - innerJoin = this.createJoin("inner", false); - innerJoinLateral = this.createJoin("inner", true); - fullJoin = this.createJoin("full", false); - crossJoin = this.createJoin("cross", false); - crossJoinLateral = this.createJoin("cross", true); - createSetOperator(type, isAll) { - return (rightSelection) => { - const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators2()) : rightSelection; - if (!(0, import_utils33.haveSameKeys)(this.getSelectedFields(), rightSelect.getSelectedFields())) { - throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order"); - } - this.config.setOperators.push({ type, isAll, rightSelect }); - return this; + BigNumber4.isBigNumber = function(v) { + if (!v || v._isBigNumber !== true) + return false; + if (!BigNumber4.DEBUG) + return true; + var i, n, c = v.c, e2 = v.e, s = v.s; + out: + if ({}.toString.call(c) == "[object Array]") { + if ((s === 1 || s === -1) && e2 >= -MAX3 && e2 <= MAX3 && e2 === mathfloor3(e2)) { + if (c[0] === 0) { + if (e2 === 0 && c.length === 1) + return true; + break out; + } + i = (e2 + 1) % LOG_BASE3; + if (i < 1) + i += LOG_BASE3; + if (String(c[0]).length == i) { + for (i = 0;i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE3 || n !== mathfloor3(n)) + break out; + } + if (n !== 0) + return true; + } + } + } else if (c === null && e2 === null && (s === null || s === 1 || s === -1)) { + return true; + } + throw Error(bignumberError3 + "Invalid BigNumber: " + v); }; - } - union = this.createSetOperator("union", false); - unionAll = this.createSetOperator("union", true); - intersect = this.createSetOperator("intersect", false); - intersectAll = this.createSetOperator("intersect", true); - except = this.createSetOperator("except", false); - exceptAll = this.createSetOperator("except", true); - addSetOperators(setOperators) { - this.config.setOperators.push(...setOperators); - return this; - } - where(where) { - if (typeof where === "function") { - where = where(new Proxy(this.config.fields, new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); - } - this.config.where = where; - return this; - } - having(having) { - if (typeof having === "function") { - having = having(new Proxy(this.config.fields, new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); - } - this.config.having = having; - return this; - } - groupBy(...columns) { - if (typeof columns[0] === "function") { - const groupBy = columns[0](new Proxy(this.config.fields, new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }))); - this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; - } else { - this.config.groupBy = columns; - } - return this; - } - orderBy(...columns) { - if (typeof columns[0] === "function") { - const orderBy = columns[0](new Proxy(this.config.fields, new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }))); - const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } else { - const orderByArray = columns; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } - return this; - } - limit(limit) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).limit = limit; - } else { - this.config.limit = limit; - } - return this; - } - offset(offset) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).offset = offset; - } else { - this.config.offset = offset; - } - return this; - } - for(strength, config = {}) { - this.config.lockingClause = { strength, config }; - return this; - } - getSQL() { - return this.dialect.buildSelectQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - as(alias) { - const usedTables = []; - usedTables.push(...(0, import_utils34.extractUsedTable)(this.config.table)); - if (this.config.joins) { - for (const it of this.config.joins) - usedTables.push(...(0, import_utils34.extractUsedTable)(it.table)); - } - return new Proxy(new import_subquery10.Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new import_selection_proxy7.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); - } - getSelectedFields() { - return new Proxy(this.config.fields, new import_selection_proxy7.SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); - } - $dynamic() { - return this; - } - $withCache(config) { - this.cacheConfig = config === undefined ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config }; - return this; - } - } - - class PgSelectBase2 extends PgSelectQueryBuilderBase2 { - static [import_entity73.entityKind] = "PgSelect"; - _prepare(name) { - const { session: session2, config, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this; - if (!session2) { - throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); - } - const { fields } = config; - return import_tracing9.tracer.startActiveSpan("drizzle.prepareQuery", () => { - const fieldsList = (0, import_utils210.orderSelectedFields)(fields); - const query = session2.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, undefined, { - type: "select", - tables: [...usedTables] - }, cacheConfig); - query.joinsNotNullableMap = joinsNotNullableMap; - return query.setToken(authToken); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return import_tracing9.tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - } - (0, import_utils33.applyMixins)(PgSelectBase2, [import_query_promise8.QueryPromise]); - function createSetOperator2(type, isAll) { - return (leftSelect, rightSelect, ...restSelects) => { - const setOperators = [rightSelect, ...restSelects].map((select) => ({ - type, - isAll, - rightSelect: select - })); - for (const setOperator of setOperators) { - if (!(0, import_utils33.haveSameKeys)(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { - throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order"); - } - } - return leftSelect.addSetOperators(setOperators); - }; - } - var getPgSetOperators2 = () => ({ - union: union2, - unionAll: unionAll2, - intersect: intersect2, - intersectAll: intersectAll2, - except: except2, - exceptAll: exceptAll2 - }); - var union2 = createSetOperator2("union", false); - var unionAll2 = createSetOperator2("union", true); - var intersect2 = createSetOperator2("intersect", false); - var intersectAll2 = createSetOperator2("intersect", true); - var except2 = createSetOperator2("except", false); - var exceptAll2 = createSetOperator2("except", true); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/query-builder.cjs -var require_query_builder2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var query_builder_exports = {}; - __export2(query_builder_exports, { - QueryBuilder: () => QueryBuilder2 - }); - module.exports = __toCommonJS2(query_builder_exports); - var import_entity73 = require_entity(); - var import_dialect3 = require_dialect(); - var import_selection_proxy7 = require_selection_proxy(); - var import_subquery10 = require_subquery(); - var import_select2 = require_select2(); - - class QueryBuilder2 { - static [import_entity73.entityKind] = "PgQueryBuilder"; - dialect; - dialectConfig; - constructor(dialect) { - this.dialect = (0, import_entity73.is)(dialect, import_dialect3.PgDialect) ? dialect : undefined; - this.dialectConfig = (0, import_entity73.is)(dialect, import_dialect3.PgDialect) ? undefined : dialect; - } - $with = (alias, selection) => { - const queryBuilder = this; - const as = (qb) => { - if (typeof qb === "function") { - qb = qb(queryBuilder); - } - return new Proxy(new import_subquery10.WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new import_selection_proxy7.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); + BigNumber4.maximum = BigNumber4.max = function() { + return maxOrMin(arguments, -1); }; - return { as }; - }; - with(...queries) { - const self2 = this; - function select(fields) { - return new import_select2.PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: self2.getDialect(), - withList: queries - }); - } - function selectDistinct(fields) { - return new import_select2.PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: self2.getDialect(), - distinct: true - }); - } - function selectDistinctOn(on, fields) { - return new import_select2.PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: self2.getDialect(), - distinct: { on } - }); - } - return { select, selectDistinct, selectDistinctOn }; - } - select(fields) { - return new import_select2.PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: this.getDialect() - }); - } - selectDistinct(fields) { - return new import_select2.PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: this.getDialect(), - distinct: true - }); - } - selectDistinctOn(on, fields) { - return new import_select2.PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: this.getDialect(), - distinct: { on } - }); - } - getDialect() { - if (!this.dialect) { - this.dialect = new import_dialect3.PgDialect(this.dialectConfig); - } - return this.dialect; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/view.cjs -var require_view2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var view_exports = {}; - __export2(view_exports, { - DefaultViewBuilderCore: () => DefaultViewBuilderCore, - ManualMaterializedViewBuilder: () => ManualMaterializedViewBuilder, - ManualViewBuilder: () => ManualViewBuilder, - MaterializedViewBuilder: () => MaterializedViewBuilder, - MaterializedViewBuilderCore: () => MaterializedViewBuilderCore, - PgMaterializedView: () => PgMaterializedView, - PgMaterializedViewConfig: () => PgMaterializedViewConfig, - PgView: () => PgView, - ViewBuilder: () => ViewBuilder, - isPgMaterializedView: () => isPgMaterializedView, - isPgView: () => isPgView, - pgMaterializedView: () => pgMaterializedView, - pgMaterializedViewWithSchema: () => pgMaterializedViewWithSchema, - pgView: () => pgView, - pgViewWithSchema: () => pgViewWithSchema - }); - module.exports = __toCommonJS2(view_exports); - var import_entity73 = require_entity(); - var import_selection_proxy7 = require_selection_proxy(); - var import_utils33 = require_utils6(); - var import_query_builder3 = require_query_builder2(); - var import_table18 = require_table2(); - var import_view_base3 = require_view_base(); - var import_view_common8 = require_view_common2(); - - class DefaultViewBuilderCore { - constructor(name, schema) { - this.name = name; - this.schema = schema; - } - static [import_entity73.entityKind] = "PgDefaultViewBuilderCore"; - config = {}; - with(config) { - this.config.with = config; - return this; - } - } - - class ViewBuilder extends DefaultViewBuilderCore { - static [import_entity73.entityKind] = "PgViewBuilder"; - as(qb) { - if (typeof qb === "function") { - qb = qb(new import_query_builder3.QueryBuilder); - } - const selectionProxy = new import_selection_proxy7.SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }); - const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy); - return new Proxy(new PgView({ - pgConfig: this.config, - config: { - name: this.name, - schema: this.schema, - selectedFields: aliasedSelection, - query: qb.getSQL().inlineParams() - } - }), selectionProxy); - } - } - - class ManualViewBuilder extends DefaultViewBuilderCore { - static [import_entity73.entityKind] = "PgManualViewBuilder"; - columns; - constructor(name, columns, schema) { - super(name, schema); - this.columns = (0, import_utils33.getTableColumns)((0, import_table18.pgTable)(name, columns)); - } - existing() { - return new Proxy(new PgView({ - pgConfig: undefined, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: undefined - } - }), new import_selection_proxy7.SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - })); - } - as(query) { - return new Proxy(new PgView({ - pgConfig: this.config, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: query.inlineParams() - } - }), new import_selection_proxy7.SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - })); - } - } - - class MaterializedViewBuilderCore { - constructor(name, schema) { - this.name = name; - this.schema = schema; - } - static [import_entity73.entityKind] = "PgMaterializedViewBuilderCore"; - config = {}; - using(using) { - this.config.using = using; - return this; - } - with(config) { - this.config.with = config; - return this; - } - tablespace(tablespace) { - this.config.tablespace = tablespace; - return this; - } - withNoData() { - this.config.withNoData = true; - return this; - } - } - - class MaterializedViewBuilder extends MaterializedViewBuilderCore { - static [import_entity73.entityKind] = "PgMaterializedViewBuilder"; - as(qb) { - if (typeof qb === "function") { - qb = qb(new import_query_builder3.QueryBuilder); - } - const selectionProxy = new import_selection_proxy7.SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - }); - const aliasedSelection = new Proxy(qb.getSelectedFields(), selectionProxy); - return new Proxy(new PgMaterializedView({ - pgConfig: { - with: this.config.with, - using: this.config.using, - tablespace: this.config.tablespace, - withNoData: this.config.withNoData - }, - config: { - name: this.name, - schema: this.schema, - selectedFields: aliasedSelection, - query: qb.getSQL().inlineParams() - } - }), selectionProxy); - } - } - - class ManualMaterializedViewBuilder extends MaterializedViewBuilderCore { - static [import_entity73.entityKind] = "PgManualMaterializedViewBuilder"; - columns; - constructor(name, columns, schema) { - super(name, schema); - this.columns = (0, import_utils33.getTableColumns)((0, import_table18.pgTable)(name, columns)); - } - existing() { - return new Proxy(new PgMaterializedView({ - pgConfig: { - tablespace: this.config.tablespace, - using: this.config.using, - with: this.config.with, - withNoData: this.config.withNoData - }, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: undefined - } - }), new import_selection_proxy7.SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - })); - } - as(query) { - return new Proxy(new PgMaterializedView({ - pgConfig: { - tablespace: this.config.tablespace, - using: this.config.using, - with: this.config.with, - withNoData: this.config.withNoData - }, - config: { - name: this.name, - schema: this.schema, - selectedFields: this.columns, - query: query.inlineParams() - } - }), new import_selection_proxy7.SelectionProxyHandler({ - alias: this.name, - sqlBehavior: "error", - sqlAliasedBehavior: "alias", - replaceOriginalName: true - })); - } - } - - class PgView extends import_view_base3.PgViewBase { - static [import_entity73.entityKind] = "PgView"; - [import_view_common8.PgViewConfig]; - constructor({ pgConfig, config }) { - super(config); - if (pgConfig) { - this[import_view_common8.PgViewConfig] = { - with: pgConfig.with - }; - } - } - } - var PgMaterializedViewConfig = Symbol.for("drizzle:PgMaterializedViewConfig"); - - class PgMaterializedView extends import_view_base3.PgViewBase { - static [import_entity73.entityKind] = "PgMaterializedView"; - [PgMaterializedViewConfig]; - constructor({ pgConfig, config }) { - super(config); - this[PgMaterializedViewConfig] = { - with: pgConfig?.with, - using: pgConfig?.using, - tablespace: pgConfig?.tablespace, - withNoData: pgConfig?.withNoData + BigNumber4.minimum = BigNumber4.min = function() { + return maxOrMin(arguments, 1); }; - } - } - function pgViewWithSchema(name, selection, schema) { - if (selection) { - return new ManualViewBuilder(name, selection, schema); - } - return new ViewBuilder(name, schema); - } - function pgMaterializedViewWithSchema(name, selection, schema) { - if (selection) { - return new ManualMaterializedViewBuilder(name, selection, schema); - } - return new MaterializedViewBuilder(name, schema); - } - function pgView(name, columns) { - return pgViewWithSchema(name, columns, undefined); - } - function pgMaterializedView(name, columns) { - return pgMaterializedViewWithSchema(name, columns, undefined); - } - function isPgView(obj) { - return (0, import_entity73.is)(obj, PgView); - } - function isPgMaterializedView(obj) { - return (0, import_entity73.is)(obj, PgMaterializedView); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/utils.cjs -var require_utils8 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var utils_exports = {}; - __export2(utils_exports, { - extractUsedTable: () => extractUsedTable2, - getMaterializedViewConfig: () => getMaterializedViewConfig, - getTableConfig: () => getTableConfig, - getViewConfig: () => getViewConfig - }); - module.exports = __toCommonJS2(utils_exports); - var import_entity73 = require_entity(); - var import_table18 = require_table2(); - var import_sql21 = require_sql(); - var import_subquery10 = require_subquery(); - var import_table22 = require_table(); - var import_view_common8 = require_view_common(); - var import_checks = require_checks(); - var import_foreign_keys2 = require_foreign_keys(); - var import_indexes = require_indexes(); - var import_policies = require_policies(); - var import_primary_keys2 = require_primary_keys(); - var import_unique_constraint2 = require_unique_constraint(); - var import_view_common22 = require_view_common2(); - var import_view = require_view2(); - function getTableConfig(table) { - const columns = Object.values(table[import_table22.Table.Symbol.Columns]); - const indexes = []; - const checks = []; - const primaryKeys = []; - const foreignKeys = Object.values(table[import_table18.PgTable.Symbol.InlineForeignKeys]); - const uniqueConstraints = []; - const name = table[import_table22.Table.Symbol.Name]; - const schema = table[import_table22.Table.Symbol.Schema]; - const policies = []; - const enableRLS = table[import_table18.PgTable.Symbol.EnableRLS]; - const extraConfigBuilder = table[import_table18.PgTable.Symbol.ExtraConfigBuilder]; - if (extraConfigBuilder !== undefined) { - const extraConfig = extraConfigBuilder(table[import_table22.Table.Symbol.ExtraConfigColumns]); - const extraValues = Array.isArray(extraConfig) ? extraConfig.flat(1) : Object.values(extraConfig); - for (const builder of extraValues) { - if ((0, import_entity73.is)(builder, import_indexes.IndexBuilder)) { - indexes.push(builder.build(table)); - } else if ((0, import_entity73.is)(builder, import_checks.CheckBuilder)) { - checks.push(builder.build(table)); - } else if ((0, import_entity73.is)(builder, import_unique_constraint2.UniqueConstraintBuilder)) { - uniqueConstraints.push(builder.build(table)); - } else if ((0, import_entity73.is)(builder, import_primary_keys2.PrimaryKeyBuilder)) { - primaryKeys.push(builder.build(table)); - } else if ((0, import_entity73.is)(builder, import_foreign_keys2.ForeignKeyBuilder)) { - foreignKeys.push(builder.build(table)); - } else if ((0, import_entity73.is)(builder, import_policies.PgPolicy)) { - policies.push(builder); - } - } - } - return { - columns, - indexes, - foreignKeys, - checks, - primaryKeys, - uniqueConstraints, - name, - schema, - policies, - enableRLS - }; - } - function extractUsedTable2(table) { - if ((0, import_entity73.is)(table, import_table18.PgTable)) { - return [table[import_table22.Schema] ? `${table[import_table22.Schema]}.${table[import_table22.Table.Symbol.BaseName]}` : table[import_table22.Table.Symbol.BaseName]]; - } - if ((0, import_entity73.is)(table, import_subquery10.Subquery)) { - return table._.usedTables ?? []; - } - if ((0, import_entity73.is)(table, import_sql21.SQL)) { - return table.usedTables ?? []; - } - return []; - } - function getViewConfig(view) { - return { - ...view[import_view_common8.ViewBaseConfig], - ...view[import_view_common22.PgViewConfig] - }; - } - function getMaterializedViewConfig(view) { - return { - ...view[import_view_common8.ViewBaseConfig], - ...view[import_view.PgMaterializedViewConfig] - }; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/delete.cjs -var require_delete = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var delete_exports = {}; - __export2(delete_exports, { - PgDeleteBase: () => PgDeleteBase2 - }); - module.exports = __toCommonJS2(delete_exports); - var import_entity73 = require_entity(); - var import_query_promise8 = require_query_promise(); - var import_selection_proxy7 = require_selection_proxy(); - var import_table18 = require_table(); - var import_tracing9 = require_tracing(); - var import_utils33 = require_utils6(); - var import_utils210 = require_utils8(); - - class PgDeleteBase2 extends import_query_promise8.QueryPromise { - constructor(table, session2, dialect, withList) { - super(); - this.session = session2; - this.dialect = dialect; - this.config = { table, withList }; - } - static [import_entity73.entityKind] = "PgDelete"; - config; - cacheConfig; - where(where) { - this.config.where = where; - return this; - } - returning(fields = this.config.table[import_table18.Table.Symbol.Columns]) { - this.config.returningFields = fields; - this.config.returning = (0, import_utils33.orderSelectedFields)(fields); - return this; - } - getSQL() { - return this.dialect.buildDeleteQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - _prepare(name) { - return import_tracing9.tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { - type: "delete", - tables: (0, import_utils210.extractUsedTable)(this.config.table) - }, this.cacheConfig); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return import_tracing9.tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - getSelectedFields() { - return this.config.returningFields ? new Proxy(this.config.returningFields, new import_selection_proxy7.SelectionProxyHandler({ - alias: (0, import_table18.getTableName)(this.config.table), - sqlAliasedBehavior: "alias", - sqlBehavior: "error" - })) : undefined; - } - $dynamic() { - return this; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/insert.cjs -var require_insert = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var insert_exports = {}; - __export2(insert_exports, { - PgInsertBase: () => PgInsertBase2, - PgInsertBuilder: () => PgInsertBuilder2 - }); - module.exports = __toCommonJS2(insert_exports); - var import_entity73 = require_entity(); - var import_query_promise8 = require_query_promise(); - var import_selection_proxy7 = require_selection_proxy(); - var import_sql21 = require_sql(); - var import_table18 = require_table(); - var import_tracing9 = require_tracing(); - var import_utils33 = require_utils6(); - var import_utils210 = require_utils8(); - var import_query_builder3 = require_query_builder2(); - - class PgInsertBuilder2 { - constructor(table, session2, dialect, withList, overridingSystemValue_) { - this.table = table; - this.session = session2; - this.dialect = dialect; - this.withList = withList; - this.overridingSystemValue_ = overridingSystemValue_; - } - static [import_entity73.entityKind] = "PgInsertBuilder"; - authToken; - setToken(token) { - this.authToken = token; - return this; - } - overridingSystemValue() { - this.overridingSystemValue_ = true; - return this; - } - values(values) { - values = Array.isArray(values) ? values : [values]; - if (values.length === 0) { - throw new Error("values() must be called with at least one value"); - } - const mappedValues = values.map((entry) => { - const result = {}; - const cols = this.table[import_table18.Table.Symbol.Columns]; - for (const colKey of Object.keys(entry)) { - const colValue = entry[colKey]; - result[colKey] = (0, import_entity73.is)(colValue, import_sql21.SQL) ? colValue : new import_sql21.Param(colValue, cols[colKey]); - } - return result; - }); - return new PgInsertBase2(this.table, mappedValues, this.session, this.dialect, this.withList, false, this.overridingSystemValue_).setToken(this.authToken); - } - select(selectQuery) { - const select = typeof selectQuery === "function" ? selectQuery(new import_query_builder3.QueryBuilder) : selectQuery; - if (!(0, import_entity73.is)(select, import_sql21.SQL) && !(0, import_utils33.haveSameKeys)(this.table[import_table18.Columns], select._.selectedFields)) { - throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition"); - } - return new PgInsertBase2(this.table, select, this.session, this.dialect, this.withList, true); - } - } - - class PgInsertBase2 extends import_query_promise8.QueryPromise { - constructor(table, values, session2, dialect, withList, select, overridingSystemValue_) { - super(); - this.session = session2; - this.dialect = dialect; - this.config = { table, values, withList, select, overridingSystemValue_ }; - } - static [import_entity73.entityKind] = "PgInsert"; - config; - cacheConfig; - returning(fields = this.config.table[import_table18.Table.Symbol.Columns]) { - this.config.returningFields = fields; - this.config.returning = (0, import_utils33.orderSelectedFields)(fields); - return this; - } - onConflictDoNothing(config = {}) { - if (config.target === undefined) { - this.config.onConflict = import_sql21.sql`do nothing`; - } else { - let targetColumn = ""; - targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target)); - const whereSql = config.where ? import_sql21.sql` where ${config.where}` : undefined; - this.config.onConflict = import_sql21.sql`(${import_sql21.sql.raw(targetColumn)})${whereSql} do nothing`; - } - return this; - } - onConflictDoUpdate(config) { - if (config.where && (config.targetWhere || config.setWhere)) { - throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'); - } - const whereSql = config.where ? import_sql21.sql` where ${config.where}` : undefined; - const targetWhereSql = config.targetWhere ? import_sql21.sql` where ${config.targetWhere}` : undefined; - const setWhereSql = config.setWhere ? import_sql21.sql` where ${config.setWhere}` : undefined; - const setSql = this.dialect.buildUpdateSet(this.config.table, (0, import_utils33.mapUpdateSet)(this.config.table, config.set)); - let targetColumn = ""; - targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target)); - this.config.onConflict = import_sql21.sql`(${import_sql21.sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`; - return this; - } - getSQL() { - return this.dialect.buildInsertQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - _prepare(name) { - return import_tracing9.tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { - type: "insert", - tables: (0, import_utils210.extractUsedTable)(this.config.table) - }, this.cacheConfig); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return import_tracing9.tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - getSelectedFields() { - return this.config.returningFields ? new Proxy(this.config.returningFields, new import_selection_proxy7.SelectionProxyHandler({ - alias: (0, import_table18.getTableName)(this.config.table), - sqlAliasedBehavior: "alias", - sqlBehavior: "error" - })) : undefined; - } - $dynamic() { - return this; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.cjs -var require_refresh_materialized_view = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var refresh_materialized_view_exports = {}; - __export2(refresh_materialized_view_exports, { - PgRefreshMaterializedView: () => PgRefreshMaterializedView2 - }); - module.exports = __toCommonJS2(refresh_materialized_view_exports); - var import_entity73 = require_entity(); - var import_query_promise8 = require_query_promise(); - var import_tracing9 = require_tracing(); - - class PgRefreshMaterializedView2 extends import_query_promise8.QueryPromise { - constructor(view, session2, dialect) { - super(); - this.session = session2; - this.dialect = dialect; - this.config = { view }; - } - static [import_entity73.entityKind] = "PgRefreshMaterializedView"; - config; - concurrently() { - if (this.config.withNoData !== undefined) { - throw new Error("Cannot use concurrently and withNoData together"); - } - this.config.concurrently = true; - return this; - } - withNoData() { - if (this.config.concurrently !== undefined) { - throw new Error("Cannot use concurrently and withNoData together"); - } - this.config.withNoData = true; - return this; - } - getSQL() { - return this.dialect.buildRefreshMaterializedViewQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - _prepare(name) { - return import_tracing9.tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true); - }); - } - prepare(name) { - return this._prepare(name); - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return import_tracing9.tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/select.types.cjs -var require_select_types = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var select_types_exports = {}; - module.exports = __toCommonJS2(select_types_exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/update.cjs -var require_update = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var update_exports = {}; - __export2(update_exports, { - PgUpdateBase: () => PgUpdateBase2, - PgUpdateBuilder: () => PgUpdateBuilder2 - }); - module.exports = __toCommonJS2(update_exports); - var import_entity73 = require_entity(); - var import_table18 = require_table2(); - var import_query_promise8 = require_query_promise(); - var import_selection_proxy7 = require_selection_proxy(); - var import_sql21 = require_sql(); - var import_subquery10 = require_subquery(); - var import_table22 = require_table(); - var import_utils33 = require_utils6(); - var import_view_common8 = require_view_common(); - var import_utils210 = require_utils8(); - - class PgUpdateBuilder2 { - constructor(table, session2, dialect, withList) { - this.table = table; - this.session = session2; - this.dialect = dialect; - this.withList = withList; - } - static [import_entity73.entityKind] = "PgUpdateBuilder"; - authToken; - setToken(token) { - this.authToken = token; - return this; - } - set(values) { - return new PgUpdateBase2(this.table, (0, import_utils33.mapUpdateSet)(this.table, values), this.session, this.dialect, this.withList).setToken(this.authToken); - } - } - - class PgUpdateBase2 extends import_query_promise8.QueryPromise { - constructor(table, set, session2, dialect, withList) { - super(); - this.session = session2; - this.dialect = dialect; - this.config = { set, table, withList, joins: [] }; - this.tableName = (0, import_utils33.getTableLikeName)(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; - } - static [import_entity73.entityKind] = "PgUpdate"; - config; - tableName; - joinsNotNullableMap; - cacheConfig; - from(source) { - const src = source; - const tableName = (0, import_utils33.getTableLikeName)(src); - if (typeof tableName === "string") { - this.joinsNotNullableMap[tableName] = true; - } - this.config.from = src; - return this; - } - getTableLikeFields(table) { - if ((0, import_entity73.is)(table, import_table18.PgTable)) { - return table[import_table22.Table.Symbol.Columns]; - } else if ((0, import_entity73.is)(table, import_subquery10.Subquery)) { - return table._.selectedFields; - } - return table[import_view_common8.ViewBaseConfig].selectedFields; - } - createJoin(joinType) { - return (table, on) => { - const tableName = (0, import_utils33.getTableLikeName)(table); - if (typeof tableName === "string" && this.config.joins.some((join2) => join2.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (typeof on === "function") { - const from = this.config.from && !(0, import_entity73.is)(this.config.from, import_sql21.SQL) ? this.getTableLikeFields(this.config.from) : undefined; - on = on(new Proxy(this.config.table[import_table22.Table.Symbol.Columns], new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new import_selection_proxy7.SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); - } - this.config.joins.push({ on, table, joinType, alias: tableName }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; - } - case "right": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = true; - break; - } - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; + BigNumber4.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor3(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a, b, e2, k, v, i = 0, c = [], rand = new BigNumber4(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck3(dp, 0, MAX3); + k = mathceil3(dp / LOG_BASE3); + if (CRYPTO) { + if (crypto.getRandomValues) { + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + for (;i < k; ) { + v = a[i] * 131072 + (a[i + 1] >>> 11); + if (v >= 9000000000000000) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + c.push(v % 100000000000000); + i += 2; + } + } + i = k / 2; + } else if (crypto.randomBytes) { + a = crypto.randomBytes(k *= 7); + for (;i < k; ) { + v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + if (v >= 9000000000000000) { + crypto.randomBytes(7).copy(a, i); + } else { + c.push(v % 100000000000000); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error(bignumberError3 + "crypto unavailable"); } - case "full": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = false; - break; + } + if (!CRYPTO) { + for (;i < k; ) { + v = random53bitInt(); + if (v < 9000000000000000) + c[i++] = v % 100000000000000; } } - } - return this; + k = c[--i]; + dp %= LOG_BASE3; + if (k && dp) { + v = POWS_TEN3[LOG_BASE3 - dp]; + c[i] = mathfloor3(k / v) * v; + } + for (;c[i] === 0; c.pop(), i--) + ; + if (i < 0) { + c = [e2 = 0]; + } else { + for (e2 = -1;c[0] === 0; c.splice(0, 1), e2 -= LOG_BASE3) + ; + for (i = 1, v = c[0];v >= 10; v /= 10, i++) + ; + if (i < LOG_BASE3) + e2 -= LOG_BASE3 - i; + } + rand.e = e2; + rand.c = c; + return rand; + }; + }(); + BigNumber4.sum = function() { + var i = 1, args = arguments, sum = new BigNumber4(args[0]); + for (;i < args.length; ) + sum = sum.plus(args[i++]); + return sum; }; - } - leftJoin = this.createJoin("left"); - rightJoin = this.createJoin("right"); - innerJoin = this.createJoin("inner"); - fullJoin = this.createJoin("full"); - where(where) { - this.config.where = where; - return this; - } - returning(fields) { - if (!fields) { - fields = Object.assign({}, this.config.table[import_table22.Table.Symbol.Columns]); - if (this.config.from) { - const tableName = (0, import_utils33.getTableLikeName)(this.config.from); - if (typeof tableName === "string" && this.config.from && !(0, import_entity73.is)(this.config.from, import_sql21.SQL)) { - const fromFields = this.getTableLikeFields(this.config.from); - fields[tableName] = fromFields; - } - for (const join2 of this.config.joins) { - const tableName2 = (0, import_utils33.getTableLikeName)(join2.table); - if (typeof tableName2 === "string" && !(0, import_entity73.is)(join2.table, import_sql21.SQL)) { - const fromFields = this.getTableLikeFields(join2.table); - fields[tableName2] = fromFields; + convertBase = function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet3) { + var j, arr = [0], arrL, i = 0, len = str.length; + for (;i < len; ) { + for (arrL = arr.length;arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet3.indexOf(str.charAt(i++)); + for (j = 0;j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) + arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } } } + return arr.reverse(); } - } - this.config.returningFields = fields; - this.config.returning = (0, import_utils33.orderSelectedFields)(fields); - return this; - } - getSQL() { - return this.dialect.buildUpdateQuery(this.config); - } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; - } - _prepare(name) { - const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { - type: "insert", - tables: (0, import_utils210.extractUsedTable)(this.config.table) - }, this.cacheConfig); - query.joinsNotNullableMap = this.joinsNotNullableMap; - return query; - } - prepare(name) { - return this._prepare(name); - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - execute = (placeholderValues) => { - return this._prepare().execute(placeholderValues, this.authToken); - }; - getSelectedFields() { - return this.config.returningFields ? new Proxy(this.config.returningFields, new import_selection_proxy7.SelectionProxyHandler({ - alias: (0, import_table22.getTableName)(this.config.table), - sqlAliasedBehavior: "alias", - sqlBehavior: "error" - })) : undefined; - } - $dynamic() { - return this; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/index.cjs -var require_query_builders = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var query_builders_exports = {}; - module.exports = __toCommonJS2(query_builders_exports); - __reExport(query_builders_exports, require_delete(), module.exports); - __reExport(query_builders_exports, require_insert(), module.exports); - __reExport(query_builders_exports, require_query_builder2(), module.exports); - __reExport(query_builders_exports, require_refresh_materialized_view(), module.exports); - __reExport(query_builders_exports, require_select2(), module.exports); - __reExport(query_builders_exports, require_select_types(), module.exports); - __reExport(query_builders_exports, require_update(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/count.cjs -var require_count = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var count_exports = {}; - __export2(count_exports, { - PgCountBuilder: () => PgCountBuilder2 - }); - module.exports = __toCommonJS2(count_exports); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - - class PgCountBuilder2 extends import_sql21.SQL { - constructor(params) { - super(PgCountBuilder2.buildEmbeddedCount(params.source, params.filters).queryChunks); - this.params = params; - this.mapWith(Number); - this.session = params.session; - this.sql = PgCountBuilder2.buildCount(params.source, params.filters); - } - sql; - token; - static [import_entity73.entityKind] = "PgCountBuilder"; - [Symbol.toStringTag] = "PgCountBuilder"; - session; - static buildEmbeddedCount(source, filters) { - return import_sql21.sql`(select count(*) from ${source}${import_sql21.sql.raw(" where ").if(filters)}${filters})`; - } - static buildCount(source, filters) { - return import_sql21.sql`select count(*) as count from ${source}${import_sql21.sql.raw(" where ").if(filters)}${filters};`; - } - setToken(token) { - this.token = token; - return this; - } - then(onfulfilled, onrejected) { - return Promise.resolve(this.session.count(this.sql, this.token)).then(onfulfilled, onrejected); - } - catch(onRejected) { - return this.then(undefined, onRejected); - } - finally(onFinally) { - return this.then((value) => { - onFinally?.(); - return value; - }, (reason) => { - onFinally?.(); - throw reason; - }); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/query.cjs -var require_query3 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var query_exports = {}; - __export2(query_exports, { - PgRelationalQuery: () => PgRelationalQuery2, - RelationalQueryBuilder: () => RelationalQueryBuilder2 - }); - module.exports = __toCommonJS2(query_exports); - var import_entity73 = require_entity(); - var import_query_promise8 = require_query_promise(); - var import_relations4 = require_relations(); - var import_tracing9 = require_tracing(); - - class RelationalQueryBuilder2 { - constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session2) { - this.fullSchema = fullSchema; - this.schema = schema; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session2; - } - static [import_entity73.entityKind] = "PgRelationalQueryBuilder"; - findMany(config) { - return new PgRelationalQuery2(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many"); - } - findFirst(config) { - return new PgRelationalQuery2(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first"); - } - } - - class PgRelationalQuery2 extends import_query_promise8.QueryPromise { - constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session2, config, mode) { - super(); - this.fullSchema = fullSchema; - this.schema = schema; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session2; - this.config = config; - this.mode = mode; - } - static [import_entity73.entityKind] = "PgRelationalQuery"; - _prepare(name) { - return import_tracing9.tracer.startActiveSpan("drizzle.prepareQuery", () => { - const { query, builtQuery } = this._toSQL(); - return this.session.prepareQuery(builtQuery, undefined, name, true, (rawRows, mapColumnValue) => { - const rows = rawRows.map((row) => (0, import_relations4.mapRelationalRow)(this.schema, this.tableConfig, row, query.selection, mapColumnValue)); - if (this.mode === "first") { - return rows[0]; - } - return rows; - }); - }); - } - prepare(name) { - return this._prepare(name); - } - _getQuery() { - return this.dialect.buildRelationalQueryWithoutPK({ - fullSchema: this.fullSchema, - schema: this.schema, - tableNamesMap: this.tableNamesMap, - table: this.table, - tableConfig: this.tableConfig, - queryConfig: this.config, - tableAlias: this.tableConfig.tsName - }); - } - getSQL() { - return this._getQuery().sql; - } - _toSQL() { - const query = this._getQuery(); - const builtQuery = this.dialect.sqlToQuery(query.sql); - return { query, builtQuery }; - } - toSQL() { - return this._toSQL().builtQuery; - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - execute() { - return import_tracing9.tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(undefined, this.authToken); - }); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/query-builders/raw.cjs -var require_raw2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var raw_exports = {}; - __export2(raw_exports, { - PgRaw: () => PgRaw2 - }); - module.exports = __toCommonJS2(raw_exports); - var import_entity73 = require_entity(); - var import_query_promise8 = require_query_promise(); - - class PgRaw2 extends import_query_promise8.QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { - super(); - this.execute = execute; - this.sql = sql2; - this.query = query; - this.mapBatchResult = mapBatchResult; - } - static [import_entity73.entityKind] = "PgRaw"; - getSQL() { - return this.sql; - } - getQuery() { - return this.query; - } - mapResult(result, isFromBatch) { - return isFromBatch ? this.mapBatchResult(result) : result; - } - _prepare() { - return this; - } - isResponseInArrayMode() { - return false; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/db.cjs -var require_db2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var db_exports = {}; - __export2(db_exports, { - PgDatabase: () => PgDatabase2, - withReplicas: () => withReplicas - }); - module.exports = __toCommonJS2(db_exports); - var import_entity73 = require_entity(); - var import_query_builders2 = require_query_builders(); - var import_selection_proxy7 = require_selection_proxy(); - var import_sql21 = require_sql(); - var import_subquery10 = require_subquery(); - var import_count2 = require_count(); - var import_query2 = require_query3(); - var import_raw2 = require_raw2(); - var import_refresh_materialized_view2 = require_refresh_materialized_view(); - - class PgDatabase2 { - constructor(dialect, session2, schema) { - this.dialect = dialect; - this.session = session2; - this._ = schema ? { - schema: schema.schema, - fullSchema: schema.fullSchema, - tableNamesMap: schema.tableNamesMap, - session: session2 - } : { - schema: undefined, - fullSchema: {}, - tableNamesMap: {}, - session: session2 - }; - this.query = {}; - if (this._.schema) { - for (const [tableName, columns] of Object.entries(this._.schema)) { - this.query[tableName] = new import_query2.RelationalQueryBuilder(schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session2); + return function(str, baseIn, baseOut, sign, callerIsToString) { + var alphabet3, d, e2, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i >= 0) { + k = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y = new BigNumber4(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + y.c = toBaseOut(toFixedPoint3(coeffToString3(x.c), x.e, "0"), 10, baseOut, decimal); + y.e = y.c.length; + } + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet3 = ALPHABET, decimal) : (alphabet3 = decimal, ALPHABET)); + e2 = k = xc.length; + for (;xc[--k] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet3.charAt(0); + if (i < 0) { + --e2; + } else { + x.c = xc; + x.e = e2; + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e2 = x.e; + } + d = e2 + dp + 1; + i = xc[d]; + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); + if (d < 1 || !xc[0]) { + str = r ? toFixedPoint3(alphabet3.charAt(1), -dp, alphabet3.charAt(0)) : alphabet3.charAt(0); + } else { + xc.length = d; + if (r) { + for (--baseOut;++xc[--d] > baseOut; ) { + xc[d] = 0; + if (!d) { + ++e2; + xc = [1].concat(xc); + } + } + } + for (k = xc.length;!xc[--k]; ) + ; + for (i = 0, str = "";i <= k; str += alphabet3.charAt(xc[i++])) + ; + str = toFixedPoint3(str, e2, alphabet3.charAt(0)); + } + return str; + }; + }(); + div = function() { + function multiply(x, k, base) { + var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE3, khi = k / SQRT_BASE3 | 0; + for (x = x.slice();i--; ) { + xlo = x[i] % SQRT_BASE3; + xhi = x[i] / SQRT_BASE3 | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + m % SQRT_BASE3 * SQRT_BASE3 + carry; + carry = (temp / base | 0) + (m / SQRT_BASE3 | 0) + khi * xhi; + x[i] = temp % base; + } + if (carry) + x = [carry].concat(x); + return x; } - } - this.$cache = { invalidate: async (_params) => {} }; - } - static [import_entity73.entityKind] = "PgDatabase"; - query; - $with = (alias, selection) => { - const self2 = this; - const as = (qb) => { - if (typeof qb === "function") { - qb = qb(new import_query_builders2.QueryBuilder(self2.dialect)); + function compare5(a, b, aL, bL) { + var i, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i = cmp = 0;i < aL; i++) { + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + return cmp; } - return new Proxy(new import_subquery10.WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new import_selection_proxy7.SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); - }; - return { as }; - }; - $count(source, filters) { - return new import_count2.PgCountBuilder({ source, filters, session: this.session }); - } - $cache; - with(...queries) { - const self2 = this; - function select(fields) { - return new import_query_builders2.PgSelectBuilder({ - fields: fields ?? undefined, - session: self2.session, - dialect: self2.dialect, - withList: queries - }); - } - function selectDistinct(fields) { - return new import_query_builders2.PgSelectBuilder({ - fields: fields ?? undefined, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: true - }); - } - function selectDistinctOn(on, fields) { - return new import_query_builders2.PgSelectBuilder({ - fields: fields ?? undefined, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: { on } - }); - } - function update(table) { - return new import_query_builders2.PgUpdateBuilder(table, self2.session, self2.dialect, queries); - } - function insert(table) { - return new import_query_builders2.PgInsertBuilder(table, self2.session, self2.dialect, queries); - } - function delete_(table) { - return new import_query_builders2.PgDeleteBase(table, self2.session, self2.dialect, queries); - } - return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ }; - } - select(fields) { - return new import_query_builders2.PgSelectBuilder({ - fields: fields ?? undefined, - session: this.session, - dialect: this.dialect - }); - } - selectDistinct(fields) { - return new import_query_builders2.PgSelectBuilder({ - fields: fields ?? undefined, - session: this.session, - dialect: this.dialect, - distinct: true - }); - } - selectDistinctOn(on, fields) { - return new import_query_builders2.PgSelectBuilder({ - fields: fields ?? undefined, - session: this.session, - dialect: this.dialect, - distinct: { on } - }); - } - update(table) { - return new import_query_builders2.PgUpdateBuilder(table, this.session, this.dialect); - } - insert(table) { - return new import_query_builders2.PgInsertBuilder(table, this.session, this.dialect); - } - delete(table) { - return new import_query_builders2.PgDeleteBase(table, this.session, this.dialect); - } - refreshMaterializedView(view) { - return new import_refresh_materialized_view2.PgRefreshMaterializedView(view, this.session, this.dialect); - } - authToken; - execute(query) { - const sequel = typeof query === "string" ? import_sql21.sql.raw(query) : query.getSQL(); - const builtQuery = this.dialect.sqlToQuery(sequel); - const prepared = this.session.prepareQuery(builtQuery, undefined, undefined, false); - return new import_raw2.PgRaw(() => prepared.execute(undefined, this.authToken), sequel, builtQuery, (result) => prepared.mapResult(result, true)); - } - transaction(transaction, config) { - return this.session.transaction(transaction, config); - } - } - var withReplicas = (primary, replicas, getReplica = () => replicas[Math.floor(Math.random() * replicas.length)]) => { - const select = (...args) => getReplica(replicas).select(...args); - const selectDistinct = (...args) => getReplica(replicas).selectDistinct(...args); - const selectDistinctOn = (...args) => getReplica(replicas).selectDistinctOn(...args); - const $count = (...args) => getReplica(replicas).$count(...args); - const _with = (...args) => getReplica(replicas).with(...args); - const $with = (arg) => getReplica(replicas).$with(arg); - const update = (...args) => primary.update(...args); - const insert = (...args) => primary.insert(...args); - const $delete = (...args) => primary.delete(...args); - const execute = (...args) => primary.execute(...args); - const transaction = (...args) => primary.transaction(...args); - const refreshMaterializedView = (...args) => primary.refreshMaterializedView(...args); - return { - ...primary, - update, - insert, - delete: $delete, - execute, - transaction, - refreshMaterializedView, - $primary: primary, - select, - selectDistinct, - selectDistinctOn, - $count, - $with, - with: _with, - get query() { - return getReplica(replicas).query; - } - }; - }; -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/roles.cjs -var require_roles = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var roles_exports = {}; - __export2(roles_exports, { - PgRole: () => PgRole, - pgRole: () => pgRole - }); - module.exports = __toCommonJS2(roles_exports); - var import_entity73 = require_entity(); - - class PgRole { - constructor(name, config) { - this.name = name; - if (config) { - this.createDb = config.createDb; - this.createRole = config.createRole; - this.inherit = config.inherit; - } - } - static [import_entity73.entityKind] = "PgRole"; - _existing; - createDb; - createRole; - inherit; - existing() { - this._existing = true; - return this; - } - } - function pgRole(name, config) { - return new PgRole(name, config); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/sequence.cjs -var require_sequence = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var sequence_exports = {}; - __export2(sequence_exports, { - PgSequence: () => PgSequence, - isPgSequence: () => isPgSequence, - pgSequence: () => pgSequence, - pgSequenceWithSchema: () => pgSequenceWithSchema - }); - module.exports = __toCommonJS2(sequence_exports); - var import_entity73 = require_entity(); - - class PgSequence { - constructor(seqName, seqOptions, schema) { - this.seqName = seqName; - this.seqOptions = seqOptions; - this.schema = schema; - } - static [import_entity73.entityKind] = "PgSequence"; - } - function pgSequence(name, options) { - return pgSequenceWithSchema(name, options, undefined); - } - function pgSequenceWithSchema(name, options, schema) { - return new PgSequence(name, options, schema); - } - function isPgSequence(obj) { - return (0, import_entity73.is)(obj, PgSequence); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/schema.cjs -var require_schema = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var schema_exports = {}; - __export2(schema_exports, { - PgSchema: () => PgSchema, - isPgSchema: () => isPgSchema, - pgSchema: () => pgSchema - }); - module.exports = __toCommonJS2(schema_exports); - var import_entity73 = require_entity(); - var import_sql21 = require_sql(); - var import_enum2 = require_enum(); - var import_sequence = require_sequence(); - var import_table18 = require_table2(); - var import_view = require_view2(); - - class PgSchema { - constructor(schemaName) { - this.schemaName = schemaName; - } - static [import_entity73.entityKind] = "PgSchema"; - table = (name, columns, extraConfig) => { - return (0, import_table18.pgTableWithSchema)(name, columns, extraConfig, this.schemaName); - }; - view = (name, columns) => { - return (0, import_view.pgViewWithSchema)(name, columns, this.schemaName); - }; - materializedView = (name, columns) => { - return (0, import_view.pgMaterializedViewWithSchema)(name, columns, this.schemaName); - }; - enum(enumName, input) { - return Array.isArray(input) ? (0, import_enum2.pgEnumWithSchema)(enumName, [...input], this.schemaName) : (0, import_enum2.pgEnumObjectWithSchema)(enumName, input, this.schemaName); - } - sequence = (name, options) => { - return (0, import_sequence.pgSequenceWithSchema)(name, options, this.schemaName); - }; - getSQL() { - return new import_sql21.SQL([import_sql21.sql.identifier(this.schemaName)]); - } - shouldOmitSQLParens() { - return true; - } - } - function isPgSchema(obj) { - return (0, import_entity73.is)(obj, PgSchema); - } - function pgSchema(name) { - if (name === "public") { - throw new Error(`You can't specify 'public' as schema name. Postgres is using public schema by default. If you want to use 'public' schema, just use pgTable() instead of creating a schema`); - } - return new PgSchema(name); - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/cache/core/cache.cjs -var require_cache = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var cache_exports = {}; - __export2(cache_exports, { - Cache: () => Cache2, - NoopCache: () => NoopCache2, - hashQuery: () => hashQuery2 - }); - module.exports = __toCommonJS2(cache_exports); - var import_entity73 = require_entity(); - - class Cache2 { - static [import_entity73.entityKind] = "Cache"; - } - - class NoopCache2 extends Cache2 { - strategy() { - return "all"; - } - static [import_entity73.entityKind] = "NoopCache"; - async get(_key) { - return; - } - async put(_hashedQuery, _response, _tables, _config) {} - async onMutate(_params) {} - } - async function hashQuery2(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; - const encoder = new TextEncoder; - const data = encoder.encode(dataToHash); - const hashBuffer = await crypto.subtle.digest("SHA-256", data); - const hashArray = [...new Uint8Array(hashBuffer)]; - const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); - return hashHex; - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/errors/index.cjs -var require_errors4 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var errors_exports = {}; - __export2(errors_exports, { - DrizzleQueryError: () => DrizzleQueryError2 - }); - module.exports = __toCommonJS2(errors_exports); - - class DrizzleQueryError2 extends Error { - constructor(query, params, cause) { - super(`Failed query: ${query} -params: ${params}`); - this.query = query; - this.params = params; - this.cause = cause; - Error.captureStackTrace(this, DrizzleQueryError2); - if (cause) - this.cause = cause; - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/session.cjs -var require_session = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var session_exports = {}; - __export2(session_exports, { - PgPreparedQuery: () => PgPreparedQuery2, - PgSession: () => PgSession2, - PgTransaction: () => PgTransaction2 - }); - module.exports = __toCommonJS2(session_exports); - var import_cache2 = require_cache(); - var import_entity73 = require_entity(); - var import_errors3 = require_errors3(); - var import_errors22 = require_errors4(); - var import_sql21 = require_sql2(); - var import_tracing9 = require_tracing(); - var import_db3 = require_db2(); - - class PgPreparedQuery2 { - constructor(query, cache, queryMetadata, cacheConfig) { - this.query = query; - this.cache = cache; - this.queryMetadata = queryMetadata; - this.cacheConfig = cacheConfig; - if (cache && cache.strategy() === "all" && cacheConfig === undefined) { - this.cacheConfig = { enable: true, autoInvalidate: true }; - } - if (!this.cacheConfig?.enable) { - this.cacheConfig = undefined; - } - } - authToken; - getQuery() { - return this.query; - } - mapResult(response, _isFromBatch) { - return response; - } - setToken(token) { - this.authToken = token; - return this; - } - static [import_entity73.entityKind] = "PgPreparedQuery"; - joinsNotNullableMap; - async queryWithCache(queryString, params, query) { - if (this.cache === undefined || (0, import_entity73.is)(this.cache, import_cache2.NoopCache) || this.queryMetadata === undefined) { - try { - return await query(); - } catch (e2) { - throw new import_errors22.DrizzleQueryError(queryString, params, e2); + function subtract(a, b, aL, base) { + var i = 0; + for (;aL--; ) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + for (;!a[0] && a.length > 1; a.splice(0, 1)) + ; } - } - if (this.cacheConfig && !this.cacheConfig.enable) { - try { - return await query(); - } catch (e2) { - throw new import_errors22.DrizzleQueryError(queryString, params, e2); + return function(x, y, dp, rm, base) { + var cmp, e2, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber4(!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s * 0 : s / 0); + } + q = new BigNumber4(s); + qc = q.c = []; + e2 = x.e - y.e; + s = dp + e2 + 1; + if (!base) { + base = BASE3; + e2 = bitFloor3(x.e / LOG_BASE3) - bitFloor3(y.e / LOG_BASE3); + s = s / LOG_BASE3 | 0; + } + for (i = 0;yc[i] == (xc[i] || 0); i++) + ; + if (yc[i] > (xc[i] || 0)) + e2--; + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + n = mathfloor3(base / (yc[0] + 1)); + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (;remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) + yc0++; + do { + n = 0; + cmp = compare5(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base + (rem[1] || 0); + n = mathfloor3(rem0 / yc0); + if (n > 1) { + if (n >= base) + n = base - 1; + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + while (compare5(prod, rem, prodL, remL) == 1) { + n--; + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + if (n == 0) { + cmp = n = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base); + remL = rem.length; + if (cmp == -1) { + while (compare5(yc, rem, yL, remL) < 1) { + n++; + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } + qc[i++] = n; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); + } + if (base == BASE3) { + for (i = 1, s = qc[0];s >= 10; s /= 10, i++) + ; + round(q, dp + (q.e = i + e2 * LOG_BASE3 - 1) + 1, rm, more); + } else { + q.e = e2; + q.r = +more; + } + return q; + }; + }(); + function format(n, i, rm, id) { + var c0, e2, ne2, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck3(rm, 0, 8); + if (!n.c) + return n.toString(); + c0 = n.c[0]; + ne2 = n.e; + if (i == null) { + str = coeffToString3(n.c); + str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential3(str, ne2) : toFixedPoint3(str, ne2, "0"); + } else { + n = round(new BigNumber4(n), i, rm); + e2 = n.e; + str = coeffToString3(n.c); + len = str.length; + if (id == 1 || id == 2 && (i <= e2 || e2 <= TO_EXP_NEG)) { + for (;len < i; str += "0", len++) + ; + str = toExponential3(str, e2); + } else { + i -= ne2 + (id === 2 && e2 > ne2); + str = toFixedPoint3(str, e2, "0"); + if (e2 + 1 > len) { + if (--i > 0) + for (str += ".";i--; str += "0") + ; + } else { + i += e2 - len; + if (i > 0) { + if (e2 + 1 == len) + str += "."; + for (;i--; str += "0") + ; + } + } + } } + return n.s < 0 && c0 ? "-" + str : str; } - if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) { - try { - const [res] = await Promise.all([ - query(), - this.cache.onMutate({ tables: this.queryMetadata.tables }) - ]); - return res; - } catch (e2) { - throw new import_errors22.DrizzleQueryError(queryString, params, e2); + function maxOrMin(args, n) { + var k, y, i = 1, x = new BigNumber4(args[0]); + for (;i < args.length; i++) { + y = new BigNumber4(args[i]); + if (!y.s || (k = compare4(x, y)) === n || k === 0 && x.s === n) { + x = y; + } } + return x; } - if (!this.cacheConfig) { - try { - return await query(); - } catch (e2) { - throw new import_errors22.DrizzleQueryError(queryString, params, e2); + function normalise(n, c, e2) { + var i = 1, j = c.length; + for (;!c[--j]; c.pop()) + ; + for (j = c[0];j >= 10; j /= 10, i++) + ; + if ((e2 = i + e2 * LOG_BASE3 - 1) > MAX_EXP) { + n.c = n.e = null; + } else if (e2 < MIN_EXP) { + n.c = [n.e = 0]; + } else { + n.e = e2; + n.c = c; } + return n; } - if (this.queryMetadata.type === "select") { - const fromCache = await this.cache.get(this.cacheConfig.tag ?? await (0, import_cache2.hashQuery)(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== undefined, this.cacheConfig.autoInvalidate); - if (fromCache === undefined) { - let result; - try { - result = await query(); - } catch (e2) { - throw new import_errors22.DrizzleQueryError(queryString, params, e2); + parseNumeric = function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x, str, isNum, b) { + var base, s = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + s = s.replace(basePrefix, function(m, p1, p2) { + base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; + return !b || b == base ? p1 : m; + }); + if (b) { + base = b; + s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s) + return new BigNumber4(s, base); + } + if (BigNumber4.DEBUG) { + throw Error(bignumberError3 + "Not a" + (b ? " base " + b : "") + " number: " + str); + } + x.s = null; + } + x.c = x.e = null; + }; + }(); + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN3; + if (xc) { + out: { + for (d = 1, k = xc[0];k >= 10; k /= 10, d++) + ; + i = sd - d; + if (i < 0) { + i += LOG_BASE3; + j = sd; + n = xc[ni = 0]; + rd = mathfloor3(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil3((i + 1) / LOG_BASE3); + if (ni >= xc.length) { + if (r) { + for (;xc.length <= ni; xc.push(0)) + ; + n = rd = 0; + d = 1; + i %= LOG_BASE3; + j = i - LOG_BASE3 + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + for (d = 1;k >= 10; k /= 10, d++) + ; + i %= LOG_BASE3; + j = i - LOG_BASE3 + d; + rd = j < 0 ? 0 : mathfloor3(n / pows10[d - j - 1] % 10); + } + } + r = r || sd < 0 || xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x.e + 1; + xc[0] = pows10[(LOG_BASE3 - sd % LOG_BASE3) % LOG_BASE3]; + x.e = -sd || 0; + } else { + xc[0] = x.e = 0; + } + return x; + } + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE3 - i]; + xc[ni] = j > 0 ? mathfloor3(n / pows10[d - j] % pows10[j]) * k : 0; + } + if (r) { + for (;; ) { + if (ni == 0) { + for (i = 1, j = xc[0];j >= 10; j /= 10, i++) + ; + j = xc[0] += k; + for (k = 1;j >= 10; j /= 10, k++) + ; + if (i != k) { + x.e++; + if (xc[0] == BASE3) + xc[0] = 1; + } + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE3) + break; + xc[ni--] = 0; + k = 1; + } + } + } + for (i = xc.length;xc[--i] === 0; xc.pop()) + ; + } + if (x.e > MAX_EXP) { + x.c = x.e = null; + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; } - await this.cache.put(this.cacheConfig.tag ?? await (0, import_cache2.hashQuery)(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== undefined, this.cacheConfig.config); - return result; } - return fromCache; - } - try { - return await query(); - } catch (e2) { - throw new import_errors22.DrizzleQueryError(queryString, params, e2); + return x; } - } - } - - class PgSession2 { - constructor(dialect) { - this.dialect = dialect; - } - static [import_entity73.entityKind] = "PgSession"; - execute(query, token) { - return import_tracing9.tracer.startActiveSpan("drizzle.operation", () => { - const prepared = import_tracing9.tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false); - }); - return prepared.setToken(token).execute(undefined, token); - }); - } - all(query) { - return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false).all(); - } - async count(sql2, token) { - const res = await this.execute(sql2, token); - return Number(res[0]["count"]); - } - } - - class PgTransaction2 extends import_db3.PgDatabase { - constructor(dialect, session2, schema, nestedIndex = 0) { - super(dialect, session2, schema); - this.schema = schema; - this.nestedIndex = nestedIndex; - } - static [import_entity73.entityKind] = "PgTransaction"; - rollback() { - throw new import_errors3.TransactionRollbackError; - } - getTransactionConfigSQL(config) { - const chunks = []; - if (config.isolationLevel) { - chunks.push(`isolation level ${config.isolationLevel}`); - } - if (config.accessMode) { - chunks.push(config.accessMode); - } - if (typeof config.deferrable === "boolean") { - chunks.push(config.deferrable ? "deferrable" : "not deferrable"); + function valueOf(n) { + var str, e2 = n.e; + if (e2 === null) + return n.toString(); + str = coeffToString3(n.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential3(str, e2) : toFixedPoint3(str, e2, "0"); + return n.s < 0 ? "-" + str : str; } - return import_sql21.sql.raw(chunks.join(" ")); - } - setTransaction(config) { - return this.session.execute(import_sql21.sql`set transaction ${this.getTransactionConfigSQL(config)}`); - } - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/subquery.cjs -var require_subquery2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var subquery_exports = {}; - module.exports = __toCommonJS2(subquery_exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/utils/index.cjs -var require_utils9 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var utils_exports = {}; - module.exports = __toCommonJS2(utils_exports); - __reExport(utils_exports, require_array(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/index.cjs -var require_pg_core = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var pg_core_exports = {}; - module.exports = __toCommonJS2(pg_core_exports); - __reExport(pg_core_exports, require_alias2(), module.exports); - __reExport(pg_core_exports, require_checks(), module.exports); - __reExport(pg_core_exports, require_columns(), module.exports); - __reExport(pg_core_exports, require_db2(), module.exports); - __reExport(pg_core_exports, require_dialect(), module.exports); - __reExport(pg_core_exports, require_foreign_keys(), module.exports); - __reExport(pg_core_exports, require_indexes(), module.exports); - __reExport(pg_core_exports, require_policies(), module.exports); - __reExport(pg_core_exports, require_primary_keys(), module.exports); - __reExport(pg_core_exports, require_query_builders(), module.exports); - __reExport(pg_core_exports, require_roles(), module.exports); - __reExport(pg_core_exports, require_schema(), module.exports); - __reExport(pg_core_exports, require_sequence(), module.exports); - __reExport(pg_core_exports, require_session(), module.exports); - __reExport(pg_core_exports, require_subquery2(), module.exports); - __reExport(pg_core_exports, require_table2(), module.exports); - __reExport(pg_core_exports, require_unique_constraint(), module.exports); - __reExport(pg_core_exports, require_utils8(), module.exports); - __reExport(pg_core_exports, require_utils9(), module.exports); - __reExport(pg_core_exports, require_view_common2(), module.exports); - __reExport(pg_core_exports, require_view2(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/logger.cjs -var require_logger2 = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __export2 = (target, all) => { - for (var name in all) - __defProp2(target, name, { get: all[name], enumerable: true }); - }; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var logger_exports = {}; - __export2(logger_exports, { - ConsoleLogWriter: () => ConsoleLogWriter2, - DefaultLogger: () => DefaultLogger2, - NoopLogger: () => NoopLogger2 - }); - module.exports = __toCommonJS2(logger_exports); - var import_entity73 = require_entity(); - - class ConsoleLogWriter2 { - static [import_entity73.entityKind] = "ConsoleLogWriter"; - write(message) { - console.log(message); - } - } - - class DefaultLogger2 { - static [import_entity73.entityKind] = "DefaultLogger"; - writer; - constructor(config) { - this.writer = config?.writer ?? new ConsoleLogWriter2; - } - logQuery(query, params) { - const stringifiedParams = params.map((p) => { - try { - return JSON.stringify(p); - } catch { - return String(p); + P.absoluteValue = P.abs = function() { + var x = new BigNumber4(this); + if (x.s < 0) + x.s = 1; + return x; + }; + P.comparedTo = function(y, b) { + return compare4(this, new BigNumber4(y, b)); + }; + P.decimalPlaces = P.dp = function(dp, rm) { + var c, n, v, x = this; + if (dp != null) { + intCheck3(dp, 0, MAX3); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck3(rm, 0, 8); + return round(new BigNumber4(x), dp + x.e + 1, rm); } - }); - const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; - this.writer.write(`Query: ${query}${paramsStr}`); - } - } - - class NoopLogger2 { - static [import_entity73.entityKind] = "NoopLogger"; - logQuery() {} - } -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/operations.cjs -var require_operations = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var operations_exports = {}; - module.exports = __toCommonJS2(operations_exports); -}); - -// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/index.cjs -var require_drizzle_orm = __commonJS((exports, module) => { - var __defProp2 = Object.defineProperty; - var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor; - var __getOwnPropNames2 = Object.getOwnPropertyNames; - var __hasOwnProp2 = Object.prototype.hasOwnProperty; - var __copyProps = (to, from, except2, desc2) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames2(from)) - if (!__hasOwnProp2.call(to, key) && key !== except2) - __defProp2(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc2(from, key)) || desc2.enumerable }); - } - return to; - }; - var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); - var __toCommonJS2 = (mod) => __copyProps(__defProp2({}, "__esModule", { value: true }), mod); - var index_exports = {}; - module.exports = __toCommonJS2(index_exports); - __reExport(index_exports, require_alias(), module.exports); - __reExport(index_exports, require_column_builder(), module.exports); - __reExport(index_exports, require_column(), module.exports); - __reExport(index_exports, require_entity(), module.exports); - __reExport(index_exports, require_errors3(), module.exports); - __reExport(index_exports, require_logger2(), module.exports); - __reExport(index_exports, require_operations(), module.exports); - __reExport(index_exports, require_query_promise(), module.exports); - __reExport(index_exports, require_relations(), module.exports); - __reExport(index_exports, require_sql2(), module.exports); - __reExport(index_exports, require_subquery(), module.exports); - __reExport(index_exports, require_table(), module.exports); - __reExport(index_exports, require_utils6(), module.exports); - __reExport(index_exports, require_view_common(), module.exports); -}); - -// ../db-schema/node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js -function fromBig2(n, le = false) { - if (le) - return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) }; - return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 }; -} -function split3(lst, le = false) { - const len = lst.length; - let Ah = new Uint32Array(len); - let Al = new Uint32Array(len); - for (let i = 0;i < len; i++) { - const { h, l } = fromBig2(lst[i], le); - [Ah[i], Al[i]] = [h, l]; - } - return [Ah, Al]; -} -var U32_MASK642, _32n2, rotlSH2 = (h, l, s) => h << s | l >>> 32 - s, rotlSL2 = (h, l, s) => l << s | h >>> 32 - s, rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s, rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s; -var init__u64 = __esm(() => { - U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1); - _32n2 = /* @__PURE__ */ BigInt(32); -}); - -// ../db-schema/node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js -function isBytes2(a) { - return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; -} -function anumber2(n, title = "") { - if (typeof n !== "number") { - const prefix = title && `"${title}" `; - throw new TypeError(`${prefix}expected number, got ${typeof n}`); - } - if (!Number.isSafeInteger(n) || n < 0) { - const prefix = title && `"${title}" `; - throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); - } -} -function abytes2(value, length, title = "") { - const bytes = isBytes2(value); - const len = value?.length; - const needsLen = length !== undefined; - if (!bytes || needsLen && len !== length) { - const prefix = title && `"${title}" `; - const ofLen = needsLen ? ` of length ${length}` : ""; - const got = bytes ? `length=${len}` : `type=${typeof value}`; - const message = prefix + "expected Uint8Array" + ofLen + ", got " + got; - if (!bytes) - throw new TypeError(message); - throw new RangeError(message); - } - return value; -} -function aexists2(instance, checkFinished = true) { - if (instance.destroyed) - throw new Error("Hash instance has been destroyed"); - if (checkFinished && instance.finished) - throw new Error("Hash#digest() has already been called"); -} -function aoutput2(out, instance) { - abytes2(out, undefined, "digestInto() output"); - const min = instance.outputLen; - if (out.length < min) { - throw new RangeError('"digestInto() output" expected to be of length >=' + min); - } -} -function u322(arr) { - return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); -} -function clean2(...arrays) { - for (let i = 0;i < arrays.length; i++) { - arrays[i].fill(0); - } -} -function byteSwap2(word) { - return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; -} -function byteSwap322(arr) { - for (let i = 0;i < arr.length; i++) { - arr[i] = byteSwap2(arr[i]); - } - return arr; -} -function createHasher2(hashCons, info = {}) { - const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); - const tmp = hashCons(undefined); - hashC.outputLen = tmp.outputLen; - hashC.blockLen = tmp.blockLen; - hashC.canXOF = tmp.canXOF; - hashC.create = (opts) => hashCons(opts); - Object.assign(hashC, info); - return Object.freeze(hashC); -} -var isLE2, swap32IfBE2, oidNist2 = (suffix) => ({ - oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) -}); -var init_utils = __esm(() => { - isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); - swap32IfBE2 = isLE2 ? (u) => u : byteSwap322; -}); - -// ../db-schema/node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha3.js -function keccakP2(s, rounds = 24) { - anumber2(rounds, "rounds"); - if (rounds < 1 || rounds > 24) - throw new Error('"rounds" expected integer 1..24'); - const B = new Uint32Array(5 * 2); - for (let round = 24 - rounds;round < 24; round++) { - for (let x = 0;x < 10; x++) - B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; - for (let x = 0;x < 10; x += 2) { - const idx1 = (x + 8) % 10; - const idx0 = (x + 2) % 10; - const B0 = B[idx0]; - const B1 = B[idx0 + 1]; - const Th = rotlH2(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL2(B0, B1, 1) ^ B[idx1 + 1]; - for (let y = 0;y < 50; y += 10) { - s[x + y] ^= Th; - s[x + y + 1] ^= Tl; - } - } - let curH = s[2]; - let curL = s[3]; - for (let t2 = 0;t2 < 24; t2++) { - const shift = SHA3_ROTL2[t2]; - const Th = rotlH2(curH, curL, shift); - const Tl = rotlL2(curH, curL, shift); - const PI = SHA3_PI2[t2]; - curH = s[PI]; - curL = s[PI + 1]; - s[PI] = Th; - s[PI + 1] = Tl; - } - for (let y = 0;y < 50; y += 10) { - const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3]; - s[y] ^= ~s[y + 2] & s[y + 4]; - s[y + 1] ^= ~s[y + 3] & s[y + 5]; - s[y + 2] ^= ~s[y + 4] & s[y + 6]; - s[y + 3] ^= ~s[y + 5] & s[y + 7]; - s[y + 4] ^= ~s[y + 6] & s[y + 8]; - s[y + 5] ^= ~s[y + 7] & s[y + 9]; - s[y + 6] ^= ~s[y + 8] & b0; - s[y + 7] ^= ~s[y + 9] & b1; - s[y + 8] ^= ~b0 & b2; - s[y + 9] ^= ~b1 & b3; - } - s[0] ^= SHA3_IOTA_H2[round]; - s[1] ^= SHA3_IOTA_L2[round]; - } - clean2(B); -} - -class Keccak2 { - state; - pos = 0; - posOut = 0; - finished = false; - state32; - destroyed = false; - blockLen; - suffix; - outputLen; - canXOF; - enableXOF = false; - rounds; - constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { - this.blockLen = blockLen; - this.suffix = suffix; - this.outputLen = outputLen; - this.enableXOF = enableXOF; - this.canXOF = enableXOF; - this.rounds = rounds; - anumber2(outputLen, "outputLen"); - if (!(0 < blockLen && blockLen < 200)) - throw new Error("only keccak-f1600 function is supported"); - this.state = new Uint8Array(200); - this.state32 = u322(this.state); - } - clone() { - return this._cloneInto(); - } - keccak() { - swap32IfBE2(this.state32); - keccakP2(this.state32, this.rounds); - swap32IfBE2(this.state32); - this.posOut = 0; - this.pos = 0; - } - update(data) { - aexists2(this); - abytes2(data); - const { blockLen, state } = this; - const len = data.length; - for (let pos = 0;pos < len; ) { - const take = Math.min(blockLen - this.pos, len - pos); - for (let i = 0;i < take; i++) - state[this.pos++] ^= data[pos++]; - if (this.pos === blockLen) - this.keccak(); - } - return this; - } - finish() { - if (this.finished) - return; - this.finished = true; - const { state, suffix, pos, blockLen } = this; - state[pos] ^= suffix; - if ((suffix & 128) !== 0 && pos === blockLen - 1) - this.keccak(); - state[blockLen - 1] ^= 128; - this.keccak(); - } - writeInto(out) { - aexists2(this, false); - abytes2(out); - this.finish(); - const bufferOut = this.state; - const { blockLen } = this; - for (let pos = 0, len = out.length;pos < len; ) { - if (this.posOut >= blockLen) - this.keccak(); - const take = Math.min(blockLen - this.posOut, len - pos); - out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); - this.posOut += take; - pos += take; - } - return out; - } - xofInto(out) { - if (!this.enableXOF) - throw new Error("XOF is not possible for this instance"); - return this.writeInto(out); - } - xof(bytes) { - anumber2(bytes); - return this.xofInto(new Uint8Array(bytes)); - } - digestInto(out) { - aoutput2(out, this); - if (this.finished) - throw new Error("digest() was already called"); - this.writeInto(out.subarray(0, this.outputLen)); - this.destroy(); - } - digest() { - const out = new Uint8Array(this.outputLen); - this.digestInto(out); - return out; - } - destroy() { - this.destroyed = true; - clean2(this.state); - } - _cloneInto(to) { - const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to ||= new Keccak2(blockLen, suffix, outputLen, enableXOF, rounds); - to.blockLen = blockLen; - to.state32.set(this.state32); - to.pos = this.pos; - to.posOut = this.posOut; - to.finished = this.finished; - to.rounds = rounds; - to.suffix = suffix; - to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.canXOF = this.canXOF; - to.destroyed = this.destroyed; - return to; - } -} -var _0n2, _1n2, _2n2, _7n2, _256n2, _0x71n2, SHA3_PI2, SHA3_ROTL2, _SHA3_IOTA2, IOTAS2, SHA3_IOTA_H2, SHA3_IOTA_L2, rotlH2 = (h, l, s) => s > 32 ? rotlBH2(h, l, s) : rotlSH2(h, l, s), rotlL2 = (h, l, s) => s > 32 ? rotlBL2(h, l, s) : rotlSL2(h, l, s), genKeccak2 = (suffix, blockLen, outputLen, info = {}) => createHasher2(() => new Keccak2(blockLen, suffix, outputLen), info), sha3_5122; -var init_sha3 = __esm(() => { - init__u64(); - init_utils(); - _0n2 = BigInt(0); - _1n2 = BigInt(1); - _2n2 = BigInt(2); - _7n2 = BigInt(7); - _256n2 = BigInt(256); - _0x71n2 = BigInt(113); - SHA3_PI2 = []; - SHA3_ROTL2 = []; - _SHA3_IOTA2 = []; - for (let round = 0, R = _1n2, x = 1, y = 0;round < 24; round++) { - [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI2.push(2 * (5 * y + x)); - SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64); - let t2 = _0n2; - for (let j = 0;j < 7; j++) { - R = (R << _1n2 ^ (R >> _7n2) * _0x71n2) % _256n2; - if (R & _2n2) - t2 ^= _1n2 << (_1n2 << BigInt(j)) - _1n2; - } - _SHA3_IOTA2.push(t2); - } - IOTAS2 = split3(_SHA3_IOTA2, true); - SHA3_IOTA_H2 = IOTAS2[0]; - SHA3_IOTA_L2 = IOTAS2[1]; - sha3_5122 = /* @__PURE__ */ genKeccak2(6, 72, 64, /* @__PURE__ */ oidNist2(10)); -}); - -// ../db-schema/node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.mjs -function clone3(configObject) { - var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber2(v, b) { - var alphabet2, c, caseChanged, e2, i, isNum, len, str, x = this; - if (!(x instanceof BigNumber2)) - return new BigNumber2(v, b); - if (b == null) { - if (v && v._isBigNumber === true) { - x.s = v.s; - if (!v.c || v.e > MAX_EXP) { - x.c = x.e = null; - } else if (v.e < MIN_EXP) { - x.c = [x.e = 0]; + if (!(c = x.c)) + return null; + n = ((v = c.length - 1) - bitFloor3(this.e / LOG_BASE3)) * LOG_BASE3; + if (v = c[v]) + for (;v % 10 == 0; v /= 10, n--) + ; + if (n < 0) + n = 0; + return n; + }; + P.dividedBy = P.div = function(y, b) { + return div(this, new BigNumber4(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + P.dividedToIntegerBy = P.idiv = function(y, b) { + return div(this, new BigNumber4(y, b), 0, 1); + }; + P.exponentiatedBy = P.pow = function(n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; + n = new BigNumber4(n); + if (n.c && !n.isInteger()) { + throw Error(bignumberError3 + "Exponent not an integer: " + valueOf(n)); + } + if (m != null) + m = new BigNumber4(m); + nIsBig = n.e > 14; + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + y = new BigNumber4(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd3(n)) : +valueOf(n))); + return m ? y.mod(m) : y; + } + nIsNeg = n.s < 0; + if (m) { + if (m.c ? !m.c[0] : !m.s) + return new BigNumber4(NaN); + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + if (isModExp) + x = x.mod(m); + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 240000000 : x.c[0] < 80000000000000 || nIsBig && x.c[0] <= 99999750000000))) { + k = x.s < 0 && isOdd3(n) ? -0 : 0; + if (x.e > -1) + k = 1 / k; + return new BigNumber4(nIsNeg ? 1 / k : k); + } else if (POW_PRECISION) { + k = mathceil3(POW_PRECISION / LOG_BASE3 + 2); + } + if (nIsBig) { + half = new BigNumber4(0.5); + if (nIsNeg) + n.s = 1; + nIsOdd = isOdd3(n); } else { - x.e = v.e; - x.c = v.c.slice(); + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; } - return; - } - if ((isNum = typeof v == "number") && v * 0 == 0) { - x.s = 1 / v < 0 ? (v = -v, -1) : 1; - if (v === ~~v) { - for (e2 = 0, i = v;i >= 10; i /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x.c = x.e = null; + y = new BigNumber4(ONE); + for (;; ) { + if (nIsOdd) { + y = y.times(x); + if (!y.c) + break; + if (k) { + if (y.c.length > k) + y.c.length = k; + } else if (isModExp) { + y = y.mod(m); + } + } + if (i) { + i = mathfloor3(i / 2); + if (i === 0) + break; + nIsOdd = i % 2; } else { - x.e = e2; - x.c = [v]; + n = n.times(half); + round(n, n.e + 1, 1); + if (n.e > 14) { + nIsOdd = isOdd3(n); + } else { + i = +valueOf(n); + if (i === 0) + break; + nIsOdd = i % 2; + } + } + x = x.times(x); + if (k) { + if (x.c && x.c.length > k) + x.c.length = k; + } else if (isModExp) { + x = x.mod(m); } - return; } - str = String(v); - } else { - if (!isNumeric2.test(str = String(v))) - return parseNumeric(x, str, isNum); - x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i; - e2 += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck2(b, 2, ALPHABET.length, "Base"); - if (b == 10 && alphabetHasNormalDecimalDigits) { - x = new BigNumber2(v); - return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); - } - str = String(v); - if (isNum = typeof v == "number") { - if (v * 0 != 0) - return parseNumeric(x, str, isNum, b); - x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits2 + v); + if (isModExp) + return y; + if (nIsNeg) + y = ONE.div(y); + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + P.integerValue = function(rm) { + var n = new BigNumber4(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck3(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + P.isEqualTo = P.eq = function(y, b) { + return compare4(this, new BigNumber4(y, b)) === 0; + }; + P.isFinite = function() { + return !!this.c; + }; + P.isGreaterThan = P.gt = function(y, b) { + return compare4(this, new BigNumber4(y, b)) > 0; + }; + P.isGreaterThanOrEqualTo = P.gte = function(y, b) { + return (b = compare4(this, new BigNumber4(y, b))) === 1 || b === 0; + }; + P.isInteger = function() { + return !!this.c && bitFloor3(this.e / LOG_BASE3) > this.c.length - 2; + }; + P.isLessThan = P.lt = function(y, b) { + return compare4(this, new BigNumber4(y, b)) < 0; + }; + P.isLessThanOrEqualTo = P.lte = function(y, b) { + return (b = compare4(this, new BigNumber4(y, b))) === -1 || b === 0; + }; + P.isNaN = function() { + return !this.s; + }; + P.isNegative = function() { + return this.s < 0; + }; + P.isPositive = function() { + return this.s > 0; + }; + P.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P.minus = function(y, b) { + var i, j, t2, xLTy, x = this, a = x.s; + y = new BigNumber4(y, b); + b = y.s; + if (!a || !b) + return new BigNumber4(NaN); + if (a != b) { + y.s = -b; + return x.plus(y); } - } else { - x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet2 = ALPHABET.slice(0, b); - e2 = i = 0; - for (len = str.length;i < len; i++) { - if (alphabet2.indexOf(c = str.charAt(i)) < 0) { - if (c == ".") { - if (i > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i = -1; - e2 = 0; - continue; - } + var xe = x.e / LOG_BASE3, ye = y.e / LOG_BASE3, xc = x.c, yc = y.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y.s = -b, y) : new BigNumber4(yc ? x : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y.s = -b, y) : new BigNumber4(xc[0] ? x : ROUNDING_MODE == 3 ? -0 : 0); } - return parseNumeric(x, String(v), isNum, b); } - } - isNum = false; - str = convertBase(str, b, 10, x.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i = 0;str.charCodeAt(i) === 48; i++) - ; - for (len = str.length;str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i, ++len)) { - len -= i; - if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER2 || v !== mathfloor2(v))) { - throw Error(tooManyDigits2 + x.s * v); - } - if ((e2 = e2 - i - 1) > MAX_EXP) { - x.c = x.e = null; - } else if (e2 < MIN_EXP) { - x.c = [x.e = 0]; - } else { - x.e = e2; - x.c = []; - i = (e2 + 1) % LOG_BASE2; - if (e2 < 0) - i += LOG_BASE2; - if (i < len) { - if (i) - x.c.push(+str.slice(0, i)); - for (len -= LOG_BASE2;i < len; ) { - x.c.push(+str.slice(i, i += LOG_BASE2)); + xe = bitFloor3(xe); + ye = bitFloor3(ye); + xc = xc.slice(); + if (a = xe - ye) { + if (xLTy = a < 0) { + a = -a; + t2 = xc; + } else { + ye = xe; + t2 = yc; } - i = LOG_BASE2 - (str = str.slice(i)).length; + t2.reverse(); + for (b = a;b--; t2.push(0)) + ; + t2.reverse(); } else { - i -= len; + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + for (a = b = 0;b < j; b++) { + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } } - for (;i--; str += "0") + if (xLTy) { + t2 = xc; + xc = yc; + yc = t2; + y.s = -y.s; + } + b = (j = yc.length) - (i = xc.length); + if (b > 0) + for (;b--; xc[i++] = 0) + ; + b = BASE3 - 1; + for (;j > a; ) { + if (xc[--j] < yc[j]) { + for (i = j;i && !xc[--i]; xc[i] = b) + ; + --xc[i]; + xc[j] += BASE3; + } + xc[j] -= yc[j]; + } + for (;xc[0] == 0; xc.splice(0, 1), --ye) ; - x.c.push(+str); - } - } else { - x.c = [x.e = 0]; - } - } - BigNumber2.clone = clone3; - BigNumber2.ROUND_UP = 0; - BigNumber2.ROUND_DOWN = 1; - BigNumber2.ROUND_CEIL = 2; - BigNumber2.ROUND_FLOOR = 3; - BigNumber2.ROUND_HALF_UP = 4; - BigNumber2.ROUND_HALF_DOWN = 5; - BigNumber2.ROUND_HALF_EVEN = 6; - BigNumber2.ROUND_HALF_CEIL = 7; - BigNumber2.ROUND_HALF_FLOOR = 8; - BigNumber2.EUCLID = 9; - BigNumber2.config = BigNumber2.set = function(obj) { - var p, v; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) { - v = obj[p]; - intCheck2(v, 0, MAX2, p); - DECIMAL_PLACES = v; + if (!xc[0]) { + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; } - if (obj.hasOwnProperty(p = "ROUNDING_MODE")) { - v = obj[p]; - intCheck2(v, 0, 8, p); - ROUNDING_MODE = v; + return normalise(y, xc, ye); + }; + P.modulo = P.mod = function(y, b) { + var q, s, x = this; + y = new BigNumber4(y, b); + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber4(NaN); + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber4(x); } - if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) { - v = obj[p]; - if (v && v.pop) { - intCheck2(v[0], -MAX2, 0, p); - intCheck2(v[1], 0, MAX2, p); - TO_EXP_NEG = v[0]; - TO_EXP_POS = v[1]; - } else { - intCheck2(v, -MAX2, MAX2, p); - TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); - } + if (MODULO_MODE == 9) { + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); } - if (obj.hasOwnProperty(p = "RANGE")) { - v = obj[p]; - if (v && v.pop) { - intCheck2(v[0], -MAX2, -1, p); - intCheck2(v[1], 1, MAX2, p); - MIN_EXP = v[0]; - MAX_EXP = v[1]; + y = x.minus(q.times(y)); + if (!y.c[0] && MODULO_MODE == 1) + y.s = x.s; + return y; + }; + P.multipliedBy = P.times = function(y, b) { + var c, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber4(y, b)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; } else { - intCheck2(v, -MAX2, MAX2, p); - if (v) { - MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + y.s *= x.s; + if (!xc || !yc) { + y.c = y.e = null; } else { - throw Error(bignumberError2 + p + " cannot be zero: " + v); + y.c = [0]; + y.e = 0; } } + return y; } - if (obj.hasOwnProperty(p = "CRYPTO")) { - v = obj[p]; - if (v === !!v) { - if (v) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v; - } else { - CRYPTO = !v; - throw Error(bignumberError2 + "crypto unavailable"); - } - } else { - CRYPTO = v; - } + e2 = bitFloor3(x.e / LOG_BASE3) + bitFloor3(y.e / LOG_BASE3); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; + } + for (i = xcL + ycL, zc = [];i--; zc.push(0)) + ; + base = BASE3; + sqrtBase = SQRT_BASE3; + for (i = ycL;--i >= 0; ) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + for (k = xcL, j = i + k;j > i; ) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + zc[j] = c; + } + if (c) { + ++e2; + } else { + zc.splice(0, 1); + } + return normalise(y, zc, e2); + }; + P.negated = function() { + var x = new BigNumber4(this); + x.s = -x.s || null; + return x; + }; + P.plus = function(y, b) { + var t2, x = this, a = x.s; + y = new BigNumber4(y, b); + b = y.s; + if (!a || !b) + return new BigNumber4(NaN); + if (a != b) { + y.s = -b; + return x.minus(y); + } + var xe = x.e / LOG_BASE3, ye = y.e / LOG_BASE3, xc = x.c, yc = y.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber4(a / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y : new BigNumber4(xc[0] ? x : a * 0); + } + xe = bitFloor3(xe); + ye = bitFloor3(ye); + xc = xc.slice(); + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t2 = yc; } else { - throw Error(bignumberError2 + p + " not true or false: " + v); + a = -a; + t2 = xc; } + t2.reverse(); + for (;a--; t2.push(0)) + ; + t2.reverse(); } - if (obj.hasOwnProperty(p = "MODULO_MODE")) { - v = obj[p]; - intCheck2(v, 0, 9, p); - MODULO_MODE = v; + a = xc.length; + b = yc.length; + if (a - b < 0) { + t2 = yc; + yc = xc; + xc = t2; + b = a; } - if (obj.hasOwnProperty(p = "POW_PRECISION")) { - v = obj[p]; - intCheck2(v, 0, MAX2, p); - POW_PRECISION = v; + for (a = 0;b; ) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE3 | 0; + xc[b] = BASE3 === xc[b] ? 0 : xc[b] % BASE3; } - if (obj.hasOwnProperty(p = "FORMAT")) { - v = obj[p]; - if (typeof v == "object") - FORMAT = v; + if (a) { + xc = [a].concat(xc); + ++ye; + } + return normalise(y, xc, ye); + }; + P.precision = P.sd = function(sd, rm) { + var c, n, v, x = this; + if (sd != null && sd !== !!sd) { + intCheck3(sd, 1, MAX3); + if (rm == null) + rm = ROUNDING_MODE; else - throw Error(bignumberError2 + p + " not an object: " + v); + intCheck3(rm, 0, 8); + return round(new BigNumber4(x), sd, rm); } - if (obj.hasOwnProperty(p = "ALPHABET")) { - v = obj[p]; - if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { - alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; - ALPHABET = v; + if (!(c = x.c)) + return null; + v = c.length - 1; + n = v * LOG_BASE3 + 1; + if (v = c[v]) { + for (;v % 10 == 0; v /= 10, n--) + ; + for (v = c[0];v >= 10; v /= 10, n++) + ; + } + if (sd && x.e + 1 > n) + n = x.e + 1; + return n; + }; + P.shiftedBy = function(k) { + intCheck3(k, -MAX_SAFE_INTEGER3, MAX_SAFE_INTEGER3); + return this.times("1e" + k); + }; + P.squareRoot = P.sqrt = function() { + var m, n, r, rep, t2, x = this, c = x.c, s = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber4("0.5"); + if (s !== 1 || !c || !c[0]) { + return new BigNumber4(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + s = Math.sqrt(+valueOf(x)); + if (s == 0 || s == 1 / 0) { + n = coeffToString3(c); + if ((n.length + e2) % 2 == 0) + n += "0"; + s = Math.sqrt(+n); + e2 = bitFloor3((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s == 1 / 0) { + n = "5e" + e2; } else { - throw Error(bignumberError2 + p + " invalid: " + v); + n = s.toExponential(); + n = n.slice(0, n.indexOf("e") + 1) + e2; } + r = new BigNumber4(n); + } else { + r = new BigNumber4(s + ""); } - } else { - throw Error(bignumberError2 + "Object expected: " + obj); - } - } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber2.isBigNumber = function(v) { - if (!v || v._isBigNumber !== true) - return false; - if (!BigNumber2.DEBUG) - return true; - var i, n, c = v.c, e2 = v.e, s = v.s; - out: - if ({}.toString.call(c) == "[object Array]") { - if ((s === 1 || s === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { - if (c[0] === 0) { - if (e2 === 0 && c.length === 1) - return true; - break out; - } - i = (e2 + 1) % LOG_BASE2; - if (i < 1) - i += LOG_BASE2; - if (String(c[0]).length == i) { - for (i = 0;i < c.length; i++) { - n = c[i]; - if (n < 0 || n >= BASE2 || n !== mathfloor2(n)) - break out; + if (r.c[0]) { + e2 = r.e; + s = e2 + dp; + if (s < 3) + s = 0; + for (;; ) { + t2 = r; + r = half.times(t2.plus(div(x, t2, dp, 1))); + if (coeffToString3(t2.c).slice(0, s) === (n = coeffToString3(r.c)).slice(0, s)) { + if (r.e < e2) + --s; + n = n.slice(s - 3, s + 1); + if (n == "9999" || !rep && n == "4999") { + if (!rep) { + round(t2, t2.e + DECIMAL_PLACES + 2, 0); + if (t2.times(t2).eq(x)) { + r = t2; + break; + } + } + dp += 4; + s += 4; + rep = 1; + } else { + if (!+n || !+n.slice(1) && n.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + break; + } } - if (n !== 0) - return true; } } - } else if (c === null && e2 === null && (s === null || s === 1 || s === -1)) { - return true; - } - throw Error(bignumberError2 + "Invalid BigNumber: " + v); - }; - BigNumber2.maximum = BigNumber2.max = function() { - return maxOrMin(arguments, -1); - }; - BigNumber2.minimum = BigNumber2.min = function() { - return maxOrMin(arguments, 1); - }; - BigNumber2.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor2(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a, b, e2, k, v, i = 0, c = [], rand = new BigNumber2(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck2(dp, 0, MAX2); - k = mathceil2(dp / LOG_BASE2); - if (CRYPTO) { - if (crypto.getRandomValues) { - a = crypto.getRandomValues(new Uint32Array(k *= 2)); - for (;i < k; ) { - v = a[i] * 131072 + (a[i + 1] >>> 11); - if (v >= 9000000000000000) { - b = crypto.getRandomValues(new Uint32Array(2)); - a[i] = b[0]; - a[i + 1] = b[1]; - } else { - c.push(v % 100000000000000); - i += 2; - } - } - i = k / 2; - } else if (crypto.randomBytes) { - a = crypto.randomBytes(k *= 7); - for (;i < k; ) { - v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; - if (v >= 9000000000000000) { - crypto.randomBytes(7).copy(a, i); - } else { - c.push(v % 100000000000000); - i += 7; - } + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + P.toExponential = function(dp, rm) { + if (dp != null) { + intCheck3(dp, 0, MAX3); + dp++; + } + return format(this, dp, rm, 1); + }; + P.toFixed = function(dp, rm) { + if (dp != null) { + intCheck3(dp, 0, MAX3); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + P.toFormat = function(dp, rm, format2) { + var str, x = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; } - i = k / 7; - } else { - CRYPTO = false; - throw Error(bignumberError2 + "crypto unavailable"); + } else if (typeof format2 != "object") { + throw Error(bignumberError3 + "Argument not an object: " + format2); } - } - if (!CRYPTO) { - for (;i < k; ) { - v = random53bitInt(); - if (v < 9000000000000000) - c[i++] = v % 100000000000000; + str = x.toFixed(dp, rm); + if (x.c) { + var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (;i < len; i += g1) + intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) + intPart += groupSeparator + intDigits.slice(i); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(new RegExp("\\d{" + g2 + "}\\B", "g"), "$&" + (format2.fractionGroupSeparator || "")) : fractionPart) : intPart; } - } - k = c[--i]; - dp %= LOG_BASE2; - if (k && dp) { - v = POWS_TEN2[LOG_BASE2 - dp]; - c[i] = mathfloor2(k / v) * v; - } - for (;c[i] === 0; c.pop(), i--) - ; - if (i < 0) { - c = [e2 = 0]; - } else { - for (e2 = -1;c[0] === 0; c.splice(0, 1), e2 -= LOG_BASE2) - ; - for (i = 1, v = c[0];v >= 10; v /= 10, i++) - ; - if (i < LOG_BASE2) - e2 -= LOG_BASE2 - i; - } - rand.e = e2; - rand.c = c; - return rand; - }; - }(); - BigNumber2.sum = function() { - var i = 1, args = arguments, sum = new BigNumber2(args[0]); - for (;i < args.length; ) - sum = sum.plus(args[i++]); - return sum; - }; - convertBase = function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet2) { - var j, arr = [0], arrL, i = 0, len = str.length; - for (;i < len; ) { - for (arrL = arr.length;arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet2.indexOf(str.charAt(i++)); - for (j = 0;j < arr.length; j++) { - if (arr[j] > baseOut - 1) { - if (arr[j + 1] == null) - arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; + return (format2.prefix || "") + str + (format2.suffix || ""); + }; + P.toFraction = function(md) { + var d, d0, d1, d2, e2, exp, n, n0, n1, q, r, s, x = this, xc = x.c; + if (md != null) { + n = new BigNumber4(md); + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error(bignumberError3 + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); } } - } - return arr.reverse(); - } - return function(str, baseIn, baseOut, sign, callerIsToString) { - var alphabet2, d, e2, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i >= 0) { - k = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y = new BigNumber2(baseIn); - x = y.pow(str.length - i); - POW_PRECISION = k; - y.c = toBaseOut(toFixedPoint2(coeffToString2(x.c), x.e, "0"), 10, baseOut, decimal); - y.e = y.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); - e2 = k = xc.length; - for (;xc[--k] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet2.charAt(0); - if (i < 0) { - --e2; - } else { - x.c = xc; - x.e = e2; - x.s = sign; - x = div(x, y, dp, rm, baseOut); - xc = x.c; - r = x.r; - e2 = x.e; - } - d = e2 + dp + 1; - i = xc[d]; - k = baseOut / 2; - r = r || d < 0 || xc[d + 1] != null; - r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); - if (d < 1 || !xc[0]) { - str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); - } else { - xc.length = d; - if (r) { - for (--baseOut;++xc[--d] > baseOut; ) { - xc[d] = 0; - if (!d) { - ++e2; - xc = [1].concat(xc); - } + if (!xc) + return new BigNumber4(x); + d = new BigNumber4(ONE); + n1 = d0 = new BigNumber4(ONE); + d1 = n0 = new BigNumber4(ONE); + s = coeffToString3(xc); + e2 = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN3[(exp = e2 % LOG_BASE3) < 0 ? LOG_BASE3 + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber4(s); + n0.c[0] = 0; + for (;; ) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x).abs().comparedTo(div(n0, d0, e2, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P.toNumber = function() { + return +valueOf(this); + }; + P.toPrecision = function(sd, rm) { + if (sd != null) + intCheck3(sd, 1, MAX3); + return format(this, sd, rm, 2); + }; + P.toString = function(b) { + var str, n = this, s = n.s, e2 = n.e; + if (e2 === null) { + if (s) { + str = "Infinity"; + if (s < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential3(coeffToString3(n.c), e2) : toFixedPoint3(coeffToString3(n.c), e2, "0"); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber4(n), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint3(coeffToString3(n.c), n.e, "0"); + } else { + intCheck3(b, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint3(coeffToString3(n.c), e2, "0"), 10, b, s, true); } + if (s < 0 && n.c[0]) + str = "-" + str; } - for (k = xc.length;!xc[--k]; ) - ; - for (i = 0, str = "";i <= k; str += alphabet2.charAt(xc[i++])) + return str; + }; + P.valueOf = P.toJSON = function() { + return valueOf(this); + }; + P._isBigNumber = true; + if (configObject != null) + BigNumber4.set(configObject); + return BigNumber4; + } + function bitFloor3(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + function coeffToString3(a) { + var s, z, i = 1, j = a.length, r = a[0] + ""; + for (;i < j; ) { + s = a[i++] + ""; + z = LOG_BASE3 - s.length; + for (;z--; s = "0" + s) ; - str = toFixedPoint2(str, e2, alphabet2.charAt(0)); + r += s; } - return str; - }; - }(); - div = function() { - function multiply(x, k, base) { - var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE2, khi = k / SQRT_BASE2 | 0; - for (x = x.slice();i--; ) { - xlo = x[i] % SQRT_BASE2; - xhi = x[i] / SQRT_BASE2 | 0; - m = khi * xlo + xhi * klo; - temp = klo * xlo + m % SQRT_BASE2 * SQRT_BASE2 + carry; - carry = (temp / base | 0) + (m / SQRT_BASE2 | 0) + khi * xhi; - x[i] = temp % base; + for (j = r.length;r.charCodeAt(--j) === 48; ) + ; + return r.slice(0, j + 1 || 1); + } + function compare4(x, y) { + var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; + if (!i || !j) + return null; + a = xc && !xc[0]; + b = yc && !yc[0]; + if (a || b) + return a ? b ? 0 : -j : i; + if (i != j) + return i; + a = i < 0; + b = k == l; + if (!xc || !yc) + return b ? 0 : !xc ^ a ? 1 : -1; + if (!b) + return k > l ^ a ? 1 : -1; + j = (k = xc.length) < (l = yc.length) ? k : l; + for (i = 0;i < j; i++) + if (xc[i] != yc[i]) + return xc[i] > yc[i] ^ a ? 1 : -1; + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + function intCheck3(n, min, max, name) { + if (n < min || n > max || n !== mathfloor3(n)) { + throw Error(bignumberError3 + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); } - if (carry) - x = [carry].concat(x); - return x; } - function compare2(a, b, aL, bL) { - var i, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; + function isOdd3(n) { + var k = n.c.length - 1; + return bitFloor3(n.e / LOG_BASE3) == k && n.c[k] % 2 != 0; + } + function toExponential3(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + function toFixedPoint3(str, e2, z) { + var len, zs; + if (e2 < 0) { + for (zs = z + ".";++e2; zs += z) + ; + str = zs + str; } else { - for (i = cmp = 0;i < aL; i++) { - if (a[i] != b[i]) { - cmp = a[i] > b[i] ? 1 : -1; - break; - } + len = str.length; + if (++e2 > len) { + for (zs = z, e2 -= len;--e2; zs += z) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); } } - return cmp; + return str; } - function subtract(a, b, aL, base) { - var i = 0; - for (;aL--; ) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; + BigNumber3 = clone4(); + BigNumber3["default"] = BigNumber3.BigNumber = BigNumber3; + if (typeof define == "function" && define.amd) { + define(function() { + return BigNumber3; + }); + } else if (typeof module != "undefined" && module.exports) { + module.exports = BigNumber3; + } else { + if (!globalObject) { + globalObject = typeof self != "undefined" && self ? self : window; } - for (;!a[0] && a.length > 1; a.splice(0, 1)) - ; + globalObject.BigNumber = BigNumber3; } - return function(x, y, dp, rm, base) { - var cmp, e2, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber2(!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s * 0 : s / 0); + })(exports); +}); + +// node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/stringify.js +var require_stringify2 = __commonJS((exports, module) => { + var BigNumber3 = require_bignumber(); + var JSON2 = exports; + (function() { + function f(n) { + return n < 10 ? "0" + n : n; + } + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { + "\b": "\\b", + "\t": "\\t", + "\n": "\\n", + "\f": "\\f", + "\r": "\\r", + '"': "\\\"", + "\\": "\\\\" + }, rep; + function quote(string2) { + escapable.lastIndex = 0; + return escapable.test(string2) ? '"' + string2.replace(escapable, function(a) { + var c = meta[a]; + return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string2 + '"'; + } + function str(key, holder) { + var i, k, v, length, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber3 || BigNumber3.isBigNumber(value)); + if (value && typeof value === "object" && typeof value.toJSON === "function") { + value = value.toJSON(key); } - q = new BigNumber2(s); - qc = q.c = []; - e2 = x.e - y.e; - s = dp + e2 + 1; - if (!base) { - base = BASE2; - e2 = bitFloor2(x.e / LOG_BASE2) - bitFloor2(y.e / LOG_BASE2); - s = s / LOG_BASE2 | 0; + if (typeof rep === "function") { + value = rep.call(holder, key, value); } - for (i = 0;yc[i] == (xc[i] || 0); i++) - ; - if (yc[i] > (xc[i] || 0)) - e2--; - if (s < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i = 0; - s += 2; - n = mathfloor2(base / (yc[0] + 1)); - if (n > 1) { - yc = multiply(yc, n, base); - xc = multiply(xc, n, base); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (;remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base / 2) - yc0++; - do { - n = 0; - cmp = compare2(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base + (rem[1] || 0); - n = mathfloor2(rem0 / yc0); - if (n > 1) { - if (n >= base) - n = base - 1; - prod = multiply(yc, n, base); - prodL = prod.length; - remL = rem.length; - while (compare2(prod, rem, prodL, remL) == 1) { - n--; - subtract(prod, yL < prodL ? yz : yc, prodL, base); - prodL = prod.length; - cmp = 1; - } - } else { - if (n == 0) { - cmp = n = 1; - } - prod = yc.slice(); - prodL = prod.length; + switch (typeof value) { + case "string": + if (isBigNumber) { + return value; + } else { + return quote(value); + } + case "number": + return isFinite(value) ? String(value) : "null"; + case "boolean": + case "null": + case "bigint": + return String(value); + case "object": + if (!value) { + return "null"; + } + gap += indent; + partial = []; + if (Object.prototype.toString.apply(value) === "[object Array]") { + length = value.length; + for (i = 0;i < length; i += 1) { + partial[i] = str(i, value) || "null"; } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base); - remL = rem.length; - if (cmp == -1) { - while (compare2(yc, rem, yL, remL) < 1) { - n++; - subtract(rem, yL < remL ? yz : yc, remL, base); - remL = rem.length; + v = partial.length === 0 ? "[]" : gap ? `[ +` + gap + partial.join(`, +` + gap) + ` +` + mind + "]" : "[" + partial.join(",") + "]"; + gap = mind; + return v; + } + if (rep && typeof rep === "object") { + length = rep.length; + for (i = 0;i < length; i += 1) { + if (typeof rep[i] === "string") { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ": " : ":") + v); + } } } - } else if (cmp === 0) { - n++; - rem = [0]; - } - qc[i++] = n; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; } else { - rem = [xc[xi]]; - remL = 1; + Object.keys(value).forEach(function(k2) { + var v2 = str(k2, value); + if (v2) { + partial.push(quote(k2) + (gap ? ": " : ":") + v2); + } + }); } - } while ((xi++ < xL || rem[0] != null) && s--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base == BASE2) { - for (i = 1, s = qc[0];s >= 10; s /= 10, i++) - ; - round(q, dp + (q.e = i + e2 * LOG_BASE2 - 1) + 1, rm, more); - } else { - q.e = e2; - q.r = +more; + v = partial.length === 0 ? "{}" : gap ? `{ +` + gap + partial.join(`, +` + gap) + ` +` + mind + "}" : "{" + partial.join(",") + "}"; + gap = mind; + return v; } - return q; + } + if (typeof JSON2.stringify !== "function") { + JSON2.stringify = function(value, replacer, space) { + var i; + gap = ""; + indent = ""; + if (typeof space === "number") { + for (i = 0;i < space; i += 1) { + indent += " "; + } + } else if (typeof space === "string") { + indent = space; + } + rep = replacer; + if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { + throw new Error("JSON.stringify"); + } + return str("", { "": value }); + }; + } + })(); +}); + +// node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/parse.js +var require_parse3 = __commonJS((exports, module) => { + var BigNumber3 = null; + var suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; + var suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; + var json_parse = function(options) { + var _options = { + strict: false, + storeAsString: false, + alwaysParseAsBig: false, + useNativeBigInt: false, + protoAction: "error", + constructorAction: "error" }; - }(); - function format(n, i, rm, id) { - var c0, e2, ne2, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - if (!n.c) - return n.toString(); - c0 = n.c[0]; - ne2 = n.e; - if (i == null) { - str = coeffToString2(n.c); - str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential2(str, ne2) : toFixedPoint2(str, ne2, "0"); - } else { - n = round(new BigNumber2(n), i, rm); - e2 = n.e; - str = coeffToString2(n.c); - len = str.length; - if (id == 1 || id == 2 && (i <= e2 || e2 <= TO_EXP_NEG)) { - for (;len < i; str += "0", len++) - ; - str = toExponential2(str, e2); - } else { - i -= ne2 + (id === 2 && e2 > ne2); - str = toFixedPoint2(str, e2, "0"); - if (e2 + 1 > len) { - if (--i > 0) - for (str += ".";i--; str += "0") - ; + if (options !== undefined && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; + _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; + if (typeof options.constructorAction !== "undefined") { + if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { + _options.constructorAction = options.constructorAction; } else { - i += e2 - len; - if (i > 0) { - if (e2 + 1 == len) - str += "."; - for (;i--; str += "0") - ; - } + throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`); } } - } - return n.s < 0 && c0 ? "-" + str : str; - } - function maxOrMin(args, n) { - var k, y, i = 1, x = new BigNumber2(args[0]); - for (;i < args.length; i++) { - y = new BigNumber2(args[i]); - if (!y.s || (k = compare2(x, y)) === n || k === 0 && x.s === n) { - x = y; + if (typeof options.protoAction !== "undefined") { + if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { + _options.protoAction = options.protoAction; + } else { + throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`); + } } } - return x; - } - function normalise(n, c, e2) { - var i = 1, j = c.length; - for (;!c[--j]; c.pop()) - ; - for (j = c[0];j >= 10; j /= 10, i++) - ; - if ((e2 = i + e2 * LOG_BASE2 - 1) > MAX_EXP) { - n.c = n.e = null; - } else if (e2 < MIN_EXP) { - n.c = [n.e = 0]; - } else { - n.e = e2; - n.c = c; - } - return n; - } - parseNumeric = function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x, str, isNum, b) { - var base, s = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s)) { - x.s = isNaN(s) ? null : s < 0 ? -1 : 1; - } else { - if (!isNum) { - s = s.replace(basePrefix, function(m, p1, p2) { - base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; - return !b || b == base ? p1 : m; - }); - if (b) { - base = b; - s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s) - return new BigNumber2(s, base); + var at, ch, escapee = { + '"': '"', + "\\": "\\", + "/": "/", + b: "\b", + f: "\f", + n: ` +`, + r: "\r", + t: "\t" + }, text3, error = function(m) { + throw { + name: "SyntaxError", + message: m, + at, + text: text3 + }; + }, next = function(c) { + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + ch = text3.charAt(at); + at += 1; + return ch; + }, number2 = function() { + var number3, string3 = ""; + if (ch === "-") { + string3 = "-"; + next("-"); + } + while (ch >= "0" && ch <= "9") { + string3 += ch; + next(); + } + if (ch === ".") { + string3 += "."; + while (next() && ch >= "0" && ch <= "9") { + string3 += ch; } - if (BigNumber2.DEBUG) { - throw Error(bignumberError2 + "Not a" + (b ? " base " + b : "") + " number: " + str); + } + if (ch === "e" || ch === "E") { + string3 += ch; + next(); + if (ch === "-" || ch === "+") { + string3 += ch; + next(); + } + while (ch >= "0" && ch <= "9") { + string3 += ch; + next(); } - x.s = null; } - x.c = x.e = null; - }; - }(); - function round(x, sd, rm, r) { - var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN2; - if (xc) { - out: { - for (d = 1, k = xc[0];k >= 10; k /= 10, d++) - ; - i = sd - d; - if (i < 0) { - i += LOG_BASE2; - j = sd; - n = xc[ni = 0]; - rd = mathfloor2(n / pows10[d - j - 1] % 10); - } else { - ni = mathceil2((i + 1) / LOG_BASE2); - if (ni >= xc.length) { - if (r) { - for (;xc.length <= ni; xc.push(0)) - ; - n = rd = 0; - d = 1; - i %= LOG_BASE2; - j = i - LOG_BASE2 + 1; + number3 = +string3; + if (!isFinite(number3)) { + error("Bad number"); + } else { + if (BigNumber3 == null) + BigNumber3 = require_bignumber(); + if (string3.length > 15) + return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber3(string3); + else + return !_options.alwaysParseAsBig ? number3 : _options.useNativeBigInt ? BigInt(number3) : new BigNumber3(number3); + } + }, string2 = function() { + var hex, i, string3 = "", uffff; + if (ch === '"') { + var startAt = at; + while (next()) { + if (ch === '"') { + if (at - 1 > startAt) + string3 += text3.substring(startAt, at - 1); + next(); + return string3; + } + if (ch === "\\") { + if (at - 1 > startAt) + string3 += text3.substring(startAt, at - 1); + next(); + if (ch === "u") { + uffff = 0; + for (i = 0;i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string3 += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === "string") { + string3 += escapee[ch]; } else { - break out; + break; } - } else { - n = k = xc[ni]; - for (d = 1;k >= 10; k /= 10, d++) - ; - i %= LOG_BASE2; - j = i - LOG_BASE2 + d; - rd = j < 0 ? 0 : mathfloor2(n / pows10[d - j - 1] % 10); + startAt = at; } } - r = r || sd < 0 || xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x.e + 1; - xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; - x.e = -sd || 0; - } else { - xc[0] = x.e = 0; + } + error("Bad string"); + }, white = function() { + while (ch && ch <= " ") { + next(); + } + }, word = function() { + switch (ch) { + case "t": + next("t"); + next("r"); + next("u"); + next("e"); + return true; + case "f": + next("f"); + next("a"); + next("l"); + next("s"); + next("e"); + return false; + case "n": + next("n"); + next("u"); + next("l"); + next("l"); + return null; + } + error("Unexpected '" + ch + "'"); + }, value, array2 = function() { + var array3 = []; + if (ch === "[") { + next("["); + white(); + if (ch === "]") { + next("]"); + return array3; + } + while (ch) { + array3.push(value()); + white(); + if (ch === "]") { + next("]"); + return array3; } - return x; + next(","); + white(); } - if (i == 0) { - xc.length = ni; - k = 1; - ni--; - } else { - xc.length = ni + 1; - k = pows10[LOG_BASE2 - i]; - xc[ni] = j > 0 ? mathfloor2(n / pows10[d - j] % pows10[j]) * k : 0; + } + error("Bad array"); + }, object2 = function() { + var key, object3 = Object.create(null); + if (ch === "{") { + next("{"); + white(); + if (ch === "}") { + next("}"); + return object3; } - if (r) { - for (;; ) { - if (ni == 0) { - for (i = 1, j = xc[0];j >= 10; j /= 10, i++) - ; - j = xc[0] += k; - for (k = 1;j >= 10; j /= 10, k++) - ; - if (i != k) { - x.e++; - if (xc[0] == BASE2) - xc[0] = 1; - } - break; + while (ch) { + key = string2(); + white(); + next(":"); + if (_options.strict === true && Object.hasOwnProperty.call(object3, key)) { + error('Duplicate key "' + key + '"'); + } + if (suspectProtoRx.test(key) === true) { + if (_options.protoAction === "error") { + error("Object contains forbidden prototype property"); + } else if (_options.protoAction === "ignore") { + value(); } else { - xc[ni] += k; - if (xc[ni] != BASE2) - break; - xc[ni--] = 0; - k = 1; + object3[key] = value(); } + } else if (suspectConstructorRx.test(key) === true) { + if (_options.constructorAction === "error") { + error("Object contains forbidden constructor property"); + } else if (_options.constructorAction === "ignore") { + value(); + } else { + object3[key] = value(); + } + } else { + object3[key] = value(); + } + white(); + if (ch === "}") { + next("}"); + return object3; } + next(","); + white(); } - for (i = xc.length;xc[--i] === 0; xc.pop()) - ; } - if (x.e > MAX_EXP) { - x.c = x.e = null; - } else if (x.e < MIN_EXP) { - x.c = [x.e = 0]; + error("Bad object"); + }; + value = function() { + white(); + switch (ch) { + case "{": + return object2(); + case "[": + return array2(); + case '"': + return string2(); + case "-": + return number2(); + default: + return ch >= "0" && ch <= "9" ? number2() : word(); } - } - return x; - } - function valueOf(n) { - var str, e2 = n.e; - if (e2 === null) - return n.toString(); - str = coeffToString2(n.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); - return n.s < 0 ? "-" + str : str; - } - P.absoluteValue = P.abs = function() { - var x = new BigNumber2(this); - if (x.s < 0) - x.s = 1; - return x; - }; - P.comparedTo = function(y, b) { - return compare2(this, new BigNumber2(y, b)); - }; - P.decimalPlaces = P.dp = function(dp, rm) { - var c, n, v, x = this; - if (dp != null) { - intCheck2(dp, 0, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber2(x), dp + x.e + 1, rm); - } - if (!(c = x.c)) - return null; - n = ((v = c.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; - if (v = c[v]) - for (;v % 10 == 0; v /= 10, n--) - ; - if (n < 0) - n = 0; - return n; - }; - P.dividedBy = P.div = function(y, b) { - return div(this, new BigNumber2(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + return function(source, reviver) { + var result; + text3 = source + ""; + at = 0; + ch = " "; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + return typeof reviver === "function" ? function walk(holder, key) { + var k, v, value2 = holder[key]; + if (value2 && typeof value2 === "object") { + Object.keys(value2).forEach(function(k2) { + v = walk(value2, k2); + if (v !== undefined) { + value2[k2] = v; + } else { + delete value2[k2]; + } + }); + } + return reviver.call(holder, key, value2); + }({ "": result }, "") : result; + }; }; - P.dividedToIntegerBy = P.idiv = function(y, b) { - return div(this, new BigNumber2(y, b), 0, 1); + module.exports = json_parse; +}); + +// node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/index.js +var require_json_bigint = __commonJS((exports, module) => { + var json_stringify = require_stringify2().stringify; + var json_parse = require_parse3(); + module.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + }; }; - P.exponentiatedBy = P.pow = function(n, m) { - var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; - n = new BigNumber2(n); - if (n.c && !n.isInteger()) { - throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n)); - } - if (m != null) - m = new BigNumber2(m); - nIsBig = n.e > 14; - if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - y = new BigNumber2(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd2(n)) : +valueOf(n))); - return m ? y.mod(m) : y; - } - nIsNeg = n.s < 0; - if (m) { - if (m.c ? !m.c[0] : !m.s) - return new BigNumber2(NaN); - isModExp = !nIsNeg && x.isInteger() && m.isInteger(); - if (isModExp) - x = x.mod(m); - } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 240000000 : x.c[0] < 80000000000000 || nIsBig && x.c[0] <= 99999750000000))) { - k = x.s < 0 && isOdd2(n) ? -0 : 0; - if (x.e > -1) - k = 1 / k; - return new BigNumber2(nIsNeg ? 1 / k : k); - } else if (POW_PRECISION) { - k = mathceil2(POW_PRECISION / LOG_BASE2 + 2); - } - if (nIsBig) { - half = new BigNumber2(0.5); - if (nIsNeg) - n.s = 1; - nIsOdd = isOdd2(n); - } else { - i = Math.abs(+valueOf(n)); - nIsOdd = i % 2; - } - y = new BigNumber2(ONE); - for (;; ) { - if (nIsOdd) { - y = y.times(x); - if (!y.c) - break; - if (k) { - if (y.c.length > k) - y.c.length = k; - } else if (isModExp) { - y = y.mod(m); - } - } - if (i) { - i = mathfloor2(i / 2); - if (i === 0) - break; - nIsOdd = i % 2; - } else { - n = n.times(half); - round(n, n.e + 1, 1); - if (n.e > 14) { - nIsOdd = isOdd2(n); - } else { - i = +valueOf(n); - if (i === 0) - break; - nIsOdd = i % 2; - } - } - x = x.times(x); - if (k) { - if (x.c && x.c.length > k) - x.c.length = k; - } else if (isModExp) { - x = x.mod(m); - } - } - if (isModExp) - return y; - if (nIsNeg) - y = ONE.div(y); - return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; - }; - P.integerValue = function(rm) { - var n = new BigNumber2(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(n, n.e + 1, rm); - }; - P.isEqualTo = P.eq = function(y, b) { - return compare2(this, new BigNumber2(y, b)) === 0; - }; - P.isFinite = function() { - return !!this.c; - }; - P.isGreaterThan = P.gt = function(y, b) { - return compare2(this, new BigNumber2(y, b)) > 0; - }; - P.isGreaterThanOrEqualTo = P.gte = function(y, b) { - return (b = compare2(this, new BigNumber2(y, b))) === 1 || b === 0; - }; - P.isInteger = function() { - return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; - }; - P.isLessThan = P.lt = function(y, b) { - return compare2(this, new BigNumber2(y, b)) < 0; - }; - P.isLessThanOrEqualTo = P.lte = function(y, b) { - return (b = compare2(this, new BigNumber2(y, b))) === -1 || b === 0; - }; - P.isNaN = function() { - return !this.s; - }; - P.isNegative = function() { - return this.s < 0; - }; - P.isPositive = function() { - return this.s > 0; - }; - P.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P.minus = function(y, b) { - var i, j, t2, xLTy, x = this, a = x.s; - y = new BigNumber2(y, b); - b = y.s; - if (!a || !b) - return new BigNumber2(NaN); - if (a != b) { - y.s = -b; - return x.plus(y); - } - var xe = x.e / LOG_BASE2, ye = y.e / LOG_BASE2, xc = x.c, yc = y.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y.s = -b, y) : new BigNumber2(yc ? x : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y.s = -b, y) : new BigNumber2(xc[0] ? x : ROUNDING_MODE == 3 ? -0 : 0); - } - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a = xe - ye) { - if (xLTy = a < 0) { - a = -a; - t2 = xc; - } else { - ye = xe; - t2 = yc; - } - t2.reverse(); - for (b = a;b--; t2.push(0)) - ; - t2.reverse(); - } else { - j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; - for (a = b = 0;b < j; b++) { - if (xc[b] != yc[b]) { - xLTy = xc[b] < yc[b]; - break; - } - } - } - if (xLTy) { - t2 = xc; - xc = yc; - yc = t2; - y.s = -y.s; - } - b = (j = yc.length) - (i = xc.length); - if (b > 0) - for (;b--; xc[i++] = 0) - ; - b = BASE2 - 1; - for (;j > a; ) { - if (xc[--j] < yc[j]) { - for (i = j;i && !xc[--i]; xc[i] = b) - ; - --xc[i]; - xc[j] += BASE2; - } - xc[j] -= yc[j]; - } - for (;xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y.s = ROUNDING_MODE == 3 ? -1 : 1; - y.c = [y.e = 0]; - return y; - } - return normalise(y, xc, ye); - }; - P.modulo = P.mod = function(y, b) { - var q, s, x = this; - y = new BigNumber2(y, b); - if (!x.c || !y.s || y.c && !y.c[0]) { - return new BigNumber2(NaN); - } else if (!y.c || x.c && !x.c[0]) { - return new BigNumber2(x); - } - if (MODULO_MODE == 9) { - s = y.s; - y.s = 1; - q = div(x, y, 0, 3); - y.s = s; - q.s *= s; - } else { - q = div(x, y, 0, MODULO_MODE); - } - y = x.minus(q.times(y)); - if (!y.c[0] && MODULO_MODE == 1) - y.s = x.s; - return y; - }; - P.multipliedBy = P.times = function(y, b) { - var c, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber2(y, b)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y.c = y.e = y.s = null; - } else { - y.s *= x.s; - if (!xc || !yc) { - y.c = y.e = null; - } else { - y.c = [0]; - y.e = 0; - } - } - return y; - } - e2 = bitFloor2(x.e / LOG_BASE2) + bitFloor2(y.e / LOG_BASE2); - y.s *= x.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) { - zc = xc; - xc = yc; - yc = zc; - i = xcL; - xcL = ycL; - ycL = i; - } - for (i = xcL + ycL, zc = [];i--; zc.push(0)) - ; - base = BASE2; - sqrtBase = SQRT_BASE2; - for (i = ycL;--i >= 0; ) { - c = 0; - ylo = yc[i] % sqrtBase; - yhi = yc[i] / sqrtBase | 0; - for (k = xcL, j = i + k;j > i; ) { - xlo = xc[--k] % sqrtBase; - xhi = xc[k] / sqrtBase | 0; - m = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c; - c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; - zc[j--] = xlo % base; - } - zc[j] = c; - } - if (c) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y, zc, e2); - }; - P.negated = function() { - var x = new BigNumber2(this); - x.s = -x.s || null; - return x; - }; - P.plus = function(y, b) { - var t2, x = this, a = x.s; - y = new BigNumber2(y, b); - b = y.s; - if (!a || !b) - return new BigNumber2(NaN); - if (a != b) { - y.s = -b; - return x.minus(y); - } - var xe = x.e / LOG_BASE2, ye = y.e / LOG_BASE2, xc = x.c, yc = y.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber2(a / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y : new BigNumber2(xc[0] ? x : a * 0); - } - xe = bitFloor2(xe); - ye = bitFloor2(ye); - xc = xc.slice(); - if (a = xe - ye) { - if (a > 0) { - ye = xe; - t2 = yc; - } else { - a = -a; - t2 = xc; - } - t2.reverse(); - for (;a--; t2.push(0)) - ; - t2.reverse(); - } - a = xc.length; - b = yc.length; - if (a - b < 0) { - t2 = yc; - yc = xc; - xc = t2; - b = a; - } - for (a = 0;b; ) { - a = (xc[--b] = xc[b] + yc[b] + a) / BASE2 | 0; - xc[b] = BASE2 === xc[b] ? 0 : xc[b] % BASE2; - } - if (a) { - xc = [a].concat(xc); - ++ye; - } - return normalise(y, xc, ye); - }; - P.precision = P.sd = function(sd, rm) { - var c, n, v, x = this; - if (sd != null && sd !== !!sd) { - intCheck2(sd, 1, MAX2); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck2(rm, 0, 8); - return round(new BigNumber2(x), sd, rm); - } - if (!(c = x.c)) - return null; - v = c.length - 1; - n = v * LOG_BASE2 + 1; - if (v = c[v]) { - for (;v % 10 == 0; v /= 10, n--) - ; - for (v = c[0];v >= 10; v /= 10, n++) - ; - } - if (sd && x.e + 1 > n) - n = x.e + 1; - return n; - }; - P.shiftedBy = function(k) { - intCheck2(k, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); - return this.times("1e" + k); - }; - P.squareRoot = P.sqrt = function() { - var m, n, r, rep, t2, x = this, c = x.c, s = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); - if (s !== 1 || !c || !c[0]) { - return new BigNumber2(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); - } - s = Math.sqrt(+valueOf(x)); - if (s == 0 || s == 1 / 0) { - n = coeffToString2(c); - if ((n.length + e2) % 2 == 0) - n += "0"; - s = Math.sqrt(+n); - e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s == 1 / 0) { - n = "5e" + e2; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf("e") + 1) + e2; - } - r = new BigNumber2(n); - } else { - r = new BigNumber2(s + ""); - } - if (r.c[0]) { - e2 = r.e; - s = e2 + dp; - if (s < 3) - s = 0; - for (;; ) { - t2 = r; - r = half.times(t2.plus(div(x, t2, dp, 1))); - if (coeffToString2(t2.c).slice(0, s) === (n = coeffToString2(r.c)).slice(0, s)) { - if (r.e < e2) - --s; - n = n.slice(s - 3, s + 1); - if (n == "9999" || !rep && n == "4999") { - if (!rep) { - round(t2, t2.e + DECIMAL_PLACES + 2, 0); - if (t2.times(t2).eq(x)) { - r = t2; - break; - } - } - dp += 4; - s += 4; - rep = 1; - } else { - if (!+n || !+n.slice(1) && n.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m = !r.times(r).eq(x); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); - }; - P.toExponential = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp++; - } - return format(this, dp, rm, 1); - }; - P.toFixed = function(dp, rm) { - if (dp != null) { - intCheck2(dp, 0, MAX2); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P.toFormat = function(dp, rm, format2) { - var str, x = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError2 + "Argument not an object: " + format2); - } - str = x.toFixed(dp, rm); - if (x.c) { - var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g2) { - i = g1; - g1 = g2; - g2 = i; - len -= i; - } - if (g1 > 0 && len > 0) { - i = len % g1 || g1; - intPart = intDigits.substr(0, i); - for (;i < len; i += g1) - intPart += groupSeparator + intDigits.substr(i, g1); - if (g2 > 0) - intPart += groupSeparator + intDigits.slice(i); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(new RegExp("\\d{" + g2 + "}\\B", "g"), "$&" + (format2.fractionGroupSeparator || "")) : fractionPart) : intPart; - } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P.toFraction = function(md) { - var d, d0, d1, d2, e2, exp, n, n0, n1, q, r, s, x = this, xc = x.c; - if (md != null) { - n = new BigNumber2(md); - if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error(bignumberError2 + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); - } - } - if (!xc) - return new BigNumber2(x); - d = new BigNumber2(ONE); - n1 = d0 = new BigNumber2(ONE); - d1 = n0 = new BigNumber2(ONE); - s = coeffToString2(xc); - e2 = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; - md = !md || n.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n = new BigNumber2(s); - n0.c[0] = 0; - for (;; ) { - q = div(n, d, 0, 1); - d2 = d0.plus(q.times(d1)); - if (d2.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d2; - n1 = n0.plus(q.times(d2 = n1)); - n0 = d2; - d = n.minus(q.times(d2 = d)); - n = d2; - } - d2 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x).abs().comparedTo(div(n0, d0, e2, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P.toNumber = function() { - return +valueOf(this); - }; - P.toPrecision = function(sd, rm) { - if (sd != null) - intCheck2(sd, 1, MAX2); - return format(this, sd, rm, 2); - }; - P.toString = function(b) { - var str, n = this, s = n.s, e2 = n.e; - if (e2 === null) { - if (s) { - str = "Infinity"; - if (s < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n.c), e2) : toFixedPoint2(coeffToString2(n.c), e2, "0"); - } else if (b === 10 && alphabetHasNormalDecimalDigits) { - n = round(new BigNumber2(n), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint2(coeffToString2(n.c), n.e, "0"); - } else { - intCheck2(b, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint2(coeffToString2(n.c), e2, "0"), 10, b, s, true); - } - if (s < 0 && n.c[0]) - str = "-" + str; - } - return str; - }; - P.valueOf = P.toJSON = function() { - return valueOf(this); + module.exports.parse = json_parse(); + module.exports.stringify = json_stringify; +}); + +// node_modules/.pnpm/gcp-metadata@8.1.2/node_modules/gcp-metadata/build/src/gcp-residency.js +var require_gcp_residency = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GCE_LINUX_BIOS_PATHS = undefined; + exports.isGoogleCloudServerless = isGoogleCloudServerless; + exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; + exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; + exports.isGoogleComputeEngine = isGoogleComputeEngine; + exports.detectGCPResidency = detectGCPResidency; + var fs_1 = __require("fs"); + var os_1 = __require("os"); + exports.GCE_LINUX_BIOS_PATHS = { + BIOS_DATE: "/sys/class/dmi/id/bios_date", + BIOS_VENDOR: "/sys/class/dmi/id/bios_vendor" }; - P._isBigNumber = true; - P[Symbol.toStringTag] = "BigNumber"; - P[Symbol.for("nodejs.util.inspect.custom")] = P.valueOf; - if (configObject != null) - BigNumber2.set(configObject); - return BigNumber2; -} -function bitFloor2(n) { - var i = n | 0; - return n > 0 || n === i ? i : i - 1; -} -function coeffToString2(a) { - var s, z, i = 1, j = a.length, r = a[0] + ""; - for (;i < j; ) { - s = a[i++] + ""; - z = LOG_BASE2 - s.length; - for (;z--; s = "0" + s) - ; - r += s; - } - for (j = r.length;r.charCodeAt(--j) === 48; ) - ; - return r.slice(0, j + 1 || 1); -} -function compare2(x, y) { - var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; - if (!i || !j) - return null; - a = xc && !xc[0]; - b = yc && !yc[0]; - if (a || b) - return a ? b ? 0 : -j : i; - if (i != j) - return i; - a = i < 0; - b = k == l; - if (!xc || !yc) - return b ? 0 : !xc ^ a ? 1 : -1; - if (!b) - return k > l ^ a ? 1 : -1; - j = (k = xc.length) < (l = yc.length) ? k : l; - for (i = 0;i < j; i++) - if (xc[i] != yc[i]) - return xc[i] > yc[i] ^ a ? 1 : -1; - return k == l ? 0 : k > l ^ a ? 1 : -1; -} -function intCheck2(n, min, max, name) { - if (n < min || n > max || n !== mathfloor2(n)) { - throw Error(bignumberError2 + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); + var GCE_MAC_ADDRESS_REGEX = /^42:01/; + function isGoogleCloudServerless() { + const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE; + return !!isGFEnvironment; } -} -function isOdd2(n) { - var k = n.c.length - 1; - return bitFloor2(n.e / LOG_BASE2) == k && n.c[k] % 2 != 0; -} -function toExponential2(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; -} -function toFixedPoint2(str, e2, z) { - var len, zs; - if (e2 < 0) { - for (zs = z + ".";++e2; zs += z) - ; - str = zs + str; - } else { - len = str.length; - if (++e2 > len) { - for (zs = z, e2 -= len;--e2; zs += z) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); + function isGoogleComputeEngineLinux() { + if ((0, os_1.platform)() !== "linux") + return false; + try { + (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); + const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, "utf8"); + return /Google/.test(biosVendor); + } catch { + return false; } } - return str; -} -var isNumeric2, mathceil2, mathfloor2, bignumberError2 = "[BigNumber Error] ", tooManyDigits2, BASE2 = 100000000000000, LOG_BASE2 = 14, MAX_SAFE_INTEGER2 = 9007199254740991, POWS_TEN2, SQRT_BASE2 = 1e7, MAX2 = 1e9, BigNumber2, bignumber_default2; -var init_bignumber = __esm(() => { - isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; - mathceil2 = Math.ceil; - mathfloor2 = Math.floor; - tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: "; - POWS_TEN2 = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000]; - BigNumber2 = clone3(); - bignumber_default2 = BigNumber2; -}); - -// ../db-schema/node_modules/.pnpm/@paralleldrive+cuid2@3.3.0/node_modules/@paralleldrive/cuid2/src/index.js -function bufToBigInt2(buf) { - let value = new bignumber_default2(0); - for (const i of buf.values()) { - value = value.multipliedBy(256).plus(i); - } - return value; -} -function lazy2(fn) { - let initialized; - return () => { - if (!initialized) { - initialized = fn(); + function isGoogleComputeEngineMACAddress() { + const interfaces = (0, os_1.networkInterfaces)(); + for (const item of Object.values(interfaces)) { + if (!item) + continue; + for (const { mac } of item) { + if (GCE_MAC_ADDRESS_REGEX.test(mac)) { + return true; + } + } } - return initialized(); - }; -} -var defaultLength2 = 24, bigLength2 = 32, createRandom2 = () => { - if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") { - return () => { - const buffer = new Uint32Array(1); - globalThis.crypto.getRandomValues(buffer); - return buffer[0] / 4294967296; - }; + return false; } - return Math.random; -}, random2, createEntropy2 = (length = 4, rand = random2) => { - let entropy = ""; - while (entropy.length < length) { - entropy = entropy + Math.floor(rand() * 36).toString(36); + function isGoogleComputeEngine() { + return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); } - return entropy; -}, hash2 = (input = "") => { - const encoder = new TextEncoder; - return bufToBigInt2(sha3_5122(encoder.encode(input))).toString(36).slice(1); -}, alphabet2, randomLetter2 = (rand) => alphabet2[Math.floor(rand() * alphabet2.length)], createFingerprint2 = ({ - globalObj = typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {}, - random: rand = random2 -} = {}) => { - const globals = Object.keys(globalObj).toString(); - const sourceString = globals.length ? globals + createEntropy2(bigLength2, rand) : createEntropy2(bigLength2, rand); - return hash2(sourceString).substring(0, bigLength2); -}, createCounter2 = (count) => () => { - return count++; -}, initialCountMax2 = 476782367, init2 = ({ - random: rand = random2, - counter = createCounter2(Math.floor(rand() * initialCountMax2)), - length = defaultLength2, - fingerprint = createFingerprint2({ random: rand }) -} = {}) => { - if (length > bigLength2) { - throw new Error(`Length must be between 2 and ${bigLength2}. Received: ${length}`); + function detectGCPResidency() { + return isGoogleCloudServerless() || isGoogleComputeEngine(); } - return function cuid2() { - const firstLetter = randomLetter2(rand); - const time2 = Date.now().toString(36); - const count = counter().toString(36); - const salt = createEntropy2(length, rand); - const hashInput = `${time2 + salt + count + fingerprint}`; - return `${firstLetter + hash2(hashInput).substring(1, length)}`; - }; -}, createId2, isCuid2 = (id, { minLength = 2, maxLength = bigLength2, length = id?.length } = {}) => { - const regex = /^[a-z][0-9a-z]+$/; - return typeof id === "string" && length >= minLength && length <= maxLength && regex.test(id); -}, getConstants2 = () => ({ defaultLength: defaultLength2, bigLength: bigLength2 }); -var init_src = __esm(() => { - init_sha3(); - init_bignumber(); - random2 = createRandom2(); - alphabet2 = Array.from({ length: 26 }, (x, i) => String.fromCharCode(i + 97)); - createId2 = lazy2(init2); -}); - -// ../db-schema/node_modules/.pnpm/@paralleldrive+cuid2@3.3.0/node_modules/@paralleldrive/cuid2/index.js -var exports_cuid2 = {}; -__export(exports_cuid2, { - isCuid: () => isCuid2, - init: () => init2, - getConstants: () => getConstants2, - createId: () => createId2 -}); -var init_cuid2 = __esm(() => { - init_src(); }); -// ../db-schema/dist/db/schema.js -var require_schema2 = __commonJS((exports) => { +// node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/colours.js +var require_colours = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.executionResult = exports.submission = exports.editorial = exports.hint = exports.testcase = exports.problemTag = exports.tag = exports.problem = exports.session = exports.authMethod = exports.user = exports.submissionModeEnum = exports.problemStatusEnum = exports.difficultyEnum = exports.verdictEnum = exports.jobStatusEnum = exports.languageEnum = exports.authProvider = exports.roleEnum = undefined; - var pg_core_1 = require_pg_core(); - var drizzle_orm_1 = require_drizzle_orm(); - var cuid2_1 = (init_cuid2(), __toCommonJS(exports_cuid2)); - exports.roleEnum = (0, pg_core_1.pgEnum)("role", ["ADMIN", "AUTHOR", "USER"]); - exports.authProvider = (0, pg_core_1.pgEnum)("AuthProvider", [ - "GOOGLE_OAUTH", - "EMAIL_PASSWORD" - ]); - exports.languageEnum = (0, pg_core_1.pgEnum)("Language", [ - "CPP", - "JAVA", - "PYTHON", - "JAVASCRIPT", - "C", - "CSHARP" - ]); - exports.jobStatusEnum = (0, pg_core_1.pgEnum)("JobStatus", [ - "PENDING", - "RUNNING", - "FAILED", - "COMPLETED" - ]); - exports.verdictEnum = (0, pg_core_1.pgEnum)("Verdict", [ - "PENDING", - "ACCEPTED", - "WRONG_ANSWER", - "TIME_LIMIT_EXCEEDED", - "MEMORY_LIMIT_EXCEEDED", - "RUNTIME_ERROR", - "COMPILE_ERROR" - ]); - exports.difficultyEnum = (0, pg_core_1.pgEnum)("Difficulty", [ - "EASY", - "MEDIUM", - "HARD", - "EXPERT" - ]); - exports.problemStatusEnum = (0, pg_core_1.pgEnum)("ProblemStatus", [ - "DRAFT", - "DONE", - "PENDING", - "APPROVED", - "REJECTED" - ]); - exports.submissionModeEnum = (0, pg_core_1.pgEnum)("SubmissionMode", [ - "SUBMIT", - "RUN" - ]); - exports.user = (0, pg_core_1.pgTable)("user", { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - email: (0, pg_core_1.text)("email"), - displayName: (0, pg_core_1.text)("display_name"), - avatarUrl: (0, pg_core_1.text)("avatar_url"), - username: (0, pg_core_1.text)("username").notNull(), - role: (0, exports.roleEnum)("role").notNull().default("USER"), - is2FaAuthEnabled: (0, pg_core_1.boolean)("is2fa_auth_enabled").default(false).notNull(), - isBanned: (0, pg_core_1.boolean)("is_banned").default(false).notNull(), - isEmailVerified: (0, pg_core_1.boolean)("is_email_verified").default(false).notNull(), - verificationToken: (0, pg_core_1.text)("verification_token"), - createdAt: (0, pg_core_1.timestamp)("created_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull() - }, (table) => [ - (0, pg_core_1.uniqueIndex)("user_email_key").using("btree", table.email.asc().nullsLast()), - (0, pg_core_1.uniqueIndex)("user_username_key").using("btree", table.username.asc().nullsLast()) - ]); - var authMethodColumns2 = { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - userId: (0, pg_core_1.text)("user_id").notNull(), - provider: (0, exports.authProvider)("provider").notNull(), - googleSub: (0, pg_core_1.text)("google_sub"), - googleEmail: (0, pg_core_1.text)("google_email"), - email: (0, pg_core_1.text)("email"), - passwordHash: (0, pg_core_1.text)("password_hash"), - createdAt: (0, pg_core_1.timestamp)("created_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull() - }; - exports.authMethod = (0, pg_core_1.pgTable)("auth_method", authMethodColumns2, (table) => [ - (0, pg_core_1.uniqueIndex)("auth_method_google_email_key").using("btree", table.googleEmail.asc().nullsLast()), - (0, pg_core_1.uniqueIndex)("auth_method_google_sub_key").using("btree", table.googleSub.asc().nullsLast()), - (0, pg_core_1.index)("auth_method_provider_idx").using("btree", table.provider.asc().nullsLast()), - (0, pg_core_1.uniqueIndex)("auth_method_user_id_key").using("btree", table.userId.asc().nullsLast()), - (0, pg_core_1.foreignKey)({ - columns: [table.userId], - foreignColumns: [exports.user.id], - name: "auth_method_user_id_fkey" - }).onUpdate("cascade").onDelete("cascade") - ]); - exports.session = (0, pg_core_1.pgTable)("session", { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - userId: (0, pg_core_1.text)("user_id").notNull().references(() => exports.user.id, { onDelete: "cascade", onUpdate: "cascade" }), - sessionToken: (0, pg_core_1.text)("session_token").notNull(), - expires: (0, pg_core_1.timestamp)("expires", { precision: 3, mode: "string" }).notNull() - }, (table) => [ - (0, pg_core_1.index)("session_user_id_idx").using("btree", table.userId.asc().nullsLast()) - ]); - exports.problem = (0, pg_core_1.pgTable)("problem", { - id: (0, pg_core_1.text)("id").primaryKey().$defaultFn(() => (0, cuid2_1.createId)()), - title: (0, pg_core_1.text)("title").notNull(), - description: (0, pg_core_1.text)("description").notNull(), - slug: (0, pg_core_1.text)("slug").notNull(), - difficulty: (0, exports.difficultyEnum)("difficulty").notNull(), - authorId: (0, pg_core_1.text)("author_id").notNull().references(() => exports.user.id, { onDelete: "restrict" }), - inputFormat: (0, pg_core_1.text)("input_format").notNull(), - outputFormat: (0, pg_core_1.text)("output_format").notNull(), - constraints: (0, pg_core_1.text)("constraints").notNull(), - status: (0, exports.problemStatusEnum)("status").notNull().default("DRAFT"), - timeLimit: (0, pg_core_1.integer)("time_limit").notNull(), - memoryLimit: (0, pg_core_1.integer)("memory_limit").notNull(), - createdAt: (0, pg_core_1.timestamp)("created_at").default((0, drizzle_orm_1.sql)`now()`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at").default((0, drizzle_orm_1.sql)`now()`).notNull() - }, (t2) => [ - (0, pg_core_1.index)("problem_author_idx").on(t2.authorId), - (0, pg_core_1.index)("problem_difficulty_idx").on(t2.difficulty) - ]); - var tagColumns2 = { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - name: (0, pg_core_1.text)("name").notNull() - }; - exports.tag = (0, pg_core_1.pgTable)("tag", tagColumns2, (table) => [ - (0, pg_core_1.uniqueIndex)("tag_name_key").using("btree", table.name.asc().nullsLast()) - ]); - exports.problemTag = (0, pg_core_1.pgTable)("problem_tag", { - problemId: (0, pg_core_1.text)("problem_id").notNull().references(() => exports.problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - tagId: (0, pg_core_1.text)("tag_id").notNull().references(() => exports.tag.id, { onDelete: "cascade", onUpdate: "cascade" }) - }, (table) => [ - (0, pg_core_1.primaryKey)({ columns: [table.problemId, table.tagId] }) - ]); - exports.testcase = (0, pg_core_1.pgTable)("testcase", { - id: (0, pg_core_1.text)("id").primaryKey().$defaultFn(() => (0, cuid2_1.createId)()), - problemId: (0, pg_core_1.text)("problem_id").notNull().references(() => exports.problem.id, { onDelete: "cascade" }), - s3Key: (0, pg_core_1.text)("s3_key").notNull(), - isSample: (0, pg_core_1.boolean)("is_sample").default(false).notNull(), - isHidden: (0, pg_core_1.boolean)("is_hidden").default(true).notNull(), - order: (0, pg_core_1.smallint)("order").default(0).notNull(), - batch: (0, pg_core_1.smallint)("batch").default(0).notNull(), - createdAt: (0, pg_core_1.timestamp)("created_at").default((0, drizzle_orm_1.sql)`now()`).notNull() - }, (t2) => [ - (0, pg_core_1.index)("testcase_problem_idx").on(t2.problemId), - (0, pg_core_1.index)("testcase_sample_idx").on(t2.isSample) - ]); - exports.hint = (0, pg_core_1.pgTable)("hint", { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - problemId: (0, pg_core_1.text)("problem_id").notNull().references(() => exports.problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - order: (0, pg_core_1.smallint)("order").notNull().default(0), - title: (0, pg_core_1.text)("title").notNull(), - content: (0, pg_core_1.text)("content").notNull(), - createdAt: (0, pg_core_1.timestamp)("created_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull() - }, (table) => [ - (0, pg_core_1.index)("hints_problem_id_idx").using("btree", table.problemId.asc().nullsLast()) - ]); - exports.editorial = (0, pg_core_1.pgTable)("editorial", { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - problemId: (0, pg_core_1.text)("problem_id").notNull().references(() => exports.problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - contentS3Key: (0, pg_core_1.text)("content_s3_key").notNull(), - editorialLink: (0, pg_core_1.text)("editorial_link"), - solutionS3Key: (0, pg_core_1.text)("solution_s3_key").notNull(), - createdAt: (0, pg_core_1.timestamp)("created_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull() - }, (table) => [ - (0, pg_core_1.uniqueIndex)("editorial_problem_id_key").using("btree", table.problemId.asc().nullsLast()) - ]); - exports.submission = (0, pg_core_1.pgTable)("submission", { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - problemId: (0, pg_core_1.text)("problem_id").notNull().references(() => exports.problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - userId: (0, pg_core_1.text)("user_id").notNull().references(() => exports.user.id, { onDelete: "cascade", onUpdate: "cascade" }), - mode: (0, exports.submissionModeEnum)("mode").notNull(), - code: (0, pg_core_1.text)("code").notNull(), - language: (0, exports.languageEnum)("language").notNull().default("CPP"), - status: (0, exports.jobStatusEnum)("status").notNull().default("PENDING"), - totalTestcases: (0, pg_core_1.integer)("total_testcases").notNull().default(0), - passedTestcases: (0, pg_core_1.integer)("passed_testcases").notNull().default(0), - failedTestcases: (0, pg_core_1.integer)("failed_testcases").notNull().default(0), - timeTaken: (0, pg_core_1.integer)("time_taken").notNull().default(0), - memoryTaken: (0, pg_core_1.integer)("memory_taken").notNull().default(0), - createdAt: (0, pg_core_1.timestamp)("created_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull() - }, (table) => [ - (0, pg_core_1.index)("submission_user_problem_idx").using("btree", table.userId.asc(), table.problemId.asc()), - (0, pg_core_1.index)("submission_problem_id_idx").using("btree", table.problemId.asc().nullsLast()), - (0, pg_core_1.index)("submission_user_id_idx").using("btree", table.userId.asc().nullsLast()), - (0, pg_core_1.index)("submission_status_idx").using("btree", table.status.asc().nullsLast()), - (0, pg_core_1.index)("submission_created_at_idx").using("btree", table.createdAt.asc().nullsLast()) - ]); - exports.executionResult = (0, pg_core_1.pgTable)("execution_result", { - id: (0, pg_core_1.text)("id").primaryKey().notNull().$defaultFn(() => (0, cuid2_1.createId)()), - submissionId: (0, pg_core_1.text)("submission_id").notNull().references(() => exports.submission.id, { onDelete: "cascade", onUpdate: "cascade" }), - verdict: (0, exports.verdictEnum)("verdict").notNull().default("PENDING"), - stdout: (0, pg_core_1.text)("stdout"), - stderr: (0, pg_core_1.text)("stderr"), - createdAt: (0, pg_core_1.timestamp)("created_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: (0, pg_core_1.timestamp)("updated_at", { precision: 3, mode: "string" }).default((0, drizzle_orm_1.sql)`(now() AT TIME ZONE 'UTC'::text)`).notNull() - }, (table) => [ - (0, pg_core_1.index)("execution_result_submission_verdict_idx").using("btree", table.submissionId.asc(), table.verdict.asc()), - (0, pg_core_1.index)("execution_result_submission_id_idx").using("btree", table.submissionId.asc().nullsLast()) - ]); -}); + exports.Colours = undefined; -// ../db-schema/dist/db/relations.js -var require_relations2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.tagRelations = exports.problemTagsRelations = exports.editorialRelations = exports.hintRelations = exports.testcaseRelations = exports.executionResultRelations = exports.submissionRelations = exports.problemRelations = exports.userRelations = undefined; - var drizzle_orm_1 = require_drizzle_orm(); - var schema_1 = require_schema2(); - exports.userRelations = (0, drizzle_orm_1.relations)(schema_1.user, ({ many }) => ({ - problem: many(schema_1.problem), - submission: many(schema_1.submission), - session: many(schema_1.session) - })); - exports.problemRelations = (0, drizzle_orm_1.relations)(schema_1.problem, ({ many }) => ({ - testcase: many(schema_1.testcase), - hint: many(schema_1.hint), - editorial: many(schema_1.editorial) - })); - exports.submissionRelations = (0, drizzle_orm_1.relations)(schema_1.submission, ({ one }) => ({ - problem: one(schema_1.problem, { - fields: [schema_1.submission.problemId], - references: [schema_1.problem.id] - }), - user: one(schema_1.user, { - fields: [schema_1.submission.userId], - references: [schema_1.user.id] - }) - })); - exports.executionResultRelations = (0, drizzle_orm_1.relations)(schema_1.executionResult, ({ one }) => ({ - submission: one(schema_1.submission, { - fields: [schema_1.executionResult.submissionId], - references: [schema_1.submission.id] - }) - })); - exports.testcaseRelations = (0, drizzle_orm_1.relations)(schema_1.testcase, ({ one }) => ({ - problem: one(schema_1.problem, { - fields: [schema_1.testcase.problemId], - references: [schema_1.problem.id] - }) - })); - exports.hintRelations = (0, drizzle_orm_1.relations)(schema_1.hint, ({ one }) => ({ - problem: one(schema_1.problem, { - fields: [schema_1.hint.problemId], - references: [schema_1.problem.id] - }) - })); - exports.editorialRelations = (0, drizzle_orm_1.relations)(schema_1.editorial, ({ one }) => ({ - problem: one(schema_1.problem, { - fields: [schema_1.editorial.problemId], - references: [schema_1.problem.id] - }) - })); - exports.problemTagsRelations = (0, drizzle_orm_1.relations)(schema_1.problemTag, ({ one }) => ({ - problem: one(schema_1.problem, { - fields: [schema_1.problemTag.problemId], - references: [schema_1.problem.id] - }), - tag: one(schema_1.tag, { - fields: [schema_1.problemTag.tagId], - references: [schema_1.tag.id] - }) - })); - exports.tagRelations = (0, drizzle_orm_1.relations)(schema_1.tag, ({ many }) => ({ - problems: many(schema_1.problemTag) - })); + class Colours { + static isEnabled(stream) { + return stream && stream.isTTY && (typeof stream.getColorDepth === "function" ? stream.getColorDepth() > 2 : true); + } + static refresh() { + Colours.enabled = Colours.isEnabled(process === null || process === undefined ? undefined : process.stderr); + if (!this.enabled) { + Colours.reset = ""; + Colours.bright = ""; + Colours.dim = ""; + Colours.red = ""; + Colours.green = ""; + Colours.yellow = ""; + Colours.blue = ""; + Colours.magenta = ""; + Colours.cyan = ""; + Colours.white = ""; + Colours.grey = ""; + } else { + Colours.reset = "\x1B[0m"; + Colours.bright = "\x1B[1m"; + Colours.dim = "\x1B[2m"; + Colours.red = "\x1B[31m"; + Colours.green = "\x1B[32m"; + Colours.yellow = "\x1B[33m"; + Colours.blue = "\x1B[34m"; + Colours.magenta = "\x1B[35m"; + Colours.cyan = "\x1B[36m"; + Colours.white = "\x1B[37m"; + Colours.grey = "\x1B[90m"; + } + } + } + exports.Colours = Colours; + Colours.enabled = false; + Colours.reset = ""; + Colours.bright = ""; + Colours.dim = ""; + Colours.red = ""; + Colours.green = ""; + Colours.yellow = ""; + Colours.blue = ""; + Colours.magenta = ""; + Colours.cyan = ""; + Colours.white = ""; + Colours.grey = ""; + Colours.refresh(); }); -// ../db-schema/dist/index.js -var require_dist4 = __commonJS((exports) => { +// node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/logging-utils.js +var require_logging_utils = __commonJS((exports) => { var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -73639,496 +66011,243 @@ var require_dist4 = __commonJS((exports) => { }; }(); Object.defineProperty(exports, "__esModule", { value: true }); - exports.schema = undefined; - var tables = __importStar(require_schema2()); - var relations = __importStar(require_relations2()); - exports.schema = { - ...tables, - ...relations - }; -}); + exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = undefined; + exports.getNodeBackend = getNodeBackend; + exports.getDebugBackend = getDebugBackend; + exports.getStructuredBackend = getStructuredBackend; + exports.setBackend = setBackend; + exports.log = log; + var events_1 = __require("events"); + var process2 = __importStar(__require("process")); + var util = __importStar(__require("util")); + var colours_1 = require_colours(); + var LogSeverity; + (function(LogSeverity2) { + LogSeverity2["DEFAULT"] = "DEFAULT"; + LogSeverity2["DEBUG"] = "DEBUG"; + LogSeverity2["INFO"] = "INFO"; + LogSeverity2["WARNING"] = "WARNING"; + LogSeverity2["ERROR"] = "ERROR"; + })(LogSeverity || (exports.LogSeverity = LogSeverity = {})); -// node_modules/.pnpm/extend@3.0.2/node_modules/extend/index.js -var require_extend = __commonJS((exports, module) => { - var hasOwn = Object.prototype.hasOwnProperty; - var toStr = Object.prototype.toString; - var defineProperty = Object.defineProperty; - var gOPD = Object.getOwnPropertyDescriptor; - var isArray = function isArray2(arr) { - if (typeof Array.isArray === "function") { - return Array.isArray(arr); - } - return toStr.call(arr) === "[object Array]"; - }; - var isPlainObject = function isPlainObject2(obj) { - if (!obj || toStr.call(obj) !== "[object Object]") { - return false; - } - var hasOwnConstructor = hasOwn.call(obj, "constructor"); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf"); - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - var key; - for (key in obj) {} - return typeof key === "undefined" || hasOwn.call(obj, key); - }; - var setProperty = function setProperty2(target, options) { - if (defineProperty && options.name === "__proto__") { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true + class AdhocDebugLogger extends events_1.EventEmitter { + constructor(namespace, upstream) { + super(); + this.namespace = namespace; + this.upstream = upstream; + this.func = Object.assign(this.invoke.bind(this), { + instance: this, + on: (event, listener) => this.on(event, listener) }); - } else { - target[options.name] = options.newValue; + this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); + this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); + this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); + this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); + this.func.sublog = (namespace2) => log(namespace2, this.func); } - }; - var getProperty = function getProperty2(obj, name) { - if (name === "__proto__") { - if (!hasOwn.call(obj, name)) { - return; - } else if (gOPD) { - return gOPD(obj, name).value; + invoke(fields, ...args) { + if (this.upstream) { + try { + this.upstream(fields, ...args); + } catch (e2) {} } + try { + this.emit("log", fields, args); + } catch (e2) {} } - return obj[name]; - }; - module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone4; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; - if (typeof target === "boolean") { - deep = target; - target = arguments[1] || {}; - i = 2; + invokeSeverity(severity, ...args) { + this.invoke({ severity }, ...args); } - if (target == null || typeof target !== "object" && typeof target !== "function") { - target = {}; + } + exports.AdhocDebugLogger = AdhocDebugLogger; + exports.placeholder = new AdhocDebugLogger("", () => {}).func; + + class DebugLogBackendBase { + constructor() { + var _a; + this.cached = new Map; + this.filters = []; + this.filtersSet = false; + let nodeFlag = (_a = process2.env[exports.env.nodeEnables]) !== null && _a !== undefined ? _a : "*"; + if (nodeFlag === "all") { + nodeFlag = "*"; + } + this.filters = nodeFlag.split(","); } - for (;i < length; ++i) { - options = arguments[i]; - if (options != null) { - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); - if (target !== copy) { - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone4 = src && isArray(src) ? src : []; - } else { - clone4 = src && isPlainObject(src) ? src : {}; - } - setProperty(target, { name, newValue: extend(deep, clone4, copy) }); - } else if (typeof copy !== "undefined") { - setProperty(target, { name, newValue: copy }); - } - } + log(namespace, fields, ...args) { + try { + if (!this.filtersSet) { + this.setFilters(); + this.filtersSet = true; + } + let logger = this.cached.get(namespace); + if (!logger) { + logger = this.makeLogger(namespace); + this.cached.set(namespace, logger); } + logger(fields, ...args); + } catch (e2) { + console.error(e2); } } - return target; - }; -}); + } + exports.DebugLogBackendBase = DebugLogBackendBase; -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/package.json -var require_package3 = __commonJS((exports, module) => { - module.exports = { - name: "gaxios", - version: "7.1.4", - description: "A simple common HTTP client specifically for Google APIs and services.", - main: "build/cjs/src/index.js", - types: "build/cjs/src/index.d.ts", - files: [ - "build/" - ], - exports: { - ".": { - import: { - types: "./build/esm/src/index.d.ts", - default: "./build/esm/src/index.js" - }, - require: { - types: "./build/cjs/src/index.d.ts", - default: "./build/cjs/src/index.js" - } + class NodeBackend extends DebugLogBackendBase { + constructor() { + super(...arguments); + this.enabledRegexp = /.*/g; + } + isEnabled(namespace) { + return this.enabledRegexp.test(namespace); + } + makeLogger(namespace) { + if (!this.enabledRegexp.test(namespace)) { + return () => {}; } - }, - scripts: { - lint: "gts check --no-inline-config", - test: "c8 mocha build/esm/test", - "presystem-test": "npm run compile", - "system-test": "mocha build/esm/system-test --timeout 80000", - compile: "tsc -b ./tsconfig.json ./tsconfig.cjs.json && node utils/enable-esm.mjs", - fix: "gts fix", - prepare: "npm run compile", - pretest: "npm run compile", - webpack: "webpack", - "prebrowser-test": "npm run compile", - "browser-test": "node build/browser-test/browser-test-runner.js", - docs: "jsdoc -c .jsdoc.js", - "docs-test": "linkinator docs", - "predocs-test": "npm run docs", - "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", - prelint: "cd samples; npm link ../; npm install", - clean: "gts clean" - }, - repository: { - type: "git", - directory: "packages/gaxios", - url: "https://github.com/googleapis/google-cloud-node-core.git" - }, - keywords: [ - "google" - ], - engines: { - node: ">=18" - }, - author: "Google, LLC", - license: "Apache-2.0", - devDependencies: { - "@babel/plugin-proposal-private-methods": "^7.18.6", - "@types/cors": "^2.8.6", - "@types/express": "^5.0.0", - "@types/extend": "^3.0.1", - "@types/mocha": "^10.0.10", - "@types/multiparty": "4.2.1", - "@types/mv": "^2.1.0", - "@types/ncp": "^2.0.8", - "@types/node": "^22.13.1", - "@types/sinon": "^17.0.3", - "@types/tmp": "^0.2.6", - assert: "^2.0.0", - browserify: "^17.0.0", - c8: "^10.1.3", - cors: "^2.8.5", - express: "^5.0.0", - gts: "^6.0.2", - "is-docker": "^3.0.0", - jsdoc: "^4.0.4", - "jsdoc-fresh": "^5.0.0", - "jsdoc-region-tag": "^4.0.0", - karma: "^6.0.0", - "karma-chrome-launcher": "^3.0.0", - "karma-coverage": "^2.0.0", - "karma-firefox-launcher": "^2.0.0", - "karma-mocha": "^2.0.0", - "karma-remap-coverage": "^0.1.5", - "karma-sourcemap-loader": "^0.4.0", - "karma-webpack": "^5.0.1", - linkinator: "^6.1.2", - mocha: "^11.1.0", - multiparty: "^4.2.1", - mv: "^2.1.1", - ncp: "^2.0.0", - nock: "^14.0.5", - "null-loader": "^4.0.1", - "pack-n-play": "^4.0.0", - puppeteer: "^24.0.0", - sinon: "^21.0.0", - "stream-browserify": "^3.0.0", - tmp: "0.2.5", - "ts-loader": "^9.5.2", - typescript: "5.8.3", - webpack: "^5.97.1", - "webpack-cli": "^6.0.1" - }, - dependencies: { - extend: "^3.0.2", - "https-proxy-agent": "^7.0.1", - "node-fetch": "^3.3.2" - }, - homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/gaxios" - }; -}); - -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/util.cjs -var require_util = __commonJS((exports, module) => { - var pkg = require_package3(); - module.exports = { pkg }; -}); - -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/common.js -var require_common4 = __commonJS((exports) => { - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = undefined; - exports.defaultErrorRedactor = defaultErrorRedactor; - var extend_1 = __importDefault(require_extend()); - var util_cjs_1 = __importDefault(require_util()); - var pkg = util_cjs_1.default.pkg; - exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${pkg.name}-gaxios-error`); - - class GaxiosError extends Error { - config; - response; - code; - status; - error; - [exports.GAXIOS_ERROR_SYMBOL] = pkg.version; - static [Symbol.hasInstance](instance) { - if (instance && typeof instance === "object" && exports.GAXIOS_ERROR_SYMBOL in instance && instance[exports.GAXIOS_ERROR_SYMBOL] === pkg.version) { - return true; - } - return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); - } - constructor(message, config, response, cause) { - super(message, { cause }); - this.config = config; - this.response = response; - this.error = cause instanceof Error ? cause : undefined; - this.config = (0, extend_1.default)(true, {}, config); - if (this.response) { - this.response.config = (0, extend_1.default)(true, {}, this.response.config); - } - if (this.response) { - try { - this.response.data = translateData(this.config.responseType, this.response?.bodyUsed ? this.response?.data : undefined); - } catch {} - this.status = this.response.status; - } - if (cause instanceof DOMException) { - this.code = cause.name; - } else if (cause && typeof cause === "object" && "code" in cause && (typeof cause.code === "string" || typeof cause.code === "number")) { - this.code = cause.code; - } - } - static extractAPIErrorFromResponse(res, defaultErrorMessage = "The request failed") { - let message = defaultErrorMessage; - if (typeof res.data === "string") { - message = res.data; - } - if (res.data && typeof res.data === "object" && "error" in res.data && res.data.error && !res.ok) { - if (typeof res.data.error === "string") { - return { - message: res.data.error, - code: res.status, - status: res.statusText - }; - } - if (typeof res.data.error === "object") { - message = "message" in res.data.error && typeof res.data.error.message === "string" ? res.data.error.message : message; - const status = "status" in res.data.error && typeof res.data.error.status === "string" ? res.data.error.status : res.statusText; - const code = "code" in res.data.error && typeof res.data.error.code === "number" ? res.data.error.code : res.status; - if ("errors" in res.data.error && Array.isArray(res.data.error.errors)) { - const errorMessages = []; - for (const e2 of res.data.error.errors) { - if (typeof e2 === "object" && "message" in e2 && typeof e2.message === "string") { - errorMessages.push(e2.message); - } - } - return Object.assign({ - message: errorMessages.join(` -`) || message, - code, - status - }, res.data.error); - } - return Object.assign({ - message, - code, - status - }, res.data.error); + return (fields, ...args) => { + var _a; + const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; + const pid = `${colours_1.Colours.yellow}${process2.pid}${colours_1.Colours.reset}`; + let level; + switch (fields.severity) { + case LogSeverity.ERROR: + level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.INFO: + level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; + break; + case LogSeverity.WARNING: + level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; + break; + default: + level = (_a = fields.severity) !== null && _a !== undefined ? _a : LogSeverity.DEFAULT; + break; } - } - return { - message, - code: res.status, - status: res.statusText + const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); + const filteredFields = Object.assign({}, fields); + delete filteredFields.severity; + const fieldsJson = Object.getOwnPropertyNames(filteredFields).length ? JSON.stringify(filteredFields) : ""; + const fieldsColour = fieldsJson ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` : ""; + console.error("%s [%s|%s] %s%s", pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ""); }; } - } - exports.GaxiosError = GaxiosError; - function translateData(responseType, data) { - switch (responseType) { - case "stream": - return data; - case "json": - return JSON.parse(JSON.stringify(data)); - case "arraybuffer": - return JSON.parse(Buffer.from(data).toString("utf8")); - case "blob": - return JSON.parse(data.text()); - default: - return data; + setFilters() { + const totalFilters = this.filters.join(","); + const regexp = totalFilters.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^"); + this.enabledRegexp = new RegExp(`^${regexp}$`, "i"); } } - function defaultErrorRedactor(data) { - const REDACT = "< - See `errorRedactor` option in `gaxios` for configuration>."; - function redactHeaders(headers) { - if (!headers) - return; - headers.forEach((_, key) => { - if (/^authentication$/i.test(key) || /^authorization$/i.test(key) || /secret/i.test(key)) - headers.set(key, REDACT); - }); - } - function redactString(obj, key) { - if (typeof obj === "object" && obj !== null && typeof obj[key] === "string") { - const text2 = obj[key]; - if (/grant_type=/i.test(text2) || /assertion=/i.test(text2) || /secret/i.test(text2)) { - obj[key] = REDACT; - } - } - } - function redactObject(obj) { - if (!obj || typeof obj !== "object") { - return; - } else if (obj instanceof FormData || obj instanceof URLSearchParams || "forEach" in obj && "set" in obj) { - obj.forEach((_, key) => { - if (["grant_type", "assertion"].includes(key) || /secret/.test(key)) { - obj.set(key, REDACT); - } - }); - } else { - if ("grant_type" in obj) { - obj["grant_type"] = REDACT; - } - if ("assertion" in obj) { - obj["assertion"] = REDACT; - } - if ("client_secret" in obj) { - obj["client_secret"] = REDACT; - } - } + function getNodeBackend() { + return new NodeBackend; + } + + class DebugBackend extends DebugLogBackendBase { + constructor(pkg) { + super(); + this.debugPkg = pkg; } - if (data.config) { - redactHeaders(data.config.headers); - redactString(data.config, "data"); - redactObject(data.config.data); - redactString(data.config, "body"); - redactObject(data.config.body); - if (data.config.url.searchParams.has("token")) { - data.config.url.searchParams.set("token", REDACT); - } - if (data.config.url.searchParams.has("client_secret")) { - data.config.url.searchParams.set("client_secret", REDACT); - } + makeLogger(namespace) { + const debugLogger = this.debugPkg(namespace); + return (fields, ...args) => { + debugLogger(args[0], ...args.slice(1)); + }; } - if (data.response) { - defaultErrorRedactor({ config: data.response.config }); - redactHeaders(data.response.headers); - if (data.response.bodyUsed) { - redactString(data.response, "data"); - redactObject(data.response.data); - } + setFilters() { + var _a; + const existingFilters = (_a = process2.env["NODE_DEBUG"]) !== null && _a !== undefined ? _a : ""; + process2.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`; } - return data; } -}); + function getDebugBackend(debugPkg) { + return new DebugBackend(debugPkg); + } -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/retry.js -var require_retry = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRetryConfig = getRetryConfig; - async function getRetryConfig(err) { - let config = getConfig(err); - if (!err || !err.config || !config && !err.config.retry) { - return { shouldRetry: false }; + class StructuredBackend extends DebugLogBackendBase { + constructor(upstream) { + var _a; + super(); + this.upstream = (_a = upstream) !== null && _a !== undefined ? _a : undefined; } - config = config || {}; - config.currentRetryAttempt = config.currentRetryAttempt || 0; - config.retry = config.retry === undefined || config.retry === null ? 3 : config.retry; - config.httpMethodsToRetry = config.httpMethodsToRetry || [ - "GET", - "HEAD", - "PUT", - "OPTIONS", - "DELETE" - ]; - config.noResponseRetries = config.noResponseRetries === undefined || config.noResponseRetries === null ? 2 : config.noResponseRetries; - config.retryDelayMultiplier = config.retryDelayMultiplier ? config.retryDelayMultiplier : 2; - config.timeOfFirstRequest = config.timeOfFirstRequest ? config.timeOfFirstRequest : Date.now(); - config.totalTimeout = config.totalTimeout ? config.totalTimeout : Number.MAX_SAFE_INTEGER; - config.maxRetryDelay = config.maxRetryDelay ? config.maxRetryDelay : Number.MAX_SAFE_INTEGER; - const retryRanges = [ - [100, 199], - [408, 408], - [429, 429], - [500, 599] - ]; - config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; - err.config.retryConfig = config; - const shouldRetryFn = config.shouldRetry || shouldRetryRequest; - if (!await shouldRetryFn(err)) { - return { shouldRetry: false, config: err.config }; + makeLogger(namespace) { + var _a; + const debugLogger = (_a = this.upstream) === null || _a === undefined ? undefined : _a.makeLogger(namespace); + return (fields, ...args) => { + var _a2; + const severity = (_a2 = fields.severity) !== null && _a2 !== undefined ? _a2 : LogSeverity.INFO; + const json3 = Object.assign({ + severity, + message: util.format(...args) + }, fields); + const jsonString = JSON.stringify(json3); + if (debugLogger) { + debugLogger(fields, jsonString); + } else { + console.log("%s", jsonString); + } + }; } - const delay = getNextRetryDelay(config); - err.config.retryConfig.currentRetryAttempt += 1; - const backoff = config.retryBackoff ? config.retryBackoff(err, delay) : new Promise((resolve) => { - setTimeout(resolve, delay); - }); - if (config.onRetryAttempt) { - await config.onRetryAttempt(err); + setFilters() { + var _a; + (_a = this.upstream) === null || _a === undefined || _a.setFilters(); } - await backoff; - return { shouldRetry: true, config: err.config }; } - function shouldRetryRequest(err) { - const config = getConfig(err); - if (err.config.signal?.aborted && err.code !== "TimeoutError" || err.code === "AbortError") { - return false; - } - if (!config || config.retry === 0) { - return false; - } - if (!err.response && (config.currentRetryAttempt || 0) >= config.noResponseRetries) { - return false; + function getStructuredBackend(upstream) { + return new StructuredBackend(upstream); + } + exports.env = { + nodeEnables: "GOOGLE_SDK_NODE_LOGGING" + }; + var loggerCache = new Map; + var cachedBackend = undefined; + function setBackend(backend) { + cachedBackend = backend; + loggerCache.clear(); + } + function log(namespace, parent) { + if (!cachedBackend) { + const enablesFlag = process2.env[exports.env.nodeEnables]; + if (!enablesFlag) { + return exports.placeholder; + } } - if (!config.httpMethodsToRetry || !config.httpMethodsToRetry.includes(err.config.method?.toUpperCase() || "GET")) { - return false; + if (!namespace) { + return exports.placeholder; } - if (err.response && err.response.status) { - let isInRange = false; - for (const [min, max] of config.statusCodesToRetry) { - const status = err.response.status; - if (status >= min && status <= max) { - isInRange = true; - break; - } - } - if (!isInRange) { - return false; - } + if (parent) { + namespace = `${parent.instance.namespace}:${namespace}`; } - config.currentRetryAttempt = config.currentRetryAttempt || 0; - if (config.currentRetryAttempt >= config.retry) { - return false; + const existing = loggerCache.get(namespace); + if (existing) { + return existing.func; } - return true; - } - function getConfig(err) { - if (err && err.config && err.config.retryConfig) { - return err.config.retryConfig; + if (cachedBackend === null) { + return exports.placeholder; + } else if (cachedBackend === undefined) { + cachedBackend = getNodeBackend(); } - return; - } - function getNextRetryDelay(config) { - const retryDelay = config.currentRetryAttempt ? 0 : config.retryDelay ?? 100; - const calculatedDelay = retryDelay + (Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / 2 * 1000; - const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); - return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); - } -}); - -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/interceptor.js -var require_interceptor = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GaxiosInterceptorManager = undefined; - - class GaxiosInterceptorManager extends Set { + const logger = (() => { + let previousBackend = undefined; + const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { + if (previousBackend !== cachedBackend) { + if (cachedBackend === null) { + return; + } else if (cachedBackend === undefined) { + cachedBackend = getNodeBackend(); + } + previousBackend = cachedBackend; + } + cachedBackend === null || cachedBackend === undefined || cachedBackend.log(namespace, fields, ...args); + }); + return newLogger; + })(); + loggerCache.set(namespace, logger); + return logger.func; } - exports.GaxiosInterceptorManager = GaxiosInterceptorManager; }); -// node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/helpers.js -var require_helpers = __commonJS((exports) => { +// node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/index.js +var require_src3 = __commonJS((exports) => { var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -74144,63 +66263,17 @@ var require_helpers = __commonJS((exports) => { k2 = k; o[k2] = m[k]; }); - var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports && exports.__importStar || function(mod) { - if (mod && mod.__esModule) - return mod; - var result = {}; - if (mod != null) { - for (var k in mod) - if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) - __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); - exports.req = exports.json = exports.toBuffer = undefined; - var http = __importStar(__require("http")); - var https = __importStar(__require("https")); - async function toBuffer(stream) { - let length = 0; - const chunks = []; - for await (const chunk of stream) { - length += chunk.length; - chunks.push(chunk); - } - return Buffer.concat(chunks, length); - } - exports.toBuffer = toBuffer; - async function json2(stream) { - const buf = await toBuffer(stream); - const str = buf.toString("utf8"); - try { - return JSON.parse(str); - } catch (_err) { - const err = _err; - err.message += ` (input: ${str})`; - throw err; - } - } - exports.json = json2; - function req(url, opts = {}) { - const href = typeof url === "string" ? url : url.href; - const req2 = (href.startsWith("https:") ? https : http).request(url, opts); - const promise = new Promise((resolve, reject) => { - req2.once("response", resolve).once("error", reject).end(); - }); - req2.then = promise.then.bind(promise); - return req2; - } - exports.req = req; + __exportStar(require_logging_utils(), exports); }); -// node_modules/.pnpm/agent-base@7.1.4/node_modules/agent-base/dist/index.js -var require_dist5 = __commonJS((exports) => { +// node_modules/.pnpm/gcp-metadata@8.1.2/node_modules/gcp-metadata/build/src/index.js +var require_src4 = __commonJS((exports) => { var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === undefined) k2 = k; @@ -74221,406 +66294,749 @@ var require_dist5 = __commonJS((exports) => { } : function(o, v) { o["default"] = v; }); - var __importStar = exports && exports.__importStar || function(mod) { - if (mod && mod.__esModule) - return mod; - var result = {}; - if (mod != null) { - for (var k in mod) - if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) - __createBinding(result, mod, k); - } - __setModuleDefault(result, mod); - return result; - }; + var __importStar = exports && exports.__importStar || function() { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function(o2) { + var ar = []; + for (var k in o2) + if (Object.prototype.hasOwnProperty.call(o2, k)) + ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return 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; + }; + }(); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); - exports.Agent = undefined; - var net = __importStar(__require("net")); - var http = __importStar(__require("http")); - var https_1 = __require("https"); - __exportStar(require_helpers(), exports); - var INTERNAL = Symbol("AgentBaseInternalState"); - - class Agent extends http.Agent { - constructor(opts) { - super(opts); - this[INTERNAL] = {}; + exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = undefined; + exports.instance = instance; + exports.project = project; + exports.universe = universe; + exports.bulk = bulk; + exports.isAvailable = isAvailable; + exports.resetIsAvailableCache = resetIsAvailableCache; + exports.getGCPResidency = getGCPResidency; + exports.setGCPResidency = setGCPResidency; + exports.requestTimeout = requestTimeout; + var gaxios_1 = require_src2(); + var jsonBigint = require_json_bigint(); + var gcp_residency_1 = require_gcp_residency(); + var logger = __importStar(require_src3()); + exports.BASE_PATH = "/computeMetadata/v1"; + exports.HOST_ADDRESS = "http://169.254.169.254"; + exports.SECONDARY_HOST_ADDRESS = "http://metadata.google.internal."; + exports.HEADER_NAME = "Metadata-Flavor"; + exports.HEADER_VALUE = "Google"; + exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); + var log = logger.log("gcp-metadata"); + exports.METADATA_SERVER_DETECTION = Object.freeze({ + "assume-present": "don't try to ping the metadata server, but assume it's present", + none: "don't try to ping the metadata server, but don't try to use it either", + "bios-only": "treat the result of a BIOS probe as canonical (don't fall back to pinging)", + "ping-only": "skip the BIOS probe, and go straight to pinging" + }); + function getBaseUrl(baseUrl) { + if (!baseUrl) { + baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports.HOST_ADDRESS; } - isSecureEndpoint(options) { - if (options) { - if (typeof options.secureEndpoint === "boolean") { - return options.secureEndpoint; - } - if (typeof options.protocol === "string") { - return options.protocol === "https:"; - } + if (!/^https?:\/\//.test(baseUrl)) { + baseUrl = `http://${baseUrl}`; + } + return new URL(exports.BASE_PATH, baseUrl).href; + } + function validate2(options) { + Object.keys(options).forEach((key) => { + switch (key) { + case "params": + case "property": + case "headers": + break; + case "qs": + throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); + default: + throw new Error(`'${key}' is not a valid configuration option.`); } - const { stack } = new Error; - if (typeof stack !== "string") - return false; - return stack.split(` -`).some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1); + }); + } + async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { + const headers = new Headers(exports.HEADERS); + let metadataKey = ""; + let params = {}; + if (typeof type === "object") { + const metadataAccessor2 = type; + new Headers(metadataAccessor2.headers).forEach((value, key) => headers.set(key, value)); + metadataKey = metadataAccessor2.metadataKey; + params = metadataAccessor2.params || params; + noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries; + fastFail = metadataAccessor2.fastFail || fastFail; + } else { + metadataKey = type; } - incrementSockets(name) { - if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) { - return null; + if (typeof options === "string") { + metadataKey += `/${options}`; + } else { + validate2(options); + if (options.property) { + metadataKey += `/${options.property}`; } - if (!this.sockets[name]) { - this.sockets[name] = []; + new Headers(options.headers).forEach((value, key) => headers.set(key, value)); + params = options.params || params; + } + const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; + const req = { + url: `${getBaseUrl()}/${metadataKey}`, + headers, + retryConfig: { noResponseRetries }, + params, + responseType: "text", + timeout: requestTimeout() + }; + log.info("instance request %j", req); + const res = await requestMethod(req); + log.info("instance metadata is %s", res.data); + const metadataFlavor = res.headers.get(exports.HEADER_NAME); + if (metadataFlavor !== exports.HEADER_VALUE) { + throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : "no header"}`); + } + if (typeof res.data === "string") { + try { + return jsonBigint.parse(res.data); + } catch {} + } + return res.data; + } + async function fastFailMetadataRequest(options) { + const secondaryOptions = { + ...options, + url: options.url?.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)) + }; + const r1 = (0, gaxios_1.request)(options); + const r2 = (0, gaxios_1.request)(secondaryOptions); + return Promise.any([r1, r2]); + } + function instance(options) { + return metadataAccessor("instance", options); + } + function project(options) { + return metadataAccessor("project", options); + } + function universe(options) { + return metadataAccessor("universe", options); + } + async function bulk(properties) { + const r = {}; + await Promise.all(properties.map((item) => { + return (async () => { + const res = await metadataAccessor(item); + const key = item.metadataKey; + r[key] = res; + })(); + })); + return r; + } + function detectGCPAvailableRetries() { + return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0; + } + var cachedIsAvailableResponse; + async function isAvailable() { + if (process.env.METADATA_SERVER_DETECTION) { + const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); + if (!(value in exports.METADATA_SERVER_DETECTION)) { + throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`); + } + switch (value) { + case "assume-present": + return true; + case "none": + return false; + case "bios-only": + return getGCPResidency(); + case "ping-only": } - const fakeSocket = new net.Socket({ writable: false }); - this.sockets[name].push(fakeSocket); - this.totalSocketCount++; - return fakeSocket; } - decrementSockets(name, socket) { - if (!this.sockets[name] || socket === null) { - return; + try { + if (cachedIsAvailableResponse === undefined) { + cachedIsAvailableResponse = metadataAccessor("instance", undefined, detectGCPAvailableRetries(), !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); } - const sockets = this.sockets[name]; - const index2 = sockets.indexOf(socket); - if (index2 !== -1) { - sockets.splice(index2, 1); - this.totalSocketCount--; - if (sockets.length === 0) { - delete this.sockets[name]; + await cachedIsAvailableResponse; + return true; + } catch (e2) { + const err = e2; + if (process.env.DEBUG_AUTH) { + console.info(err); + } + if (err.type === "request-timeout") { + return false; + } + if (err.response && err.response.status === 404) { + return false; + } else { + if (!(err.response && err.response.status === 404) && (!err.code || ![ + "EHOSTDOWN", + "EHOSTUNREACH", + "ENETUNREACH", + "ENOENT", + "ENOTFOUND", + "ECONNREFUSED" + ].includes(err.code.toString()))) { + let code = "UNKNOWN"; + if (err.code) + code = err.code.toString(); + process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, "MetadataLookupWarning"); } + return false; } } - getName(options) { - const secureEndpoint = this.isSecureEndpoint(options); - if (secureEndpoint) { - return https_1.Agent.prototype.getName.call(this, options); - } - return super.getName(options); + } + function resetIsAvailableCache() { + cachedIsAvailableResponse = undefined; + } + exports.gcpResidencyCache = null; + function getGCPResidency() { + if (exports.gcpResidencyCache === null) { + setGCPResidency(); } - createSocket(req, options, cb) { - const connectOpts = { - ...options, - secureEndpoint: this.isSecureEndpoint(options) - }; - const name = this.getName(connectOpts); - const fakeSocket = this.incrementSockets(name); - Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => { - this.decrementSockets(name, fakeSocket); - if (socket instanceof http.Agent) { - try { - return socket.addRequest(req, connectOpts); - } catch (err) { - return cb(err); - } - } - this[INTERNAL].currentSocket = socket; - super.createSocket(req, options, cb); - }, (err) => { - this.decrementSockets(name, fakeSocket); - cb(err); - }); + return exports.gcpResidencyCache; + } + function setGCPResidency(value = null) { + exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); + } + function requestTimeout() { + return getGCPResidency() ? 0 : 3000; + } + __exportStar(require_gcp_residency(), exports); +}); + +// node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js +var require_base64_js = __commonJS((exports) => { + exports.byteLength = byteLength; + exports.toByteArray = toByteArray; + exports.fromByteArray = fromByteArray; + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (i = 0, len = code.length;i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + var i; + var len; + revLookup[45] = 62; + revLookup[95] = 63; + function getLens(b64) { + var len2 = b64.length; + if (len2 % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); } - createConnection() { - const socket = this[INTERNAL].currentSocket; - this[INTERNAL].currentSocket = undefined; - if (!socket) { - throw new Error("No socket was returned in the `connect()` function"); - } - return socket; + var validLen = b64.indexOf("="); + if (validLen === -1) + validLen = len2; + var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; + } + function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; + } + function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i2; + for (i2 = 0;i2 < len2; i2 += 4) { + tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; } - get defaultPort() { - return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80); + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; + arr[curByte++] = tmp & 255; } - set defaultPort(v) { - if (this[INTERNAL]) { - this[INTERNAL].defaultPort = v; - } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; } - get protocol() { - return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:"); + return arr; + } + function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; + } + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i2 = start;i2 < end; i2 += 3) { + tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); + output.push(tripletToBase64(tmp)); } - set protocol(v) { - if (this[INTERNAL]) { - this[INTERNAL].protocol = v; - } + return output.join(""); + } + function fromByteArray(uint8) { + var tmp; + var len2 = uint8.length; + var extraBytes = len2 % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i2 = 0, len22 = len2 - extraBytes;i2 < len22; i2 += maxChunkLength) { + parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); } + if (extraBytes === 1) { + tmp = uint8[len2 - 1]; + parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); + } else if (extraBytes === 2) { + tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; + parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); + } + return parts.join(""); } - exports.Agent = Agent; }); -// node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/parse-proxy-response.js -var require_parse_proxy_response = __commonJS((exports) => { - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/shared.js +var require_shared = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.parseProxyResponse = undefined; - var debug_1 = __importDefault(require_src()); - var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response"); - function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once("readable", read); - } - function cleanup() { - socket.removeListener("end", onend); - socket.removeListener("error", onerror); - socket.removeListener("readable", read); - } - function onend() { - cleanup(); - debug("onend"); - reject(new Error("Proxy connection ended before receiving CONNECT response")); - } - function onerror(err) { - cleanup(); - debug("onerror %o", err); - reject(err); - } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf(`\r -\r -`); - if (endOfHeaders === -1) { - debug("have not received end of HTTP headers yet..."); - read(); - return; - } - const headerParts = buffered.slice(0, endOfHeaders).toString("ascii").split(`\r -`); - const firstLine = headerParts.shift(); - if (!firstLine) { - socket.destroy(); - return reject(new Error("No header received from proxy CONNECT response")); - } - const firstLineParts = firstLine.split(" "); - const statusCode = +firstLineParts[1]; - const statusText = firstLineParts.slice(2).join(" "); - const headers = {}; - for (const header of headerParts) { - if (!header) - continue; - const firstColon = header.indexOf(":"); - if (firstColon === -1) { - socket.destroy(); - return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`)); - } - const key = header.slice(0, firstColon).toLowerCase(); - const value = header.slice(firstColon + 1).trimStart(); - const current = headers[key]; - if (typeof current === "string") { - headers[key] = [current, value]; - } else if (Array.isArray(current)) { - current.push(value); - } else { - headers[key] = value; - } - } - debug("got proxy server response: %o %o", firstLine, headers); - cleanup(); - resolve({ - connect: { - statusCode, - statusText, - headers - }, - buffered - }); - } - socket.on("error", onerror); - socket.on("end", onend); - read(); - }); + exports.fromArrayBufferToHex = fromArrayBufferToHex; + function fromArrayBufferToHex(arrayBuffer) { + const byteArray = Array.from(new Uint8Array(arrayBuffer)); + return byteArray.map((byte) => { + return byte.toString(16).padStart(2, "0"); + }).join(""); } - exports.parseProxyResponse = parseProxyResponse; }); -// node_modules/.pnpm/https-proxy-agent@7.0.6/node_modules/https-proxy-agent/dist/index.js -var require_dist6 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/browser/crypto.js +var require_crypto = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BrowserCrypto = undefined; + var base64js = require_base64_js(); + var shared_1 = require_shared(); + + class BrowserCrypto { + constructor() { + if (typeof window === "undefined" || window.crypto === undefined || window.crypto.subtle === undefined) { + throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + } } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports && exports.__importStar || function(mod) { - if (mod && mod.__esModule) - return mod; - var result = {}; - if (mod != null) { - for (var k in mod) - if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) - __createBinding(result, mod, k); + async sha256DigestBase64(str) { + const inputBuffer = new TextEncoder().encode(str); + const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer); + return base64js.fromByteArray(new Uint8Array(outputBuffer)); } - __setModuleDefault(result, mod); - return result; - }; - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { default: mod }; - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.HttpsProxyAgent = undefined; - var net = __importStar(__require("net")); - var tls = __importStar(__require("tls")); - var assert_1 = __importDefault(__require("assert")); - var debug_1 = __importDefault(require_src()); - var agent_base_1 = require_dist5(); - var url_1 = __require("url"); - var parse_proxy_response_1 = require_parse_proxy_response(); - var debug = (0, debug_1.default)("https-proxy-agent"); - var setServernameFromNonIpHost = (options) => { - if (options.servername === undefined && options.host && !net.isIP(options.host)) { - return { - ...options, - servername: options.host + randomBytesBase64(count2) { + const array2 = new Uint8Array(count2); + window.crypto.getRandomValues(array2); + return base64js.fromByteArray(array2); + } + static padBase64(base64) { + while (base64.length % 4 !== 0) { + base64 += "="; + } + return base64; + } + async verify(pubkey, data, signature) { + const algo = { + name: "RSASSA-PKCS1-v1_5", + hash: { name: "SHA-256" } }; + const dataArray = new TextEncoder().encode(data); + const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); + const cryptoKey = await window.crypto.subtle.importKey("jwk", pubkey, algo, true, ["verify"]); + const result = await window.crypto.subtle.verify(algo, cryptoKey, Buffer.from(signatureArray), dataArray); + return result; } - return options; - }; - - class HttpsProxyAgent extends agent_base_1.Agent { - constructor(proxy, opts) { - super(opts); - this.options = { path: undefined }; - this.proxy = typeof proxy === "string" ? new url_1.URL(proxy) : proxy; - this.proxyHeaders = opts?.headers ?? {}; - debug("Creating new HttpsProxyAgent instance: %o", this.proxy.href); - const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, ""); - const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.proxy.protocol === "https:" ? 443 : 80; - this.connectOpts = { - ALPNProtocols: ["http/1.1"], - ...opts ? omit(opts, "headers") : null, - host, - port + async sign(privateKey, data) { + const algo = { + name: "RSASSA-PKCS1-v1_5", + hash: { name: "SHA-256" } }; + const dataArray = new TextEncoder().encode(data); + const cryptoKey = await window.crypto.subtle.importKey("jwk", privateKey, algo, true, ["sign"]); + const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); + return base64js.fromByteArray(new Uint8Array(result)); } - async connect(req, opts) { - const { proxy } = this; - if (!opts.host) { - throw new TypeError('No "host" provided'); - } - let socket; - if (proxy.protocol === "https:") { - debug("Creating `tls.Socket`: %o", this.connectOpts); - socket = tls.connect(setServernameFromNonIpHost(this.connectOpts)); - } else { - debug("Creating `net.Socket`: %o", this.connectOpts); - socket = net.connect(this.connectOpts); - } - const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders }; - const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host; - let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r -`; - if (proxy.username || proxy.password) { - const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`; - headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`; - } - headers.Host = `${host}:${opts.port}`; - if (!headers["Proxy-Connection"]) { - headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close"; - } - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r -`; - } - const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket); - socket.write(`${payload}\r -`); - const { connect, buffered } = await proxyResponsePromise; - req.emit("proxyConnect", connect); - this.emit("proxyConnect", connect, req); - if (connect.statusCode === 200) { - req.once("socket", resume); - if (opts.secureEndpoint) { - debug("Upgrading socket connection to TLS"); - return tls.connect({ - ...omit(setServernameFromNonIpHost(opts), "host", "path", "port"), - socket - }); + decodeBase64StringUtf8(base64) { + const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); + const result = new TextDecoder().decode(uint8array); + return result; + } + encodeBase64StringUtf8(text3) { + const uint8array = new TextEncoder().encode(text3); + const result = base64js.fromByteArray(uint8array); + return result; + } + async sha256DigestHex(str) { + const inputBuffer = new TextEncoder().encode(str); + const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer); + return (0, shared_1.fromArrayBufferToHex)(outputBuffer); + } + async signWithHmacSha256(key, msg) { + const rawKey = typeof key === "string" ? key : String.fromCharCode(...new Uint16Array(key)); + const enc = new TextEncoder; + const cryptoKey = await window.crypto.subtle.importKey("raw", enc.encode(rawKey), { + name: "HMAC", + hash: { + name: "SHA-256" } - return socket; - } - socket.destroy(); - const fakeSocket = new net.Socket({ writable: false }); - fakeSocket.readable = true; - req.once("socket", (s) => { - debug("Replaying proxy buffer for failed request"); - (0, assert_1.default)(s.listenerCount("data") > 0); - s.push(buffered); - s.push(null); - }); - return fakeSocket; + }, false, ["sign"]); + return window.crypto.subtle.sign("HMAC", cryptoKey, enc.encode(msg)); } } - HttpsProxyAgent.protocols = ["http", "https"]; - exports.HttpsProxyAgent = HttpsProxyAgent; - function resume(socket) { - socket.resume(); + exports.BrowserCrypto = BrowserCrypto; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/node/crypto.js +var require_crypto2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.NodeCrypto = undefined; + var crypto2 = __require("crypto"); + + class NodeCrypto { + async sha256DigestBase64(str) { + return crypto2.createHash("sha256").update(str).digest("base64"); + } + randomBytesBase64(count2) { + return crypto2.randomBytes(count2).toString("base64"); + } + async verify(pubkey, data, signature) { + const verifier = crypto2.createVerify("RSA-SHA256"); + verifier.update(data); + verifier.end(); + return verifier.verify(pubkey, signature, "base64"); + } + async sign(privateKey, data) { + const signer = crypto2.createSign("RSA-SHA256"); + signer.update(data); + signer.end(); + return signer.sign(privateKey, "base64"); + } + decodeBase64StringUtf8(base64) { + return Buffer.from(base64, "base64").toString("utf-8"); + } + encodeBase64StringUtf8(text3) { + return Buffer.from(text3, "utf-8").toString("base64"); + } + async sha256DigestHex(str) { + return crypto2.createHash("sha256").update(str).digest("hex"); + } + async signWithHmacSha256(key, msg) { + const cryptoKey = typeof key === "string" ? key : toBuffer(key); + return toArrayBuffer(crypto2.createHmac("sha256", cryptoKey).update(msg).digest()); + } } - function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; + exports.NodeCrypto = NodeCrypto; + function toArrayBuffer(buffer) { + const ab = new ArrayBuffer(buffer.length); + const view = new Uint8Array(ab); + for (let i = 0;i < buffer.length; ++i) { + view[i] = buffer[i]; + } + return ab; + } + function toBuffer(arrayBuffer) { + return Buffer.from(arrayBuffer); + } +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/crypto.js +var require_crypto3 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); + }; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.createCrypto = createCrypto; + exports.hasBrowserCrypto = hasBrowserCrypto; + var crypto_1 = require_crypto(); + var crypto_2 = require_crypto2(); + __exportStar(require_shared(), exports); + function createCrypto() { + if (hasBrowserCrypto()) { + return new crypto_1.BrowserCrypto; + } + return new crypto_2.NodeCrypto; + } + function hasBrowserCrypto() { + return typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.subtle !== "undefined"; + } +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/util.js +var require_util2 = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LRUCache = undefined; + exports.snakeToCamel = snakeToCamel; + exports.originalOrCamelOptions = originalOrCamelOptions; + exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject; + exports.isValidFile = isValidFile; + exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation; + var fs = __require("fs"); + var os = __require("os"); + var path2 = __require("path"); + var WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json"; + var CLOUDSDK_CONFIG_DIRECTORY = "gcloud"; + function snakeToCamel(str) { + return str.replace(/([_][^_])/g, (match) => match.slice(1).toUpperCase()); + } + function originalOrCamelOptions(obj) { + function get(key) { + const o = obj || {}; + return o[key] ?? o[snakeToCamel(key)]; + } + return { get }; + } + + class LRUCache { + capacity; + #cache = new Map; + maxAge; + constructor(options) { + this.capacity = options.capacity; + this.maxAge = options.maxAge; + } + #moveToEnd(key, value) { + this.#cache.delete(key); + this.#cache.set(key, { + value, + lastAccessed: Date.now() + }); + } + set(key, value) { + this.#moveToEnd(key, value); + this.#evict(); + } + get(key) { + const item = this.#cache.get(key); + if (!item) + return; + this.#moveToEnd(key, item.value); + this.#evict(); + return item.value; + } + #evict() { + const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; + let oldestItem = this.#cache.entries().next(); + while (!oldestItem.done && (this.#cache.size > this.capacity || oldestItem.value[1].lastAccessed < cutoffDate)) { + this.#cache.delete(oldestItem.value[0]); + oldestItem = this.#cache.entries().next(); } } - return ret; + } + exports.LRUCache = LRUCache; + function removeUndefinedValuesInObject(object2) { + Object.entries(object2).forEach(([key, value]) => { + if (value === undefined || value === "undefined") { + delete object2[key]; + } + }); + return object2; + } + async function isValidFile(filePath) { + try { + const stats = await fs.promises.lstat(filePath); + return stats.isFile(); + } catch (e2) { + return false; + } + } + function getWellKnownCertificateConfigFileLocation() { + const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path2.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path2.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY)); + return path2.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE); + } + function _isWindows() { + return os.platform().startsWith("win"); } }); -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/gaxios.js -var require_gaxios = __commonJS((exports) => { - var __importDefault = exports && exports.__importDefault || function(mod) { - return mod && mod.__esModule ? mod : { default: mod }; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/package.json +var require_package4 = __commonJS((exports, module) => { + module.exports = { + name: "google-auth-library", + version: "10.6.2", + author: "Google Inc.", + description: "Google APIs Authentication Client Library for Node.js", + engines: { + node: ">=18" + }, + main: "./build/src/index.js", + types: "./build/src/index.d.ts", + repository: { + type: "git", + directory: "packages/google-auth-library-nodejs", + url: "https://github.com/googleapis/google-cloud-node-core.git" + }, + keywords: [ + "google", + "api", + "google apis", + "client", + "client library" + ], + dependencies: { + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + gaxios: "^7.1.4", + "gcp-metadata": "8.1.2", + "google-logging-utils": "1.1.3", + jws: "^4.0.0" + }, + devDependencies: { + "@types/base64-js": "^1.2.5", + "@types/jws": "^3.1.0", + "@types/mocha": "^10.0.10", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.8", + "@types/node": "^24.0.0", + "@types/sinon": "^21.0.0", + "assert-rejects": "^1.0.0", + c8: "^10.1.3", + codecov: "^3.8.3", + gts: "^6.0.2", + "is-docker": "^3.0.0", + jsdoc: "^4.0.4", + "jsdoc-fresh": "^5.0.0", + "jsdoc-region-tag": "^4.0.0", + karma: "^6.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^2.0.0", + "karma-mocha": "^2.0.0", + "karma-sourcemap-loader": "^0.4.0", + "karma-webpack": "^5.0.1", + keypair: "^1.0.4", + mocha: "^11.1.0", + mv: "^2.1.1", + ncp: "^2.0.0", + nock: "^14.0.5", + "null-loader": "^4.0.1", + puppeteer: "^24.0.0", + sinon: "^21.0.0", + "ts-loader": "^9.5.2", + typescript: "5.8.3", + webpack: "^5.97.1", + "webpack-cli": "^6.0.1" + }, + files: [ + "build/src", + "!build/src/**/*.map" + ], + scripts: { + test: "c8 mocha build/test", + clean: "gts clean", + prepare: "npm run compile", + lint: "gts check --no-inline-config", + compile: "tsc -p .", + fix: "gts fix", + pretest: "npm run compile -- --sourceMap", + docs: "jsdoc -c .jsdoc.js", + "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 60000", + "presystem-test": "npm run compile -- --sourceMap", + webpack: "webpack", + "browser-test": "karma start", + "docs-test": "echo 'disabled until linkinator is fixed'", + "predocs-test": "npm run docs", + prelint: "cd samples; npm link ../; npm install" + }, + license: "Apache-2.0", + homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs" }; - var _a; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/shared.cjs +var require_shared2 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.Gaxios = undefined; - var extend_1 = __importDefault(require_extend()); - var https_1 = __require("https"); - var common_js_1 = require_common4(); - var retry_js_1 = require_retry(); - var stream_1 = __require("stream"); - var interceptor_js_1 = require_interceptor(); - var randomUUID = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID(); - var HTTP_STATUS_NO_CONTENT = 204; + exports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = undefined; + var pkg = require_package4(); + exports.pkg = pkg; + var PRODUCT_NAME = "google-api-nodejs-client"; + exports.PRODUCT_NAME = PRODUCT_NAME; + var USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; + exports.USER_AGENT = USER_AGENT; +}); - class Gaxios { - agentCache = new Map; - defaults; - interceptors; - constructor(defaults2) { - this.defaults = defaults2 || {}; - this.interceptors = { - request: new interceptor_js_1.GaxiosInterceptorManager, - response: new interceptor_js_1.GaxiosInterceptorManager - }; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/authclient.js +var require_authclient = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = undefined; + var events_1 = __require("events"); + var gaxios_1 = require_src2(); + var util_1 = require_util2(); + var google_logging_utils_1 = require_src3(); + var shared_cjs_1 = require_shared2(); + exports.DEFAULT_UNIVERSE = "googleapis.com"; + exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; + + class AuthClient extends events_1.EventEmitter { + apiKey; + projectId; + quotaProjectId; + transporter; + credentials = {}; + eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; + forceRefreshOnFailure = false; + universeDomain = exports.DEFAULT_UNIVERSE; + static RequestMethodNameSymbol = Symbol("request method name"); + static RequestLogIdSymbol = Symbol("request log id"); + constructor(opts = {}) { + super(); + const options = (0, util_1.originalOrCamelOptions)(opts); + this.apiKey = opts.apiKey; + this.projectId = options.get("project_id") ?? null; + this.quotaProjectId = options.get("quota_project_id"); + this.credentials = options.get("credentials") ?? {}; + this.universeDomain = options.get("universe_domain") ?? exports.DEFAULT_UNIVERSE; + this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions); + if (options.get("useAuthRequestParameters") !== false) { + this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR); + this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR); + } + if (opts.eagerRefreshThresholdMillis) { + this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; + } + this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false; } fetch(...args) { const input = args[0]; @@ -74635,10 +67051,10 @@ var require_gaxios = __commonJS((exports) => { url = new URL(input.url); } if (input && typeof input === "object" && "headers" in input) { - _a.mergeHeaders(headers, input.headers); + gaxios_1.Gaxios.mergeHeaders(headers, input.headers); } if (init3) { - _a.mergeHeaders(headers, new Headers(init3.headers)); + gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init3.headers)); } if (typeof input === "object" && !(input instanceof URL)) { return this.request({ ...init3, ...input, headers, url }); @@ -74646,3860 +67062,2093 @@ var require_gaxios = __commonJS((exports) => { return this.request({ ...init3, headers, url }); } } - async request(opts = {}) { - let prepared = await this.#prepareRequest(opts); - prepared = await this.#applyRequestInterceptors(prepared); - return this.#applyResponseInterceptors(this._request(prepared)); - } - async _defaultAdapter(config) { - const fetchImpl = config.fetchImplementation || this.defaults.fetchImplementation || await _a.#getFetch(); - const preparedOpts = { ...config }; - delete preparedOpts.data; - const res = await fetchImpl(config.url, preparedOpts); - const data = await this.getResponseData(config, res); - if (!Object.getOwnPropertyDescriptor(res, "data")?.configurable) { - Object.defineProperties(res, { - data: { - configurable: true, - writable: true, - enumerable: true, - value: data - } - }); - } - return Object.assign(res, { config, data }); + setCredentials(credentials) { + this.credentials = credentials; } - async _request(opts) { - try { - let translatedResponse; - if (opts.adapter) { - translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); - } else { - translatedResponse = await this._defaultAdapter(opts); - } - if (!opts.validateStatus(translatedResponse.status)) { - if (opts.responseType === "stream") { - const response = []; - for await (const chunk of translatedResponse.data) { - response.push(chunk); - } - translatedResponse.data = response.toString(); - } - const errorInfo = common_js_1.GaxiosError.extractAPIErrorFromResponse(translatedResponse, `Request failed with status code ${translatedResponse.status}`); - throw new common_js_1.GaxiosError(errorInfo?.message, opts, translatedResponse, errorInfo); - } - return translatedResponse; - } catch (e2) { - let err; - if (e2 instanceof common_js_1.GaxiosError) { - err = e2; - } else if (e2 instanceof Error) { - err = new common_js_1.GaxiosError(e2.message, opts, undefined, e2); - } else { - err = new common_js_1.GaxiosError("Unexpected Gaxios Error", opts, undefined, e2); - } - const { shouldRetry, config } = await (0, retry_js_1.getRetryConfig)(err); - if (shouldRetry && config) { - err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; - opts.retryConfig = err.config?.retryConfig; - this.#appendTimeoutToSignal(opts); - return this._request(opts); - } - if (opts.errorRedactor) { - opts.errorRedactor(err); - } - throw err; + addSharedMetadataHeaders(headers) { + if (!headers.has("x-goog-user-project") && this.quotaProjectId) { + headers.set("x-goog-user-project", this.quotaProjectId); } + return headers; } - async getResponseData(opts, res) { - if (res.status === HTTP_STATUS_NO_CONTENT) { - return ""; - } - if (opts.maxContentLength && res.headers.has("content-length") && opts.maxContentLength < Number.parseInt(res.headers?.get("content-length") || "")) { - throw new common_js_1.GaxiosError("Response's `Content-Length` is over the limit.", opts, Object.assign(res, { config: opts })); + addUserProjectAndAuthHeaders(target, source) { + const xGoogUserProject = source.get("x-goog-user-project"); + const authorizationHeader = source.get("authorization"); + if (xGoogUserProject) { + target.set("x-goog-user-project", xGoogUserProject); } - switch (opts.responseType) { - case "stream": - return res.body; - case "json": { - const data = await res.text(); - try { - return JSON.parse(data); - } catch { - return data; - } - } - case "arraybuffer": - return res.arrayBuffer(); - case "blob": - return res.blob(); - case "text": - return res.text(); - default: - return this.getResponseDataFromContentType(res); + if (authorizationHeader) { + target.set("authorization", authorizationHeader); } + return target; } - #urlMayUseProxy(url, noProxy = []) { - const candidate = new URL(url); - const noProxyList = [...noProxy]; - const noProxyEnvList = (process.env.NO_PROXY ?? process.env.no_proxy)?.split(",") || []; - for (const rule of noProxyEnvList) { - noProxyList.push(rule.trim()); - } - for (const rule of noProxyList) { - if (rule instanceof RegExp) { - if (rule.test(candidate.toString())) { - return false; + static log = (0, google_logging_utils_1.log)("auth"); + static DEFAULT_REQUEST_INTERCEPTOR = { + resolved: async (config) => { + if (!config.headers.has("x-goog-api-client")) { + const nodeVersion = process.version.replace(/^v/, ""); + config.headers.set("x-goog-api-client", `gl-node/${nodeVersion}`); + } + const userAgent = config.headers.get("User-Agent"); + if (!userAgent) { + config.headers.set("User-Agent", shared_cjs_1.USER_AGENT); + } else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) { + config.headers.set("User-Agent", `${userAgent} ${shared_cjs_1.USER_AGENT}`); + } + try { + const symbols = config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = `${Math.floor(Math.random() * 1000)}`; + symbols[AuthClient.RequestLogIdSymbol] = logId; + const logObject = { + url: config.url, + headers: config.headers + }; + if (methodName) { + AuthClient.log.info("%s [%s] request %j", methodName, logId, logObject); + } else { + AuthClient.log.info("[%s] request %j", logId, logObject); } - } else if (rule instanceof URL) { - if (rule.origin === candidate.origin) { - return false; + } catch (e2) {} + return config; + } + }; + static DEFAULT_RESPONSE_INTERCEPTOR = { + resolved: async (response) => { + try { + const symbols = response.config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = symbols[AuthClient.RequestLogIdSymbol]; + if (methodName) { + AuthClient.log.info("%s [%s] response %j", methodName, logId, response.data); + } else { + AuthClient.log.info("[%s] response %j", logId, response.data); } - } else if (rule.startsWith("*.") || rule.startsWith(".")) { - const cleanedRule = rule.replace(/^\*\./, "."); - if (candidate.hostname.endsWith(cleanedRule)) { - return false; + } catch (e2) {} + return response; + }, + rejected: async (error) => { + try { + const symbols = error.config; + const methodName = symbols[AuthClient.RequestMethodNameSymbol]; + const logId = symbols[AuthClient.RequestLogIdSymbol]; + if (methodName) { + AuthClient.log.info("%s [%s] error %j", methodName, logId, error.response?.data); + } else { + AuthClient.log.error("[%s] error %j", logId, error.response?.data); } - } else if (rule === candidate.origin || rule === candidate.hostname || rule === candidate.href) { - return false; - } + } catch (e2) {} + throw error; } - return true; + }; + static setMethodName(config, methodName) { + try { + const symbols = config; + symbols[AuthClient.RequestMethodNameSymbol] = methodName; + } catch (e2) {} } - async#applyRequestInterceptors(options) { - let promiseChain = Promise.resolve(options); - for (const interceptor of this.interceptors.request.values()) { - if (interceptor) { - promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"] } - } - return promiseChain; + }; } - async#applyResponseInterceptors(response) { - let promiseChain = Promise.resolve(response); - for (const interceptor of this.interceptors.response.values()) { - if (interceptor) { - promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); - } - } - return promiseChain; + } + exports.AuthClient = AuthClient; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/loginticket.js +var require_loginticket = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.LoginTicket = undefined; + + class LoginTicket { + envelope; + payload; + constructor(env2, pay) { + this.envelope = env2; + this.payload = pay; } - async#prepareRequest(options) { - const preparedHeaders = new Headers(this.defaults.headers); - _a.mergeHeaders(preparedHeaders, options.headers); - const opts = (0, extend_1.default)(true, {}, this.defaults, options); - if (!opts.url) { - throw new Error("URL is required."); + getEnvelope() { + return this.envelope; + } + getPayload() { + return this.payload; + } + getUserId() { + const payload = this.getPayload(); + if (payload && payload.sub) { + return payload.sub; } - if (opts.baseURL) { - opts.url = new URL(opts.url, opts.baseURL); + return null; + } + getAttributes() { + return { envelope: this.getEnvelope(), payload: this.getPayload() }; + } + } + exports.LoginTicket = LoginTicket; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/oauth2client.js +var require_oauth2client = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = undefined; + var gaxios_1 = require_src2(); + var querystring = __require("querystring"); + var stream = __require("stream"); + var formatEcdsa = require_ecdsa_sig_formatter(); + var util_1 = require_util2(); + var crypto_1 = require_crypto3(); + var authclient_1 = require_authclient(); + var loginticket_1 = require_loginticket(); + var CodeChallengeMethod; + (function(CodeChallengeMethod2) { + CodeChallengeMethod2["Plain"] = "plain"; + CodeChallengeMethod2["S256"] = "S256"; + })(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); + var CertificateFormat; + (function(CertificateFormat2) { + CertificateFormat2["PEM"] = "PEM"; + CertificateFormat2["JWK"] = "JWK"; + })(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); + var ClientAuthentication; + (function(ClientAuthentication2) { + ClientAuthentication2["ClientSecretPost"] = "ClientSecretPost"; + ClientAuthentication2["ClientSecretBasic"] = "ClientSecretBasic"; + ClientAuthentication2["None"] = "None"; + })(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); + + class OAuth2Client extends authclient_1.AuthClient { + redirectUri; + certificateCache = {}; + certificateExpiry = null; + certificateCacheFormat = CertificateFormat.PEM; + refreshTokenPromises = new Map; + endpoints; + issuers; + clientAuthentication; + _clientId; + _clientSecret; + refreshHandler; + constructor(options = {}, clientSecret, redirectUri) { + super(typeof options === "object" ? options : {}); + if (typeof options !== "object") { + options = { + clientId: options, + clientSecret, + redirectUri + }; } - opts.url = new URL(opts.url); - if (opts.params) { - if (opts.paramsSerializer) { - let additionalQueryParams = opts.paramsSerializer(opts.params); - if (additionalQueryParams.startsWith("?")) { - additionalQueryParams = additionalQueryParams.slice(1); - } - const prefix = opts.url.toString().includes("?") ? "&" : "?"; - opts.url = opts.url + prefix + additionalQueryParams; - } else { - const url = opts.url instanceof URL ? opts.url : new URL(opts.url); - for (const [key, value] of new URLSearchParams(opts.params)) { - url.searchParams.append(key, value); - } - opts.url = url; - } + this._clientId = options.clientId || options.client_id; + this._clientSecret = options.clientSecret || options.client_secret; + this.redirectUri = options.redirectUri || options.redirect_uris?.[0]; + this.endpoints = { + tokenInfoUrl: "https://oauth2.googleapis.com/tokeninfo", + oauth2AuthBaseUrl: "https://accounts.google.com/o/oauth2/v2/auth", + oauth2TokenUrl: "https://oauth2.googleapis.com/token", + oauth2RevokeUrl: "https://oauth2.googleapis.com/revoke", + oauth2FederatedSignonPemCertsUrl: "https://www.googleapis.com/oauth2/v1/certs", + oauth2FederatedSignonJwkCertsUrl: "https://www.googleapis.com/oauth2/v3/certs", + oauth2IapPublicKeyUrl: "https://www.gstatic.com/iap/verify/public_key", + ...options.endpoints + }; + this.clientAuthentication = options.clientAuthentication || ClientAuthentication.ClientSecretPost; + this.issuers = options.issuers || [ + "accounts.google.com", + "https://accounts.google.com", + this.universeDomain + ]; + } + static GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; + static CLOCK_SKEW_SECS_ = 300; + static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; + generateAuthUrl(opts = {}) { + if (opts.code_challenge_method && !opts.code_challenge) { + throw new Error("If a code_challenge_method is provided, code_challenge must be included."); } - if (typeof options.maxContentLength === "number") { - opts.size = options.maxContentLength; + opts.response_type = opts.response_type || "code"; + opts.client_id = opts.client_id || this._clientId; + opts.redirect_uri = opts.redirect_uri || this.redirectUri; + if (Array.isArray(opts.scope)) { + opts.scope = opts.scope.join(" "); } - if (typeof options.maxRedirects === "number") { - opts.follow = options.maxRedirects; + const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); + return rootUrl + "?" + querystring.stringify(opts); + } + generateCodeVerifier() { + throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead."); + } + async generateCodeVerifierAsync() { + const crypto2 = (0, crypto_1.createCrypto)(); + const randomString = crypto2.randomBytesBase64(96); + const codeVerifier = randomString.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-"); + const unencodedCodeChallenge = await crypto2.sha256DigestBase64(codeVerifier); + const codeChallenge = unencodedCodeChallenge.split("=")[0].replace(/\+/g, "-").replace(/\//g, "_"); + return { codeVerifier, codeChallenge }; + } + getToken(codeOrOptions, callback) { + const options = typeof codeOrOptions === "string" ? { code: codeOrOptions } : codeOrOptions; + if (callback) { + this.getTokenAsync(options).then((r) => callback(null, r.tokens, r.res), (e2) => callback(e2, null, e2.response)); + } else { + return this.getTokenAsync(options); } - const shouldDirectlyPassData = typeof opts.data === "string" || opts.data instanceof ArrayBuffer || opts.data instanceof Blob || globalThis.File && opts.data instanceof File || opts.data instanceof FormData || opts.data instanceof stream_1.Readable || opts.data instanceof ReadableStream || opts.data instanceof String || opts.data instanceof URLSearchParams || ArrayBuffer.isView(opts.data) || ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || ""); - if (opts.multipart?.length) { - const boundary = await randomUUID(); - preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`); - opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary)); - } else if (shouldDirectlyPassData) { - opts.body = opts.data; - } else if (typeof opts.data === "object") { - if (preparedHeaders.get("Content-Type") === "application/x-www-form-urlencoded") { - opts.body = opts.paramsSerializer ? opts.paramsSerializer(opts.data) : new URLSearchParams(opts.data); - } else { - if (!preparedHeaders.has("content-type")) { - preparedHeaders.set("content-type", "application/json"); - } - opts.body = JSON.stringify(opts.data); - } - } else if (opts.data) { - opts.body = opts.data; + } + async getTokenAsync(options) { + const url = this.endpoints.oauth2TokenUrl.toString(); + const headers = new Headers; + const values = { + client_id: options.client_id || this._clientId, + code_verifier: options.codeVerifier, + code: options.code, + grant_type: "authorization_code", + redirect_uri: options.redirect_uri || this.redirectUri + }; + if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { + const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); + headers.set("authorization", `Basic ${basic.toString("base64")}`); } - opts.validateStatus = opts.validateStatus || this.validateStatus; - opts.responseType = opts.responseType || "unknown"; - if (!preparedHeaders.has("accept") && opts.responseType === "json") { - preparedHeaders.set("accept", "application/json"); + if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { + values.client_secret = this._clientSecret; } - const proxy = opts.proxy || process?.env?.HTTPS_PROXY || process?.env?.https_proxy || process?.env?.HTTP_PROXY || process?.env?.http_proxy; - if (opts.agent) {} else if (proxy && this.#urlMayUseProxy(opts.url, opts.noProxy)) { - const HttpsProxyAgent = await _a.#getProxyAgent(); - if (this.agentCache.has(proxy)) { - opts.agent = this.agentCache.get(proxy); - } else { - opts.agent = new HttpsProxyAgent(proxy, { - cert: opts.cert, - key: opts.key - }); - this.agentCache.set(proxy, opts.agent); - } - } else if (opts.cert && opts.key) { - if (this.agentCache.has(opts.key)) { - opts.agent = this.agentCache.get(opts.key); - } else { - opts.agent = new https_1.Agent({ - cert: opts.cert, - key: opts.key - }); - this.agentCache.set(opts.key, opts.agent); - } + const opts = { + ...OAuth2Client.RETRY_CONFIG, + method: "POST", + url, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), + headers + }; + authclient_1.AuthClient.setMethodName(opts, "getTokenAsync"); + const res = await this.transporter.request(opts); + const tokens = res.data; + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; } - if (typeof opts.errorRedactor !== "function" && opts.errorRedactor !== false) { - opts.errorRedactor = common_js_1.defaultErrorRedactor; + this.emit("tokens", tokens); + return { tokens, res }; + } + async refreshToken(refreshToken) { + if (!refreshToken) { + return this.refreshTokenNoCache(refreshToken); } - if (opts.body && !("duplex" in opts)) { - opts.duplex = "half"; + if (this.refreshTokenPromises.has(refreshToken)) { + return this.refreshTokenPromises.get(refreshToken); } - this.#appendTimeoutToSignal(opts); - return Object.assign(opts, { - headers: preparedHeaders, - url: opts.url instanceof URL ? opts.url : new URL(opts.url) + const p = this.refreshTokenNoCache(refreshToken).then((r) => { + this.refreshTokenPromises.delete(refreshToken); + return r; + }, (e2) => { + this.refreshTokenPromises.delete(refreshToken); + throw e2; }); + this.refreshTokenPromises.set(refreshToken, p); + return p; } - #appendTimeoutToSignal(opts) { - if (opts.timeout) { - const timeoutSignal = AbortSignal.timeout(opts.timeout); - if (opts.signal && !opts.signal.aborted) { - opts.signal = AbortSignal.any([opts.signal, timeoutSignal]); - } else { - opts.signal = timeoutSignal; + async refreshTokenNoCache(refreshToken) { + if (!refreshToken) { + throw new Error("No refresh token is set."); + } + const url = this.endpoints.oauth2TokenUrl.toString(); + const data = { + refresh_token: refreshToken, + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: "refresh_token" + }; + let res; + try { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + method: "POST", + url, + data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)) + }; + authclient_1.AuthClient.setMethodName(opts, "refreshTokenNoCache"); + res = await this.transporter.request(opts); + } catch (e2) { + if (e2 instanceof gaxios_1.GaxiosError && e2.message === "invalid_grant" && e2.response?.data && /ReAuth/i.test(e2.response.data.error_description)) { + e2.message = JSON.stringify(e2.response.data); } + throw e2; } + const tokens = res.data; + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit("tokens", tokens); + return { tokens, res }; } - validateStatus(status) { - return status >= 200 && status < 300; - } - async getResponseDataFromContentType(response) { - let contentType = response.headers.get("Content-Type"); - if (contentType === null) { - return response.text(); + refreshAccessToken(callback) { + if (callback) { + this.refreshAccessTokenAsync().then((r) => callback(null, r.credentials, r.res), callback); + } else { + return this.refreshAccessTokenAsync(); } - contentType = contentType.toLowerCase(); - if (contentType.includes("application/json")) { - let data = await response.text(); - try { - data = JSON.parse(data); - } catch {} - return data; - } else if (contentType.match(/^text\//)) { - return response.text(); + } + async refreshAccessTokenAsync() { + const r = await this.refreshToken(this.credentials.refresh_token); + const tokens = r.tokens; + tokens.refresh_token = this.credentials.refresh_token; + this.credentials = tokens; + return { credentials: this.credentials, res: r.res }; + } + getAccessToken(callback) { + if (callback) { + this.getAccessTokenAsync().then((r) => callback(null, r.token, r.res), callback); } else { - return response.blob(); + return this.getAccessTokenAsync(); } } - async* getMultipartRequest(multipartOptions, boundary) { - const finale = `--${boundary}--`; - for (const currentPart of multipartOptions) { - const partContentType = currentPart.headers.get("Content-Type") || "application/octet-stream"; - const preamble = `--${boundary}\r -Content-Type: ${partContentType}\r -\r -`; - yield preamble; - if (typeof currentPart.content === "string") { - yield currentPart.content; - } else { - yield* currentPart.content; + async getAccessTokenAsync() { + const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); + if (shouldRefresh) { + if (!this.credentials.refresh_token) { + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken?.access_token) { + this.setCredentials(refreshedAccessToken); + return { token: this.credentials.access_token }; + } + } else { + throw new Error("No refresh token or refresh handler callback is set."); + } } - yield `\r -`; + const r = await this.refreshAccessTokenAsync(); + if (!r.credentials || r.credentials && !r.credentials.access_token) { + throw new Error("Could not refresh access token."); + } + return { token: r.credentials.access_token, res: r.res }; + } else { + return { token: this.credentials.access_token }; } - yield finale; - } - static #proxyAgent; - static #fetch; - static async#getProxyAgent() { - this.#proxyAgent ||= (await Promise.resolve().then(() => __toESM(require_dist6()))).HttpsProxyAgent; - return this.#proxyAgent; } - static async#getFetch() { - const hasWindow = typeof window !== "undefined" && !!window; - this.#fetch ||= hasWindow ? window.fetch : (await import("node-fetch")).default; - return this.#fetch; + async getRequestHeaders(url) { + const headers = (await this.getRequestMetadataAsync(url)).headers; + return headers; } - static mergeHeaders(base, ...append) { - base = base instanceof Headers ? base : new Headers(base); - for (const headers of append) { - const add = headers instanceof Headers ? headers : new Headers(headers); - add.forEach((value, key) => { - key === "set-cookie" ? base.append(key, value) : base.set(key, value); + async getRequestMetadataAsync(url) { + const thisCreds = this.credentials; + if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey && !this.refreshHandler) { + throw new Error("No access, refresh token, API key or refresh handler callback is set."); + } + if (thisCreds.access_token && !this.isTokenExpiring()) { + thisCreds.token_type = thisCreds.token_type || "Bearer"; + const headers2 = new Headers({ + authorization: thisCreds.token_type + " " + thisCreds.access_token }); + return { headers: this.addSharedMetadataHeaders(headers2) }; } - return base; - } - } - exports.Gaxios = Gaxios; - _a = Gaxios; -}); - -// node_modules/.pnpm/gaxios@7.1.4/node_modules/gaxios/build/cjs/src/index.js -var require_src2 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) - __createBinding(exports2, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.instance = exports.Gaxios = exports.GaxiosError = undefined; - exports.request = request; - var gaxios_js_1 = require_gaxios(); - Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function() { - return gaxios_js_1.Gaxios; - } }); - var common_js_1 = require_common4(); - Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function() { - return common_js_1.GaxiosError; - } }); - __exportStar(require_interceptor(), exports); - exports.instance = new gaxios_js_1.Gaxios; - async function request(opts) { - return exports.instance.request(opts); - } -}); - -// node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js -var require_bignumber = __commonJS((exports, module) => { - (function(globalObject) { - var BigNumber3, isNumeric3 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, mathceil3 = Math.ceil, mathfloor3 = Math.floor, bignumberError3 = "[BigNumber Error] ", tooManyDigits3 = bignumberError3 + "Number primitive has more than 15 significant digits: ", BASE3 = 100000000000000, LOG_BASE3 = 14, MAX_SAFE_INTEGER3 = 9007199254740991, POWS_TEN3 = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000], SQRT_BASE3 = 1e7, MAX3 = 1e9; - function clone4(configObject) { - var div, convertBase, parseNumeric, P = BigNumber4.prototype = { constructor: BigNumber4, toString: null, valueOf: null }, ONE = new BigNumber4(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { - prefix: "", - groupSize: 3, - secondaryGroupSize: 0, - groupSeparator: ",", - decimalSeparator: ".", - fractionGroupSize: 0, - fractionGroupSeparator: "\xA0", - suffix: "" - }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber4(v, b) { - var alphabet3, c, caseChanged, e2, i, isNum, len, str, x = this; - if (!(x instanceof BigNumber4)) - return new BigNumber4(v, b); - if (b == null) { - if (v && v._isBigNumber === true) { - x.s = v.s; - if (!v.c || v.e > MAX_EXP) { - x.c = x.e = null; - } else if (v.e < MIN_EXP) { - x.c = [x.e = 0]; - } else { - x.e = v.e; - x.c = v.c.slice(); - } - return; - } - if ((isNum = typeof v == "number") && v * 0 == 0) { - x.s = 1 / v < 0 ? (v = -v, -1) : 1; - if (v === ~~v) { - for (e2 = 0, i = v;i >= 10; i /= 10, e2++) - ; - if (e2 > MAX_EXP) { - x.c = x.e = null; - } else { - x.e = e2; - x.c = [v]; - } - return; - } - str = String(v); - } else { - if (!isNumeric3.test(str = String(v))) - return parseNumeric(x, str, isNum); - x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; - } - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - if ((i = str.search(/e/i)) > 0) { - if (e2 < 0) - e2 = i; - e2 += +str.slice(i + 1); - str = str.substring(0, i); - } else if (e2 < 0) { - e2 = str.length; - } - } else { - intCheck3(b, 2, ALPHABET.length, "Base"); - if (b == 10 && alphabetHasNormalDecimalDigits) { - x = new BigNumber4(v); - return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); - } - str = String(v); - if (isNum = typeof v == "number") { - if (v * 0 != 0) - return parseNumeric(x, str, isNum, b); - x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber4.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits3 + v); - } - } else { - x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; - } - alphabet3 = ALPHABET.slice(0, b); - e2 = i = 0; - for (len = str.length;i < len; i++) { - if (alphabet3.indexOf(c = str.charAt(i)) < 0) { - if (c == ".") { - if (i > e2) { - e2 = len; - continue; - } - } else if (!caseChanged) { - if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { - caseChanged = true; - i = -1; - e2 = 0; - continue; - } - } - return parseNumeric(x, String(v), isNum, b); - } - } - isNum = false; - str = convertBase(str, b, 10, x.s); - if ((e2 = str.indexOf(".")) > -1) - str = str.replace(".", ""); - else - e2 = str.length; - } - for (i = 0;str.charCodeAt(i) === 48; i++) - ; - for (len = str.length;str.charCodeAt(--len) === 48; ) - ; - if (str = str.slice(i, ++len)) { - len -= i; - if (isNum && BigNumber4.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER3 || v !== mathfloor3(v))) { - throw Error(tooManyDigits3 + x.s * v); - } - if ((e2 = e2 - i - 1) > MAX_EXP) { - x.c = x.e = null; - } else if (e2 < MIN_EXP) { - x.c = [x.e = 0]; - } else { - x.e = e2; - x.c = []; - i = (e2 + 1) % LOG_BASE3; - if (e2 < 0) - i += LOG_BASE3; - if (i < len) { - if (i) - x.c.push(+str.slice(0, i)); - for (len -= LOG_BASE3;i < len; ) { - x.c.push(+str.slice(i, i += LOG_BASE3)); - } - i = LOG_BASE3 - (str = str.slice(i)).length; - } else { - i -= len; - } - for (;i--; str += "0") - ; - x.c.push(+str); - } - } else { - x.c = [x.e = 0]; + if (this.refreshHandler) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken?.access_token) { + this.setCredentials(refreshedAccessToken); + const headers2 = new Headers({ + authorization: "Bearer " + this.credentials.access_token + }); + return { headers: this.addSharedMetadataHeaders(headers2) }; } } - BigNumber4.clone = clone4; - BigNumber4.ROUND_UP = 0; - BigNumber4.ROUND_DOWN = 1; - BigNumber4.ROUND_CEIL = 2; - BigNumber4.ROUND_FLOOR = 3; - BigNumber4.ROUND_HALF_UP = 4; - BigNumber4.ROUND_HALF_DOWN = 5; - BigNumber4.ROUND_HALF_EVEN = 6; - BigNumber4.ROUND_HALF_CEIL = 7; - BigNumber4.ROUND_HALF_FLOOR = 8; - BigNumber4.EUCLID = 9; - BigNumber4.config = BigNumber4.set = function(obj) { - var p, v; - if (obj != null) { - if (typeof obj == "object") { - if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) { - v = obj[p]; - intCheck3(v, 0, MAX3, p); - DECIMAL_PLACES = v; - } - if (obj.hasOwnProperty(p = "ROUNDING_MODE")) { - v = obj[p]; - intCheck3(v, 0, 8, p); - ROUNDING_MODE = v; - } - if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) { - v = obj[p]; - if (v && v.pop) { - intCheck3(v[0], -MAX3, 0, p); - intCheck3(v[1], 0, MAX3, p); - TO_EXP_NEG = v[0]; - TO_EXP_POS = v[1]; - } else { - intCheck3(v, -MAX3, MAX3, p); - TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); - } - } - if (obj.hasOwnProperty(p = "RANGE")) { - v = obj[p]; - if (v && v.pop) { - intCheck3(v[0], -MAX3, -1, p); - intCheck3(v[1], 1, MAX3, p); - MIN_EXP = v[0]; - MAX_EXP = v[1]; - } else { - intCheck3(v, -MAX3, MAX3, p); - if (v) { - MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); - } else { - throw Error(bignumberError3 + p + " cannot be zero: " + v); - } - } - } - if (obj.hasOwnProperty(p = "CRYPTO")) { - v = obj[p]; - if (v === !!v) { - if (v) { - if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { - CRYPTO = v; - } else { - CRYPTO = !v; - throw Error(bignumberError3 + "crypto unavailable"); - } - } else { - CRYPTO = v; - } - } else { - throw Error(bignumberError3 + p + " not true or false: " + v); - } - } - if (obj.hasOwnProperty(p = "MODULO_MODE")) { - v = obj[p]; - intCheck3(v, 0, 9, p); - MODULO_MODE = v; - } - if (obj.hasOwnProperty(p = "POW_PRECISION")) { - v = obj[p]; - intCheck3(v, 0, MAX3, p); - POW_PRECISION = v; - } - if (obj.hasOwnProperty(p = "FORMAT")) { - v = obj[p]; - if (typeof v == "object") - FORMAT = v; - else - throw Error(bignumberError3 + p + " not an object: " + v); - } - if (obj.hasOwnProperty(p = "ALPHABET")) { - v = obj[p]; - if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { - alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; - ALPHABET = v; - } else { - throw Error(bignumberError3 + p + " invalid: " + v); - } - } - } else { - throw Error(bignumberError3 + "Object expected: " + obj); - } + if (this.apiKey) { + return { headers: new Headers({ "X-Goog-Api-Key": this.apiKey }) }; + } + let r = null; + let tokens = null; + try { + r = await this.refreshToken(thisCreds.refresh_token); + tokens = r.tokens; + } catch (err) { + const e2 = err; + if (e2.response && (e2.response.status === 403 || e2.response.status === 404)) { + e2.message = `Could not refresh access token: ${e2.message}`; } - return { - DECIMAL_PLACES, - ROUNDING_MODE, - EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], - RANGE: [MIN_EXP, MAX_EXP], - CRYPTO, - MODULO_MODE, - POW_PRECISION, - FORMAT, - ALPHABET - }; - }; - BigNumber4.isBigNumber = function(v) { - if (!v || v._isBigNumber !== true) - return false; - if (!BigNumber4.DEBUG) - return true; - var i, n, c = v.c, e2 = v.e, s = v.s; - out: - if ({}.toString.call(c) == "[object Array]") { - if ((s === 1 || s === -1) && e2 >= -MAX3 && e2 <= MAX3 && e2 === mathfloor3(e2)) { - if (c[0] === 0) { - if (e2 === 0 && c.length === 1) - return true; - break out; - } - i = (e2 + 1) % LOG_BASE3; - if (i < 1) - i += LOG_BASE3; - if (String(c[0]).length == i) { - for (i = 0;i < c.length; i++) { - n = c[i]; - if (n < 0 || n >= BASE3 || n !== mathfloor3(n)) - break out; - } - if (n !== 0) - return true; - } - } - } else if (c === null && e2 === null && (s === null || s === 1 || s === -1)) { - return true; - } - throw Error(bignumberError3 + "Invalid BigNumber: " + v); - }; - BigNumber4.maximum = BigNumber4.max = function() { - return maxOrMin(arguments, -1); - }; - BigNumber4.minimum = BigNumber4.min = function() { - return maxOrMin(arguments, 1); - }; - BigNumber4.random = function() { - var pow2_53 = 9007199254740992; - var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor3(Math.random() * pow2_53); - } : function() { - return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); - }; - return function(dp) { - var a, b, e2, k, v, i = 0, c = [], rand = new BigNumber4(ONE); - if (dp == null) - dp = DECIMAL_PLACES; - else - intCheck3(dp, 0, MAX3); - k = mathceil3(dp / LOG_BASE3); - if (CRYPTO) { - if (crypto.getRandomValues) { - a = crypto.getRandomValues(new Uint32Array(k *= 2)); - for (;i < k; ) { - v = a[i] * 131072 + (a[i + 1] >>> 11); - if (v >= 9000000000000000) { - b = crypto.getRandomValues(new Uint32Array(2)); - a[i] = b[0]; - a[i + 1] = b[1]; - } else { - c.push(v % 100000000000000); - i += 2; - } - } - i = k / 2; - } else if (crypto.randomBytes) { - a = crypto.randomBytes(k *= 7); - for (;i < k; ) { - v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; - if (v >= 9000000000000000) { - crypto.randomBytes(7).copy(a, i); - } else { - c.push(v % 100000000000000); - i += 7; - } - } - i = k / 7; - } else { - CRYPTO = false; - throw Error(bignumberError3 + "crypto unavailable"); - } - } - if (!CRYPTO) { - for (;i < k; ) { - v = random53bitInt(); - if (v < 9000000000000000) - c[i++] = v % 100000000000000; - } - } - k = c[--i]; - dp %= LOG_BASE3; - if (k && dp) { - v = POWS_TEN3[LOG_BASE3 - dp]; - c[i] = mathfloor3(k / v) * v; - } - for (;c[i] === 0; c.pop(), i--) - ; - if (i < 0) { - c = [e2 = 0]; - } else { - for (e2 = -1;c[0] === 0; c.splice(0, 1), e2 -= LOG_BASE3) - ; - for (i = 1, v = c[0];v >= 10; v /= 10, i++) - ; - if (i < LOG_BASE3) - e2 -= LOG_BASE3 - i; - } - rand.e = e2; - rand.c = c; - return rand; - }; - }(); - BigNumber4.sum = function() { - var i = 1, args = arguments, sum = new BigNumber4(args[0]); - for (;i < args.length; ) - sum = sum.plus(args[i++]); - return sum; + throw e2; + } + const credentials = this.credentials; + credentials.token_type = credentials.token_type || "Bearer"; + tokens.refresh_token = credentials.refresh_token; + this.credentials = tokens; + const headers = new Headers({ + authorization: credentials.token_type + " " + tokens.access_token + }); + return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; + } + static getRevokeTokenUrl(token) { + return new OAuth2Client().getRevokeTokenURL(token).toString(); + } + getRevokeTokenURL(token) { + const url = new URL(this.endpoints.oauth2RevokeUrl); + url.searchParams.append("token", token); + return url; + } + revokeToken(token, callback) { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url: this.getRevokeTokenURL(token).toString(), + method: "POST" }; - convertBase = function() { - var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet3) { - var j, arr = [0], arrL, i = 0, len = str.length; - for (;i < len; ) { - for (arrL = arr.length;arrL--; arr[arrL] *= baseIn) - ; - arr[0] += alphabet3.indexOf(str.charAt(i++)); - for (j = 0;j < arr.length; j++) { - if (arr[j] > baseOut - 1) { - if (arr[j + 1] == null) - arr[j + 1] = 0; - arr[j + 1] += arr[j] / baseOut | 0; - arr[j] %= baseOut; - } - } - } - return arr.reverse(); + authclient_1.AuthClient.setMethodName(opts, "revokeToken"); + if (callback) { + this.transporter.request(opts).then((r) => callback(null, r), callback); + } else { + return this.transporter.request(opts); + } + } + revokeCredentials(callback) { + if (callback) { + this.revokeCredentialsAsync().then((res) => callback(null, res), callback); + } else { + return this.revokeCredentialsAsync(); + } + } + async revokeCredentialsAsync() { + const token = this.credentials.access_token; + this.credentials = {}; + if (token) { + return this.revokeToken(token); + } else { + throw new Error("No access token to revoke."); + } + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then((r) => callback(null, r), (e2) => { + return callback(e2, e2.response); + }); + } else { + return this.requestAsync(opts); + } + } + async requestAsync(opts, reAuthRetried = false) { + try { + const r = await this.getRequestMetadataAsync(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, r.headers); + if (this.apiKey) { + opts.headers.set("X-Goog-Api-Key", this.apiKey); } - return function(str, baseIn, baseOut, sign, callerIsToString) { - var alphabet3, d, e2, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; - if (i >= 0) { - k = POW_PRECISION; - POW_PRECISION = 0; - str = str.replace(".", ""); - y = new BigNumber4(baseIn); - x = y.pow(str.length - i); - POW_PRECISION = k; - y.c = toBaseOut(toFixedPoint3(coeffToString3(x.c), x.e, "0"), 10, baseOut, decimal); - y.e = y.c.length; - } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet3 = ALPHABET, decimal) : (alphabet3 = decimal, ALPHABET)); - e2 = k = xc.length; - for (;xc[--k] == 0; xc.pop()) - ; - if (!xc[0]) - return alphabet3.charAt(0); - if (i < 0) { - --e2; - } else { - x.c = xc; - x.e = e2; - x.s = sign; - x = div(x, y, dp, rm, baseOut); - xc = x.c; - r = x.r; - e2 = x.e; - } - d = e2 + dp + 1; - i = xc[d]; - k = baseOut / 2; - r = r || d < 0 || xc[d + 1] != null; - r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); - if (d < 1 || !xc[0]) { - str = r ? toFixedPoint3(alphabet3.charAt(1), -dp, alphabet3.charAt(0)) : alphabet3.charAt(0); - } else { - xc.length = d; - if (r) { - for (--baseOut;++xc[--d] > baseOut; ) { - xc[d] = 0; - if (!d) { - ++e2; - xc = [1].concat(xc); - } - } + return await this.transporter.request(opts); + } catch (e2) { + const res = e2.response; + if (res) { + const statusCode = res.status; + const mayRequireRefresh = this.credentials && this.credentials.access_token && this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure); + const mayRequireRefreshWithNoRefreshToken = this.credentials && this.credentials.access_token && !this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure) && this.refreshHandler; + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefresh) { + await this.refreshAccessTokenAsync(); + return this.requestAsync(opts, true); + } else if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefreshWithNoRefreshToken) { + const refreshedAccessToken = await this.processAndValidateRefreshHandler(); + if (refreshedAccessToken?.access_token) { + this.setCredentials(refreshedAccessToken); } - for (k = xc.length;!xc[--k]; ) - ; - for (i = 0, str = "";i <= k; str += alphabet3.charAt(xc[i++])) - ; - str = toFixedPoint3(str, e2, alphabet3.charAt(0)); - } - return str; - }; - }(); - div = function() { - function multiply(x, k, base) { - var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE3, khi = k / SQRT_BASE3 | 0; - for (x = x.slice();i--; ) { - xlo = x[i] % SQRT_BASE3; - xhi = x[i] / SQRT_BASE3 | 0; - m = khi * xlo + xhi * klo; - temp = klo * xlo + m % SQRT_BASE3 * SQRT_BASE3 + carry; - carry = (temp / base | 0) + (m / SQRT_BASE3 | 0) + khi * xhi; - x[i] = temp % base; + return this.requestAsync(opts, true); } - if (carry) - x = [carry].concat(x); - return x; } - function compare5(a, b, aL, bL) { - var i, cmp; - if (aL != bL) { - cmp = aL > bL ? 1 : -1; - } else { - for (i = cmp = 0;i < aL; i++) { - if (a[i] != b[i]) { - cmp = a[i] > b[i] ? 1 : -1; - break; - } - } - } - return cmp; + throw e2; + } + } + verifyIdToken(options, callback) { + if (callback && typeof callback !== "function") { + throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry."); + } + if (callback) { + this.verifyIdTokenAsync(options).then((r) => callback(null, r), callback); + } else { + return this.verifyIdTokenAsync(options); + } + } + async verifyIdTokenAsync(options) { + if (!options.idToken) { + throw new Error("The verifyIdToken method requires an ID Token"); + } + const response = await this.getFederatedSignonCertsAsync(); + const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); + return login; + } + async getTokenInfo(accessToken) { + const { data } = await this.transporter.request({ + ...OAuth2Client.RETRY_CONFIG, + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded;charset=UTF-8", + authorization: `Bearer ${accessToken}` + }, + url: this.endpoints.tokenInfoUrl.toString() + }); + const info = Object.assign({ + expiry_date: new Date().getTime() + data.expires_in * 1000, + scopes: data.scope.split(" ") + }, data); + delete info.expires_in; + delete info.scope; + return info; + } + getFederatedSignonCerts(callback) { + if (callback) { + this.getFederatedSignonCertsAsync().then((r) => callback(null, r.certs, r.res), callback); + } else { + return this.getFederatedSignonCertsAsync(); + } + } + async getFederatedSignonCertsAsync() { + const nowTime = new Date().getTime(); + const format = (0, crypto_1.hasBrowserCrypto)() ? CertificateFormat.JWK : CertificateFormat.PEM; + if (this.certificateExpiry && nowTime < this.certificateExpiry.getTime() && this.certificateCacheFormat === format) { + return { certs: this.certificateCache, format }; + } + let res; + let url; + switch (format) { + case CertificateFormat.PEM: + url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); + break; + case CertificateFormat.JWK: + url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + try { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url + }; + authclient_1.AuthClient.setMethodName(opts, "getFederatedSignonCertsAsync"); + res = await this.transporter.request(opts); + } catch (e2) { + if (e2 instanceof Error) { + e2.message = `Failed to retrieve verification certificates: ${e2.message}`; } - function subtract(a, b, aL, base) { - var i = 0; - for (;aL--; ) { - a[aL] -= i; - i = a[aL] < b[aL] ? 1 : 0; - a[aL] = i * base + a[aL] - b[aL]; - } - for (;!a[0] && a.length > 1; a.splice(0, 1)) - ; + throw e2; + } + const cacheControl = res?.headers.get("cache-control"); + let cacheAge = -1; + if (cacheControl) { + const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups?.maxAge; + if (maxAge) { + cacheAge = Number(maxAge) * 1000; } - return function(x, y, dp, rm, base) { - var cmp, e2, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; - if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber4(!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s * 0 : s / 0); - } - q = new BigNumber4(s); - qc = q.c = []; - e2 = x.e - y.e; - s = dp + e2 + 1; - if (!base) { - base = BASE3; - e2 = bitFloor3(x.e / LOG_BASE3) - bitFloor3(y.e / LOG_BASE3); - s = s / LOG_BASE3 | 0; - } - for (i = 0;yc[i] == (xc[i] || 0); i++) - ; - if (yc[i] > (xc[i] || 0)) - e2--; - if (s < 0) { - qc.push(1); - more = true; - } else { - xL = xc.length; - yL = yc.length; - i = 0; - s += 2; - n = mathfloor3(base / (yc[0] + 1)); - if (n > 1) { - yc = multiply(yc, n, base); - xc = multiply(xc, n, base); - yL = yc.length; - xL = xc.length; - } - xi = yL; - rem = xc.slice(0, yL); - remL = rem.length; - for (;remL < yL; rem[remL++] = 0) - ; - yz = yc.slice(); - yz = [0].concat(yz); - yc0 = yc[0]; - if (yc[1] >= base / 2) - yc0++; - do { - n = 0; - cmp = compare5(yc, rem, yL, remL); - if (cmp < 0) { - rem0 = rem[0]; - if (yL != remL) - rem0 = rem0 * base + (rem[1] || 0); - n = mathfloor3(rem0 / yc0); - if (n > 1) { - if (n >= base) - n = base - 1; - prod = multiply(yc, n, base); - prodL = prod.length; - remL = rem.length; - while (compare5(prod, rem, prodL, remL) == 1) { - n--; - subtract(prod, yL < prodL ? yz : yc, prodL, base); - prodL = prod.length; - cmp = 1; - } - } else { - if (n == 0) { - cmp = n = 1; - } - prod = yc.slice(); - prodL = prod.length; - } - if (prodL < remL) - prod = [0].concat(prod); - subtract(rem, prod, remL, base); - remL = rem.length; - if (cmp == -1) { - while (compare5(yc, rem, yL, remL) < 1) { - n++; - subtract(rem, yL < remL ? yz : yc, remL, base); - remL = rem.length; - } - } - } else if (cmp === 0) { - n++; - rem = [0]; - } - qc[i++] = n; - if (rem[0]) { - rem[remL++] = xc[xi] || 0; - } else { - rem = [xc[xi]]; - remL = 1; - } - } while ((xi++ < xL || rem[0] != null) && s--); - more = rem[0] != null; - if (!qc[0]) - qc.splice(0, 1); - } - if (base == BASE3) { - for (i = 1, s = qc[0];s >= 10; s /= 10, i++) - ; - round(q, dp + (q.e = i + e2 * LOG_BASE3 - 1) + 1, rm, more); - } else { - q.e = e2; - q.r = +more; + } + let certificates = {}; + switch (format) { + case CertificateFormat.PEM: + certificates = res.data; + break; + case CertificateFormat.JWK: + for (const key of res.data.keys) { + certificates[key.kid] = key; } - return q; + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + const now = new Date; + this.certificateExpiry = cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); + this.certificateCache = certificates; + this.certificateCacheFormat = format; + return { certs: certificates, format, res }; + } + getIapPublicKeys(callback) { + if (callback) { + this.getIapPublicKeysAsync().then((r) => callback(null, r.pubkeys, r.res), callback); + } else { + return this.getIapPublicKeysAsync(); + } + } + async getIapPublicKeysAsync() { + let res; + const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); + try { + const opts = { + ...OAuth2Client.RETRY_CONFIG, + url }; - }(); - function format(n, i, rm, id) { - var c0, e2, ne2, len, str; - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck3(rm, 0, 8); - if (!n.c) - return n.toString(); - c0 = n.c[0]; - ne2 = n.e; - if (i == null) { - str = coeffToString3(n.c); - str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential3(str, ne2) : toFixedPoint3(str, ne2, "0"); - } else { - n = round(new BigNumber4(n), i, rm); - e2 = n.e; - str = coeffToString3(n.c); - len = str.length; - if (id == 1 || id == 2 && (i <= e2 || e2 <= TO_EXP_NEG)) { - for (;len < i; str += "0", len++) - ; - str = toExponential3(str, e2); - } else { - i -= ne2 + (id === 2 && e2 > ne2); - str = toFixedPoint3(str, e2, "0"); - if (e2 + 1 > len) { - if (--i > 0) - for (str += ".";i--; str += "0") - ; - } else { - i += e2 - len; - if (i > 0) { - if (e2 + 1 == len) - str += "."; - for (;i--; str += "0") - ; - } - } - } + authclient_1.AuthClient.setMethodName(opts, "getIapPublicKeysAsync"); + res = await this.transporter.request(opts); + } catch (e2) { + if (e2 instanceof Error) { + e2.message = `Failed to retrieve verification certificates: ${e2.message}`; } - return n.s < 0 && c0 ? "-" + str : str; + throw e2; } - function maxOrMin(args, n) { - var k, y, i = 1, x = new BigNumber4(args[0]); - for (;i < args.length; i++) { - y = new BigNumber4(args[i]); - if (!y.s || (k = compare4(x, y)) === n || k === 0 && x.s === n) { - x = y; - } + return { pubkeys: res.data, res }; + } + verifySignedJwtWithCerts() { + throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead."); + } + async verifySignedJwtWithCertsAsync(jwt2, certs, requiredAudience, issuers, maxExpiry) { + const crypto2 = (0, crypto_1.createCrypto)(); + if (!maxExpiry) { + maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; + } + const segments = jwt2.split("."); + if (segments.length !== 3) { + throw new Error("Wrong number of segments in token: " + jwt2); + } + const signed = segments[0] + "." + segments[1]; + let signature = segments[2]; + let envelope; + let payload; + try { + envelope = JSON.parse(crypto2.decodeBase64StringUtf8(segments[0])); + } catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; } - return x; + throw err; } - function normalise(n, c, e2) { - var i = 1, j = c.length; - for (;!c[--j]; c.pop()) - ; - for (j = c[0];j >= 10; j /= 10, i++) - ; - if ((e2 = i + e2 * LOG_BASE3 - 1) > MAX_EXP) { - n.c = n.e = null; - } else if (e2 < MIN_EXP) { - n.c = [n.e = 0]; - } else { - n.e = e2; - n.c = c; + if (!envelope) { + throw new Error("Can't parse token envelope: " + segments[0]); + } + try { + payload = JSON.parse(crypto2.decodeBase64StringUtf8(segments[1])); + } catch (err) { + if (err instanceof Error) { + err.message = `Can't parse token payload '${segments[0]}`; } - return n; + throw err; } - parseNumeric = function() { - var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; - return function(x, str, isNum, b) { - var base, s = isNum ? str : str.replace(whitespaceOrPlus, ""); - if (isInfinityOrNaN.test(s)) { - x.s = isNaN(s) ? null : s < 0 ? -1 : 1; - } else { - if (!isNum) { - s = s.replace(basePrefix, function(m, p1, p2) { - base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; - return !b || b == base ? p1 : m; - }); - if (b) { - base = b; - s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); - } - if (str != s) - return new BigNumber4(s, base); - } - if (BigNumber4.DEBUG) { - throw Error(bignumberError3 + "Not a" + (b ? " base " + b : "") + " number: " + str); - } - x.s = null; - } - x.c = x.e = null; - }; - }(); - function round(x, sd, rm, r) { - var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN3; - if (xc) { - out: { - for (d = 1, k = xc[0];k >= 10; k /= 10, d++) - ; - i = sd - d; - if (i < 0) { - i += LOG_BASE3; - j = sd; - n = xc[ni = 0]; - rd = mathfloor3(n / pows10[d - j - 1] % 10); - } else { - ni = mathceil3((i + 1) / LOG_BASE3); - if (ni >= xc.length) { - if (r) { - for (;xc.length <= ni; xc.push(0)) - ; - n = rd = 0; - d = 1; - i %= LOG_BASE3; - j = i - LOG_BASE3 + 1; - } else { - break out; - } - } else { - n = k = xc[ni]; - for (d = 1;k >= 10; k /= 10, d++) - ; - i %= LOG_BASE3; - j = i - LOG_BASE3 + d; - rd = j < 0 ? 0 : mathfloor3(n / pows10[d - j - 1] % 10); - } - } - r = r || sd < 0 || xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); - r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7)); - if (sd < 1 || !xc[0]) { - xc.length = 0; - if (r) { - sd -= x.e + 1; - xc[0] = pows10[(LOG_BASE3 - sd % LOG_BASE3) % LOG_BASE3]; - x.e = -sd || 0; - } else { - xc[0] = x.e = 0; - } - return x; - } - if (i == 0) { - xc.length = ni; - k = 1; - ni--; - } else { - xc.length = ni + 1; - k = pows10[LOG_BASE3 - i]; - xc[ni] = j > 0 ? mathfloor3(n / pows10[d - j] % pows10[j]) * k : 0; - } - if (r) { - for (;; ) { - if (ni == 0) { - for (i = 1, j = xc[0];j >= 10; j /= 10, i++) - ; - j = xc[0] += k; - for (k = 1;j >= 10; j /= 10, k++) - ; - if (i != k) { - x.e++; - if (xc[0] == BASE3) - xc[0] = 1; - } - break; - } else { - xc[ni] += k; - if (xc[ni] != BASE3) - break; - xc[ni--] = 0; - k = 1; - } - } - } - for (i = xc.length;xc[--i] === 0; xc.pop()) - ; - } - if (x.e > MAX_EXP) { - x.c = x.e = null; - } else if (x.e < MIN_EXP) { - x.c = [x.e = 0]; - } - } - return x; + if (!payload) { + throw new Error("Can't parse token payload: " + segments[1]); } - function valueOf(n) { - var str, e2 = n.e; - if (e2 === null) - return n.toString(); - str = coeffToString3(n.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential3(str, e2) : toFixedPoint3(str, e2, "0"); - return n.s < 0 ? "-" + str : str; + if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { + throw new Error("No pem found for envelope: " + JSON.stringify(envelope)); } - P.absoluteValue = P.abs = function() { - var x = new BigNumber4(this); - if (x.s < 0) - x.s = 1; - return x; - }; - P.comparedTo = function(y, b) { - return compare4(this, new BigNumber4(y, b)); - }; - P.decimalPlaces = P.dp = function(dp, rm) { - var c, n, v, x = this; - if (dp != null) { - intCheck3(dp, 0, MAX3); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck3(rm, 0, 8); - return round(new BigNumber4(x), dp + x.e + 1, rm); - } - if (!(c = x.c)) - return null; - n = ((v = c.length - 1) - bitFloor3(this.e / LOG_BASE3)) * LOG_BASE3; - if (v = c[v]) - for (;v % 10 == 0; v /= 10, n--) - ; - if (n < 0) - n = 0; - return n; - }; - P.dividedBy = P.div = function(y, b) { - return div(this, new BigNumber4(y, b), DECIMAL_PLACES, ROUNDING_MODE); - }; - P.dividedToIntegerBy = P.idiv = function(y, b) { - return div(this, new BigNumber4(y, b), 0, 1); - }; - P.exponentiatedBy = P.pow = function(n, m) { - var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; - n = new BigNumber4(n); - if (n.c && !n.isInteger()) { - throw Error(bignumberError3 + "Exponent not an integer: " + valueOf(n)); - } - if (m != null) - m = new BigNumber4(m); - nIsBig = n.e > 14; - if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - y = new BigNumber4(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd3(n)) : +valueOf(n))); - return m ? y.mod(m) : y; - } - nIsNeg = n.s < 0; - if (m) { - if (m.c ? !m.c[0] : !m.s) - return new BigNumber4(NaN); - isModExp = !nIsNeg && x.isInteger() && m.isInteger(); - if (isModExp) - x = x.mod(m); - } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 240000000 : x.c[0] < 80000000000000 || nIsBig && x.c[0] <= 99999750000000))) { - k = x.s < 0 && isOdd3(n) ? -0 : 0; - if (x.e > -1) - k = 1 / k; - return new BigNumber4(nIsNeg ? 1 / k : k); - } else if (POW_PRECISION) { - k = mathceil3(POW_PRECISION / LOG_BASE3 + 2); - } - if (nIsBig) { - half = new BigNumber4(0.5); - if (nIsNeg) - n.s = 1; - nIsOdd = isOdd3(n); - } else { - i = Math.abs(+valueOf(n)); - nIsOdd = i % 2; - } - y = new BigNumber4(ONE); - for (;; ) { - if (nIsOdd) { - y = y.times(x); - if (!y.c) - break; - if (k) { - if (y.c.length > k) - y.c.length = k; - } else if (isModExp) { - y = y.mod(m); - } - } - if (i) { - i = mathfloor3(i / 2); - if (i === 0) - break; - nIsOdd = i % 2; - } else { - n = n.times(half); - round(n, n.e + 1, 1); - if (n.e > 14) { - nIsOdd = isOdd3(n); - } else { - i = +valueOf(n); - if (i === 0) - break; - nIsOdd = i % 2; - } - } - x = x.times(x); - if (k) { - if (x.c && x.c.length > k) - x.c.length = k; - } else if (isModExp) { - x = x.mod(m); - } - } - if (isModExp) - return y; - if (nIsNeg) - y = ONE.div(y); - return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; - }; - P.integerValue = function(rm) { - var n = new BigNumber4(this); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck3(rm, 0, 8); - return round(n, n.e + 1, rm); - }; - P.isEqualTo = P.eq = function(y, b) { - return compare4(this, new BigNumber4(y, b)) === 0; - }; - P.isFinite = function() { - return !!this.c; - }; - P.isGreaterThan = P.gt = function(y, b) { - return compare4(this, new BigNumber4(y, b)) > 0; - }; - P.isGreaterThanOrEqualTo = P.gte = function(y, b) { - return (b = compare4(this, new BigNumber4(y, b))) === 1 || b === 0; - }; - P.isInteger = function() { - return !!this.c && bitFloor3(this.e / LOG_BASE3) > this.c.length - 2; - }; - P.isLessThan = P.lt = function(y, b) { - return compare4(this, new BigNumber4(y, b)) < 0; - }; - P.isLessThanOrEqualTo = P.lte = function(y, b) { - return (b = compare4(this, new BigNumber4(y, b))) === -1 || b === 0; - }; - P.isNaN = function() { - return !this.s; - }; - P.isNegative = function() { - return this.s < 0; - }; - P.isPositive = function() { - return this.s > 0; - }; - P.isZero = function() { - return !!this.c && this.c[0] == 0; - }; - P.minus = function(y, b) { - var i, j, t2, xLTy, x = this, a = x.s; - y = new BigNumber4(y, b); - b = y.s; - if (!a || !b) - return new BigNumber4(NaN); - if (a != b) { - y.s = -b; - return x.plus(y); - } - var xe = x.e / LOG_BASE3, ye = y.e / LOG_BASE3, xc = x.c, yc = y.c; - if (!xe || !ye) { - if (!xc || !yc) - return xc ? (y.s = -b, y) : new BigNumber4(yc ? x : NaN); - if (!xc[0] || !yc[0]) { - return yc[0] ? (y.s = -b, y) : new BigNumber4(xc[0] ? x : ROUNDING_MODE == 3 ? -0 : 0); - } - } - xe = bitFloor3(xe); - ye = bitFloor3(ye); - xc = xc.slice(); - if (a = xe - ye) { - if (xLTy = a < 0) { - a = -a; - t2 = xc; - } else { - ye = xe; - t2 = yc; - } - t2.reverse(); - for (b = a;b--; t2.push(0)) - ; - t2.reverse(); - } else { - j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; - for (a = b = 0;b < j; b++) { - if (xc[b] != yc[b]) { - xLTy = xc[b] < yc[b]; - break; - } - } - } - if (xLTy) { - t2 = xc; - xc = yc; - yc = t2; - y.s = -y.s; - } - b = (j = yc.length) - (i = xc.length); - if (b > 0) - for (;b--; xc[i++] = 0) - ; - b = BASE3 - 1; - for (;j > a; ) { - if (xc[--j] < yc[j]) { - for (i = j;i && !xc[--i]; xc[i] = b) - ; - --xc[i]; - xc[j] += BASE3; - } - xc[j] -= yc[j]; - } - for (;xc[0] == 0; xc.splice(0, 1), --ye) - ; - if (!xc[0]) { - y.s = ROUNDING_MODE == 3 ? -1 : 1; - y.c = [y.e = 0]; - return y; - } - return normalise(y, xc, ye); - }; - P.modulo = P.mod = function(y, b) { - var q, s, x = this; - y = new BigNumber4(y, b); - if (!x.c || !y.s || y.c && !y.c[0]) { - return new BigNumber4(NaN); - } else if (!y.c || x.c && !x.c[0]) { - return new BigNumber4(x); - } - if (MODULO_MODE == 9) { - s = y.s; - y.s = 1; - q = div(x, y, 0, 3); - y.s = s; - q.s *= s; - } else { - q = div(x, y, 0, MODULO_MODE); - } - y = x.minus(q.times(y)); - if (!y.c[0] && MODULO_MODE == 1) - y.s = x.s; - return y; - }; - P.multipliedBy = P.times = function(y, b) { - var c, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber4(y, b)).c; - if (!xc || !yc || !xc[0] || !yc[0]) { - if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { - y.c = y.e = y.s = null; - } else { - y.s *= x.s; - if (!xc || !yc) { - y.c = y.e = null; - } else { - y.c = [0]; - y.e = 0; - } - } - return y; - } - e2 = bitFloor3(x.e / LOG_BASE3) + bitFloor3(y.e / LOG_BASE3); - y.s *= x.s; - xcL = xc.length; - ycL = yc.length; - if (xcL < ycL) { - zc = xc; - xc = yc; - yc = zc; - i = xcL; - xcL = ycL; - ycL = i; - } - for (i = xcL + ycL, zc = [];i--; zc.push(0)) - ; - base = BASE3; - sqrtBase = SQRT_BASE3; - for (i = ycL;--i >= 0; ) { - c = 0; - ylo = yc[i] % sqrtBase; - yhi = yc[i] / sqrtBase | 0; - for (k = xcL, j = i + k;j > i; ) { - xlo = xc[--k] % sqrtBase; - xhi = xc[k] / sqrtBase | 0; - m = yhi * xlo + xhi * ylo; - xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c; - c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; - zc[j--] = xlo % base; - } - zc[j] = c; - } - if (c) { - ++e2; - } else { - zc.splice(0, 1); - } - return normalise(y, zc, e2); - }; - P.negated = function() { - var x = new BigNumber4(this); - x.s = -x.s || null; - return x; - }; - P.plus = function(y, b) { - var t2, x = this, a = x.s; - y = new BigNumber4(y, b); - b = y.s; - if (!a || !b) - return new BigNumber4(NaN); - if (a != b) { - y.s = -b; - return x.minus(y); - } - var xe = x.e / LOG_BASE3, ye = y.e / LOG_BASE3, xc = x.c, yc = y.c; - if (!xe || !ye) { - if (!xc || !yc) - return new BigNumber4(a / 0); - if (!xc[0] || !yc[0]) - return yc[0] ? y : new BigNumber4(xc[0] ? x : a * 0); - } - xe = bitFloor3(xe); - ye = bitFloor3(ye); - xc = xc.slice(); - if (a = xe - ye) { - if (a > 0) { - ye = xe; - t2 = yc; - } else { - a = -a; - t2 = xc; - } - t2.reverse(); - for (;a--; t2.push(0)) - ; - t2.reverse(); - } - a = xc.length; - b = yc.length; - if (a - b < 0) { - t2 = yc; - yc = xc; - xc = t2; - b = a; - } - for (a = 0;b; ) { - a = (xc[--b] = xc[b] + yc[b] + a) / BASE3 | 0; - xc[b] = BASE3 === xc[b] ? 0 : xc[b] % BASE3; - } - if (a) { - xc = [a].concat(xc); - ++ye; - } - return normalise(y, xc, ye); - }; - P.precision = P.sd = function(sd, rm) { - var c, n, v, x = this; - if (sd != null && sd !== !!sd) { - intCheck3(sd, 1, MAX3); - if (rm == null) - rm = ROUNDING_MODE; - else - intCheck3(rm, 0, 8); - return round(new BigNumber4(x), sd, rm); - } - if (!(c = x.c)) - return null; - v = c.length - 1; - n = v * LOG_BASE3 + 1; - if (v = c[v]) { - for (;v % 10 == 0; v /= 10, n--) - ; - for (v = c[0];v >= 10; v /= 10, n++) - ; - } - if (sd && x.e + 1 > n) - n = x.e + 1; - return n; - }; - P.shiftedBy = function(k) { - intCheck3(k, -MAX_SAFE_INTEGER3, MAX_SAFE_INTEGER3); - return this.times("1e" + k); - }; - P.squareRoot = P.sqrt = function() { - var m, n, r, rep, t2, x = this, c = x.c, s = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber4("0.5"); - if (s !== 1 || !c || !c[0]) { - return new BigNumber4(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); - } - s = Math.sqrt(+valueOf(x)); - if (s == 0 || s == 1 / 0) { - n = coeffToString3(c); - if ((n.length + e2) % 2 == 0) - n += "0"; - s = Math.sqrt(+n); - e2 = bitFloor3((e2 + 1) / 2) - (e2 < 0 || e2 % 2); - if (s == 1 / 0) { - n = "5e" + e2; - } else { - n = s.toExponential(); - n = n.slice(0, n.indexOf("e") + 1) + e2; - } - r = new BigNumber4(n); + const cert = certs[envelope.kid]; + if (envelope.alg === "ES256") { + signature = formatEcdsa.joseToDer(signature, "ES256").toString("base64"); + } + const verified = await crypto2.verify(cert, signed, signature); + if (!verified) { + throw new Error("Invalid token signature: " + jwt2); + } + if (!payload.iat) { + throw new Error("No issue time in token: " + JSON.stringify(payload)); + } + if (!payload.exp) { + throw new Error("No expiration time in token: " + JSON.stringify(payload)); + } + const iat = Number(payload.iat); + if (isNaN(iat)) + throw new Error("iat field using invalid format"); + const exp = Number(payload.exp); + if (isNaN(exp)) + throw new Error("exp field using invalid format"); + const now = new Date().getTime() / 1000; + if (exp >= now + maxExpiry) { + throw new Error("Expiration time too far in future: " + JSON.stringify(payload)); + } + const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; + const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; + if (now < earliest) { + throw new Error("Token used too early, " + now + " < " + earliest + ": " + JSON.stringify(payload)); + } + if (now > latest) { + throw new Error("Token used too late, " + now + " > " + latest + ": " + JSON.stringify(payload)); + } + if (issuers && issuers.indexOf(payload.iss) < 0) { + throw new Error("Invalid issuer, expected one of [" + issuers + "], but got " + payload.iss); + } + if (typeof requiredAudience !== "undefined" && requiredAudience !== null) { + const aud = payload.aud; + let audVerified = false; + if (requiredAudience.constructor === Array) { + audVerified = requiredAudience.indexOf(aud) > -1; } else { - r = new BigNumber4(s + ""); - } - if (r.c[0]) { - e2 = r.e; - s = e2 + dp; - if (s < 3) - s = 0; - for (;; ) { - t2 = r; - r = half.times(t2.plus(div(x, t2, dp, 1))); - if (coeffToString3(t2.c).slice(0, s) === (n = coeffToString3(r.c)).slice(0, s)) { - if (r.e < e2) - --s; - n = n.slice(s - 3, s + 1); - if (n == "9999" || !rep && n == "4999") { - if (!rep) { - round(t2, t2.e + DECIMAL_PLACES + 2, 0); - if (t2.times(t2).eq(x)) { - r = t2; - break; - } - } - dp += 4; - s += 4; - rep = 1; - } else { - if (!+n || !+n.slice(1) && n.charAt(0) == "5") { - round(r, r.e + DECIMAL_PLACES + 2, 1); - m = !r.times(r).eq(x); - } - break; - } - } - } - } - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); - }; - P.toExponential = function(dp, rm) { - if (dp != null) { - intCheck3(dp, 0, MAX3); - dp++; - } - return format(this, dp, rm, 1); - }; - P.toFixed = function(dp, rm) { - if (dp != null) { - intCheck3(dp, 0, MAX3); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - P.toFormat = function(dp, rm, format2) { - var str, x = this; - if (format2 == null) { - if (dp != null && rm && typeof rm == "object") { - format2 = rm; - rm = null; - } else if (dp && typeof dp == "object") { - format2 = dp; - dp = rm = null; - } else { - format2 = FORMAT; - } - } else if (typeof format2 != "object") { - throw Error(bignumberError3 + "Argument not an object: " + format2); + audVerified = aud === requiredAudience; } - str = x.toFixed(dp, rm); - if (x.c) { - var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; - if (g2) { - i = g1; - g1 = g2; - g2 = i; - len -= i; - } - if (g1 > 0 && len > 0) { - i = len % g1 || g1; - intPart = intDigits.substr(0, i); - for (;i < len; i += g1) - intPart += groupSeparator + intDigits.substr(i, g1); - if (g2 > 0) - intPart += groupSeparator + intDigits.slice(i); - if (isNeg) - intPart = "-" + intPart; - } - str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(new RegExp("\\d{" + g2 + "}\\B", "g"), "$&" + (format2.fractionGroupSeparator || "")) : fractionPart) : intPart; + if (!audVerified) { + throw new Error("Wrong recipient, payload audience != requiredAudience"); } - return (format2.prefix || "") + str + (format2.suffix || ""); - }; - P.toFraction = function(md) { - var d, d0, d1, d2, e2, exp, n, n0, n1, q, r, s, x = this, xc = x.c; - if (md != null) { - n = new BigNumber4(md); - if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error(bignumberError3 + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); - } + } + return new loginticket_1.LoginTicket(envelope, payload); + } + async processAndValidateRefreshHandler() { + if (this.refreshHandler) { + const accessTokenResponse = await this.refreshHandler(); + if (!accessTokenResponse.access_token) { + throw new Error("No access token is returned by the refreshHandler callback."); } - if (!xc) - return new BigNumber4(x); - d = new BigNumber4(ONE); - n1 = d0 = new BigNumber4(ONE); - d1 = n0 = new BigNumber4(ONE); - s = coeffToString3(xc); - e2 = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN3[(exp = e2 % LOG_BASE3) < 0 ? LOG_BASE3 + exp : exp]; - md = !md || n.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n; - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n = new BigNumber4(s); - n0.c[0] = 0; - for (;; ) { - q = div(n, d, 0, 1); - d2 = d0.plus(q.times(d1)); - if (d2.comparedTo(md) == 1) - break; - d0 = d1; - d1 = d2; - n1 = n0.plus(q.times(d2 = n1)); - n0 = d2; - d = n.minus(q.times(d2 = d)); - n = d2; + return accessTokenResponse; + } + return; + } + isTokenExpiring() { + const expiryDate = this.credentials.expiry_date; + return expiryDate ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis : false; + } + } + exports.OAuth2Client = OAuth2Client; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/computeclient.js +var require_computeclient = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Compute = undefined; + var gaxios_1 = require_src2(); + var gcpMetadata = require_src4(); + var oauth2client_1 = require_oauth2client(); + + class Compute extends oauth2client_1.OAuth2Client { + serviceAccountEmail; + scopes; + constructor(options = {}) { + super(options); + this.credentials = { expiry_date: 1, refresh_token: "compute-placeholder" }; + this.serviceAccountEmail = options.serviceAccountEmail || "default"; + this.scopes = Array.isArray(options.scopes) ? options.scopes : options.scopes ? [options.scopes] : []; + } + async refreshTokenNoCache() { + const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; + let data; + try { + const instanceOptions = { + property: tokenPath + }; + if (this.scopes.length > 0) { + instanceOptions.params = { + scopes: this.scopes.join(",") + }; } - d2 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - e2 = e2 * 2; - r = div(n1, d1, e2, ROUNDING_MODE).minus(x).abs().comparedTo(div(n0, d0, e2, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; - MAX_EXP = exp; - return r; - }; - P.toNumber = function() { - return +valueOf(this); - }; - P.toPrecision = function(sd, rm) { - if (sd != null) - intCheck3(sd, 1, MAX3); - return format(this, sd, rm, 2); - }; - P.toString = function(b) { - var str, n = this, s = n.s, e2 = n.e; - if (e2 === null) { - if (s) { - str = "Infinity"; - if (s < 0) - str = "-" + str; - } else { - str = "NaN"; - } - } else { - if (b == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential3(coeffToString3(n.c), e2) : toFixedPoint3(coeffToString3(n.c), e2, "0"); - } else if (b === 10 && alphabetHasNormalDecimalDigits) { - n = round(new BigNumber4(n), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint3(coeffToString3(n.c), n.e, "0"); - } else { - intCheck3(b, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint3(coeffToString3(n.c), e2, "0"), 10, b, s, true); - } - if (s < 0 && n.c[0]) - str = "-" + str; + data = await gcpMetadata.instance(instanceOptions); + } catch (e2) { + if (e2 instanceof gaxios_1.GaxiosError) { + e2.message = `Could not refresh access token: ${e2.message}`; + this.wrapError(e2); } - return str; - }; - P.valueOf = P.toJSON = function() { - return valueOf(this); - }; - P._isBigNumber = true; - if (configObject != null) - BigNumber4.set(configObject); - return BigNumber4; + throw e2; + } + const tokens = data; + if (data && data.expires_in) { + tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit("tokens", tokens); + return { tokens, res: null }; } - function bitFloor3(n) { - var i = n | 0; - return n > 0 || n === i ? i : i - 1; + async fetchIdToken(targetAudience) { + const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + `?format=full&audience=${targetAudience}`; + let idToken; + try { + const instanceOptions = { + property: idTokenPath + }; + idToken = await gcpMetadata.instance(instanceOptions); + } catch (e2) { + if (e2 instanceof Error) { + e2.message = `Could not fetch ID token: ${e2.message}`; + } + throw e2; + } + return idToken; } - function coeffToString3(a) { - var s, z, i = 1, j = a.length, r = a[0] + ""; - for (;i < j; ) { - s = a[i++] + ""; - z = LOG_BASE3 - s.length; - for (;z--; s = "0" + s) - ; - r += s; + wrapError(e2) { + const res = e2.response; + if (res && res.status) { + e2.status = res.status; + if (res.status === 403) { + e2.message = "A Forbidden error was returned while attempting to retrieve an access " + "token for the Compute Engine built-in service account. This may be because the Compute " + "Engine instance does not have the correct permission scopes specified: " + e2.message; + } else if (res.status === 404) { + e2.message = "A Not Found error was returned while attempting to retrieve an access" + "token for the Compute Engine built-in service account. This may be because the Compute " + "Engine instance does not have any permission scopes specified: " + e2.message; + } } - for (j = r.length;r.charCodeAt(--j) === 48; ) - ; - return r.slice(0, j + 1 || 1); } - function compare4(x, y) { - var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; - if (!i || !j) - return null; - a = xc && !xc[0]; - b = yc && !yc[0]; - if (a || b) - return a ? b ? 0 : -j : i; - if (i != j) - return i; - a = i < 0; - b = k == l; - if (!xc || !yc) - return b ? 0 : !xc ^ a ? 1 : -1; - if (!b) - return k > l ^ a ? 1 : -1; - j = (k = xc.length) < (l = yc.length) ? k : l; - for (i = 0;i < j; i++) - if (xc[i] != yc[i]) - return xc[i] > yc[i] ^ a ? 1 : -1; - return k == l ? 0 : k > l ^ a ? 1 : -1; + } + exports.Compute = Compute; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/idtokenclient.js +var require_idtokenclient = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.IdTokenClient = undefined; + var oauth2client_1 = require_oauth2client(); + + class IdTokenClient extends oauth2client_1.OAuth2Client { + targetAudience; + idTokenProvider; + constructor(options) { + super(options); + this.targetAudience = options.targetAudience; + this.idTokenProvider = options.idTokenProvider; } - function intCheck3(n, min, max, name) { - if (n < min || n > max || n !== mathfloor3(n)) { - throw Error(bignumberError3 + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); + async getRequestMetadataAsync() { + if (!this.credentials.id_token || !this.credentials.expiry_date || this.isTokenExpiring()) { + const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); + this.credentials = { + id_token: idToken, + expiry_date: this.getIdTokenExpiryDate(idToken) + }; } + const headers = new Headers({ + authorization: "Bearer " + this.credentials.id_token + }); + return { headers }; } - function isOdd3(n) { - var k = n.c.length - 1; - return bitFloor3(n.e / LOG_BASE3) == k && n.c[k] % 2 != 0; + getIdTokenExpiryDate(idToken) { + const payloadB64 = idToken.split(".")[1]; + if (payloadB64) { + const payload = JSON.parse(Buffer.from(payloadB64, "base64").toString("ascii")); + return payload.exp * 1000; + } } - function toExponential3(str, e2) { - return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; + } + exports.IdTokenClient = IdTokenClient; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/envDetect.js +var require_envDetect = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GCPEnv = undefined; + exports.clear = clear; + exports.getEnv = getEnv; + var gcpMetadata = require_src4(); + var GCPEnv; + (function(GCPEnv2) { + GCPEnv2["APP_ENGINE"] = "APP_ENGINE"; + GCPEnv2["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; + GCPEnv2["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; + GCPEnv2["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; + GCPEnv2["CLOUD_RUN"] = "CLOUD_RUN"; + GCPEnv2["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS"; + GCPEnv2["NONE"] = "NONE"; + })(GCPEnv || (exports.GCPEnv = GCPEnv = {})); + var envPromise; + function clear() { + envPromise = undefined; + } + async function getEnv() { + if (envPromise) { + return envPromise; } - function toFixedPoint3(str, e2, z) { - var len, zs; - if (e2 < 0) { - for (zs = z + ".";++e2; zs += z) - ; - str = zs + str; + envPromise = getEnvMemoized(); + return envPromise; + } + async function getEnvMemoized() { + let env2 = GCPEnv.NONE; + if (isAppEngine()) { + env2 = GCPEnv.APP_ENGINE; + } else if (isCloudFunction()) { + env2 = GCPEnv.CLOUD_FUNCTIONS; + } else if (await isComputeEngine()) { + if (await isKubernetesEngine()) { + env2 = GCPEnv.KUBERNETES_ENGINE; + } else if (isCloudRun()) { + env2 = GCPEnv.CLOUD_RUN; + } else if (isCloudRunJob()) { + env2 = GCPEnv.CLOUD_RUN_JOBS; } else { - len = str.length; - if (++e2 > len) { - for (zs = z, e2 -= len;--e2; zs += z) - ; - str += zs; - } else if (e2 < len) { - str = str.slice(0, e2) + "." + str.slice(e2); - } + env2 = GCPEnv.COMPUTE_ENGINE; } - return str; - } - BigNumber3 = clone4(); - BigNumber3["default"] = BigNumber3.BigNumber = BigNumber3; - if (typeof define == "function" && define.amd) { - define(function() { - return BigNumber3; - }); - } else if (typeof module != "undefined" && module.exports) { - module.exports = BigNumber3; } else { - if (!globalObject) { - globalObject = typeof self != "undefined" && self ? self : window; - } - globalObject.BigNumber = BigNumber3; + env2 = GCPEnv.NONE; } - })(exports); + return env2; + } + function isAppEngine() { + return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); + } + function isCloudFunction() { + return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); + } + function isCloudRun() { + return !!process.env.K_CONFIGURATION; + } + function isCloudRunJob() { + return !!process.env.CLOUD_RUN_JOB; + } + async function isKubernetesEngine() { + try { + await gcpMetadata.instance("attributes/cluster-name"); + return true; + } catch (e2) { + return false; + } + } + async function isComputeEngine() { + return gcpMetadata.isAvailable(); + } }); -// node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/stringify.js -var require_stringify2 = __commonJS((exports, module) => { - var BigNumber3 = require_bignumber(); - var JSON2 = exports; - (function() { - function f(n) { - return n < 10 ? "0" + n : n; - } - var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { - "\b": "\\b", - "\t": "\\t", - "\n": "\\n", - "\f": "\\f", - "\r": "\\r", - '"': "\\\"", - "\\": "\\\\" - }, rep; - function quote(string2) { - escapable.lastIndex = 0; - return escapable.test(string2) ? '"' + string2.replace(escapable, function(a) { - var c = meta[a]; - return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); - }) + '"' : '"' + string2 + '"'; - } - function str(key, holder) { - var i, k, v, length, mind = gap, partial, value = holder[key], isBigNumber = value != null && (value instanceof BigNumber3 || BigNumber3.isBigNumber(value)); - if (value && typeof value === "object" && typeof value.toJSON === "function") { - value = value.toJSON(key); - } - if (typeof rep === "function") { - value = rep.call(holder, key, value); - } - switch (typeof value) { - case "string": - if (isBigNumber) { - return value; - } else { - return quote(value); - } - case "number": - return isFinite(value) ? String(value) : "null"; - case "boolean": - case "null": - case "bigint": - return String(value); - case "object": - if (!value) { - return "null"; - } - gap += indent; - partial = []; - if (Object.prototype.toString.apply(value) === "[object Array]") { - length = value.length; - for (i = 0;i < length; i += 1) { - partial[i] = str(i, value) || "null"; - } - v = partial.length === 0 ? "[]" : gap ? `[ -` + gap + partial.join(`, -` + gap) + ` -` + mind + "]" : "[" + partial.join(",") + "]"; - gap = mind; - return v; - } - if (rep && typeof rep === "object") { - length = rep.length; - for (i = 0;i < length; i += 1) { - if (typeof rep[i] === "string") { - k = rep[i]; - v = str(k, value); - if (v) { - partial.push(quote(k) + (gap ? ": " : ":") + v); - } - } - } - } else { - Object.keys(value).forEach(function(k2) { - var v2 = str(k2, value); - if (v2) { - partial.push(quote(k2) + (gap ? ": " : ":") + v2); - } - }); - } - v = partial.length === 0 ? "{}" : gap ? `{ -` + gap + partial.join(`, -` + gap) + ` -` + mind + "}" : "{" + partial.join(",") + "}"; - gap = mind; - return v; - } - } - if (typeof JSON2.stringify !== "function") { - JSON2.stringify = function(value, replacer, space) { - var i; - gap = ""; - indent = ""; - if (typeof space === "number") { - for (i = 0;i < space; i += 1) { - indent += " "; - } - } else if (typeof space === "string") { - indent = space; - } - rep = replacer; - if (replacer && typeof replacer !== "function" && (typeof replacer !== "object" || typeof replacer.length !== "number")) { - throw new Error("JSON.stringify"); - } - return str("", { "": value }); - }; - } - })(); -}); - -// node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/lib/parse.js -var require_parse3 = __commonJS((exports, module) => { - var BigNumber3 = null; - var suspectProtoRx = /(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])/; - var suspectConstructorRx = /(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)/; - var json_parse = function(options) { - var _options = { - strict: false, - storeAsString: false, - alwaysParseAsBig: false, - useNativeBigInt: false, - protoAction: "error", - constructorAction: "error" - }; - if (options !== undefined && options !== null) { - if (options.strict === true) { - _options.strict = true; - } - if (options.storeAsString === true) { - _options.storeAsString = true; - } - _options.alwaysParseAsBig = options.alwaysParseAsBig === true ? options.alwaysParseAsBig : false; - _options.useNativeBigInt = options.useNativeBigInt === true ? options.useNativeBigInt : false; - if (typeof options.constructorAction !== "undefined") { - if (options.constructorAction === "error" || options.constructorAction === "ignore" || options.constructorAction === "preserve") { - _options.constructorAction = options.constructorAction; - } else { - throw new Error(`Incorrect value for constructorAction option, must be "error", "ignore" or undefined but passed ${options.constructorAction}`); - } - } - if (typeof options.protoAction !== "undefined") { - if (options.protoAction === "error" || options.protoAction === "ignore" || options.protoAction === "preserve") { - _options.protoAction = options.protoAction; - } else { - throw new Error(`Incorrect value for protoAction option, must be "error", "ignore" or undefined but passed ${options.protoAction}`); - } - } - } - var at, ch, escapee = { - '"': '"', - "\\": "\\", - "/": "/", - b: "\b", - f: "\f", - n: ` -`, - r: "\r", - t: "\t" - }, text2, error = function(m) { - throw { - name: "SyntaxError", - message: m, - at, - text: text2 - }; - }, next = function(c) { - if (c && c !== ch) { - error("Expected '" + c + "' instead of '" + ch + "'"); - } - ch = text2.charAt(at); - at += 1; - return ch; - }, number2 = function() { - var number3, string3 = ""; - if (ch === "-") { - string3 = "-"; - next("-"); - } - while (ch >= "0" && ch <= "9") { - string3 += ch; - next(); - } - if (ch === ".") { - string3 += "."; - while (next() && ch >= "0" && ch <= "9") { - string3 += ch; - } - } - if (ch === "e" || ch === "E") { - string3 += ch; - next(); - if (ch === "-" || ch === "+") { - string3 += ch; - next(); - } - while (ch >= "0" && ch <= "9") { - string3 += ch; - next(); - } - } - number3 = +string3; - if (!isFinite(number3)) { - error("Bad number"); - } else { - if (BigNumber3 == null) - BigNumber3 = require_bignumber(); - if (string3.length > 15) - return _options.storeAsString ? string3 : _options.useNativeBigInt ? BigInt(string3) : new BigNumber3(string3); - else - return !_options.alwaysParseAsBig ? number3 : _options.useNativeBigInt ? BigInt(number3) : new BigNumber3(number3); - } - }, string2 = function() { - var hex, i, string3 = "", uffff; - if (ch === '"') { - var startAt = at; - while (next()) { - if (ch === '"') { - if (at - 1 > startAt) - string3 += text2.substring(startAt, at - 1); - next(); - return string3; - } - if (ch === "\\") { - if (at - 1 > startAt) - string3 += text2.substring(startAt, at - 1); - next(); - if (ch === "u") { - uffff = 0; - for (i = 0;i < 4; i += 1) { - hex = parseInt(next(), 16); - if (!isFinite(hex)) { - break; - } - uffff = uffff * 16 + hex; - } - string3 += String.fromCharCode(uffff); - } else if (typeof escapee[ch] === "string") { - string3 += escapee[ch]; - } else { - break; - } - startAt = at; - } - } - } - error("Bad string"); - }, white = function() { - while (ch && ch <= " ") { - next(); - } - }, word = function() { - switch (ch) { - case "t": - next("t"); - next("r"); - next("u"); - next("e"); - return true; - case "f": - next("f"); - next("a"); - next("l"); - next("s"); - next("e"); - return false; - case "n": - next("n"); - next("u"); - next("l"); - next("l"); - return null; - } - error("Unexpected '" + ch + "'"); - }, value, array2 = function() { - var array3 = []; - if (ch === "[") { - next("["); - white(); - if (ch === "]") { - next("]"); - return array3; - } - while (ch) { - array3.push(value()); - white(); - if (ch === "]") { - next("]"); - return array3; - } - next(","); - white(); - } - } - error("Bad array"); - }, object2 = function() { - var key, object3 = Object.create(null); - if (ch === "{") { - next("{"); - white(); - if (ch === "}") { - next("}"); - return object3; - } - while (ch) { - key = string2(); - white(); - next(":"); - if (_options.strict === true && Object.hasOwnProperty.call(object3, key)) { - error('Duplicate key "' + key + '"'); - } - if (suspectProtoRx.test(key) === true) { - if (_options.protoAction === "error") { - error("Object contains forbidden prototype property"); - } else if (_options.protoAction === "ignore") { - value(); - } else { - object3[key] = value(); - } - } else if (suspectConstructorRx.test(key) === true) { - if (_options.constructorAction === "error") { - error("Object contains forbidden constructor property"); - } else if (_options.constructorAction === "ignore") { - value(); - } else { - object3[key] = value(); - } - } else { - object3[key] = value(); - } - white(); - if (ch === "}") { - next("}"); - return object3; - } - next(","); - white(); - } - } - error("Bad object"); - }; - value = function() { - white(); - switch (ch) { - case "{": - return object2(); - case "[": - return array2(); - case '"': - return string2(); - case "-": - return number2(); - default: - return ch >= "0" && ch <= "9" ? number2() : word(); - } - }; - return function(source, reviver) { - var result; - text2 = source + ""; - at = 0; - ch = " "; - result = value(); - white(); - if (ch) { - error("Syntax error"); - } - return typeof reviver === "function" ? function walk(holder, key) { - var k, v, value2 = holder[key]; - if (value2 && typeof value2 === "object") { - Object.keys(value2).forEach(function(k2) { - v = walk(value2, k2); - if (v !== undefined) { - value2[k2] = v; - } else { - delete value2[k2]; - } - }); - } - return reviver.call(holder, key, value2); - }({ "": result }, "") : result; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/jwsSign.js +var require_jwsSign = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.buildPayloadForJwsSign = buildPayloadForJwsSign; + exports.getJwsSign = getJwsSign; + var jws_1 = require_jws(); + var ALG_RS256 = "RS256"; + var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"; + function buildPayloadForJwsSign(tokenOptions) { + const iat = Math.floor(new Date().getTime() / 1000); + const payload = { + iss: tokenOptions.iss, + scope: tokenOptions.scope, + aud: GOOGLE_TOKEN_URL, + exp: iat + 3600, + iat, + sub: tokenOptions.sub, + ...tokenOptions.additionalClaims }; - }; - module.exports = json_parse; + return payload; + } + function getJwsSign(tokenOptions) { + const payload = buildPayloadForJwsSign(tokenOptions); + return (0, jws_1.sign)({ + header: { alg: ALG_RS256 }, + payload, + secret: tokenOptions.key + }); + } }); -// node_modules/.pnpm/json-bigint@1.0.0/node_modules/json-bigint/index.js -var require_json_bigint = __commonJS((exports, module) => { - var json_stringify = require_stringify2().stringify; - var json_parse = require_parse3(); - module.exports = function(options) { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/getToken.js +var require_getToken = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getToken = getToken; + var jwsSign_1 = require_jwsSign(); + var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"; + var GOOGLE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; + var generateRequestOptions = (tokenOptions) => { return { - parse: json_parse(options), - stringify: json_stringify + method: "POST", + url: GOOGLE_TOKEN_URL, + data: new URLSearchParams({ + grant_type: GOOGLE_GRANT_TYPE, + assertion: (0, jwsSign_1.getJwsSign)(tokenOptions) + }), + responseType: "json", + retryConfig: { + httpMethodsToRetry: ["POST"] + } }; }; - module.exports.parse = json_parse(); - module.exports.stringify = json_stringify; -}); - -// node_modules/.pnpm/gcp-metadata@8.1.2/node_modules/gcp-metadata/build/src/gcp-residency.js -var require_gcp_residency = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GCE_LINUX_BIOS_PATHS = undefined; - exports.isGoogleCloudServerless = isGoogleCloudServerless; - exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; - exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; - exports.isGoogleComputeEngine = isGoogleComputeEngine; - exports.detectGCPResidency = detectGCPResidency; - var fs_1 = __require("fs"); - var os_1 = __require("os"); - exports.GCE_LINUX_BIOS_PATHS = { - BIOS_DATE: "/sys/class/dmi/id/bios_date", - BIOS_VENDOR: "/sys/class/dmi/id/bios_vendor" - }; - var GCE_MAC_ADDRESS_REGEX = /^42:01/; - function isGoogleCloudServerless() { - const isGFEnvironment = process.env.CLOUD_RUN_JOB || process.env.FUNCTION_NAME || process.env.K_SERVICE; - return !!isGFEnvironment; - } - function isGoogleComputeEngineLinux() { - if ((0, os_1.platform)() !== "linux") - return false; - try { - (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); - const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, "utf8"); - return /Google/.test(biosVendor); - } catch { - return false; + async function getToken(tokenOptions) { + if (!tokenOptions.transporter) { + throw new Error("No transporter set."); } - } - function isGoogleComputeEngineMACAddress() { - const interfaces = (0, os_1.networkInterfaces)(); - for (const item of Object.values(interfaces)) { - if (!item) - continue; - for (const { mac } of item) { - if (GCE_MAC_ADDRESS_REGEX.test(mac)) { - return true; - } + try { + const gaxiosOptions = generateRequestOptions(tokenOptions); + const response = await tokenOptions.transporter.request(gaxiosOptions); + return response.data; + } catch (e2) { + const err = e2; + const errorData = err.response?.data; + if (errorData?.error) { + err.message = `${errorData.error}: ${errorData.error_description}`; } + throw err; } - return false; - } - function isGoogleComputeEngine() { - return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); - } - function detectGCPResidency() { - return isGoogleCloudServerless() || isGoogleComputeEngine(); } }); -// node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/colours.js -var require_colours = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/errorWithCode.js +var require_errorWithCode = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.Colours = undefined; + exports.ErrorWithCode = undefined; - class Colours { - static isEnabled(stream) { - return stream && stream.isTTY && (typeof stream.getColorDepth === "function" ? stream.getColorDepth() > 2 : true); - } - static refresh() { - Colours.enabled = Colours.isEnabled(process === null || process === undefined ? undefined : process.stderr); - if (!this.enabled) { - Colours.reset = ""; - Colours.bright = ""; - Colours.dim = ""; - Colours.red = ""; - Colours.green = ""; - Colours.yellow = ""; - Colours.blue = ""; - Colours.magenta = ""; - Colours.cyan = ""; - Colours.white = ""; - Colours.grey = ""; - } else { - Colours.reset = "\x1B[0m"; - Colours.bright = "\x1B[1m"; - Colours.dim = "\x1B[2m"; - Colours.red = "\x1B[31m"; - Colours.green = "\x1B[32m"; - Colours.yellow = "\x1B[33m"; - Colours.blue = "\x1B[34m"; - Colours.magenta = "\x1B[35m"; - Colours.cyan = "\x1B[36m"; - Colours.white = "\x1B[37m"; - Colours.grey = "\x1B[90m"; - } + class ErrorWithCode extends Error { + code; + constructor(message, code) { + super(message); + this.code = code; } } - exports.Colours = Colours; - Colours.enabled = false; - Colours.reset = ""; - Colours.bright = ""; - Colours.dim = ""; - Colours.red = ""; - Colours.green = ""; - Colours.yellow = ""; - Colours.blue = ""; - Colours.magenta = ""; - Colours.cyan = ""; - Colours.white = ""; - Colours.grey = ""; - Colours.refresh(); + exports.ErrorWithCode = ErrorWithCode; }); -// node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/logging-utils.js -var require_logging_utils = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports && exports.__importStar || function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) - if (Object.prototype.hasOwnProperty.call(o2, k)) - ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return 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; - }; - }(); +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/getCredentials.js +var require_getCredentials = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = undefined; - exports.getNodeBackend = getNodeBackend; - exports.getDebugBackend = getDebugBackend; - exports.getStructuredBackend = getStructuredBackend; - exports.setBackend = setBackend; - exports.log = log; - var events_1 = __require("events"); - var process2 = __importStar(__require("process")); - var util = __importStar(__require("util")); - var colours_1 = require_colours(); - var LogSeverity; - (function(LogSeverity2) { - LogSeverity2["DEFAULT"] = "DEFAULT"; - LogSeverity2["DEBUG"] = "DEBUG"; - LogSeverity2["INFO"] = "INFO"; - LogSeverity2["WARNING"] = "WARNING"; - LogSeverity2["ERROR"] = "ERROR"; - })(LogSeverity || (exports.LogSeverity = LogSeverity = {})); + exports.getCredentials = getCredentials; + var path2 = __require("path"); + var fs = __require("fs"); + var util_1 = __require("util"); + var errorWithCode_1 = require_errorWithCode(); + var readFile = fs.readFile ? (0, util_1.promisify)(fs.readFile) : async () => { + throw new errorWithCode_1.ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS"); + }; + var ExtensionFiles; + (function(ExtensionFiles2) { + ExtensionFiles2["JSON"] = ".json"; + ExtensionFiles2["DER"] = ".der"; + ExtensionFiles2["CRT"] = ".crt"; + ExtensionFiles2["PEM"] = ".pem"; + ExtensionFiles2["P12"] = ".p12"; + ExtensionFiles2["PFX"] = ".pfx"; + })(ExtensionFiles || (ExtensionFiles = {})); - class AdhocDebugLogger extends events_1.EventEmitter { - constructor(namespace, upstream) { - super(); - this.namespace = namespace; - this.upstream = upstream; - this.func = Object.assign(this.invoke.bind(this), { - instance: this, - on: (event, listener) => this.on(event, listener) - }); - this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); - this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); - this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); - this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); - this.func.sublog = (namespace2) => log(namespace2, this.func); + class JsonCredentialsProvider { + keyFilePath; + constructor(keyFilePath) { + this.keyFilePath = keyFilePath; } - invoke(fields, ...args) { - if (this.upstream) { - try { - this.upstream(fields, ...args); - } catch (e2) {} - } + async getCredentials() { + const key = await readFile(this.keyFilePath, "utf8"); + let body; try { - this.emit("log", fields, args); - } catch (e2) {} + body = JSON.parse(key); + } catch (error) { + const err = error; + throw new Error(`Invalid JSON key file: ${err.message}`); + } + const privateKey = body.private_key; + const clientEmail = body.client_email; + if (!privateKey || !clientEmail) { + throw new errorWithCode_1.ErrorWithCode("private_key and client_email are required.", "MISSING_CREDENTIALS"); + } + return { privateKey, clientEmail }; } - invokeSeverity(severity, ...args) { - this.invoke({ severity }, ...args); + } + + class PemCredentialsProvider { + keyFilePath; + constructor(keyFilePath) { + this.keyFilePath = keyFilePath; + } + async getCredentials() { + const privateKey = await readFile(this.keyFilePath, "utf8"); + return { privateKey }; } } - exports.AdhocDebugLogger = AdhocDebugLogger; - exports.placeholder = new AdhocDebugLogger("", () => {}).func; - class DebugLogBackendBase { - constructor() { - var _a; - this.cached = new Map; - this.filters = []; - this.filtersSet = false; - let nodeFlag = (_a = process2.env[exports.env.nodeEnables]) !== null && _a !== undefined ? _a : "*"; - if (nodeFlag === "all") { - nodeFlag = "*"; - } - this.filters = nodeFlag.split(","); + class P12CredentialsProvider { + async getCredentials() { + throw new errorWithCode_1.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. " + "Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.", "UNKNOWN_CERTIFICATE_TYPE"); } - log(namespace, fields, ...args) { - try { - if (!this.filtersSet) { - this.setFilters(); - this.filtersSet = true; - } - let logger = this.cached.get(namespace); - if (!logger) { - logger = this.makeLogger(namespace); - this.cached.set(namespace, logger); - } - logger(fields, ...args); - } catch (e2) { - console.error(e2); + } + + class CredentialsProviderFactory { + static create(keyFilePath) { + const keyFileExtension = path2.extname(keyFilePath); + switch (keyFileExtension) { + case ExtensionFiles.JSON: + return new JsonCredentialsProvider(keyFilePath); + case ExtensionFiles.DER: + case ExtensionFiles.CRT: + case ExtensionFiles.PEM: + return new PemCredentialsProvider(keyFilePath); + case ExtensionFiles.P12: + case ExtensionFiles.PFX: + return new P12CredentialsProvider; + default: + throw new errorWithCode_1.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. " + "Current supported extensions are *.json, and *.pem.", "UNKNOWN_CERTIFICATE_TYPE"); } } } - exports.DebugLogBackendBase = DebugLogBackendBase; + async function getCredentials(keyFilePath) { + const provider = CredentialsProviderFactory.create(keyFilePath); + return provider.getCredentials(); + } +}); - class NodeBackend extends DebugLogBackendBase { - constructor() { - super(...arguments); - this.enabledRegexp = /.*/g; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/tokenHandler.js +var require_tokenHandler = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TokenHandler = undefined; + var getToken_1 = require_getToken(); + var getCredentials_1 = require_getCredentials(); + + class TokenHandler { + token; + tokenExpiresAt; + inFlightRequest; + tokenOptions; + constructor(tokenOptions) { + this.tokenOptions = tokenOptions; } - isEnabled(namespace) { - return this.enabledRegexp.test(namespace); + async processCredentials() { + if (!this.tokenOptions.key && !this.tokenOptions.keyFile) { + throw new Error("No key or keyFile set."); + } + if (!this.tokenOptions.key && this.tokenOptions.keyFile) { + const credentials = await (0, getCredentials_1.getCredentials)(this.tokenOptions.keyFile); + this.tokenOptions.key = credentials.privateKey; + this.tokenOptions.email = credentials.clientEmail; + } } - makeLogger(namespace) { - if (!this.enabledRegexp.test(namespace)) { - return () => {}; + isTokenExpiring() { + if (!this.token || !this.tokenExpiresAt) { + return true; } - return (fields, ...args) => { - var _a; - const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; - const pid = `${colours_1.Colours.yellow}${process2.pid}${colours_1.Colours.reset}`; - let level; - switch (fields.severity) { - case LogSeverity.ERROR: - level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; - break; - case LogSeverity.INFO: - level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; - break; - case LogSeverity.WARNING: - level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; - break; - default: - level = (_a = fields.severity) !== null && _a !== undefined ? _a : LogSeverity.DEFAULT; - break; - } - const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); - const filteredFields = Object.assign({}, fields); - delete filteredFields.severity; - const fieldsJson = Object.getOwnPropertyNames(filteredFields).length ? JSON.stringify(filteredFields) : ""; - const fieldsColour = fieldsJson ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` : ""; - console.error("%s [%s|%s] %s%s", pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ""); - }; + const now = new Date().getTime(); + const eagerRefreshThresholdMillis = this.tokenOptions.eagerRefreshThresholdMillis ?? 0; + return this.tokenExpiresAt <= now + eagerRefreshThresholdMillis; } - setFilters() { - const totalFilters = this.filters.join(","); - const regexp = totalFilters.replace(/[|\\{}()[\]^$+?.]/g, "\\$&").replace(/\*/g, ".*").replace(/,/g, "$|^"); - this.enabledRegexp = new RegExp(`^${regexp}$`, "i"); + hasExpired() { + const now = new Date().getTime(); + if (this.token && this.tokenExpiresAt) { + const now2 = new Date().getTime(); + return now2 >= this.tokenExpiresAt; + } + return true; + } + async getToken(forceRefresh) { + await this.processCredentials(); + if (this.inFlightRequest && !forceRefresh) { + return this.inFlightRequest; + } + if (this.token && !this.isTokenExpiring() && !forceRefresh) { + return this.token; + } + try { + this.inFlightRequest = (0, getToken_1.getToken)(this.tokenOptions); + const token = await this.inFlightRequest; + this.token = token; + this.tokenExpiresAt = new Date().getTime() + (token.expires_in ?? 0) * 1000; + return token; + } finally { + this.inFlightRequest = undefined; + } } } - function getNodeBackend() { - return new NodeBackend; + exports.TokenHandler = TokenHandler; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/revokeToken.js +var require_revokeToken = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.revokeToken = revokeToken; + var GOOGLE_REVOKE_TOKEN_URL = "https://oauth2.googleapis.com/revoke?token="; + var DEFAULT_RETRY_VALUE = true; + async function revokeToken(accessToken, transporter) { + const url = GOOGLE_REVOKE_TOKEN_URL + accessToken; + return await transporter.request({ + url, + retry: DEFAULT_RETRY_VALUE + }); } +}); - class DebugBackend extends DebugLogBackendBase { - constructor(pkg) { - super(); - this.debugPkg = pkg; - } - makeLogger(namespace) { - const debugLogger = this.debugPkg(namespace); - return (fields, ...args) => { - debugLogger(args[0], ...args.slice(1)); +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/googleToken.js +var require_googleToken = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.GoogleToken = undefined; + var gaxios_1 = require_src2(); + var tokenHandler_1 = require_tokenHandler(); + var revokeToken_1 = require_revokeToken(); + + class GoogleToken { + tokenOptions; + tokenHandler; + constructor(options) { + this.tokenOptions = options || {}; + this.tokenOptions.transporter = this.tokenOptions.transporter || { + request: (opts) => (0, gaxios_1.request)(opts) }; + if (!this.tokenOptions.iss) { + this.tokenOptions.iss = this.tokenOptions.email; + } + if (typeof this.tokenOptions.scope === "object") { + this.tokenOptions.scope = this.tokenOptions.scope.join(" "); + } + this.tokenHandler = new tokenHandler_1.TokenHandler(this.tokenOptions); } - setFilters() { - var _a; - const existingFilters = (_a = process2.env["NODE_DEBUG"]) !== null && _a !== undefined ? _a : ""; - process2.env["NODE_DEBUG"] = `${existingFilters}${existingFilters ? "," : ""}${this.filters.join(",")}`; + get expiresAt() { + return this.tokenHandler.tokenExpiresAt; } - } - function getDebugBackend(debugPkg) { - return new DebugBackend(debugPkg); - } - - class StructuredBackend extends DebugLogBackendBase { - constructor(upstream) { - var _a; - super(); - this.upstream = (_a = upstream) !== null && _a !== undefined ? _a : undefined; + get accessToken() { + return this.tokenHandler.token?.access_token; } - makeLogger(namespace) { - var _a; - const debugLogger = (_a = this.upstream) === null || _a === undefined ? undefined : _a.makeLogger(namespace); - return (fields, ...args) => { - var _a2; - const severity = (_a2 = fields.severity) !== null && _a2 !== undefined ? _a2 : LogSeverity.INFO; - const json2 = Object.assign({ - severity, - message: util.format(...args) - }, fields); - const jsonString = JSON.stringify(json2); - if (debugLogger) { - debugLogger(fields, jsonString); - } else { - console.log("%s", jsonString); - } - }; + get idToken() { + return this.tokenHandler.token?.id_token; } - setFilters() { - var _a; - (_a = this.upstream) === null || _a === undefined || _a.setFilters(); + get tokenType() { + return this.tokenHandler.token?.token_type; } - } - function getStructuredBackend(upstream) { - return new StructuredBackend(upstream); - } - exports.env = { - nodeEnables: "GOOGLE_SDK_NODE_LOGGING" - }; - var loggerCache = new Map; - var cachedBackend = undefined; - function setBackend(backend) { - cachedBackend = backend; - loggerCache.clear(); - } - function log(namespace, parent) { - if (!cachedBackend) { - const enablesFlag = process2.env[exports.env.nodeEnables]; - if (!enablesFlag) { - return exports.placeholder; - } + get refreshToken() { + return this.tokenHandler.token?.refresh_token; } - if (!namespace) { - return exports.placeholder; + hasExpired() { + return this.tokenHandler.hasExpired(); } - if (parent) { - namespace = `${parent.instance.namespace}:${namespace}`; + isTokenExpiring() { + return this.tokenHandler.isTokenExpiring(); } - const existing = loggerCache.get(namespace); - if (existing) { - return existing.func; + getToken(callbackOrOptions, opts = { forceRefresh: false }) { + let callback; + if (typeof callbackOrOptions === "function") { + callback = callbackOrOptions; + } else if (typeof callbackOrOptions === "object") { + opts = callbackOrOptions; + } + const promise = this.tokenHandler.getToken(opts.forceRefresh ?? false); + if (callback) { + promise.then((token) => callback(null, token), callback); + } + return promise; } - if (cachedBackend === null) { - return exports.placeholder; - } else if (cachedBackend === undefined) { - cachedBackend = getNodeBackend(); + revokeToken(callback) { + if (!this.accessToken) { + return Promise.reject(new Error("No token to revoke.")); + } + const promise = (0, revokeToken_1.revokeToken)(this.accessToken, this.tokenOptions.transporter); + if (callback) { + promise.then(() => callback(), callback); + } + this.tokenHandler = new tokenHandler_1.TokenHandler(this.tokenOptions); + } + get googleTokenOptions() { + return this.tokenOptions; } - const logger = (() => { - let previousBackend = undefined; - const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { - if (previousBackend !== cachedBackend) { - if (cachedBackend === null) { - return; - } else if (cachedBackend === undefined) { - cachedBackend = getNodeBackend(); - } - previousBackend = cachedBackend; - } - cachedBackend === null || cachedBackend === undefined || cachedBackend.log(namespace, fields, ...args); - }); - return newLogger; - })(); - loggerCache.set(namespace, logger); - return logger.func; } + exports.GoogleToken = GoogleToken; }); -// node_modules/.pnpm/google-logging-utils@1.1.3/node_modules/google-logging-utils/build/src/index.js -var require_src3 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) - __createBinding(exports2, m, p); - }; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/jwtaccess.js +var require_jwtaccess = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - __exportStar(require_logging_utils(), exports); -}); + exports.JWTAccess = undefined; + var jws = require_jws(); + var util_1 = require_util2(); + var DEFAULT_HEADER = { + alg: "RS256", + typ: "JWT" + }; -// node_modules/.pnpm/gcp-metadata@8.1.2/node_modules/gcp-metadata/build/src/index.js -var require_src4 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; + class JWTAccess { + email; + key; + keyId; + projectId; + eagerRefreshThresholdMillis; + cache = new util_1.LRUCache({ + capacity: 500, + maxAge: 60 * 60 * 1000 + }); + constructor(email, key, keyId, eagerRefreshThresholdMillis) { + this.email = email; + this.key = key; + this.keyId = keyId; + this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis ?? 5 * 60 * 1000; } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); - } : function(o, v) { - o["default"] = v; - }); - var __importStar = exports && exports.__importStar || function() { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function(o2) { - var ar = []; - for (var k in o2) - if (Object.prototype.hasOwnProperty.call(o2, k)) - ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return 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]); + getCachedKey(url, scopes) { + let cacheKey = url; + if (scopes && Array.isArray(scopes) && scopes.length) { + cacheKey = url ? `${url}_${scopes.join("_")}` : `${scopes.join("_")}`; + } else if (typeof scopes === "string") { + cacheKey = url ? `${url}_${scopes}` : scopes; } - __setModuleDefault(result, mod); - return result; - }; - }(); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) - __createBinding(exports2, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = undefined; - exports.instance = instance; - exports.project = project; - exports.universe = universe; - exports.bulk = bulk; - exports.isAvailable = isAvailable; - exports.resetIsAvailableCache = resetIsAvailableCache; - exports.getGCPResidency = getGCPResidency; - exports.setGCPResidency = setGCPResidency; - exports.requestTimeout = requestTimeout; - var gaxios_1 = require_src2(); - var jsonBigint = require_json_bigint(); - var gcp_residency_1 = require_gcp_residency(); - var logger = __importStar(require_src3()); - exports.BASE_PATH = "/computeMetadata/v1"; - exports.HOST_ADDRESS = "http://169.254.169.254"; - exports.SECONDARY_HOST_ADDRESS = "http://metadata.google.internal."; - exports.HEADER_NAME = "Metadata-Flavor"; - exports.HEADER_VALUE = "Google"; - exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); - var log = logger.log("gcp-metadata"); - exports.METADATA_SERVER_DETECTION = Object.freeze({ - "assume-present": "don't try to ping the metadata server, but assume it's present", - none: "don't try to ping the metadata server, but don't try to use it either", - "bios-only": "treat the result of a BIOS probe as canonical (don't fall back to pinging)", - "ping-only": "skip the BIOS probe, and go straight to pinging" - }); - function getBaseUrl(baseUrl) { - if (!baseUrl) { - baseUrl = process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST || exports.HOST_ADDRESS; - } - if (!/^https?:\/\//.test(baseUrl)) { - baseUrl = `http://${baseUrl}`; - } - return new URL(exports.BASE_PATH, baseUrl).href; - } - function validate2(options) { - Object.keys(options).forEach((key) => { - switch (key) { - case "params": - case "property": - case "headers": - break; - case "qs": - throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); - default: - throw new Error(`'${key}' is not a valid configuration option.`); + if (!cacheKey) { + throw Error("Scopes or url must be provided"); } - }); - } - async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { - const headers = new Headers(exports.HEADERS); - let metadataKey = ""; - let params = {}; - if (typeof type === "object") { - const metadataAccessor2 = type; - new Headers(metadataAccessor2.headers).forEach((value, key) => headers.set(key, value)); - metadataKey = metadataAccessor2.metadataKey; - params = metadataAccessor2.params || params; - noResponseRetries = metadataAccessor2.noResponseRetries || noResponseRetries; - fastFail = metadataAccessor2.fastFail || fastFail; - } else { - metadataKey = type; + return cacheKey; } - if (typeof options === "string") { - metadataKey += `/${options}`; - } else { - validate2(options); - if (options.property) { - metadataKey += `/${options.property}`; + getRequestHeaders(url, additionalClaims, scopes) { + const key = this.getCachedKey(url, scopes); + const cachedToken = this.cache.get(key); + const now = Date.now(); + if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { + return new Headers(cachedToken.headers); } - new Headers(options.headers).forEach((value, key) => headers.set(key, value)); - params = options.params || params; - } - const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; - const req = { - url: `${getBaseUrl()}/${metadataKey}`, - headers, - retryConfig: { noResponseRetries }, - params, - responseType: "text", - timeout: requestTimeout() - }; - log.info("instance request %j", req); - const res = await requestMethod(req); - log.info("instance metadata is %s", res.data); - const metadataFlavor = res.headers.get(exports.HEADER_NAME); - if (metadataFlavor !== exports.HEADER_VALUE) { - throw new RangeError(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${metadataFlavor ? `'${metadataFlavor}'` : "no header"}`); - } - if (typeof res.data === "string") { - try { - return jsonBigint.parse(res.data); - } catch {} - } - return res.data; - } - async function fastFailMetadataRequest(options) { - const secondaryOptions = { - ...options, - url: options.url?.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)) - }; - const r1 = (0, gaxios_1.request)(options); - const r2 = (0, gaxios_1.request)(secondaryOptions); - return Promise.any([r1, r2]); - } - function instance(options) { - return metadataAccessor("instance", options); - } - function project(options) { - return metadataAccessor("project", options); - } - function universe(options) { - return metadataAccessor("universe", options); - } - async function bulk(properties) { - const r = {}; - await Promise.all(properties.map((item) => { - return (async () => { - const res = await metadataAccessor(item); - const key = item.metadataKey; - r[key] = res; - })(); - })); - return r; - } - function detectGCPAvailableRetries() { - return process.env.DETECT_GCP_RETRIES ? Number(process.env.DETECT_GCP_RETRIES) : 0; - } - var cachedIsAvailableResponse; - async function isAvailable() { - if (process.env.METADATA_SERVER_DETECTION) { - const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); - if (!(value in exports.METADATA_SERVER_DETECTION)) { - throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join("`, `")}\`, or unset`); + const iat = Math.floor(Date.now() / 1000); + const exp = JWTAccess.getExpirationTime(iat); + let defaultClaims; + if (Array.isArray(scopes)) { + scopes = scopes.join(" "); } - switch (value) { - case "assume-present": - return true; - case "none": - return false; - case "bios-only": - return getGCPResidency(); - case "ping-only": + if (scopes) { + defaultClaims = { + iss: this.email, + sub: this.email, + scope: scopes, + exp, + iat + }; + } else { + defaultClaims = { + iss: this.email, + sub: this.email, + aud: url, + exp, + iat + }; + } + if (additionalClaims) { + for (const claim in defaultClaims) { + if (additionalClaims[claim]) { + throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); + } + } } + const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER; + const payload = Object.assign(defaultClaims, additionalClaims); + const signedJWT = jws.sign({ header, payload, secret: this.key }); + const headers = new Headers({ authorization: `Bearer ${signedJWT}` }); + this.cache.set(key, { + expiration: exp * 1000, + headers + }); + return headers; } - try { - if (cachedIsAvailableResponse === undefined) { - cachedIsAvailableResponse = metadataAccessor("instance", undefined, detectGCPAvailableRetries(), !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); + static getExpirationTime(iat) { + const exp = iat + 3600; + return exp; + } + fromJSON(json3) { + if (!json3) { + throw new Error("Must pass in a JSON object containing the service account auth settings."); } - await cachedIsAvailableResponse; - return true; - } catch (e2) { - const err = e2; - if (process.env.DEBUG_AUTH) { - console.info(err); + if (!json3.client_email) { + throw new Error("The incoming JSON object does not contain a client_email field"); } - if (err.type === "request-timeout") { - return false; + if (!json3.private_key) { + throw new Error("The incoming JSON object does not contain a private_key field"); } - if (err.response && err.response.status === 404) { - return false; + this.email = json3.client_email; + this.key = json3.private_key; + this.keyId = json3.private_key_id; + this.projectId = json3.project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); } else { - if (!(err.response && err.response.status === 404) && (!err.code || ![ - "EHOSTDOWN", - "EHOSTUNREACH", - "ENETUNREACH", - "ENOENT", - "ENOTFOUND", - "ECONNREFUSED" - ].includes(err.code.toString()))) { - let code = "UNKNOWN"; - if (err.code) - code = err.code.toString(); - process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, "MetadataLookupWarning"); - } - return false; + return this.fromStreamAsync(inputStream); } } - } - function resetIsAvailableCache() { - cachedIsAvailableResponse = undefined; - } - exports.gcpResidencyCache = null; - function getGCPResidency() { - if (exports.gcpResidencyCache === null) { - setGCPResidency(); + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + reject(new Error("Must pass in a stream containing the service account auth settings.")); + } + let s = ""; + inputStream.setEncoding("utf8").on("data", (chunk) => s += chunk).on("error", reject).on("end", () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } catch (err) { + reject(err); + } + }); + }); } - return exports.gcpResidencyCache; - } - function setGCPResidency(value = null) { - exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); - } - function requestTimeout() { - return getGCPResidency() ? 0 : 3000; } - __exportStar(require_gcp_residency(), exports); + exports.JWTAccess = JWTAccess; }); -// node_modules/.pnpm/base64-js@1.5.1/node_modules/base64-js/index.js -var require_base64_js = __commonJS((exports) => { - exports.byteLength = byteLength; - exports.toByteArray = toByteArray; - exports.fromByteArray = fromByteArray; - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; - var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - for (i = 0, len = code.length;i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - var i; - var len; - revLookup[45] = 62; - revLookup[95] = 63; - function getLens(b64) { - var len2 = b64.length; - if (len2 % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) - validLen = len2; - var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; - } - function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; - } - function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i2; - for (i2 = 0;i2 < len2; i2 += 4) { - tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - return arr; - } - function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; - } - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i2 = start;i2 < end; i2 += 3) { - tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); - output.push(tripletToBase64(tmp)); +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/jwtclient.js +var require_jwtclient = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JWT = undefined; + var googleToken_1 = require_googleToken(); + var getCredentials_1 = require_getCredentials(); + var jwtaccess_1 = require_jwtaccess(); + var oauth2client_1 = require_oauth2client(); + var authclient_1 = require_authclient(); + + class JWT extends oauth2client_1.OAuth2Client { + email; + keyFile; + key; + keyId; + defaultScopes; + scopes; + scope; + subject; + gtoken; + additionalClaims; + useJWTAccessWithScope; + defaultServicePath; + access; + constructor(options = {}) { + super(options); + this.email = options.email; + this.keyFile = options.keyFile; + this.key = options.key; + this.keyId = options.keyId; + this.scopes = options.scopes; + this.subject = options.subject; + this.additionalClaims = options.additionalClaims; + this.credentials = { refresh_token: "jwt-placeholder", expiry_date: 1 }; } - return output.join(""); - } - function fromByteArray(uint8) { - var tmp; - var len2 = uint8.length; - var extraBytes = len2 % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i2 = 0, len22 = len2 - extraBytes;i2 < len22; i2 += maxChunkLength) { - parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); + createScoped(scopes) { + const jwt2 = new JWT(this); + jwt2.scopes = scopes; + return jwt2; } - if (extraBytes === 1) { - tmp = uint8[len2 - 1]; - parts.push(lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "=="); - } else if (extraBytes === 2) { - tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; - parts.push(lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "="); + async getRequestMetadataAsync(url) { + url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; + const useSelfSignedJWT = !this.hasUserScopes() && url || this.useJWTAccessWithScope && this.hasAnyScopes() || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { + throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); + } + if (!this.apiKey && useSelfSignedJWT) { + if (this.additionalClaims && this.additionalClaims.target_audience) { + const { tokens } = await this.refreshToken(); + return { + headers: this.addSharedMetadataHeaders(new Headers({ + authorization: `Bearer ${tokens.id_token}` + })) + }; + } else { + if (!this.access) { + this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); + } + let scopes; + if (this.hasUserScopes()) { + scopes = this.scopes; + } else if (!url) { + scopes = this.defaultScopes; + } + const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; + const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims, useScopes ? scopes : undefined); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } else if (this.hasAnyScopes() || this.apiKey) { + return super.getRequestMetadataAsync(url); + } else { + return { headers: new Headers }; + } } - return parts.join(""); - } -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/shared.js -var require_shared = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.fromArrayBufferToHex = fromArrayBufferToHex; - function fromArrayBufferToHex(arrayBuffer) { - const byteArray = Array.from(new Uint8Array(arrayBuffer)); - return byteArray.map((byte) => { - return byte.toString(16).padStart(2, "0"); - }).join(""); - } -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/browser/crypto.js -var require_crypto = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.BrowserCrypto = undefined; - var base64js = require_base64_js(); - var shared_1 = require_shared(); - - class BrowserCrypto { - constructor() { - if (typeof window === "undefined" || window.crypto === undefined || window.crypto.subtle === undefined) { - throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + async fetchIdToken(targetAudience) { + const gtoken = new googleToken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: { target_audience: targetAudience }, + transporter: this.transporter + }); + await gtoken.getToken({ + forceRefresh: true + }); + if (!gtoken.idToken) { + throw new Error("Unknown error: Failed to fetch ID token"); } + return gtoken.idToken; } - async sha256DigestBase64(str) { - const inputBuffer = new TextEncoder().encode(str); - const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer); - return base64js.fromByteArray(new Uint8Array(outputBuffer)); + hasUserScopes() { + if (!this.scopes) { + return false; + } + return this.scopes.length > 0; } - randomBytesBase64(count) { - const array2 = new Uint8Array(count); - window.crypto.getRandomValues(array2); - return base64js.fromByteArray(array2); + hasAnyScopes() { + if (this.scopes && this.scopes.length > 0) + return true; + if (this.defaultScopes && this.defaultScopes.length > 0) + return true; + return false; } - static padBase64(base64) { - while (base64.length % 4 !== 0) { - base64 += "="; + authorize(callback) { + if (callback) { + this.authorizeAsync().then((r) => callback(null, r), callback); + } else { + return this.authorizeAsync(); } - return base64; } - async verify(pubkey, data, signature) { - const algo = { - name: "RSASSA-PKCS1-v1_5", - hash: { name: "SHA-256" } - }; - const dataArray = new TextEncoder().encode(data); - const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); - const cryptoKey = await window.crypto.subtle.importKey("jwk", pubkey, algo, true, ["verify"]); - const result = await window.crypto.subtle.verify(algo, cryptoKey, Buffer.from(signatureArray), dataArray); - return result; + async authorizeAsync() { + const result = await this.refreshToken(); + if (!result) { + throw new Error("No result returned"); + } + this.credentials = result.tokens; + this.credentials.refresh_token = "jwt-placeholder"; + this.key = this.gtoken.googleTokenOptions?.key; + this.email = this.gtoken.googleTokenOptions?.iss; + return result.tokens; } - async sign(privateKey, data) { - const algo = { - name: "RSASSA-PKCS1-v1_5", - hash: { name: "SHA-256" } + async refreshTokenNoCache() { + const gtoken = this.createGToken(); + const token = await gtoken.getToken({ + forceRefresh: this.isTokenExpiring() + }); + const tokens = { + access_token: token.access_token, + token_type: "Bearer", + expiry_date: gtoken.expiresAt, + id_token: gtoken.idToken }; - const dataArray = new TextEncoder().encode(data); - const cryptoKey = await window.crypto.subtle.importKey("jwk", privateKey, algo, true, ["sign"]); - const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); - return base64js.fromByteArray(new Uint8Array(result)); + this.emit("tokens", tokens); + return { res: null, tokens }; } - decodeBase64StringUtf8(base64) { - const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); - const result = new TextDecoder().decode(uint8array); - return result; + createGToken() { + if (!this.gtoken) { + this.gtoken = new googleToken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes || this.defaultScopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: this.additionalClaims, + transporter: this.transporter + }); + } + return this.gtoken; } - encodeBase64StringUtf8(text2) { - const uint8array = new TextEncoder().encode(text2); - const result = base64js.fromByteArray(uint8array); - return result; + fromJSON(json3) { + if (!json3) { + throw new Error("Must pass in a JSON object containing the service account auth settings."); + } + if (!json3.client_email) { + throw new Error("The incoming JSON object does not contain a client_email field"); + } + if (!json3.private_key) { + throw new Error("The incoming JSON object does not contain a private_key field"); + } + this.email = json3.client_email; + this.key = json3.private_key; + this.keyId = json3.private_key_id; + this.projectId = json3.project_id; + this.quotaProjectId = json3.quota_project_id; + this.universeDomain = json3.universe_domain || this.universeDomain; } - async sha256DigestHex(str) { - const inputBuffer = new TextEncoder().encode(str); - const outputBuffer = await window.crypto.subtle.digest("SHA-256", inputBuffer); - return (0, shared_1.fromArrayBufferToHex)(outputBuffer); + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } else { + return this.fromStreamAsync(inputStream); + } } - async signWithHmacSha256(key, msg) { - const rawKey = typeof key === "string" ? key : String.fromCharCode(...new Uint16Array(key)); - const enc = new TextEncoder; - const cryptoKey = await window.crypto.subtle.importKey("raw", enc.encode(rawKey), { - name: "HMAC", - hash: { - name: "SHA-256" + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error("Must pass in a stream containing the service account auth settings."); } - }, false, ["sign"]); - return window.crypto.subtle.sign("HMAC", cryptoKey, enc.encode(msg)); + let s = ""; + inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s += chunk).on("end", () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } catch (e2) { + reject(e2); + } + }); + }); + } + fromAPIKey(apiKey) { + if (typeof apiKey !== "string") { + throw new Error("Must provide an API Key string."); + } + this.apiKey = apiKey; + } + async getCredentials() { + if (this.key) { + return { private_key: this.key, client_email: this.email }; + } else if (this.keyFile) { + const gtoken = this.createGToken(); + const creds = await (0, getCredentials_1.getCredentials)(this.keyFile); + return { private_key: creds.privateKey, client_email: creds.clientEmail }; + } + throw new Error("A key or a keyFile must be provided to getCredentials."); } } - exports.BrowserCrypto = BrowserCrypto; + exports.JWT = JWT; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/node/crypto.js -var require_crypto2 = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/refreshclient.js +var require_refreshclient = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.NodeCrypto = undefined; - var crypto2 = __require("crypto"); + exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = undefined; + var oauth2client_1 = require_oauth2client(); + var authclient_1 = require_authclient(); + exports.USER_REFRESH_ACCOUNT_TYPE = "authorized_user"; - class NodeCrypto { - async sha256DigestBase64(str) { - return crypto2.createHash("sha256").update(str).digest("base64"); - } - randomBytesBase64(count) { - return crypto2.randomBytes(count).toString("base64"); - } - async verify(pubkey, data, signature) { - const verifier = crypto2.createVerify("RSA-SHA256"); - verifier.update(data); - verifier.end(); - return verifier.verify(pubkey, signature, "base64"); + class UserRefreshClient extends oauth2client_1.OAuth2Client { + _refreshToken; + constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { + const opts = optionsOrClientId && typeof optionsOrClientId === "object" ? optionsOrClientId : { + clientId: optionsOrClientId, + clientSecret, + refreshToken, + eagerRefreshThresholdMillis, + forceRefreshOnFailure + }; + super(opts); + this._refreshToken = opts.refreshToken; + this.credentials.refresh_token = opts.refreshToken; } - async sign(privateKey, data) { - const signer = crypto2.createSign("RSA-SHA256"); - signer.update(data); - signer.end(); - return signer.sign(privateKey, "base64"); + async refreshTokenNoCache() { + return super.refreshTokenNoCache(this._refreshToken); } - decodeBase64StringUtf8(base64) { - return Buffer.from(base64, "base64").toString("utf-8"); + async fetchIdToken(targetAudience) { + const opts = { + ...UserRefreshClient.RETRY_CONFIG, + url: this.endpoints.oauth2TokenUrl, + method: "POST", + data: new URLSearchParams({ + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: "refresh_token", + refresh_token: this._refreshToken, + target_audience: targetAudience + }), + responseType: "json" + }; + authclient_1.AuthClient.setMethodName(opts, "fetchIdToken"); + const res = await this.transporter.request(opts); + return res.data.id_token; } - encodeBase64StringUtf8(text2) { - return Buffer.from(text2, "utf-8").toString("base64"); + fromJSON(json3) { + if (!json3) { + throw new Error("Must pass in a JSON object containing the user refresh token"); + } + if (json3.type !== "authorized_user") { + throw new Error('The incoming JSON object does not have the "authorized_user" type'); + } + if (!json3.client_id) { + throw new Error("The incoming JSON object does not contain a client_id field"); + } + if (!json3.client_secret) { + throw new Error("The incoming JSON object does not contain a client_secret field"); + } + if (!json3.refresh_token) { + throw new Error("The incoming JSON object does not contain a refresh_token field"); + } + this._clientId = json3.client_id; + this._clientSecret = json3.client_secret; + this._refreshToken = json3.refresh_token; + this.credentials.refresh_token = json3.refresh_token; + this.quotaProjectId = json3.quota_project_id; + this.universeDomain = json3.universe_domain || this.universeDomain; } - async sha256DigestHex(str) { - return crypto2.createHash("sha256").update(str).digest("hex"); + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(() => callback(), callback); + } else { + return this.fromStreamAsync(inputStream); + } } - async signWithHmacSha256(key, msg) { - const cryptoKey = typeof key === "string" ? key : toBuffer(key); - return toArrayBuffer(crypto2.createHmac("sha256", cryptoKey).update(msg).digest()); + async fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + return reject(new Error("Must pass in a stream containing the user refresh token.")); + } + let s = ""; + inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s += chunk).on("end", () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + return resolve(); + } catch (err) { + return reject(err); + } + }); + }); } - } - exports.NodeCrypto = NodeCrypto; - function toArrayBuffer(buffer) { - const ab = new ArrayBuffer(buffer.length); - const view = new Uint8Array(ab); - for (let i = 0;i < buffer.length; ++i) { - view[i] = buffer[i]; + static fromJSON(json3) { + const client = new UserRefreshClient; + client.fromJSON(json3); + return client; } - return ab; - } - function toBuffer(arrayBuffer) { - return Buffer.from(arrayBuffer); } + exports.UserRefreshClient = UserRefreshClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/crypto/crypto.js -var require_crypto3 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) - __createBinding(exports2, m, p); - }; +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/impersonated.js +var require_impersonated = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.createCrypto = createCrypto; - exports.hasBrowserCrypto = hasBrowserCrypto; - var crypto_1 = require_crypto(); - var crypto_2 = require_crypto2(); - __exportStar(require_shared(), exports); - function createCrypto() { - if (hasBrowserCrypto()) { - return new crypto_1.BrowserCrypto; + exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = undefined; + var oauth2client_1 = require_oauth2client(); + var gaxios_1 = require_src2(); + var util_1 = require_util2(); + exports.IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account"; + + class Impersonated extends oauth2client_1.OAuth2Client { + sourceClient; + targetPrincipal; + targetScopes; + delegates; + lifetime; + endpoint; + constructor(options = {}) { + super(options); + this.credentials = { + expiry_date: 1, + refresh_token: "impersonated-placeholder" + }; + this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client; + this.targetPrincipal = options.targetPrincipal ?? ""; + this.delegates = options.delegates ?? []; + this.targetScopes = options.targetScopes ?? []; + this.lifetime = options.lifetime ?? 3600; + const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get("universe_domain"); + if (!usingExplicitUniverseDomain) { + this.universeDomain = this.sourceClient.universeDomain; + } else if (this.sourceClient.universeDomain !== this.universeDomain) { + throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); + } + this.endpoint = options.endpoint ?? `https://iamcredentials.${this.universeDomain}`; + } + async sign(blobToSign) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:signBlob`; + const body = { + delegates: this.delegates, + payload: Buffer.from(blobToSign).toString("base64") + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: "POST" + }); + return res.data; + } + getTargetPrincipal() { + return this.targetPrincipal; + } + async refreshToken() { + try { + await this.sourceClient.getAccessToken(); + const name = "projects/-/serviceAccounts/" + this.targetPrincipal; + const u = `${this.endpoint}/v1/${name}:generateAccessToken`; + const body = { + delegates: this.delegates, + scope: this.targetScopes, + lifetime: this.lifetime + "s" + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: "POST" + }); + const tokenResponse = res.data; + this.credentials.access_token = tokenResponse.accessToken; + this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); + return { + tokens: this.credentials, + res + }; + } catch (error) { + if (!(error instanceof Error)) + throw error; + let status = 0; + let message = ""; + if (error instanceof gaxios_1.GaxiosError) { + status = error?.response?.data?.error?.status; + message = error?.response?.data?.error?.message; + } + if (status && message) { + error.message = `${status}: unable to impersonate: ${message}`; + throw error; + } else { + error.message = `unable to impersonate: ${error}`; + throw error; + } + } + } + async fetchIdToken(targetAudience, options) { + await this.sourceClient.getAccessToken(); + const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; + const u = `${this.endpoint}/v1/${name}:generateIdToken`; + const body = { + delegates: this.delegates, + audience: targetAudience, + includeEmail: options?.includeEmail ?? true, + useEmailAzp: options?.includeEmail ?? true + }; + const res = await this.sourceClient.request({ + ...Impersonated.RETRY_CONFIG, + url: u, + data: body, + method: "POST" + }); + return res.data.token; } - return new crypto_2.NodeCrypto; - } - function hasBrowserCrypto() { - return typeof window !== "undefined" && typeof window.crypto !== "undefined" && typeof window.crypto.subtle !== "undefined"; } + exports.Impersonated = Impersonated; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/util.js -var require_util2 = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/oauth2common.js +var require_oauth2common = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.LRUCache = undefined; - exports.snakeToCamel = snakeToCamel; - exports.originalOrCamelOptions = originalOrCamelOptions; - exports.removeUndefinedValuesInObject = removeUndefinedValuesInObject; - exports.isValidFile = isValidFile; - exports.getWellKnownCertificateConfigFileLocation = getWellKnownCertificateConfigFileLocation; - var fs = __require("fs"); - var os = __require("os"); - var path2 = __require("path"); - var WELL_KNOWN_CERTIFICATE_CONFIG_FILE = "certificate_config.json"; - var CLOUDSDK_CONFIG_DIRECTORY = "gcloud"; - function snakeToCamel(str) { - return str.replace(/([_][^_])/g, (match) => match.slice(1).toUpperCase()); - } - function originalOrCamelOptions(obj) { - function get(key) { - const o = obj || {}; - return o[key] ?? o[snakeToCamel(key)]; - } - return { get }; - } + exports.OAuthClientAuthHandler = undefined; + exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; + var gaxios_1 = require_src2(); + var crypto_1 = require_crypto3(); + var METHODS_SUPPORTING_REQUEST_BODY = ["PUT", "POST", "PATCH"]; - class LRUCache { - capacity; - #cache = new Map; - maxAge; + class OAuthClientAuthHandler { + #crypto = (0, crypto_1.createCrypto)(); + #clientAuthentication; + transporter; constructor(options) { - this.capacity = options.capacity; - this.maxAge = options.maxAge; - } - #moveToEnd(key, value) { - this.#cache.delete(key); - this.#cache.set(key, { - value, - lastAccessed: Date.now() - }); + if (options && "clientId" in options) { + this.#clientAuthentication = options; + this.transporter = new gaxios_1.Gaxios; + } else { + this.#clientAuthentication = options?.clientAuthentication; + this.transporter = options?.transporter || new gaxios_1.Gaxios; + } } - set(key, value) { - this.#moveToEnd(key, value); - this.#evict(); + applyClientAuthenticationOptions(opts, bearerToken) { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.injectAuthenticatedHeaders(opts, bearerToken); + if (!bearerToken) { + this.injectAuthenticatedRequestBody(opts); + } } - get(key) { - const item = this.#cache.get(key); - if (!item) - return; - this.#moveToEnd(key, item.value); - this.#evict(); - return item.value; + injectAuthenticatedHeaders(opts, bearerToken) { + if (bearerToken) { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, { + authorization: `Bearer ${bearerToken}` + }); + } else if (this.#clientAuthentication?.confidentialClientType === "basic") { + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + const clientId = this.#clientAuthentication.clientId; + const clientSecret = this.#clientAuthentication.clientSecret || ""; + const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); + gaxios_1.Gaxios.mergeHeaders(opts.headers, { + authorization: `Basic ${base64EncodedCreds}` + }); + } } - #evict() { - const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; - let oldestItem = this.#cache.entries().next(); - while (!oldestItem.done && (this.#cache.size > this.capacity || oldestItem.value[1].lastAccessed < cutoffDate)) { - this.#cache.delete(oldestItem.value[0]); - oldestItem = this.#cache.entries().next(); + injectAuthenticatedRequestBody(opts) { + if (this.#clientAuthentication?.confidentialClientType === "request-body") { + const method = (opts.method || "GET").toUpperCase(); + if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) { + throw new Error(`${method} HTTP method does not support ` + `${this.#clientAuthentication.confidentialClientType} ` + "client authentication"); + } + const headers = new Headers(opts.headers); + const contentType = headers.get("content-type"); + if (contentType?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) { + const data = new URLSearchParams(opts.data ?? ""); + data.append("client_id", this.#clientAuthentication.clientId); + data.append("client_secret", this.#clientAuthentication.clientSecret || ""); + opts.data = data; + } else if (contentType?.startsWith("application/json")) { + opts.data = opts.data || {}; + Object.assign(opts.data, { + client_id: this.#clientAuthentication.clientId, + client_secret: this.#clientAuthentication.clientSecret || "" + }); + } else { + throw new Error(`${contentType} content-types are not supported with ` + `${this.#clientAuthentication.confidentialClientType} ` + "client authentication"); + } } } + static get RETRY_CONFIG() { + return { + retry: true, + retryConfig: { + httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"] + } + }; + } } - exports.LRUCache = LRUCache; - function removeUndefinedValuesInObject(object2) { - Object.entries(object2).forEach(([key, value]) => { - if (value === undefined || value === "undefined") { - delete object2[key]; - } - }); - return object2; - } - async function isValidFile(filePath) { - try { - const stats = await fs.promises.lstat(filePath); - return stats.isFile(); - } catch (e2) { - return false; - } - } - function getWellKnownCertificateConfigFileLocation() { - const configDir = process.env.CLOUDSDK_CONFIG || (_isWindows() ? path2.join(process.env.APPDATA || "", CLOUDSDK_CONFIG_DIRECTORY) : path2.join(process.env.HOME || "", ".config", CLOUDSDK_CONFIG_DIRECTORY)); - return path2.join(configDir, WELL_KNOWN_CERTIFICATE_CONFIG_FILE); - } - function _isWindows() { - return os.platform().startsWith("win"); - } -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/package.json -var require_package4 = __commonJS((exports, module) => { - module.exports = { - name: "google-auth-library", - version: "10.6.2", - author: "Google Inc.", - description: "Google APIs Authentication Client Library for Node.js", - engines: { - node: ">=18" - }, - main: "./build/src/index.js", - types: "./build/src/index.d.ts", - repository: { - type: "git", - directory: "packages/google-auth-library-nodejs", - url: "https://github.com/googleapis/google-cloud-node-core.git" - }, - keywords: [ - "google", - "api", - "google apis", - "client", - "client library" - ], - dependencies: { - "base64-js": "^1.3.0", - "ecdsa-sig-formatter": "^1.0.11", - gaxios: "^7.1.4", - "gcp-metadata": "8.1.2", - "google-logging-utils": "1.1.3", - jws: "^4.0.0" - }, - devDependencies: { - "@types/base64-js": "^1.2.5", - "@types/jws": "^3.1.0", - "@types/mocha": "^10.0.10", - "@types/mv": "^2.1.0", - "@types/ncp": "^2.0.8", - "@types/node": "^24.0.0", - "@types/sinon": "^21.0.0", - "assert-rejects": "^1.0.0", - c8: "^10.1.3", - codecov: "^3.8.3", - gts: "^6.0.2", - "is-docker": "^3.0.0", - jsdoc: "^4.0.4", - "jsdoc-fresh": "^5.0.0", - "jsdoc-region-tag": "^4.0.0", - karma: "^6.0.0", - "karma-chrome-launcher": "^3.0.0", - "karma-coverage": "^2.0.0", - "karma-firefox-launcher": "^2.0.0", - "karma-mocha": "^2.0.0", - "karma-sourcemap-loader": "^0.4.0", - "karma-webpack": "^5.0.1", - keypair: "^1.0.4", - mocha: "^11.1.0", - mv: "^2.1.1", - ncp: "^2.0.0", - nock: "^14.0.5", - "null-loader": "^4.0.1", - puppeteer: "^24.0.0", - sinon: "^21.0.0", - "ts-loader": "^9.5.2", - typescript: "5.8.3", - webpack: "^5.97.1", - "webpack-cli": "^6.0.1" - }, - files: [ - "build/src", - "!build/src/**/*.map" - ], - scripts: { - test: "c8 mocha build/test", - clean: "gts clean", - prepare: "npm run compile", - lint: "gts check --no-inline-config", - compile: "tsc -p .", - fix: "gts fix", - pretest: "npm run compile -- --sourceMap", - docs: "jsdoc -c .jsdoc.js", - "samples-setup": "cd samples/ && npm link ../ && npm run setup && cd ../", - "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", - "system-test": "mocha build/system-test --timeout 60000", - "presystem-test": "npm run compile -- --sourceMap", - webpack: "webpack", - "browser-test": "karma start", - "docs-test": "echo 'disabled until linkinator is fixed'", - "predocs-test": "npm run docs", - prelint: "cd samples; npm link ../; npm install" - }, - license: "Apache-2.0", - homepage: "https://github.com/googleapis/google-cloud-node-core/tree/main/packages/google-auth-library-nodejs" - }; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/shared.cjs -var require_shared2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.USER_AGENT = exports.PRODUCT_NAME = exports.pkg = undefined; - var pkg = require_package4(); - exports.pkg = pkg; - var PRODUCT_NAME = "google-api-nodejs-client"; - exports.PRODUCT_NAME = PRODUCT_NAME; - var USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; - exports.USER_AGENT = USER_AGENT; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/authclient.js -var require_authclient = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = undefined; - var events_1 = __require("events"); - var gaxios_1 = require_src2(); - var util_1 = require_util2(); - var google_logging_utils_1 = require_src3(); - var shared_cjs_1 = require_shared2(); - exports.DEFAULT_UNIVERSE = "googleapis.com"; - exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; - - class AuthClient extends events_1.EventEmitter { - apiKey; - projectId; - quotaProjectId; - transporter; - credentials = {}; - eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; - forceRefreshOnFailure = false; - universeDomain = exports.DEFAULT_UNIVERSE; - static RequestMethodNameSymbol = Symbol("request method name"); - static RequestLogIdSymbol = Symbol("request log id"); - constructor(opts = {}) { - super(); - const options = (0, util_1.originalOrCamelOptions)(opts); - this.apiKey = opts.apiKey; - this.projectId = options.get("project_id") ?? null; - this.quotaProjectId = options.get("quota_project_id"); - this.credentials = options.get("credentials") ?? {}; - this.universeDomain = options.get("universe_domain") ?? exports.DEFAULT_UNIVERSE; - this.transporter = opts.transporter ?? new gaxios_1.Gaxios(opts.transporterOptions); - if (options.get("useAuthRequestParameters") !== false) { - this.transporter.interceptors.request.add(AuthClient.DEFAULT_REQUEST_INTERCEPTOR); - this.transporter.interceptors.response.add(AuthClient.DEFAULT_RESPONSE_INTERCEPTOR); - } - if (opts.eagerRefreshThresholdMillis) { - this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; - } - this.forceRefreshOnFailure = opts.forceRefreshOnFailure ?? false; - } - fetch(...args) { - const input = args[0]; - const init3 = args[1]; - let url = undefined; - const headers = new Headers; - if (typeof input === "string") { - url = new URL(input); - } else if (input instanceof URL) { - url = input; - } else if (input && input.url) { - url = new URL(input.url); - } - if (input && typeof input === "object" && "headers" in input) { - gaxios_1.Gaxios.mergeHeaders(headers, input.headers); - } - if (init3) { - gaxios_1.Gaxios.mergeHeaders(headers, new Headers(init3.headers)); - } - if (typeof input === "object" && !(input instanceof URL)) { - return this.request({ ...init3, ...input, headers, url }); - } else { - return this.request({ ...init3, headers, url }); - } - } - setCredentials(credentials) { - this.credentials = credentials; - } - addSharedMetadataHeaders(headers) { - if (!headers.has("x-goog-user-project") && this.quotaProjectId) { - headers.set("x-goog-user-project", this.quotaProjectId); - } - return headers; + exports.OAuthClientAuthHandler = OAuthClientAuthHandler; + function getErrorFromOAuthErrorResponse(resp, err) { + const errorCode = resp.error; + const errorDescription = resp.error_description; + const errorUri = resp.error_uri; + let message = `Error code ${errorCode}`; + if (typeof errorDescription !== "undefined") { + message += `: ${errorDescription}`; } - addUserProjectAndAuthHeaders(target, source) { - const xGoogUserProject = source.get("x-goog-user-project"); - const authorizationHeader = source.get("authorization"); - if (xGoogUserProject) { - target.set("x-goog-user-project", xGoogUserProject); - } - if (authorizationHeader) { - target.set("authorization", authorizationHeader); - } - return target; + if (typeof errorUri !== "undefined") { + message += ` - ${errorUri}`; } - static log = (0, google_logging_utils_1.log)("auth"); - static DEFAULT_REQUEST_INTERCEPTOR = { - resolved: async (config) => { - if (!config.headers.has("x-goog-api-client")) { - const nodeVersion = process.version.replace(/^v/, ""); - config.headers.set("x-goog-api-client", `gl-node/${nodeVersion}`); - } - const userAgent = config.headers.get("User-Agent"); - if (!userAgent) { - config.headers.set("User-Agent", shared_cjs_1.USER_AGENT); - } else if (!userAgent.includes(`${shared_cjs_1.PRODUCT_NAME}/`)) { - config.headers.set("User-Agent", `${userAgent} ${shared_cjs_1.USER_AGENT}`); - } - try { - const symbols = config; - const methodName = symbols[AuthClient.RequestMethodNameSymbol]; - const logId = `${Math.floor(Math.random() * 1000)}`; - symbols[AuthClient.RequestLogIdSymbol] = logId; - const logObject = { - url: config.url, - headers: config.headers - }; - if (methodName) { - AuthClient.log.info("%s [%s] request %j", methodName, logId, logObject); - } else { - AuthClient.log.info("[%s] request %j", logId, logObject); - } - } catch (e2) {} - return config; - } - }; - static DEFAULT_RESPONSE_INTERCEPTOR = { - resolved: async (response) => { - try { - const symbols = response.config; - const methodName = symbols[AuthClient.RequestMethodNameSymbol]; - const logId = symbols[AuthClient.RequestLogIdSymbol]; - if (methodName) { - AuthClient.log.info("%s [%s] response %j", methodName, logId, response.data); - } else { - AuthClient.log.info("[%s] response %j", logId, response.data); - } - } catch (e2) {} - return response; - }, - rejected: async (error) => { - try { - const symbols = error.config; - const methodName = symbols[AuthClient.RequestMethodNameSymbol]; - const logId = symbols[AuthClient.RequestLogIdSymbol]; - if (methodName) { - AuthClient.log.info("%s [%s] error %j", methodName, logId, error.response?.data); - } else { - AuthClient.log.error("[%s] error %j", logId, error.response?.data); - } - } catch (e2) {} - throw error; + const newError = new Error(message); + if (err) { + const keys = Object.keys(err); + if (err.stack) { + keys.push("stack"); } - }; - static setMethodName(config, methodName) { - try { - const symbols = config; - symbols[AuthClient.RequestMethodNameSymbol] = methodName; - } catch (e2) {} - } - static get RETRY_CONFIG() { - return { - retry: true, - retryConfig: { - httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"] + keys.forEach((key) => { + if (key !== "message") { + Object.defineProperty(newError, key, { + value: err[key], + writable: false, + enumerable: true + }); } - }; - } - } - exports.AuthClient = AuthClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/loginticket.js -var require_loginticket = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.LoginTicket = undefined; - - class LoginTicket { - envelope; - payload; - constructor(env2, pay) { - this.envelope = env2; - this.payload = pay; - } - getEnvelope() { - return this.envelope; - } - getPayload() { - return this.payload; - } - getUserId() { - const payload = this.getPayload(); - if (payload && payload.sub) { - return payload.sub; - } - return null; - } - getAttributes() { - return { envelope: this.getEnvelope(), payload: this.getPayload() }; + }); } + return newError; } - exports.LoginTicket = LoginTicket; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/oauth2client.js -var require_oauth2client = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/stscredentials.js +var require_stscredentials = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = undefined; + exports.StsCredentials = undefined; var gaxios_1 = require_src2(); - var querystring = __require("querystring"); - var stream = __require("stream"); - var formatEcdsa = require_ecdsa_sig_formatter(); - var util_1 = require_util2(); - var crypto_1 = require_crypto3(); var authclient_1 = require_authclient(); - var loginticket_1 = require_loginticket(); - var CodeChallengeMethod; - (function(CodeChallengeMethod2) { - CodeChallengeMethod2["Plain"] = "plain"; - CodeChallengeMethod2["S256"] = "S256"; - })(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); - var CertificateFormat; - (function(CertificateFormat2) { - CertificateFormat2["PEM"] = "PEM"; - CertificateFormat2["JWK"] = "JWK"; - })(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); - var ClientAuthentication; - (function(ClientAuthentication2) { - ClientAuthentication2["ClientSecretPost"] = "ClientSecretPost"; - ClientAuthentication2["ClientSecretBasic"] = "ClientSecretBasic"; - ClientAuthentication2["None"] = "None"; - })(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); + var oauth2common_1 = require_oauth2common(); + var util_1 = require_util2(); - class OAuth2Client extends authclient_1.AuthClient { - redirectUri; - certificateCache = {}; - certificateExpiry = null; - certificateCacheFormat = CertificateFormat.PEM; - refreshTokenPromises = new Map; - endpoints; - issuers; - clientAuthentication; - _clientId; - _clientSecret; - refreshHandler; - constructor(options = {}, clientSecret, redirectUri) { - super(typeof options === "object" ? options : {}); - if (typeof options !== "object") { + class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { + #tokenExchangeEndpoint; + constructor(options = { + tokenExchangeEndpoint: "" + }, clientAuthentication) { + if (typeof options !== "object" || options instanceof URL) { options = { - clientId: options, - clientSecret, - redirectUri + tokenExchangeEndpoint: options, + clientAuthentication }; } - this._clientId = options.clientId || options.client_id; - this._clientSecret = options.clientSecret || options.client_secret; - this.redirectUri = options.redirectUri || options.redirect_uris?.[0]; - this.endpoints = { - tokenInfoUrl: "https://oauth2.googleapis.com/tokeninfo", - oauth2AuthBaseUrl: "https://accounts.google.com/o/oauth2/v2/auth", - oauth2TokenUrl: "https://oauth2.googleapis.com/token", - oauth2RevokeUrl: "https://oauth2.googleapis.com/revoke", - oauth2FederatedSignonPemCertsUrl: "https://www.googleapis.com/oauth2/v1/certs", - oauth2FederatedSignonJwkCertsUrl: "https://www.googleapis.com/oauth2/v3/certs", - oauth2IapPublicKeyUrl: "https://www.gstatic.com/iap/verify/public_key", - ...options.endpoints - }; - this.clientAuthentication = options.clientAuthentication || ClientAuthentication.ClientSecretPost; - this.issuers = options.issuers || [ - "accounts.google.com", - "https://accounts.google.com", - this.universeDomain - ]; - } - static GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; - static CLOCK_SKEW_SECS_ = 300; - static DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; - generateAuthUrl(opts = {}) { - if (opts.code_challenge_method && !opts.code_challenge) { - throw new Error("If a code_challenge_method is provided, code_challenge must be included."); - } - opts.response_type = opts.response_type || "code"; - opts.client_id = opts.client_id || this._clientId; - opts.redirect_uri = opts.redirect_uri || this.redirectUri; - if (Array.isArray(opts.scope)) { - opts.scope = opts.scope.join(" "); - } - const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); - return rootUrl + "?" + querystring.stringify(opts); - } - generateCodeVerifier() { - throw new Error("generateCodeVerifier is removed, please use generateCodeVerifierAsync instead."); - } - async generateCodeVerifierAsync() { - const crypto2 = (0, crypto_1.createCrypto)(); - const randomString = crypto2.randomBytesBase64(96); - const codeVerifier = randomString.replace(/\+/g, "~").replace(/=/g, "_").replace(/\//g, "-"); - const unencodedCodeChallenge = await crypto2.sha256DigestBase64(codeVerifier); - const codeChallenge = unencodedCodeChallenge.split("=")[0].replace(/\+/g, "-").replace(/\//g, "_"); - return { codeVerifier, codeChallenge }; - } - getToken(codeOrOptions, callback) { - const options = typeof codeOrOptions === "string" ? { code: codeOrOptions } : codeOrOptions; - if (callback) { - this.getTokenAsync(options).then((r) => callback(null, r.tokens, r.res), (e2) => callback(e2, null, e2.response)); - } else { - return this.getTokenAsync(options); - } + super(options); + this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint; } - async getTokenAsync(options) { - const url = this.endpoints.oauth2TokenUrl.toString(); - const headers = new Headers; + async exchangeToken(stsCredentialsOptions, headers, options) { const values = { - client_id: options.client_id || this._clientId, - code_verifier: options.codeVerifier, - code: options.code, - grant_type: "authorization_code", - redirect_uri: options.redirect_uri || this.redirectUri + grant_type: stsCredentialsOptions.grantType, + resource: stsCredentialsOptions.resource, + audience: stsCredentialsOptions.audience, + scope: stsCredentialsOptions.scope?.join(" "), + requested_token_type: stsCredentialsOptions.requestedTokenType, + subject_token: stsCredentialsOptions.subjectToken, + subject_token_type: stsCredentialsOptions.subjectTokenType, + actor_token: stsCredentialsOptions.actingParty?.actorToken, + actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType, + options: options && JSON.stringify(options) }; - if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { - const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); - headers.set("authorization", `Basic ${basic.toString("base64")}`); - } - if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { - values.client_secret = this._clientSecret; - } const opts = { - ...OAuth2Client.RETRY_CONFIG, + ...StsCredentials.RETRY_CONFIG, + url: this.#tokenExchangeEndpoint.toString(), method: "POST", - url, + headers, data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), - headers + responseType: "json" }; - authclient_1.AuthClient.setMethodName(opts, "getTokenAsync"); - const res = await this.transporter.request(opts); - const tokens = res.data; - if (res.data && res.data.expires_in) { - tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; - delete tokens.expires_in; - } - this.emit("tokens", tokens); - return { tokens, res }; - } - async refreshToken(refreshToken) { - if (!refreshToken) { - return this.refreshTokenNoCache(refreshToken); - } - if (this.refreshTokenPromises.has(refreshToken)) { - return this.refreshTokenPromises.get(refreshToken); + authclient_1.AuthClient.setMethodName(opts, "exchangeToken"); + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + const stsSuccessfulResponse = response.data; + stsSuccessfulResponse.res = response; + return stsSuccessfulResponse; + } catch (error) { + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, error); + } + throw error; } - const p = this.refreshTokenNoCache(refreshToken).then((r) => { - this.refreshTokenPromises.delete(refreshToken); - return r; - }, (e2) => { - this.refreshTokenPromises.delete(refreshToken); - throw e2; - }); - this.refreshTokenPromises.set(refreshToken, p); - return p; } - async refreshTokenNoCache(refreshToken) { - if (!refreshToken) { - throw new Error("No refresh token is set."); + } + exports.StsCredentials = StsCredentials; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/baseexternalclient.js +var require_baseexternalclient = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = undefined; + var gaxios_1 = require_src2(); + var stream = __require("stream"); + var authclient_1 = require_authclient(); + var sts = require_stscredentials(); + var util_1 = require_util2(); + var shared_cjs_1 = require_shared2(); + var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; + var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; + var DEFAULT_OAUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform"; + var DEFAULT_TOKEN_LIFESPAN = 3600; + exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; + exports.EXTERNAL_ACCOUNT_TYPE = "external_account"; + exports.CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"; + var WORKFORCE_AUDIENCE_PATTERN = "//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+"; + var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/token"; + + class BaseExternalAccountClient extends authclient_1.AuthClient { + scopes; + projectNumber; + audience; + subjectTokenType; + stsCredential; + clientAuth; + credentialSourceType; + cachedAccessToken; + serviceAccountImpersonationUrl; + serviceAccountImpersonationLifetime; + workforcePoolUserProject; + configLifetimeRequested; + tokenUrl; + cloudResourceManagerURL; + supplierContext; + #pendingAccessToken = null; + constructor(options) { + super(options); + const opts = (0, util_1.originalOrCamelOptions)(options); + const type = opts.get("type"); + if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { + throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + `received "${options.type}"`); } - const url = this.endpoints.oauth2TokenUrl.toString(); - const data = { - refresh_token: refreshToken, - client_id: this._clientId, - client_secret: this._clientSecret, - grant_type: "refresh_token" - }; - let res; - try { - const opts = { - ...OAuth2Client.RETRY_CONFIG, - method: "POST", - url, - data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(data)) + const clientId = opts.get("client_id"); + const clientSecret = opts.get("client_secret"); + this.tokenUrl = opts.get("token_url") ?? DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain); + const subjectTokenType = opts.get("subject_token_type"); + const workforcePoolUserProject = opts.get("workforce_pool_user_project"); + const serviceAccountImpersonationUrl = opts.get("service_account_impersonation_url"); + const serviceAccountImpersonation = opts.get("service_account_impersonation"); + const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get("token_lifetime_seconds"); + this.cloudResourceManagerURL = new URL(opts.get("cloud_resource_manager_url") || `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); + if (clientId) { + this.clientAuth = { + confidentialClientType: "basic", + clientId, + clientSecret }; - authclient_1.AuthClient.setMethodName(opts, "refreshTokenNoCache"); - res = await this.transporter.request(opts); - } catch (e2) { - if (e2 instanceof gaxios_1.GaxiosError && e2.message === "invalid_grant" && e2.response?.data && /ReAuth/i.test(e2.response.data.error_description)) { - e2.message = JSON.stringify(e2.response.data); - } - throw e2; - } - const tokens = res.data; - if (res.data && res.data.expires_in) { - tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; - delete tokens.expires_in; } - this.emit("tokens", tokens); - return { tokens, res }; - } - refreshAccessToken(callback) { - if (callback) { - this.refreshAccessTokenAsync().then((r) => callback(null, r.credentials, r.res), callback); - } else { - return this.refreshAccessTokenAsync(); + this.stsCredential = new sts.StsCredentials({ + tokenExchangeEndpoint: this.tokenUrl, + clientAuthentication: this.clientAuth + }); + this.scopes = opts.get("scopes") || [DEFAULT_OAUTH_SCOPE]; + this.cachedAccessToken = null; + this.audience = opts.get("audience"); + this.subjectTokenType = subjectTokenType; + this.workforcePoolUserProject = workforcePoolUserProject; + const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); + if (this.workforcePoolUserProject && !this.audience.match(workforceAudiencePattern)) { + throw new Error("workforcePoolUserProject should not be set for non-workforce pool " + "credentials."); } - } - async refreshAccessTokenAsync() { - const r = await this.refreshToken(this.credentials.refresh_token); - const tokens = r.tokens; - tokens.refresh_token = this.credentials.refresh_token; - this.credentials = tokens; - return { credentials: this.credentials, res: r.res }; - } - getAccessToken(callback) { - if (callback) { - this.getAccessTokenAsync().then((r) => callback(null, r.token, r.res), callback); + this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; + this.serviceAccountImpersonationLifetime = serviceAccountImpersonationLifetime; + if (this.serviceAccountImpersonationLifetime) { + this.configLifetimeRequested = true; } else { - return this.getAccessTokenAsync(); + this.configLifetimeRequested = false; + this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; } + this.projectNumber = this.getProjectNumber(this.audience); + this.supplierContext = { + audience: this.audience, + subjectTokenType: this.subjectTokenType, + transporter: this.transporter + }; } - async getAccessTokenAsync() { - const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); - if (shouldRefresh) { - if (!this.credentials.refresh_token) { - if (this.refreshHandler) { - const refreshedAccessToken = await this.processAndValidateRefreshHandler(); - if (refreshedAccessToken?.access_token) { - this.setCredentials(refreshedAccessToken); - return { token: this.credentials.access_token }; - } - } else { - throw new Error("No refresh token or refresh handler callback is set."); - } - } - const r = await this.refreshAccessTokenAsync(); - if (!r.credentials || r.credentials && !r.credentials.access_token) { - throw new Error("Could not refresh access token."); + getServiceAccountEmail() { + if (this.serviceAccountImpersonationUrl) { + if (this.serviceAccountImpersonationUrl.length > 256) { + throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); } - return { token: r.credentials.access_token, res: r.res }; - } else { - return { token: this.credentials.access_token }; + const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; + const result = re.exec(this.serviceAccountImpersonationUrl); + return result?.groups?.email || null; } + return null; } - async getRequestHeaders(url) { - const headers = (await this.getRequestMetadataAsync(url)).headers; - return headers; + setCredentials(credentials) { + super.setCredentials(credentials); + this.cachedAccessToken = credentials; } - async getRequestMetadataAsync(url) { - const thisCreds = this.credentials; - if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey && !this.refreshHandler) { - throw new Error("No access, refresh token, API key or refresh handler callback is set."); - } - if (thisCreds.access_token && !this.isTokenExpiring()) { - thisCreds.token_type = thisCreds.token_type || "Bearer"; - const headers2 = new Headers({ - authorization: thisCreds.token_type + " " + thisCreds.access_token - }); - return { headers: this.addSharedMetadataHeaders(headers2) }; - } - if (this.refreshHandler) { - const refreshedAccessToken = await this.processAndValidateRefreshHandler(); - if (refreshedAccessToken?.access_token) { - this.setCredentials(refreshedAccessToken); - const headers2 = new Headers({ - authorization: "Bearer " + this.credentials.access_token - }); - return { headers: this.addSharedMetadataHeaders(headers2) }; - } - } - if (this.apiKey) { - return { headers: new Headers({ "X-Goog-Api-Key": this.apiKey }) }; - } - let r = null; - let tokens = null; - try { - r = await this.refreshToken(thisCreds.refresh_token); - tokens = r.tokens; - } catch (err) { - const e2 = err; - if (e2.response && (e2.response.status === 403 || e2.response.status === 404)) { - e2.message = `Could not refresh access token: ${e2.message}`; - } - throw e2; + async getAccessToken() { + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); } - const credentials = this.credentials; - credentials.token_type = credentials.token_type || "Bearer"; - tokens.refresh_token = credentials.refresh_token; - this.credentials = tokens; - const headers = new Headers({ - authorization: credentials.token_type + " " + tokens.access_token - }); - return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; - } - static getRevokeTokenUrl(token) { - return new OAuth2Client().getRevokeTokenURL(token).toString(); - } - getRevokeTokenURL(token) { - const url = new URL(this.endpoints.oauth2RevokeUrl); - url.searchParams.append("token", token); - return url; - } - revokeToken(token, callback) { - const opts = { - ...OAuth2Client.RETRY_CONFIG, - url: this.getRevokeTokenURL(token).toString(), - method: "POST" + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res }; - authclient_1.AuthClient.setMethodName(opts, "revokeToken"); - if (callback) { - this.transporter.request(opts).then((r) => callback(null, r), callback); - } else { - return this.transporter.request(opts); - } - } - revokeCredentials(callback) { - if (callback) { - this.revokeCredentialsAsync().then((res) => callback(null, res), callback); - } else { - return this.revokeCredentialsAsync(); - } } - async revokeCredentialsAsync() { - const token = this.credentials.access_token; - this.credentials = {}; - if (token) { - return this.revokeToken(token); - } else { - throw new Error("No access token to revoke."); - } + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = new Headers({ + authorization: `Bearer ${accessTokenResponse.token}` + }); + return this.addSharedMetadataHeaders(headers); } request(opts, callback) { if (callback) { @@ -78510,1625 +69159,1923 @@ var require_oauth2client = __commonJS((exports) => { return this.requestAsync(opts); } } + async getProjectId() { + const projectNumber = this.projectNumber || this.workforcePoolUserProject; + if (this.projectId) { + return this.projectId; + } else if (projectNumber) { + const headers = await this.getRequestHeaders(); + const opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + headers, + url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, + responseType: "json" + }; + authclient_1.AuthClient.setMethodName(opts, "getProjectId"); + const response = await this.transporter.request(opts); + this.projectId = response.data.projectId; + return this.projectId; + } + return null; + } async requestAsync(opts, reAuthRetried = false) { + let response; try { - const r = await this.getRequestMetadataAsync(); + const requestHeaders = await this.getRequestHeaders(); opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); - this.addUserProjectAndAuthHeaders(opts.headers, r.headers); - if (this.apiKey) { - opts.headers.set("X-Goog-Api-Key", this.apiKey); - } - return await this.transporter.request(opts); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + response = await this.transporter.request(opts); } catch (e2) { const res = e2.response; if (res) { const statusCode = res.status; - const mayRequireRefresh = this.credentials && this.credentials.access_token && this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure); - const mayRequireRefreshWithNoRefreshToken = this.credentials && this.credentials.access_token && !this.credentials.refresh_token && (!this.credentials.expiry_date || this.forceRefreshOnFailure) && this.refreshHandler; const isReadableStream = res.config.data instanceof stream.Readable; const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefresh) { + if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { await this.refreshAccessTokenAsync(); - return this.requestAsync(opts, true); - } else if (!reAuthRetried && isAuthErr && !isReadableStream && mayRequireRefreshWithNoRefreshToken) { - const refreshedAccessToken = await this.processAndValidateRefreshHandler(); - if (refreshedAccessToken?.access_token) { - this.setCredentials(refreshedAccessToken); - } - return this.requestAsync(opts, true); + return await this.requestAsync(opts, true); } } throw e2; } + return response; } - verifyIdToken(options, callback) { - if (callback && typeof callback !== "function") { - throw new Error("This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry."); + async refreshAccessTokenAsync() { + this.#pendingAccessToken = this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync(); + try { + return await this.#pendingAccessToken; + } finally { + this.#pendingAccessToken = null; } - if (callback) { - this.verifyIdTokenAsync(options).then((r) => callback(null, r), callback); + } + async#internalRefreshAccessTokenAsync() { + const subjectToken = await this.retrieveSubjectToken(); + const stsCredentialsOptions = { + grantType: STS_GRANT_TYPE, + audience: this.audience, + requestedTokenType: STS_REQUEST_TOKEN_TYPE, + subjectToken, + subjectTokenType: this.subjectTokenType, + scope: this.serviceAccountImpersonationUrl ? [DEFAULT_OAUTH_SCOPE] : this.getScopesArray() + }; + const additionalOptions = !this.clientAuth && this.workforcePoolUserProject ? { userProject: this.workforcePoolUserProject } : undefined; + const additionalHeaders = new Headers({ + "x-goog-api-client": this.getMetricsHeaderValue() + }); + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); + if (this.serviceAccountImpersonationUrl) { + this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); + } else if (stsResponse.expires_in) { + this.cachedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, + res: stsResponse.res + }; } else { - return this.verifyIdTokenAsync(options); + this.cachedAccessToken = { + access_token: stsResponse.access_token, + res: stsResponse.res + }; } + this.credentials = {}; + Object.assign(this.credentials, this.cachedAccessToken); + delete this.credentials.res; + this.emit("tokens", { + refresh_token: null, + expiry_date: this.cachedAccessToken.expiry_date, + access_token: this.cachedAccessToken.access_token, + token_type: "Bearer", + id_token: null + }); + return this.cachedAccessToken; } - async verifyIdTokenAsync(options) { - if (!options.idToken) { - throw new Error("The verifyIdToken method requires an ID Token"); + getProjectNumber(audience) { + const match = audience.match(/\/projects\/([^/]+)/); + if (!match) { + return null; } - const response = await this.getFederatedSignonCertsAsync(); - const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); - return login; + return match[1]; } - async getTokenInfo(accessToken) { - const { data } = await this.transporter.request({ - ...OAuth2Client.RETRY_CONFIG, + async getImpersonatedAccessToken(token) { + const opts = { + ...BaseExternalAccountClient.RETRY_CONFIG, + url: this.serviceAccountImpersonationUrl, method: "POST", headers: { - "content-type": "application/x-www-form-urlencoded;charset=UTF-8", - authorization: `Bearer ${accessToken}` + "content-type": "application/json", + authorization: `Bearer ${token}` }, - url: this.endpoints.tokenInfoUrl.toString() - }); - const info = Object.assign({ - expiry_date: new Date().getTime() + data.expires_in * 1000, - scopes: data.scope.split(" ") - }, data); - delete info.expires_in; - delete info.scope; - return info; + data: { + scope: this.getScopesArray(), + lifetime: this.serviceAccountImpersonationLifetime + "s" + }, + responseType: "json" + }; + authclient_1.AuthClient.setMethodName(opts, "getImpersonatedAccessToken"); + const response = await this.transporter.request(opts); + const successResponse = response.data; + return { + access_token: successResponse.accessToken, + expiry_date: new Date(successResponse.expireTime).getTime(), + res: response + }; } - getFederatedSignonCerts(callback) { - if (callback) { - this.getFederatedSignonCertsAsync().then((r) => callback(null, r.certs, r.res), callback); - } else { - return this.getFederatedSignonCertsAsync(); - } + isExpired(accessToken) { + const now = new Date().getTime(); + return accessToken.expiry_date ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis : false; } - async getFederatedSignonCertsAsync() { - const nowTime = new Date().getTime(); - const format = (0, crypto_1.hasBrowserCrypto)() ? CertificateFormat.JWK : CertificateFormat.PEM; - if (this.certificateExpiry && nowTime < this.certificateExpiry.getTime() && this.certificateCacheFormat === format) { - return { certs: this.certificateCache, format }; - } - let res; - let url; - switch (format) { - case CertificateFormat.PEM: - url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); - break; - case CertificateFormat.JWK: - url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); - break; - default: - throw new Error(`Unsupported certificate format ${format}`); + getScopesArray() { + if (typeof this.scopes === "string") { + return [this.scopes]; } + return this.scopes || [DEFAULT_OAUTH_SCOPE]; + } + getMetricsHeaderValue() { + const nodeVersion = process.version.replace(/^v/, ""); + const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; + const credentialSourceType = this.credentialSourceType ? this.credentialSourceType : "unknown"; + return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; + } + getTokenUrl() { + return this.tokenUrl; + } + } + exports.BaseExternalAccountClient = BaseExternalAccountClient; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js +var require_filesubjecttokensupplier = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FileSubjectTokenSupplier = undefined; + var util_1 = __require("util"); + var fs = __require("fs"); + var readFile = (0, util_1.promisify)(fs.readFile ?? (() => {})); + var realpath = (0, util_1.promisify)(fs.realpath ?? (() => {})); + var lstat = (0, util_1.promisify)(fs.lstat ?? (() => {})); + + class FileSubjectTokenSupplier { + filePath; + formatType; + subjectTokenFieldName; + constructor(opts) { + this.filePath = opts.filePath; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + } + async getSubjectToken() { + let parsedFilePath = this.filePath; try { - const opts = { - ...OAuth2Client.RETRY_CONFIG, - url - }; - authclient_1.AuthClient.setMethodName(opts, "getFederatedSignonCertsAsync"); - res = await this.transporter.request(opts); - } catch (e2) { - if (e2 instanceof Error) { - e2.message = `Failed to retrieve verification certificates: ${e2.message}`; + parsedFilePath = await realpath(parsedFilePath); + if (!(await lstat(parsedFilePath)).isFile()) { + throw new Error; } - throw e2; - } - const cacheControl = res?.headers.get("cache-control"); - let cacheAge = -1; - if (cacheControl) { - const maxAge = /max-age=(?[0-9]+)/.exec(cacheControl)?.groups?.maxAge; - if (maxAge) { - cacheAge = Number(maxAge) * 1000; + } catch (err) { + if (err instanceof Error) { + err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; } + throw err; } - let certificates = {}; - switch (format) { - case CertificateFormat.PEM: - certificates = res.data; - break; - case CertificateFormat.JWK: - for (const key of res.data.keys) { - certificates[key.kid] = key; - } - break; - default: - throw new Error(`Unsupported certificate format ${format}`); + let subjectToken; + const rawText = await readFile(parsedFilePath, { encoding: "utf8" }); + if (this.formatType === "text") { + subjectToken = rawText; + } else if (this.formatType === "json" && this.subjectTokenFieldName) { + const json3 = JSON.parse(rawText); + subjectToken = json3[this.subjectTokenFieldName]; } - const now = new Date; - this.certificateExpiry = cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); - this.certificateCache = certificates; - this.certificateCacheFormat = format; - return { certs: certificates, format, res }; - } - getIapPublicKeys(callback) { - if (callback) { - this.getIapPublicKeysAsync().then((r) => callback(null, r.pubkeys, r.res), callback); - } else { - return this.getIapPublicKeysAsync(); + if (!subjectToken) { + throw new Error("Unable to parse the subject_token from the credential_source file"); } + return subjectToken; } - async getIapPublicKeysAsync() { - let res; - const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); - try { - const opts = { - ...OAuth2Client.RETRY_CONFIG, - url - }; - authclient_1.AuthClient.setMethodName(opts, "getIapPublicKeysAsync"); - res = await this.transporter.request(opts); - } catch (e2) { - if (e2 instanceof Error) { - e2.message = `Failed to retrieve verification certificates: ${e2.message}`; - } - throw e2; + } + exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js +var require_urlsubjecttokensupplier = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.UrlSubjectTokenSupplier = undefined; + var authclient_1 = require_authclient(); + + class UrlSubjectTokenSupplier { + url; + headers; + formatType; + subjectTokenFieldName; + additionalGaxiosOptions; + constructor(opts) { + this.url = opts.url; + this.formatType = opts.formatType; + this.subjectTokenFieldName = opts.subjectTokenFieldName; + this.headers = opts.headers; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; + } + async getSubjectToken(context) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.url, + method: "GET", + headers: this.headers, + responseType: this.formatType + }; + authclient_1.AuthClient.setMethodName(opts, "getSubjectToken"); + let subjectToken; + if (this.formatType === "text") { + const response = await context.transporter.request(opts); + subjectToken = response.data; + } else if (this.formatType === "json" && this.subjectTokenFieldName) { + const response = await context.transporter.request(opts); + subjectToken = response.data[this.subjectTokenFieldName]; } - return { pubkeys: res.data, res }; + if (!subjectToken) { + throw new Error("Unable to parse the subject_token from the credential_source URL"); + } + return subjectToken; } - verifySignedJwtWithCerts() { - throw new Error("verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead."); + } + exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js +var require_certificatesubjecttokensupplier = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = undefined; + var util_1 = require_util2(); + var fs = __require("fs"); + var crypto_1 = __require("crypto"); + var https = __require("https"); + exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG"; + + class CertificateSourceUnavailableError extends Error { + constructor(message) { + super(message); + this.name = "CertificateSourceUnavailableError"; } - async verifySignedJwtWithCertsAsync(jwt2, certs, requiredAudience, issuers, maxExpiry) { - const crypto2 = (0, crypto_1.createCrypto)(); - if (!maxExpiry) { - maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; - } - const segments = jwt2.split("."); - if (segments.length !== 3) { - throw new Error("Wrong number of segments in token: " + jwt2); + } + exports.CertificateSourceUnavailableError = CertificateSourceUnavailableError; + + class InvalidConfigurationError extends Error { + constructor(message) { + super(message); + this.name = "InvalidConfigurationError"; + } + } + exports.InvalidConfigurationError = InvalidConfigurationError; + + class CertificateSubjectTokenSupplier { + certificateConfigPath; + trustChainPath; + cert; + key; + constructor(opts) { + if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) { + throw new InvalidConfigurationError("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided."); } - const signed = segments[0] + "." + segments[1]; - let signature = segments[2]; - let envelope; - let payload; - try { - envelope = JSON.parse(crypto2.decodeBase64StringUtf8(segments[0])); - } catch (err) { - if (err instanceof Error) { - err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; - } - throw err; + if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) { + throw new InvalidConfigurationError("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided."); } - if (!envelope) { - throw new Error("Can't parse token envelope: " + segments[0]); + this.trustChainPath = opts.trustChainPath; + this.certificateConfigPath = opts.certificateConfigLocation ?? ""; + } + async createMtlsHttpsAgent() { + if (!this.key || !this.cert) { + throw new InvalidConfigurationError("Cannot create mTLS Agent with missing certificate or key"); } - try { - payload = JSON.parse(crypto2.decodeBase64StringUtf8(segments[1])); - } catch (err) { - if (err instanceof Error) { - err.message = `Can't parse token payload '${segments[0]}`; + return new https.Agent({ key: this.key, cert: this.cert }); + } + async getSubjectToken() { + this.certificateConfigPath = await this.#resolveCertificateConfigFilePath(); + const { certPath, keyPath } = await this.#getCertAndKeyPaths(); + ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath)); + return await this.#processChainFromPaths(this.cert); + } + async#resolveCertificateConfigFilePath() { + const overridePath = this.certificateConfigPath; + if (overridePath) { + if (await (0, util_1.isValidFile)(overridePath)) { + return overridePath; } - throw err; - } - if (!payload) { - throw new Error("Can't parse token payload: " + segments[1]); - } - if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { - throw new Error("No pem found for envelope: " + JSON.stringify(envelope)); - } - const cert = certs[envelope.kid]; - if (envelope.alg === "ES256") { - signature = formatEcdsa.joseToDer(signature, "ES256").toString("base64"); + throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`); } - const verified = await crypto2.verify(cert, signed, signature); - if (!verified) { - throw new Error("Invalid token signature: " + jwt2); + const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE]; + if (envPath) { + if (await (0, util_1.isValidFile)(envPath)) { + return envPath; + } + throw new CertificateSourceUnavailableError(`Path from environment variable "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`); } - if (!payload.iat) { - throw new Error("No issue time in token: " + JSON.stringify(payload)); + const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)(); + if (await (0, util_1.isValidFile)(wellKnownPath)) { + return wellKnownPath; } - if (!payload.exp) { - throw new Error("No expiration time in token: " + JSON.stringify(payload)); + throw new CertificateSourceUnavailableError("Could not find certificate configuration file. Searched override path, " + `the "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`); + } + async#getCertAndKeyPaths() { + const configPath = this.certificateConfigPath; + let fileContents; + try { + fileContents = await fs.promises.readFile(configPath, "utf8"); + } catch (err) { + throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`); } - const iat = Number(payload.iat); - if (isNaN(iat)) - throw new Error("iat field using invalid format"); - const exp = Number(payload.exp); - if (isNaN(exp)) - throw new Error("exp field using invalid format"); - const now = new Date().getTime() / 1000; - if (exp >= now + maxExpiry) { - throw new Error("Expiration time too far in future: " + JSON.stringify(payload)); + try { + const config = JSON.parse(fileContents); + const certPath = config?.cert_configs?.workload?.cert_path; + const keyPath = config?.cert_configs?.workload?.key_path; + if (!certPath || !keyPath) { + throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`); + } + return { certPath, keyPath }; + } catch (e2) { + if (e2 instanceof InvalidConfigurationError) + throw e2; + throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e2.message}`); } - const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; - const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; - if (now < earliest) { - throw new Error("Token used too early, " + now + " < " + earliest + ": " + JSON.stringify(payload)); + } + async#getKeyAndCert(certPath, keyPath) { + let cert, key; + try { + cert = await fs.promises.readFile(certPath); + new crypto_1.X509Certificate(cert); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`); } - if (now > latest) { - throw new Error("Token used too late, " + now + " > " + latest + ": " + JSON.stringify(payload)); + try { + key = await fs.promises.readFile(keyPath); + (0, crypto_1.createPrivateKey)(key); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`); } - if (issuers && issuers.indexOf(payload.iss) < 0) { - throw new Error("Invalid issuer, expected one of [" + issuers + "], but got " + payload.iss); + return { cert, key }; + } + async#processChainFromPaths(leafCertBuffer) { + const leafCert = new crypto_1.X509Certificate(leafCertBuffer); + if (!this.trustChainPath) { + return JSON.stringify([leafCert.raw.toString("base64")]); } - if (typeof requiredAudience !== "undefined" && requiredAudience !== null) { - const aud = payload.aud; - let audVerified = false; - if (requiredAudience.constructor === Array) { - audVerified = requiredAudience.indexOf(aud) > -1; + try { + const chainPems = await fs.promises.readFile(this.trustChainPath, "utf8"); + const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? []; + const chainCerts = pemBlocks.map((pem, index3) => { + try { + return new crypto_1.X509Certificate(pem); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + throw new InvalidConfigurationError(`Failed to parse certificate at index ${index3} in trust chain file ${this.trustChainPath}: ${message}`); + } + }); + const leafIndex = chainCerts.findIndex((chainCert) => leafCert.raw.equals(chainCert.raw)); + let finalChain; + if (leafIndex === -1) { + finalChain = [leafCert, ...chainCerts]; + } else if (leafIndex === 0) { + finalChain = chainCerts; } else { - audVerified = aud === requiredAudience; - } - if (!audVerified) { - throw new Error("Wrong recipient, payload audience != requiredAudience"); - } - } - return new loginticket_1.LoginTicket(envelope, payload); - } - async processAndValidateRefreshHandler() { - if (this.refreshHandler) { - const accessTokenResponse = await this.refreshHandler(); - if (!accessTokenResponse.access_token) { - throw new Error("No access token is returned by the refreshHandler callback."); + throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`); } - return accessTokenResponse; + return JSON.stringify(finalChain.map((cert) => cert.raw.toString("base64"))); + } catch (err) { + if (err instanceof InvalidConfigurationError) + throw err; + const message = err instanceof Error ? err.message : String(err); + throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`); } - return; - } - isTokenExpiring() { - const expiryDate = this.credentials.expiry_date; - return expiryDate ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis : false; } } - exports.OAuth2Client = OAuth2Client; + exports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/computeclient.js -var require_computeclient = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/identitypoolclient.js +var require_identitypoolclient = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.Compute = undefined; + exports.IdentityPoolClient = undefined; + var baseexternalclient_1 = require_baseexternalclient(); + var util_1 = require_util2(); + var filesubjecttokensupplier_1 = require_filesubjecttokensupplier(); + var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier(); + var certificatesubjecttokensupplier_1 = require_certificatesubjecttokensupplier(); + var stscredentials_1 = require_stscredentials(); var gaxios_1 = require_src2(); - var gcpMetadata = require_src4(); - var oauth2client_1 = require_oauth2client(); - class Compute extends oauth2client_1.OAuth2Client { - serviceAccountEmail; - scopes; - constructor(options = {}) { + class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { + subjectTokenSupplier; + constructor(options) { super(options); - this.credentials = { expiry_date: 1, refresh_token: "compute-placeholder" }; - this.serviceAccountEmail = options.serviceAccountEmail || "default"; - this.scopes = Array.isArray(options.scopes) ? options.scopes : options.scopes ? [options.scopes] : []; - } - async refreshTokenNoCache() { - const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; - let data; - try { - const instanceOptions = { - property: tokenPath - }; - if (this.scopes.length > 0) { - instanceOptions.params = { - scopes: this.scopes.join(",") - }; - } - data = await gcpMetadata.instance(instanceOptions); - } catch (e2) { - if (e2 instanceof gaxios_1.GaxiosError) { - e2.message = `Could not refresh access token: ${e2.message}`; - this.wrapError(e2); - } - throw e2; + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get("credential_source"); + const subjectTokenSupplier = opts.get("subject_token_supplier"); + if (!credentialSource && !subjectTokenSupplier) { + throw new Error("A credential source or subject token supplier must be specified."); } - const tokens = data; - if (data && data.expires_in) { - tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; - delete tokens.expires_in; + if (credentialSource && subjectTokenSupplier) { + throw new Error("Only one of credential source or subject token supplier can be specified."); } - this.emit("tokens", tokens); - return { tokens, res: null }; - } - async fetchIdToken(targetAudience) { - const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + `?format=full&audience=${targetAudience}`; - let idToken; - try { - const instanceOptions = { - property: idTokenPath - }; - idToken = await gcpMetadata.instance(instanceOptions); - } catch (e2) { - if (e2 instanceof Error) { - e2.message = `Could not fetch ID token: ${e2.message}`; + if (subjectTokenSupplier) { + this.subjectTokenSupplier = subjectTokenSupplier; + this.credentialSourceType = "programmatic"; + } else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get("format")); + const formatType = formatOpts.get("type") || "text"; + const formatSubjectTokenFieldName = formatOpts.get("subject_token_field_name"); + if (formatType !== "json" && formatType !== "text") { + throw new Error(`Invalid credential_source format "${formatType}"`); + } + if (formatType === "json" && !formatSubjectTokenFieldName) { + throw new Error("Missing subject_token_field_name for JSON credential_source format"); + } + const file = credentialSourceOpts.get("file"); + const url = credentialSourceOpts.get("url"); + const certificate = credentialSourceOpts.get("certificate"); + const headers = credentialSourceOpts.get("headers"); + if (file && url || url && certificate || file && certificate) { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); + } else if (file) { + this.credentialSourceType = "file"; + this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ + filePath: file, + formatType, + subjectTokenFieldName: formatSubjectTokenFieldName + }); + } else if (url) { + this.credentialSourceType = "url"; + this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ + url, + formatType, + subjectTokenFieldName: formatSubjectTokenFieldName, + headers, + additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG + }); + } else if (certificate) { + this.credentialSourceType = "certificate"; + const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({ + useDefaultCertificateConfig: certificate.use_default_certificate_config, + certificateConfigLocation: certificate.certificate_config_location, + trustChainPath: certificate.trust_chain_path + }); + this.subjectTokenSupplier = certificateSubjecttokensupplier; + } else { + throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); } - throw e2; } - return idToken; } - wrapError(e2) { - const res = e2.response; - if (res && res.status) { - e2.status = res.status; - if (res.status === 403) { - e2.message = "A Forbidden error was returned while attempting to retrieve an access " + "token for the Compute Engine built-in service account. This may be because the Compute " + "Engine instance does not have the correct permission scopes specified: " + e2.message; - } else if (res.status === 404) { - e2.message = "A Not Found error was returned while attempting to retrieve an access" + "token for the Compute Engine built-in service account. This may be because the Compute " + "Engine instance does not have any permission scopes specified: " + e2.message; - } + async retrieveSubjectToken() { + const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext); + if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) { + const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent(); + this.stsCredential = new stscredentials_1.StsCredentials({ + tokenExchangeEndpoint: this.getTokenUrl(), + clientAuthentication: this.clientAuth, + transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }) + }); + this.transporter = new gaxios_1.Gaxios({ + ...this.transporter.defaults || {}, + agent: mtlsAgent + }); } + return subjectToken; } } - exports.Compute = Compute; + exports.IdentityPoolClient = IdentityPoolClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/idtokenclient.js -var require_idtokenclient = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js +var require_awsrequestsigner = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.IdTokenClient = undefined; - var oauth2client_1 = require_oauth2client(); + exports.AwsRequestSigner = undefined; + var gaxios_1 = require_src2(); + var crypto_1 = require_crypto3(); + var AWS_ALGORITHM = "AWS4-HMAC-SHA256"; + var AWS_REQUEST_TYPE = "aws4_request"; - class IdTokenClient extends oauth2client_1.OAuth2Client { - targetAudience; - idTokenProvider; - constructor(options) { - super(options); - this.targetAudience = options.targetAudience; - this.idTokenProvider = options.idTokenProvider; + class AwsRequestSigner { + getCredentials; + region; + crypto; + constructor(getCredentials, region) { + this.getCredentials = getCredentials; + this.region = region; + this.crypto = (0, crypto_1.createCrypto)(); } - async getRequestMetadataAsync() { - if (!this.credentials.id_token || !this.credentials.expiry_date || this.isTokenExpiring()) { - const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); - this.credentials = { - id_token: idToken, - expiry_date: this.getIdTokenExpiryDate(idToken) - }; + async getRequestOptions(amzOptions) { + if (!amzOptions.url) { + throw new RangeError('"url" is required in "amzOptions"'); } - const headers = new Headers({ - authorization: "Bearer " + this.credentials.id_token + const requestPayloadData = typeof amzOptions.data === "object" ? JSON.stringify(amzOptions.data) : amzOptions.data; + const url = amzOptions.url; + const method = amzOptions.method || "GET"; + const requestPayload = amzOptions.body || requestPayloadData; + const additionalAmzHeaders = amzOptions.headers; + const awsSecurityCredentials = await this.getCredentials(); + const uri = new URL(url); + if (typeof requestPayload !== "string" && requestPayload !== undefined) { + throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`); + } + const headerMap = await generateAuthenticationHeaderMap({ + crypto: this.crypto, + host: uri.host, + canonicalUri: uri.pathname, + canonicalQuerystring: uri.search.slice(1), + method, + region: this.region, + securityCredentials: awsSecurityCredentials, + requestPayload, + additionalAmzHeaders }); - return { headers }; - } - getIdTokenExpiryDate(idToken) { - const payloadB64 = idToken.split(".")[1]; - if (payloadB64) { - const payload = JSON.parse(Buffer.from(payloadB64, "base64").toString("ascii")); - return payload.exp * 1000; + const headers = gaxios_1.Gaxios.mergeHeaders(headerMap.amzDate ? { "x-amz-date": headerMap.amzDate } : {}, { + authorization: headerMap.authorizationHeader, + host: uri.host + }, additionalAmzHeaders || {}); + if (awsSecurityCredentials.token) { + gaxios_1.Gaxios.mergeHeaders(headers, { + "x-amz-security-token": awsSecurityCredentials.token + }); } - } - } - exports.IdTokenClient = IdTokenClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/envDetect.js -var require_envDetect = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GCPEnv = undefined; - exports.clear = clear; - exports.getEnv = getEnv; - var gcpMetadata = require_src4(); - var GCPEnv; - (function(GCPEnv2) { - GCPEnv2["APP_ENGINE"] = "APP_ENGINE"; - GCPEnv2["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; - GCPEnv2["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; - GCPEnv2["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; - GCPEnv2["CLOUD_RUN"] = "CLOUD_RUN"; - GCPEnv2["CLOUD_RUN_JOBS"] = "CLOUD_RUN_JOBS"; - GCPEnv2["NONE"] = "NONE"; - })(GCPEnv || (exports.GCPEnv = GCPEnv = {})); - var envPromise; - function clear() { - envPromise = undefined; - } - async function getEnv() { - if (envPromise) { - return envPromise; - } - envPromise = getEnvMemoized(); - return envPromise; - } - async function getEnvMemoized() { - let env2 = GCPEnv.NONE; - if (isAppEngine()) { - env2 = GCPEnv.APP_ENGINE; - } else if (isCloudFunction()) { - env2 = GCPEnv.CLOUD_FUNCTIONS; - } else if (await isComputeEngine()) { - if (await isKubernetesEngine()) { - env2 = GCPEnv.KUBERNETES_ENGINE; - } else if (isCloudRun()) { - env2 = GCPEnv.CLOUD_RUN; - } else if (isCloudRunJob()) { - env2 = GCPEnv.CLOUD_RUN_JOBS; - } else { - env2 = GCPEnv.COMPUTE_ENGINE; + const awsSignedReq = { + url, + method, + headers + }; + if (requestPayload !== undefined) { + awsSignedReq.body = requestPayload; } - } else { - env2 = GCPEnv.NONE; + return awsSignedReq; } - return env2; - } - function isAppEngine() { - return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); } - function isCloudFunction() { - return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); - } - function isCloudRun() { - return !!process.env.K_CONFIGURATION; + exports.AwsRequestSigner = AwsRequestSigner; + async function sign(crypto2, key, msg) { + return await crypto2.signWithHmacSha256(key, msg); } - function isCloudRunJob() { - return !!process.env.CLOUD_RUN_JOB; + async function getSigningKey(crypto2, key, dateStamp, region, serviceName) { + const kDate = await sign(crypto2, `AWS4${key}`, dateStamp); + const kRegion = await sign(crypto2, kDate, region); + const kService = await sign(crypto2, kRegion, serviceName); + const kSigning = await sign(crypto2, kService, "aws4_request"); + return kSigning; } - async function isKubernetesEngine() { - try { - await gcpMetadata.instance("attributes/cluster-name"); - return true; - } catch (e2) { - return false; + async function generateAuthenticationHeaderMap(options) { + const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders); + const requestPayload = options.requestPayload || ""; + const serviceName = options.host.split(".")[0]; + const now = new Date; + const amzDate = now.toISOString().replace(/[-:]/g, "").replace(/\.[0-9]+/, ""); + const dateStamp = now.toISOString().replace(/[-]/g, "").replace(/T.*/, ""); + if (options.securityCredentials.token) { + additionalAmzHeaders.set("x-amz-security-token", options.securityCredentials.token); } - } - async function isComputeEngine() { - return gcpMetadata.isAvailable(); - } -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/jwsSign.js -var require_jwsSign = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.buildPayloadForJwsSign = buildPayloadForJwsSign; - exports.getJwsSign = getJwsSign; - var jws_1 = require_jws(); - var ALG_RS256 = "RS256"; - var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"; - function buildPayloadForJwsSign(tokenOptions) { - const iat = Math.floor(new Date().getTime() / 1000); - const payload = { - iss: tokenOptions.iss, - scope: tokenOptions.scope, - aud: GOOGLE_TOKEN_URL, - exp: iat + 3600, - iat, - sub: tokenOptions.sub, - ...tokenOptions.additionalClaims - }; - return payload; - } - function getJwsSign(tokenOptions) { - const payload = buildPayloadForJwsSign(tokenOptions); - return (0, jws_1.sign)({ - header: { alg: ALG_RS256 }, - payload, - secret: tokenOptions.key + const amzHeaders = gaxios_1.Gaxios.mergeHeaders({ + host: options.host + }, additionalAmzHeaders.has("date") ? {} : { "x-amz-date": amzDate }, additionalAmzHeaders); + let canonicalHeaders = ""; + const signedHeadersList = [ + ...amzHeaders.keys() + ].sort(); + signedHeadersList.forEach((key) => { + canonicalHeaders += `${key}:${amzHeaders.get(key)} +`; }); - } -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/getToken.js -var require_getToken = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getToken = getToken; - var jwsSign_1 = require_jwsSign(); - var GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"; - var GOOGLE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer"; - var generateRequestOptions = (tokenOptions) => { + const signedHeaders = signedHeadersList.join(";"); + const payloadHash = await options.crypto.sha256DigestHex(requestPayload); + const canonicalRequest = `${options.method.toUpperCase()} +` + `${options.canonicalUri} +` + `${options.canonicalQuerystring} +` + `${canonicalHeaders} +` + `${signedHeaders} +` + `${payloadHash}`; + const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; + const stringToSign = `${AWS_ALGORITHM} +` + `${amzDate} +` + `${credentialScope} +` + await options.crypto.sha256DigestHex(canonicalRequest); + const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); + const signature = await sign(options.crypto, signingKey, stringToSign); + const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; return { - method: "POST", - url: GOOGLE_TOKEN_URL, - data: new URLSearchParams({ - grant_type: GOOGLE_GRANT_TYPE, - assertion: (0, jwsSign_1.getJwsSign)(tokenOptions) - }), - responseType: "json", - retryConfig: { - httpMethodsToRetry: ["POST"] - } + amzDate: additionalAmzHeaders.has("date") ? undefined : amzDate, + authorizationHeader, + canonicalQuerystring: options.canonicalQuerystring }; - }; - async function getToken(tokenOptions) { - if (!tokenOptions.transporter) { - throw new Error("No transporter set."); - } - try { - const gaxiosOptions = generateRequestOptions(tokenOptions); - const response = await tokenOptions.transporter.request(gaxiosOptions); - return response.data; - } catch (e2) { - const err = e2; - const errorData = err.response?.data; - if (errorData?.error) { - err.message = `${errorData.error}: ${errorData.error_description}`; - } - throw err; - } } }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/errorWithCode.js -var require_errorWithCode = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js +var require_defaultawssecuritycredentialssupplier = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.ErrorWithCode = undefined; + exports.DefaultAwsSecurityCredentialsSupplier = undefined; + var authclient_1 = require_authclient(); - class ErrorWithCode extends Error { - code; - constructor(message, code) { - super(message); - this.code = code; + class DefaultAwsSecurityCredentialsSupplier { + regionUrl; + securityCredentialsUrl; + imdsV2SessionTokenUrl; + additionalGaxiosOptions; + constructor(opts) { + this.regionUrl = opts.regionUrl; + this.securityCredentialsUrl = opts.securityCredentialsUrl; + this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; + this.additionalGaxiosOptions = opts.additionalGaxiosOptions; } - } - exports.ErrorWithCode = ErrorWithCode; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/getCredentials.js -var require_getCredentials = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getCredentials = getCredentials; - var path2 = __require("path"); - var fs = __require("fs"); - var util_1 = __require("util"); - var errorWithCode_1 = require_errorWithCode(); - var readFile = fs.readFile ? (0, util_1.promisify)(fs.readFile) : async () => { - throw new errorWithCode_1.ErrorWithCode("use key rather than keyFile.", "MISSING_CREDENTIALS"); - }; - var ExtensionFiles; - (function(ExtensionFiles2) { - ExtensionFiles2["JSON"] = ".json"; - ExtensionFiles2["DER"] = ".der"; - ExtensionFiles2["CRT"] = ".crt"; - ExtensionFiles2["PEM"] = ".pem"; - ExtensionFiles2["P12"] = ".p12"; - ExtensionFiles2["PFX"] = ".pfx"; - })(ExtensionFiles || (ExtensionFiles = {})); - - class JsonCredentialsProvider { - keyFilePath; - constructor(keyFilePath) { - this.keyFilePath = keyFilePath; + async getAwsRegion(context) { + if (this.#regionFromEnv) { + return this.#regionFromEnv; + } + const metadataHeaders = new Headers; + if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) { + metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context.transporter)); + } + if (!this.regionUrl) { + throw new RangeError("Unable to determine AWS region due to missing " + '"options.credential_source.region_url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.regionUrl, + method: "GET", + responseType: "text", + headers: metadataHeaders + }; + authclient_1.AuthClient.setMethodName(opts, "getAwsRegion"); + const response = await context.transporter.request(opts); + return response.data.substr(0, response.data.length - 1); } - async getCredentials() { - const key = await readFile(this.keyFilePath, "utf8"); - let body; - try { - body = JSON.parse(key); - } catch (error) { - const err = error; - throw new Error(`Invalid JSON key file: ${err.message}`); + async getAwsSecurityCredentials(context) { + if (this.#securityCredentialsFromEnv) { + return this.#securityCredentialsFromEnv; } - const privateKey = body.private_key; - const clientEmail = body.client_email; - if (!privateKey || !clientEmail) { - throw new errorWithCode_1.ErrorWithCode("private_key and client_email are required.", "MISSING_CREDENTIALS"); + const metadataHeaders = new Headers; + if (this.imdsV2SessionTokenUrl) { + metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context.transporter)); } - return { privateKey, clientEmail }; + const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter); + const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter); + return { + accessKeyId: awsCreds.AccessKeyId, + secretAccessKey: awsCreds.SecretAccessKey, + token: awsCreds.Token + }; } - } - - class PemCredentialsProvider { - keyFilePath; - constructor(keyFilePath) { - this.keyFilePath = keyFilePath; + async#getImdsV2SessionToken(transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: this.imdsV2SessionTokenUrl, + method: "PUT", + responseType: "text", + headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" } + }; + authclient_1.AuthClient.setMethodName(opts, "#getImdsV2SessionToken"); + const response = await transporter.request(opts); + return response.data; } - async getCredentials() { - const privateKey = await readFile(this.keyFilePath, "utf8"); - return { privateKey }; + async#getAwsRoleName(headers, transporter) { + if (!this.securityCredentialsUrl) { + throw new Error("Unable to determine AWS role name due to missing " + '"options.credential_source.url"'); + } + const opts = { + ...this.additionalGaxiosOptions, + url: this.securityCredentialsUrl, + method: "GET", + responseType: "text", + headers + }; + authclient_1.AuthClient.setMethodName(opts, "#getAwsRoleName"); + const response = await transporter.request(opts); + return response.data; } - } - - class P12CredentialsProvider { - async getCredentials() { - throw new errorWithCode_1.ErrorWithCode("*.p12 certificates are not supported after v6.1.2. " + "Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.", "UNKNOWN_CERTIFICATE_TYPE"); + async#retrieveAwsSecurityCredentials(roleName, headers, transporter) { + const opts = { + ...this.additionalGaxiosOptions, + url: `${this.securityCredentialsUrl}/${roleName}`, + headers, + responseType: "json" + }; + authclient_1.AuthClient.setMethodName(opts, "#retrieveAwsSecurityCredentials"); + const response = await transporter.request(opts); + return response.data; } - } - - class CredentialsProviderFactory { - static create(keyFilePath) { - const keyFileExtension = path2.extname(keyFilePath); - switch (keyFileExtension) { - case ExtensionFiles.JSON: - return new JsonCredentialsProvider(keyFilePath); - case ExtensionFiles.DER: - case ExtensionFiles.CRT: - case ExtensionFiles.PEM: - return new PemCredentialsProvider(keyFilePath); - case ExtensionFiles.P12: - case ExtensionFiles.PFX: - return new P12CredentialsProvider; - default: - throw new errorWithCode_1.ErrorWithCode("Unknown certificate type. Type is determined based on file extension. " + "Current supported extensions are *.json, and *.pem.", "UNKNOWN_CERTIFICATE_TYPE"); + get #regionFromEnv() { + return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null; + } + get #securityCredentialsFromEnv() { + if (process.env["AWS_ACCESS_KEY_ID"] && process.env["AWS_SECRET_ACCESS_KEY"]) { + return { + accessKeyId: process.env["AWS_ACCESS_KEY_ID"], + secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"], + token: process.env["AWS_SESSION_TOKEN"] + }; } + return null; } } - async function getCredentials(keyFilePath) { - const provider = CredentialsProviderFactory.create(keyFilePath); - return provider.getCredentials(); - } + exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/tokenHandler.js -var require_tokenHandler = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/awsclient.js +var require_awsclient = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.TokenHandler = undefined; - var getToken_1 = require_getToken(); - var getCredentials_1 = require_getCredentials(); + exports.AwsClient = undefined; + var awsrequestsigner_1 = require_awsrequestsigner(); + var baseexternalclient_1 = require_baseexternalclient(); + var defaultawssecuritycredentialssupplier_1 = require_defaultawssecuritycredentialssupplier(); + var util_1 = require_util2(); + var gaxios_1 = require_src2(); - class TokenHandler { - token; - tokenExpiresAt; - inFlightRequest; - tokenOptions; - constructor(tokenOptions) { - this.tokenOptions = tokenOptions; - } - async processCredentials() { - if (!this.tokenOptions.key && !this.tokenOptions.keyFile) { - throw new Error("No key or keyFile set."); + class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { + environmentId; + awsSecurityCredentialsSupplier; + regionalCredVerificationUrl; + awsRequestSigner; + region; + static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; + static AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254"; + static AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254"; + constructor(options) { + super(options); + const opts = (0, util_1.originalOrCamelOptions)(options); + const credentialSource = opts.get("credential_source"); + const awsSecurityCredentialsSupplier = opts.get("aws_security_credentials_supplier"); + if (!credentialSource && !awsSecurityCredentialsSupplier) { + throw new Error("A credential source or AWS security credentials supplier must be specified."); } - if (!this.tokenOptions.key && this.tokenOptions.keyFile) { - const credentials = await (0, getCredentials_1.getCredentials)(this.tokenOptions.keyFile); - this.tokenOptions.key = credentials.privateKey; - this.tokenOptions.email = credentials.clientEmail; + if (credentialSource && awsSecurityCredentialsSupplier) { + throw new Error("Only one of credential source or AWS security credentials supplier can be specified."); } - } - isTokenExpiring() { - if (!this.token || !this.tokenExpiresAt) { - return true; + if (awsSecurityCredentialsSupplier) { + this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; + this.regionalCredVerificationUrl = AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; + this.credentialSourceType = "programmatic"; + } else { + const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); + this.environmentId = credentialSourceOpts.get("environment_id"); + const regionUrl = credentialSourceOpts.get("region_url"); + const securityCredentialsUrl = credentialSourceOpts.get("url"); + const imdsV2SessionTokenUrl = credentialSourceOpts.get("imdsv2_session_token_url"); + this.awsSecurityCredentialsSupplier = new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ + regionUrl, + securityCredentialsUrl, + imdsV2SessionTokenUrl + }); + this.regionalCredVerificationUrl = credentialSourceOpts.get("regional_cred_verification_url"); + this.credentialSourceType = "aws"; + this.validateEnvironmentId(); } - const now = new Date().getTime(); - const eagerRefreshThresholdMillis = this.tokenOptions.eagerRefreshThresholdMillis ?? 0; - return this.tokenExpiresAt <= now + eagerRefreshThresholdMillis; + this.awsRequestSigner = null; + this.region = ""; } - hasExpired() { - const now = new Date().getTime(); - if (this.token && this.tokenExpiresAt) { - const now2 = new Date().getTime(); - return now2 >= this.tokenExpiresAt; + validateEnvironmentId() { + const match = this.environmentId?.match(/^(aws)(\d+)$/); + if (!match || !this.regionalCredVerificationUrl) { + throw new Error('No valid AWS "credential_source" provided'); + } else if (parseInt(match[2], 10) !== 1) { + throw new Error(`aws version "${match[2]}" is not supported in the current build.`); } - return true; } - async getToken(forceRefresh) { - await this.processCredentials(); - if (this.inFlightRequest && !forceRefresh) { - return this.inFlightRequest; - } - if (this.token && !this.isTokenExpiring() && !forceRefresh) { - return this.token; - } - try { - this.inFlightRequest = (0, getToken_1.getToken)(this.tokenOptions); - const token = await this.inFlightRequest; - this.token = token; - this.tokenExpiresAt = new Date().getTime() + (token.expires_in ?? 0) * 1000; - return token; - } finally { - this.inFlightRequest = undefined; + async retrieveSubjectToken() { + if (!this.awsRequestSigner) { + this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); + this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { + return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); + }, this.region); } + const options = await this.awsRequestSigner.getRequestOptions({ + ...AwsClient.RETRY_CONFIG, + url: this.regionalCredVerificationUrl.replace("{region}", this.region), + method: "POST" + }); + const reformattedHeader = []; + const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({ + "x-goog-cloud-target-resource": this.audience + }, options.headers); + extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value })); + return encodeURIComponent(JSON.stringify({ + url: options.url, + method: options.method, + headers: reformattedHeader + })); } } - exports.TokenHandler = TokenHandler; + exports.AwsClient = AwsClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/revokeToken.js -var require_revokeToken = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/executable-response.js +var require_executable_response = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.revokeToken = revokeToken; - var GOOGLE_REVOKE_TOKEN_URL = "https://oauth2.googleapis.com/revoke?token="; - var DEFAULT_RETRY_VALUE = true; - async function revokeToken(accessToken, transporter) { - const url = GOOGLE_REVOKE_TOKEN_URL + accessToken; - return await transporter.request({ - url, - retry: DEFAULT_RETRY_VALUE - }); - } -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/gtoken/googleToken.js -var require_googleToken = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GoogleToken = undefined; - var gaxios_1 = require_src2(); - var tokenHandler_1 = require_tokenHandler(); - var revokeToken_1 = require_revokeToken(); + exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = undefined; + var SAML_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:saml2"; + var OIDC_SUBJECT_TOKEN_TYPE1 = "urn:ietf:params:oauth:token-type:id_token"; + var OIDC_SUBJECT_TOKEN_TYPE2 = "urn:ietf:params:oauth:token-type:jwt"; - class GoogleToken { - tokenOptions; - tokenHandler; - constructor(options) { - this.tokenOptions = options || {}; - this.tokenOptions.transporter = this.tokenOptions.transporter || { - request: (opts) => (0, gaxios_1.request)(opts) - }; - if (!this.tokenOptions.iss) { - this.tokenOptions.iss = this.tokenOptions.email; - } - if (typeof this.tokenOptions.scope === "object") { - this.tokenOptions.scope = this.tokenOptions.scope.join(" "); + class ExecutableResponse { + version; + success; + expirationTime; + tokenType; + errorCode; + errorMessage; + subjectToken; + constructor(responseJson) { + if (!responseJson.version) { + throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); } - this.tokenHandler = new tokenHandler_1.TokenHandler(this.tokenOptions); - } - get expiresAt() { - return this.tokenHandler.tokenExpiresAt; - } - get accessToken() { - return this.tokenHandler.token?.access_token; - } - get idToken() { - return this.tokenHandler.token?.id_token; - } - get tokenType() { - return this.tokenHandler.token?.token_type; - } - get refreshToken() { - return this.tokenHandler.token?.refresh_token; - } - hasExpired() { - return this.tokenHandler.hasExpired(); - } - isTokenExpiring() { - return this.tokenHandler.isTokenExpiring(); - } - getToken(callbackOrOptions, opts = { forceRefresh: false }) { - let callback; - if (typeof callbackOrOptions === "function") { - callback = callbackOrOptions; - } else if (typeof callbackOrOptions === "object") { - opts = callbackOrOptions; + if (responseJson.success === undefined) { + throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); } - const promise = this.tokenHandler.getToken(opts.forceRefresh ?? false); - if (callback) { - promise.then((token) => callback(null, token), callback); + this.version = responseJson.version; + this.success = responseJson.success; + if (this.success) { + this.expirationTime = responseJson.expiration_time; + this.tokenType = responseJson.token_type; + if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { + throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); + } + if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { + if (!responseJson.saml_response) { + throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); + } + this.subjectToken = responseJson.saml_response; + } else { + if (!responseJson.id_token) { + throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); + } + this.subjectToken = responseJson.id_token; + } + } else { + if (!responseJson.code) { + throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); + } + if (!responseJson.message) { + throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); + } + this.errorCode = responseJson.code; + this.errorMessage = responseJson.message; } - return promise; } - revokeToken(callback) { - if (!this.accessToken) { - return Promise.reject(new Error("No token to revoke.")); - } - const promise = (0, revokeToken_1.revokeToken)(this.accessToken, this.tokenOptions.transporter); - if (callback) { - promise.then(() => callback(), callback); - } - this.tokenHandler = new tokenHandler_1.TokenHandler(this.tokenOptions); + isValid() { + return !this.isExpired() && this.success; } - get googleTokenOptions() { - return this.tokenOptions; + isExpired() { + return this.expirationTime !== undefined && this.expirationTime < Math.round(Date.now() / 1000); } } - exports.GoogleToken = GoogleToken; + exports.ExecutableResponse = ExecutableResponse; + + class ExecutableResponseError extends Error { + constructor(message) { + super(message); + Object.setPrototypeOf(this, new.target.prototype); + } + } + exports.ExecutableResponseError = ExecutableResponseError; + + class InvalidVersionFieldError extends ExecutableResponseError { + } + exports.InvalidVersionFieldError = InvalidVersionFieldError; + + class InvalidSuccessFieldError extends ExecutableResponseError { + } + exports.InvalidSuccessFieldError = InvalidSuccessFieldError; + + class InvalidExpirationTimeFieldError extends ExecutableResponseError { + } + exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; + + class InvalidTokenTypeFieldError extends ExecutableResponseError { + } + exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; + + class InvalidCodeFieldError extends ExecutableResponseError { + } + exports.InvalidCodeFieldError = InvalidCodeFieldError; + + class InvalidMessageFieldError extends ExecutableResponseError { + } + exports.InvalidMessageFieldError = InvalidMessageFieldError; + + class InvalidSubjectTokenError extends ExecutableResponseError { + } + exports.InvalidSubjectTokenError = InvalidSubjectTokenError; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/jwtaccess.js -var require_jwtaccess = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js +var require_pluggable_auth_handler = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.JWTAccess = undefined; - var jws = require_jws(); - var util_1 = require_util2(); - var DEFAULT_HEADER = { - alg: "RS256", - typ: "JWT" - }; + exports.PluggableAuthHandler = exports.ExecutableError = undefined; + var executable_response_1 = require_executable_response(); + var childProcess = __require("child_process"); + var fs = __require("fs"); - class JWTAccess { - email; - key; - keyId; - projectId; - eagerRefreshThresholdMillis; - cache = new util_1.LRUCache({ - capacity: 500, - maxAge: 60 * 60 * 1000 - }); - constructor(email, key, keyId, eagerRefreshThresholdMillis) { - this.email = email; - this.key = key; - this.keyId = keyId; - this.eagerRefreshThresholdMillis = eagerRefreshThresholdMillis ?? 5 * 60 * 1000; + class ExecutableError extends Error { + code; + constructor(message, code) { + super(`The executable failed with exit code: ${code} and error message: ${message}.`); + this.code = code; + Object.setPrototypeOf(this, new.target.prototype); } - getCachedKey(url, scopes) { - let cacheKey = url; - if (scopes && Array.isArray(scopes) && scopes.length) { - cacheKey = url ? `${url}_${scopes.join("_")}` : `${scopes.join("_")}`; - } else if (typeof scopes === "string") { - cacheKey = url ? `${url}_${scopes}` : scopes; + } + exports.ExecutableError = ExecutableError; + + class PluggableAuthHandler { + commandComponents; + timeoutMillis; + outputFile; + constructor(options) { + if (!options.command) { + throw new Error("No command provided."); } - if (!cacheKey) { - throw Error("Scopes or url must be provided"); + this.commandComponents = PluggableAuthHandler.parseCommand(options.command); + this.timeoutMillis = options.timeoutMillis; + if (!this.timeoutMillis) { + throw new Error("No timeoutMillis provided."); } - return cacheKey; + this.outputFile = options.outputFile; } - getRequestHeaders(url, additionalClaims, scopes) { - const key = this.getCachedKey(url, scopes); - const cachedToken = this.cache.get(key); - const now = Date.now(); - if (cachedToken && cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { - return new Headers(cachedToken.headers); - } - const iat = Math.floor(Date.now() / 1000); - const exp = JWTAccess.getExpirationTime(iat); - let defaultClaims; - if (Array.isArray(scopes)) { - scopes = scopes.join(" "); - } - if (scopes) { - defaultClaims = { - iss: this.email, - sub: this.email, - scope: scopes, - exp, - iat - }; - } else { - defaultClaims = { - iss: this.email, - sub: this.email, - aud: url, - exp, - iat - }; - } - if (additionalClaims) { - for (const claim in defaultClaims) { - if (additionalClaims[claim]) { - throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); + retrieveResponseFromExecutable(envMap) { + return new Promise((resolve, reject) => { + const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { + env: { ...process.env, ...Object.fromEntries(envMap) } + }); + let output = ""; + child.stdout.on("data", (data) => { + output += data; + }); + child.stderr.on("data", (err) => { + output += err; + }); + const timeout = setTimeout(() => { + child.removeAllListeners(); + child.kill(); + return reject(new Error("The executable failed to finish within the timeout specified.")); + }, this.timeoutMillis); + child.on("close", (code) => { + clearTimeout(timeout); + if (code === 0) { + try { + const responseJson = JSON.parse(output); + const response = new executable_response_1.ExecutableResponse(responseJson); + return resolve(response); + } catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + return reject(error); + } + return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); + } + } else { + return reject(new ExecutableError(output, code.toString())); } - } - } - const header = this.keyId ? { ...DEFAULT_HEADER, kid: this.keyId } : DEFAULT_HEADER; - const payload = Object.assign(defaultClaims, additionalClaims); - const signedJWT = jws.sign({ header, payload, secret: this.key }); - const headers = new Headers({ authorization: `Bearer ${signedJWT}` }); - this.cache.set(key, { - expiration: exp * 1000, - headers + }); }); - return headers; - } - static getExpirationTime(iat) { - const exp = iat + 3600; - return exp; } - fromJSON(json2) { - if (!json2) { - throw new Error("Must pass in a JSON object containing the service account auth settings."); + async retrieveCachedResponse() { + if (!this.outputFile || this.outputFile.length === 0) { + return; } - if (!json2.client_email) { - throw new Error("The incoming JSON object does not contain a client_email field"); + let filePath; + try { + filePath = await fs.promises.realpath(this.outputFile); + } catch { + return; } - if (!json2.private_key) { - throw new Error("The incoming JSON object does not contain a private_key field"); + if (!(await fs.promises.lstat(filePath)).isFile()) { + return; } - this.email = json2.client_email; - this.key = json2.private_key; - this.keyId = json2.private_key_id; - this.projectId = json2.project_id; - } - fromStream(inputStream, callback) { - if (callback) { - this.fromStreamAsync(inputStream).then(() => callback(), callback); - } else { - return this.fromStreamAsync(inputStream); + const responseString = await fs.promises.readFile(filePath, { + encoding: "utf8" + }); + if (responseString === "") { + return; + } + try { + const responseJson = JSON.parse(responseString); + const response = new executable_response_1.ExecutableResponse(responseJson); + if (response.isValid()) { + return new executable_response_1.ExecutableResponse(responseJson); + } + return; + } catch (error) { + if (error instanceof executable_response_1.ExecutableResponseError) { + throw error; + } + throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); } } - fromStreamAsync(inputStream) { - return new Promise((resolve, reject) => { - if (!inputStream) { - reject(new Error("Must pass in a stream containing the service account auth settings.")); + static parseCommand(command) { + const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); + if (!components) { + throw new Error(`Provided command: "${command}" could not be parsed.`); + } + for (let i = 0;i < components.length; i++) { + if (components[i][0] === '"' && components[i].slice(-1) === '"') { + components[i] = components[i].slice(1, -1); } - let s = ""; - inputStream.setEncoding("utf8").on("data", (chunk) => s += chunk).on("error", reject).on("end", () => { - try { - const data = JSON.parse(s); - this.fromJSON(data); - resolve(); - } catch (err) { - reject(err); - } - }); - }); + } + return components; } } - exports.JWTAccess = JWTAccess; + exports.PluggableAuthHandler = PluggableAuthHandler; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/jwtclient.js -var require_jwtclient = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js +var require_pluggable_auth_client = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.JWT = undefined; - var googleToken_1 = require_googleToken(); - var getCredentials_1 = require_getCredentials(); - var jwtaccess_1 = require_jwtaccess(); - var oauth2client_1 = require_oauth2client(); - var authclient_1 = require_authclient(); + exports.PluggableAuthClient = exports.ExecutableError = undefined; + var baseexternalclient_1 = require_baseexternalclient(); + var executable_response_1 = require_executable_response(); + var pluggable_auth_handler_1 = require_pluggable_auth_handler(); + var pluggable_auth_handler_2 = require_pluggable_auth_handler(); + Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function() { + return pluggable_auth_handler_2.ExecutableError; + } }); + var DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; + var MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; + var MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; + var GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES"; + var MAXIMUM_EXECUTABLE_VERSION = 1; - class JWT extends oauth2client_1.OAuth2Client { - email; - keyFile; - key; - keyId; - defaultScopes; - scopes; - scope; - subject; - gtoken; - additionalClaims; - useJWTAccessWithScope; - defaultServicePath; - access; - constructor(options = {}) { + class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { + command; + timeoutMillis; + outputFile; + handler; + constructor(options) { super(options); - this.email = options.email; - this.keyFile = options.keyFile; - this.key = options.key; - this.keyId = options.keyId; - this.scopes = options.scopes; - this.subject = options.subject; - this.additionalClaims = options.additionalClaims; - this.credentials = { refresh_token: "jwt-placeholder", expiry_date: 1 }; - } - createScoped(scopes) { - const jwt2 = new JWT(this); - jwt2.scopes = scopes; - return jwt2; - } - async getRequestMetadataAsync(url) { - url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; - const useSelfSignedJWT = !this.hasUserScopes() && url || this.useJWTAccessWithScope && this.hasAnyScopes() || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; - if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { - throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); + if (!options.credential_source.executable) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); } - if (!this.apiKey && useSelfSignedJWT) { - if (this.additionalClaims && this.additionalClaims.target_audience) { - const { tokens } = await this.refreshToken(); - return { - headers: this.addSharedMetadataHeaders(new Headers({ - authorization: `Bearer ${tokens.id_token}` - })) - }; - } else { - if (!this.access) { - this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); - } - let scopes; - if (this.hasUserScopes()) { - scopes = this.scopes; - } else if (!url) { - scopes = this.defaultScopes; - } - const useScopes = this.useJWTAccessWithScope || this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; - const headers = await this.access.getRequestHeaders(url ?? undefined, this.additionalClaims, useScopes ? scopes : undefined); - return { headers: this.addSharedMetadataHeaders(headers) }; - } - } else if (this.hasAnyScopes() || this.apiKey) { - return super.getRequestMetadataAsync(url); + this.command = options.credential_source.executable.command; + if (!this.command) { + throw new Error('No valid Pluggable Auth "credential_source" provided.'); + } + if (options.credential_source.executable.timeout_millis === undefined) { + this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; } else { - return { headers: new Headers }; + this.timeoutMillis = options.credential_source.executable.timeout_millis; + if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { + throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); + } } - } - async fetchIdToken(targetAudience) { - const gtoken = new googleToken_1.GoogleToken({ - iss: this.email, - sub: this.subject, - scope: this.scopes || this.defaultScopes, - keyFile: this.keyFile, - key: this.key, - additionalClaims: { target_audience: targetAudience }, - transporter: this.transporter - }); - await gtoken.getToken({ - forceRefresh: true + this.outputFile = options.credential_source.executable.output_file; + this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ + command: this.command, + timeoutMillis: this.timeoutMillis, + outputFile: this.outputFile }); - if (!gtoken.idToken) { - throw new Error("Unknown error: Failed to fetch ID token"); - } - return gtoken.idToken; + this.credentialSourceType = "executable"; } - hasUserScopes() { - if (!this.scopes) { - return false; + async retrieveSubjectToken() { + if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== "1") { + throw new Error("Pluggable Auth executables need to be explicitly allowed to run by " + "setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment " + "Variable to 1."); } - return this.scopes.length > 0; - } - hasAnyScopes() { - if (this.scopes && this.scopes.length > 0) - return true; - if (this.defaultScopes && this.defaultScopes.length > 0) - return true; - return false; - } - authorize(callback) { - if (callback) { - this.authorizeAsync().then((r) => callback(null, r), callback); - } else { - return this.authorizeAsync(); + let executableResponse = undefined; + if (this.outputFile) { + executableResponse = await this.handler.retrieveCachedResponse(); } - } - async authorizeAsync() { - const result = await this.refreshToken(); - if (!result) { - throw new Error("No result returned"); + if (!executableResponse) { + const envMap = new Map; + envMap.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE", this.audience); + envMap.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE", this.subjectTokenType); + envMap.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE", "0"); + if (this.outputFile) { + envMap.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE", this.outputFile); + } + const serviceAccountEmail = this.getServiceAccountEmail(); + if (serviceAccountEmail) { + envMap.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL", serviceAccountEmail); + } + executableResponse = await this.handler.retrieveResponseFromExecutable(envMap); } - this.credentials = result.tokens; - this.credentials.refresh_token = "jwt-placeholder"; - this.key = this.gtoken.googleTokenOptions?.key; - this.email = this.gtoken.googleTokenOptions?.iss; - return result.tokens; - } - async refreshTokenNoCache() { - const gtoken = this.createGToken(); - const token = await gtoken.getToken({ - forceRefresh: this.isTokenExpiring() - }); - const tokens = { - access_token: token.access_token, - token_type: "Bearer", - expiry_date: gtoken.expiresAt, - id_token: gtoken.idToken - }; - this.emit("tokens", tokens); - return { res: null, tokens }; - } - createGToken() { - if (!this.gtoken) { - this.gtoken = new googleToken_1.GoogleToken({ - iss: this.email, - sub: this.subject, - scope: this.scopes || this.defaultScopes, - keyFile: this.keyFile, - key: this.key, - additionalClaims: this.additionalClaims, - transporter: this.transporter - }); + if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { + throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); } - return this.gtoken; - } - fromJSON(json2) { - if (!json2) { - throw new Error("Must pass in a JSON object containing the service account auth settings."); + if (!executableResponse.success) { + throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); } - if (!json2.client_email) { - throw new Error("The incoming JSON object does not contain a client_email field"); + if (this.outputFile) { + if (!executableResponse.expirationTime) { + throw new executable_response_1.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration."); + } } - if (!json2.private_key) { - throw new Error("The incoming JSON object does not contain a private_key field"); + if (executableResponse.isExpired()) { + throw new Error("Executable response is expired."); } - this.email = json2.client_email; - this.key = json2.private_key; - this.keyId = json2.private_key_id; - this.projectId = json2.project_id; - this.quotaProjectId = json2.quota_project_id; - this.universeDomain = json2.universe_domain || this.universeDomain; + return executableResponse.subjectToken; } - fromStream(inputStream, callback) { - if (callback) { - this.fromStreamAsync(inputStream).then(() => callback(), callback); - } else { - return this.fromStreamAsync(inputStream); - } + } + exports.PluggableAuthClient = PluggableAuthClient; +}); + +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/externalclient.js +var require_externalclient = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ExternalAccountClient = undefined; + var baseexternalclient_1 = require_baseexternalclient(); + var identitypoolclient_1 = require_identitypoolclient(); + var awsclient_1 = require_awsclient(); + var pluggable_auth_client_1 = require_pluggable_auth_client(); + + class ExternalAccountClient { + constructor() { + throw new Error("ExternalAccountClients should be initialized via: " + "ExternalAccountClient.fromJSON(), " + "directly via explicit constructors, eg. " + "new AwsClient(options), new IdentityPoolClient(options), new" + "PluggableAuthClientOptions, or via " + "new GoogleAuth(options).getClient()"); } - fromStreamAsync(inputStream) { - return new Promise((resolve, reject) => { - if (!inputStream) { - throw new Error("Must pass in a stream containing the service account auth settings."); + static fromJSON(options) { + if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + if (options.credential_source?.environment_id) { + return new awsclient_1.AwsClient(options); + } else if (options.credential_source?.executable) { + return new pluggable_auth_client_1.PluggableAuthClient(options); + } else { + return new identitypoolclient_1.IdentityPoolClient(options); } - let s = ""; - inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s += chunk).on("end", () => { - try { - const data = JSON.parse(s); - this.fromJSON(data); - resolve(); - } catch (e2) { - reject(e2); - } - }); - }); - } - fromAPIKey(apiKey) { - if (typeof apiKey !== "string") { - throw new Error("Must provide an API Key string."); - } - this.apiKey = apiKey; - } - async getCredentials() { - if (this.key) { - return { private_key: this.key, client_email: this.email }; - } else if (this.keyFile) { - const gtoken = this.createGToken(); - const creds = await (0, getCredentials_1.getCredentials)(this.keyFile); - return { private_key: creds.privateKey, client_email: creds.clientEmail }; + } else { + return null; } - throw new Error("A key or a keyFile must be provided to getCredentials."); } } - exports.JWT = JWT; + exports.ExternalAccountClient = ExternalAccountClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/refreshclient.js -var require_refreshclient = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js +var require_externalAccountAuthorizedUserClient = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = undefined; - var oauth2client_1 = require_oauth2client(); + exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = undefined; var authclient_1 = require_authclient(); - exports.USER_REFRESH_ACCOUNT_TYPE = "authorized_user"; + var oauth2common_1 = require_oauth2common(); + var gaxios_1 = require_src2(); + var stream = __require("stream"); + var baseexternalclient_1 = require_baseexternalclient(); + exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user"; + var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/oauthtoken"; - class UserRefreshClient extends oauth2client_1.OAuth2Client { - _refreshToken; - constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { - const opts = optionsOrClientId && typeof optionsOrClientId === "object" ? optionsOrClientId : { - clientId: optionsOrClientId, - clientSecret, - refreshToken, - eagerRefreshThresholdMillis, - forceRefreshOnFailure - }; - super(opts); - this._refreshToken = opts.refreshToken; - this.credentials.refresh_token = opts.refreshToken; - } - async refreshTokenNoCache() { - return super.refreshTokenNoCache(this._refreshToken); + class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { + #tokenRefreshEndpoint; + constructor(options) { + super(options); + this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint; } - async fetchIdToken(targetAudience) { + async refreshToken(refreshToken, headers) { const opts = { - ...UserRefreshClient.RETRY_CONFIG, - url: this.endpoints.oauth2TokenUrl, + ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, + url: this.#tokenRefreshEndpoint, method: "POST", + headers, data: new URLSearchParams({ - client_id: this._clientId, - client_secret: this._clientSecret, grant_type: "refresh_token", - refresh_token: this._refreshToken, - target_audience: targetAudience + refresh_token: refreshToken }), responseType: "json" }; - authclient_1.AuthClient.setMethodName(opts, "fetchIdToken"); - const res = await this.transporter.request(opts); - return res.data.id_token; - } - fromJSON(json2) { - if (!json2) { - throw new Error("Must pass in a JSON object containing the user refresh token"); - } - if (json2.type !== "authorized_user") { - throw new Error('The incoming JSON object does not have the "authorized_user" type'); + authclient_1.AuthClient.setMethodName(opts, "refreshToken"); + this.applyClientAuthenticationOptions(opts); + try { + const response = await this.transporter.request(opts); + const tokenRefreshResponse = response.data; + tokenRefreshResponse.res = response; + return tokenRefreshResponse; + } catch (error) { + if (error instanceof gaxios_1.GaxiosError && error.response) { + throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, error); + } + throw error; } - if (!json2.client_id) { - throw new Error("The incoming JSON object does not contain a client_id field"); + } + } + + class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { + cachedAccessToken; + externalAccountAuthorizedUserHandler; + refreshToken; + constructor(options) { + super(options); + if (options.universe_domain) { + this.universeDomain = options.universe_domain; } - if (!json2.client_secret) { - throw new Error("The incoming JSON object does not contain a client_secret field"); + this.refreshToken = options.refresh_token; + const clientAuthentication = { + confidentialClientType: "basic", + clientId: options.client_id, + clientSecret: options.client_secret + }; + this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler({ + tokenRefreshEndpoint: options.token_url ?? DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain), + transporter: this.transporter, + clientAuthentication + }); + this.cachedAccessToken = null; + this.quotaProjectId = options.quota_project_id; + if (typeof options?.eagerRefreshThresholdMillis !== "number") { + this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; + } else { + this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis; } - if (!json2.refresh_token) { - throw new Error("The incoming JSON object does not contain a refresh_token field"); + this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure; + } + async getAccessToken() { + if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + await this.refreshAccessTokenAsync(); } - this._clientId = json2.client_id; - this._clientSecret = json2.client_secret; - this._refreshToken = json2.refresh_token; - this.credentials.refresh_token = json2.refresh_token; - this.quotaProjectId = json2.quota_project_id; - this.universeDomain = json2.universe_domain || this.universeDomain; + return { + token: this.cachedAccessToken.access_token, + res: this.cachedAccessToken.res + }; } - fromStream(inputStream, callback) { + async getRequestHeaders() { + const accessTokenResponse = await this.getAccessToken(); + const headers = new Headers({ + authorization: `Bearer ${accessTokenResponse.token}` + }); + return this.addSharedMetadataHeaders(headers); + } + request(opts, callback) { if (callback) { - this.fromStreamAsync(inputStream).then(() => callback(), callback); + this.requestAsync(opts).then((r) => callback(null, r), (e2) => { + return callback(e2, e2.response); + }); } else { - return this.fromStreamAsync(inputStream); + return this.requestAsync(opts); } } - async fromStreamAsync(inputStream) { - return new Promise((resolve, reject) => { - if (!inputStream) { - return reject(new Error("Must pass in a stream containing the user refresh token.")); - } - let s = ""; - inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => s += chunk).on("end", () => { - try { - const data = JSON.parse(s); - this.fromJSON(data); - return resolve(); - } catch (err) { - return reject(err); + async requestAsync(opts, reAuthRetried = false) { + let response; + try { + const requestHeaders = await this.getRequestHeaders(); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); + this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); + response = await this.transporter.request(opts); + } catch (e2) { + const res = e2.response; + if (res) { + const statusCode = res.status; + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { + await this.refreshAccessTokenAsync(); + return await this.requestAsync(opts, true); } - }); - }); + } + throw e2; + } + return response; } - static fromJSON(json2) { - const client = new UserRefreshClient; - client.fromJSON(json2); - return client; + async refreshAccessTokenAsync() { + const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); + this.cachedAccessToken = { + access_token: refreshResponse.access_token, + expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, + res: refreshResponse.res + }; + if (refreshResponse.refresh_token !== undefined) { + this.refreshToken = refreshResponse.refresh_token; + } + return this.cachedAccessToken; + } + isExpired(credentials) { + const now = new Date().getTime(); + return credentials.expiry_date ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis : false; } } - exports.UserRefreshClient = UserRefreshClient; + exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/impersonated.js -var require_impersonated = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/googleauth.js +var require_googleauth = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = undefined; - var oauth2client_1 = require_oauth2client(); + exports.GoogleAuth = exports.GoogleAuthExceptionMessages = undefined; + var child_process_1 = __require("child_process"); + var fs = __require("fs"); var gaxios_1 = require_src2(); + var gcpMetadata = require_src4(); + var os = __require("os"); + var path2 = __require("path"); + var crypto_1 = require_crypto3(); + var computeclient_1 = require_computeclient(); + var idtokenclient_1 = require_idtokenclient(); + var envDetect_1 = require_envDetect(); + var jwtclient_1 = require_jwtclient(); + var refreshclient_1 = require_refreshclient(); + var impersonated_1 = require_impersonated(); + var externalclient_1 = require_externalclient(); + var baseexternalclient_1 = require_baseexternalclient(); + var authclient_1 = require_authclient(); + var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient(); var util_1 = require_util2(); - exports.IMPERSONATED_ACCOUNT_TYPE = "impersonated_service_account"; + exports.GoogleAuthExceptionMessages = { + API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.", + NO_PROJECT_ID_FOUND: `Unable to detect a Project Id in the current environment. +` + `To learn more about authentication and Google APIs, visit: +` + "https://cloud.google.com/docs/authentication/getting-started", + NO_CREDENTIALS_FOUND: `Unable to find credentials in current environment. +` + `To learn more about authentication and Google APIs, visit: +` + "https://cloud.google.com/docs/authentication/getting-started", + NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.", + NO_UNIVERSE_DOMAIN_FOUND: `Unable to detect a Universe Domain in the current environment. +` + `To learn more about Universe Domain retrieval, visit: +` + "https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys" + }; - class Impersonated extends oauth2client_1.OAuth2Client { - sourceClient; - targetPrincipal; - targetScopes; - delegates; - lifetime; - endpoint; - constructor(options = {}) { - super(options); - this.credentials = { - expiry_date: 1, - refresh_token: "impersonated-placeholder" - }; - this.sourceClient = options.sourceClient ?? new oauth2client_1.OAuth2Client; - this.targetPrincipal = options.targetPrincipal ?? ""; - this.delegates = options.delegates ?? []; - this.targetScopes = options.targetScopes ?? []; - this.lifetime = options.lifetime ?? 3600; - const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get("universe_domain"); - if (!usingExplicitUniverseDomain) { - this.universeDomain = this.sourceClient.universeDomain; - } else if (this.sourceClient.universeDomain !== this.universeDomain) { - throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); + class GoogleAuth { + checkIsGCE = undefined; + useJWTAccessWithScope; + defaultServicePath; + get isGCE() { + return this.checkIsGCE; + } + _findProjectIdPromise; + _cachedProjectId; + jsonContent = null; + apiKey; + cachedCredential = null; + #pendingAuthClient = null; + defaultScopes; + keyFilename; + scopes; + clientOptions = {}; + constructor(opts = {}) { + this._cachedProjectId = opts.projectId || null; + this.cachedCredential = opts.authClient || null; + this.keyFilename = opts.keyFilename || opts.keyFile; + this.scopes = opts.scopes; + this.clientOptions = opts.clientOptions || {}; + this.jsonContent = opts.credentials || null; + this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; + if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { + throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); + } + if (opts.universeDomain) { + this.clientOptions.universeDomain = opts.universeDomain; } - this.endpoint = options.endpoint ?? `https://iamcredentials.${this.universeDomain}`; } - async sign(blobToSign) { - await this.sourceClient.getAccessToken(); - const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; - const u = `${this.endpoint}/v1/${name}:signBlob`; - const body = { - delegates: this.delegates, - payload: Buffer.from(blobToSign).toString("base64") - }; - const res = await this.sourceClient.request({ - ...Impersonated.RETRY_CONFIG, - url: u, - data: body, - method: "POST" - }); - return res.data; + setGapicJWTValues(client) { + client.defaultServicePath = this.defaultServicePath; + client.useJWTAccessWithScope = this.useJWTAccessWithScope; + client.defaultScopes = this.defaultScopes; } - getTargetPrincipal() { - return this.targetPrincipal; + getProjectId(callback) { + if (callback) { + this.getProjectIdAsync().then((r) => callback(null, r), callback); + } else { + return this.getProjectIdAsync(); + } } - async refreshToken() { + async getProjectIdOptional() { try { - await this.sourceClient.getAccessToken(); - const name = "projects/-/serviceAccounts/" + this.targetPrincipal; - const u = `${this.endpoint}/v1/${name}:generateAccessToken`; - const body = { - delegates: this.delegates, - scope: this.targetScopes, - lifetime: this.lifetime + "s" - }; - const res = await this.sourceClient.request({ - ...Impersonated.RETRY_CONFIG, - url: u, - data: body, - method: "POST" - }); - const tokenResponse = res.data; - this.credentials.access_token = tokenResponse.accessToken; - this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); - return { - tokens: this.credentials, - res - }; - } catch (error) { - if (!(error instanceof Error)) - throw error; - let status = 0; - let message = ""; - if (error instanceof gaxios_1.GaxiosError) { - status = error?.response?.data?.error?.status; - message = error?.response?.data?.error?.message; - } - if (status && message) { - error.message = `${status}: unable to impersonate: ${message}`; - throw error; + return await this.getProjectId(); + } catch (e2) { + if (e2 instanceof Error && e2.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { + return null; } else { - error.message = `unable to impersonate: ${error}`; - throw error; + throw e2; } } } - async fetchIdToken(targetAudience, options) { - await this.sourceClient.getAccessToken(); - const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; - const u = `${this.endpoint}/v1/${name}:generateIdToken`; - const body = { - delegates: this.delegates, - audience: targetAudience, - includeEmail: options?.includeEmail ?? true, - useEmailAzp: options?.includeEmail ?? true - }; - const res = await this.sourceClient.request({ - ...Impersonated.RETRY_CONFIG, - url: u, - data: body, - method: "POST" - }); - return res.data.token; - } - } - exports.Impersonated = Impersonated; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/oauth2common.js -var require_oauth2common = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.OAuthClientAuthHandler = undefined; - exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; - var gaxios_1 = require_src2(); - var crypto_1 = require_crypto3(); - var METHODS_SUPPORTING_REQUEST_BODY = ["PUT", "POST", "PATCH"]; - - class OAuthClientAuthHandler { - #crypto = (0, crypto_1.createCrypto)(); - #clientAuthentication; - transporter; - constructor(options) { - if (options && "clientId" in options) { - this.#clientAuthentication = options; - this.transporter = new gaxios_1.Gaxios; + async findAndCacheProjectId() { + let projectId = null; + projectId ||= await this.getProductionProjectId(); + projectId ||= await this.getFileProjectId(); + projectId ||= await this.getDefaultServiceProjectId(); + projectId ||= await this.getGCEProjectId(); + projectId ||= await this.getExternalAccountClientProjectId(); + if (projectId) { + this._cachedProjectId = projectId; + return projectId; } else { - this.#clientAuthentication = options?.clientAuthentication; - this.transporter = options?.transporter || new gaxios_1.Gaxios; + throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); } } - applyClientAuthenticationOptions(opts, bearerToken) { - opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); - this.injectAuthenticatedHeaders(opts, bearerToken); - if (!bearerToken) { - this.injectAuthenticatedRequestBody(opts); + async getProjectIdAsync() { + if (this._cachedProjectId) { + return this._cachedProjectId; + } + if (!this._findProjectIdPromise) { + this._findProjectIdPromise = this.findAndCacheProjectId(); } + return this._findProjectIdPromise; } - injectAuthenticatedHeaders(opts, bearerToken) { - if (bearerToken) { - opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, { - authorization: `Bearer ${bearerToken}` + async getUniverseDomainFromMetadataServer() { + let universeDomain; + try { + universeDomain = await gcpMetadata.universe("universe-domain"); + universeDomain ||= authclient_1.DEFAULT_UNIVERSE; + } catch (e2) { + if (e2 && e2?.response?.status === 404) { + universeDomain = authclient_1.DEFAULT_UNIVERSE; + } else { + throw e2; + } + } + return universeDomain; + } + async getUniverseDomain() { + let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain"); + try { + universeDomain ??= (await this.getClient()).universeDomain; + } catch { + universeDomain ??= authclient_1.DEFAULT_UNIVERSE; + } + return universeDomain; + } + getAnyScopes() { + return this.scopes || this.defaultScopes; + } + getApplicationDefault(optionsOrCallback = {}, callback) { + let options; + if (typeof optionsOrCallback === "function") { + callback = optionsOrCallback; + } else { + options = optionsOrCallback; + } + if (callback) { + this.getApplicationDefaultAsync(options).then((r) => callback(null, r.credential, r.projectId), callback); + } else { + return this.getApplicationDefaultAsync(options); + } + } + async getApplicationDefaultAsync(options = {}) { + if (this.cachedCredential) { + return await this.#prepareAndCacheClient(this.cachedCredential, null); + } + let credential; + credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await this.#prepareAndCacheClient(credential); + } + credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { + credential.scopes = this.getAnyScopes(); + } + return await this.#prepareAndCacheClient(credential); + } + if (await this._checkIsGCE()) { + options.scopes = this.getAnyScopes(); + return await this.#prepareAndCacheClient(new computeclient_1.Compute(options)); + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); + } + async#prepareAndCacheClient(credential, quotaProjectIdOverride = process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || null) { + const projectId = await this.getProjectIdOptional(); + if (quotaProjectIdOverride) { + credential.quotaProjectId = quotaProjectIdOverride; + } + this.cachedCredential = credential; + return { credential, projectId }; + } + async _checkIsGCE() { + if (this.checkIsGCE === undefined) { + this.checkIsGCE = gcpMetadata.getGCPResidency() || await gcpMetadata.isAvailable(); + } + return this.checkIsGCE; + } + async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { + const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] || process.env["google_application_credentials"]; + if (!credentialsPath || credentialsPath.length === 0) { + return null; + } + try { + return this._getApplicationCredentialsFromFilePath(credentialsPath, options); + } catch (e2) { + if (e2 instanceof Error) { + e2.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e2.message}`; + } + throw e2; + } + } + async _tryGetApplicationCredentialsFromWellKnownFile(options) { + let location = null; + if (this._isWindows()) { + location = process.env["APPDATA"]; + } else { + const home = process.env["HOME"]; + if (home) { + location = path2.join(home, ".config"); + } + } + if (location) { + location = path2.join(location, "gcloud", "application_default_credentials.json"); + if (!fs.existsSync(location)) { + location = null; + } + } + if (!location) { + return null; + } + const client = await this._getApplicationCredentialsFromFilePath(location, options); + return client; + } + async _getApplicationCredentialsFromFilePath(filePath, options = {}) { + if (!filePath || filePath.length === 0) { + throw new Error("The file path is invalid."); + } + try { + filePath = fs.realpathSync(filePath); + if (!fs.lstatSync(filePath).isFile()) { + throw new Error; + } + } catch (err) { + if (err instanceof Error) { + err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; + } + throw err; + } + const readStream = fs.createReadStream(filePath); + return this.fromStream(readStream, options); + } + fromImpersonatedJSON(json3) { + if (!json3) { + throw new Error("Must pass in a JSON object containing an impersonated refresh token"); + } + if (json3.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); + } + if (!json3.source_credentials) { + throw new Error("The incoming JSON object does not contain a source_credentials field"); + } + if (!json3.service_account_impersonation_url) { + throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field"); + } + const sourceClient = this.fromJSON(json3.source_credentials); + if (json3.service_account_impersonation_url?.length > 256) { + throw new RangeError(`Target principal is too long: ${json3.service_account_impersonation_url}`); + } + const targetPrincipal = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json3.service_account_impersonation_url)?.groups?.target; + if (!targetPrincipal) { + throw new RangeError(`Cannot extract target principal from ${json3.service_account_impersonation_url}`); + } + const targetScopes = (this.scopes || json3.scopes || this.defaultScopes) ?? []; + return new impersonated_1.Impersonated({ + ...json3, + sourceClient, + targetPrincipal, + targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes] + }); + } + fromJSON(json3, options = {}) { + let client; + const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get("universe_domain"); + if (json3.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { + client = new refreshclient_1.UserRefreshClient(options); + client.fromJSON(json3); + } else if (json3.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { + client = this.fromImpersonatedJSON(json3); + } else if (json3.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + client = externalclient_1.ExternalAccountClient.fromJSON({ + ...json3, + ...options }); - } else if (this.#clientAuthentication?.confidentialClientType === "basic") { - opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); - const clientId = this.#clientAuthentication.clientId; - const clientSecret = this.#clientAuthentication.clientSecret || ""; - const base64EncodedCreds = this.#crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); - gaxios_1.Gaxios.mergeHeaders(opts.headers, { - authorization: `Basic ${base64EncodedCreds}` + client.scopes = this.getAnyScopes(); + } else if (json3.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { + client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({ + ...json3, + ...options }); + } else { + options.scopes = this.scopes; + client = new jwtclient_1.JWT(options); + this.setGapicJWTValues(client); + client.fromJSON(json3); + } + if (preferredUniverseDomain) { + client.universeDomain = preferredUniverseDomain; } + return client; } - injectAuthenticatedRequestBody(opts) { - if (this.#clientAuthentication?.confidentialClientType === "request-body") { - const method = (opts.method || "GET").toUpperCase(); - if (!METHODS_SUPPORTING_REQUEST_BODY.includes(method)) { - throw new Error(`${method} HTTP method does not support ` + `${this.#clientAuthentication.confidentialClientType} ` + "client authentication"); + _cacheClientFromJSON(json3, options) { + const client = this.fromJSON(json3, options); + this.jsonContent = json3; + this.cachedCredential = client; + return client; + } + fromStream(inputStream, optionsOrCallback = {}, callback) { + let options = {}; + if (typeof optionsOrCallback === "function") { + callback = optionsOrCallback; + } else { + options = optionsOrCallback; + } + if (callback) { + this.fromStreamAsync(inputStream, options).then((r) => callback(null, r), callback); + } else { + return this.fromStreamAsync(inputStream, options); + } + } + fromStreamAsync(inputStream, options) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error("Must pass in a stream containing the Google auth settings."); } - const headers = new Headers(opts.headers); - const contentType = headers.get("content-type"); - if (contentType?.startsWith("application/x-www-form-urlencoded") || opts.data instanceof URLSearchParams) { - const data = new URLSearchParams(opts.data ?? ""); - data.append("client_id", this.#clientAuthentication.clientId); - data.append("client_secret", this.#clientAuthentication.clientSecret || ""); - opts.data = data; - } else if (contentType?.startsWith("application/json")) { - opts.data = opts.data || {}; - Object.assign(opts.data, { - client_id: this.#clientAuthentication.clientId, - client_secret: this.#clientAuthentication.clientSecret || "" - }); - } else { - throw new Error(`${contentType} content-types are not supported with ` + `${this.#clientAuthentication.confidentialClientType} ` + "client authentication"); + const chunks = []; + inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => chunks.push(chunk)).on("end", () => { + try { + try { + const data = JSON.parse(chunks.join("")); + const r = this._cacheClientFromJSON(data, options); + return resolve(r); + } catch (err) { + if (!this.keyFilename) + throw err; + const client = new jwtclient_1.JWT({ + ...this.clientOptions, + keyFile: this.keyFilename + }); + this.cachedCredential = client; + this.setGapicJWTValues(client); + return resolve(client); + } + } catch (err) { + return reject(err); + } + }); + }); + } + fromAPIKey(apiKey, options = {}) { + return new jwtclient_1.JWT({ ...options, apiKey }); + } + _isWindows() { + const sys = os.platform(); + if (sys && sys.length >= 3) { + if (sys.substring(0, 3).toLowerCase() === "win") { + return true; } } + return false; } - static get RETRY_CONFIG() { - return { - retry: true, - retryConfig: { - httpMethodsToRetry: ["GET", "PUT", "POST", "HEAD", "OPTIONS", "DELETE"] + async getDefaultServiceProjectId() { + return new Promise((resolve) => { + (0, child_process_1.exec)("gcloud config config-helper --format json", (err, stdout) => { + if (!err && stdout) { + try { + const projectId = JSON.parse(stdout).configuration.properties.core.project; + resolve(projectId); + return; + } catch (e2) {} + } + resolve(null); + }); + }); + } + getProductionProjectId() { + return process.env["GCLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["gcloud_project"] || process.env["google_cloud_project"]; + } + async getFileProjectId() { + if (this.cachedCredential) { + return this.cachedCredential.projectId; + } + if (this.keyFilename) { + const creds = await this.getClient(); + if (creds && creds.projectId) { + return creds.projectId; } - }; + } + const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); + if (r) { + return r.projectId; + } else { + return null; + } } - } - exports.OAuthClientAuthHandler = OAuthClientAuthHandler; - function getErrorFromOAuthErrorResponse(resp, err) { - const errorCode = resp.error; - const errorDescription = resp.error_description; - const errorUri = resp.error_uri; - let message = `Error code ${errorCode}`; - if (typeof errorDescription !== "undefined") { - message += `: ${errorDescription}`; + async getExternalAccountClientProjectId() { + if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { + return null; + } + const creds = await this.getClient(); + return await creds.getProjectId(); } - if (typeof errorUri !== "undefined") { - message += ` - ${errorUri}`; + async getGCEProjectId() { + try { + const r = await gcpMetadata.project("project-id"); + return r; + } catch (e2) { + return null; + } } - const newError = new Error(message); - if (err) { - const keys = Object.keys(err); - if (err.stack) { - keys.push("stack"); + getCredentials(callback) { + if (callback) { + this.getCredentialsAsync().then((r) => callback(null, r), callback); + } else { + return this.getCredentialsAsync(); } - keys.forEach((key) => { - if (key !== "message") { - Object.defineProperty(newError, key, { - value: err[key], - writable: false, - enumerable: true - }); + } + async getCredentialsAsync() { + const client = await this.getClient(); + if (client instanceof impersonated_1.Impersonated) { + return { client_email: client.getTargetPrincipal() }; + } + if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { + const serviceAccountEmail = client.getServiceAccountEmail(); + if (serviceAccountEmail) { + return { + client_email: serviceAccountEmail, + universe_domain: client.universeDomain + }; + } + } + if (this.jsonContent) { + return { + client_email: this.jsonContent.client_email, + private_key: this.jsonContent.private_key, + universe_domain: this.jsonContent.universe_domain + }; + } + if (await this._checkIsGCE()) { + const [client_email, universe_domain] = await Promise.all([ + gcpMetadata.instance("service-accounts/default/email"), + this.getUniverseDomain() + ]); + return { client_email, universe_domain }; + } + throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); + } + async getClient() { + if (this.cachedCredential) { + return this.cachedCredential; + } + this.#pendingAuthClient = this.#pendingAuthClient || this.#determineClient(); + try { + return await this.#pendingAuthClient; + } finally { + this.#pendingAuthClient = null; + } + } + async#determineClient() { + if (this.jsonContent) { + return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); + } else if (this.keyFilename) { + const filePath = path2.resolve(this.keyFilename); + const stream = fs.createReadStream(filePath); + return await this.fromStreamAsync(stream, this.clientOptions); + } else if (this.apiKey) { + const client = await this.fromAPIKey(this.apiKey, this.clientOptions); + client.scopes = this.scopes; + const { credential } = await this.#prepareAndCacheClient(client); + return credential; + } else { + const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); + return credential; + } + } + async getIdTokenClient(targetAudience) { + const client = await this.getClient(); + if (!("fetchIdToken" in client)) { + throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file."); + } + return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); + } + async getAccessToken() { + const client = await this.getClient(); + return (await client.getAccessToken()).token; + } + async getRequestHeaders(url) { + const client = await this.getClient(); + return client.getRequestHeaders(url); + } + async authorizeRequest(opts = {}) { + const url = opts.url; + const client = await this.getClient(); + const headers = await client.getRequestHeaders(url); + opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers); + return opts; + } + async fetch(...args) { + const client = await this.getClient(); + return client.fetch(...args); + } + async request(opts) { + const client = await this.getClient(); + return client.request(opts); + } + getEnv() { + return (0, envDetect_1.getEnv)(); + } + async sign(data, endpoint) { + const client = await this.getClient(); + const universe = await this.getUniverseDomain(); + endpoint = endpoint || `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; + if (client instanceof impersonated_1.Impersonated) { + const signed = await client.sign(data); + return signed.signedBlob; + } + const crypto2 = (0, crypto_1.createCrypto)(); + if (client instanceof jwtclient_1.JWT && client.key) { + const sign = await crypto2.sign(client.key, data); + return sign; + } + const creds = await this.getCredentials(); + if (!creds.client_email) { + throw new Error("Cannot sign data without `client_email`."); + } + return this.signBlob(crypto2, creds.client_email, data, endpoint); + } + async signBlob(crypto2, emailOrUniqueId, data, endpoint) { + const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); + const res = await this.request({ + method: "POST", + url: url.href, + data: { + payload: crypto2.encodeBase64StringUtf8(data) + }, + retry: true, + retryConfig: { + httpMethodsToRetry: ["POST"] } }); + return res.data.signedBlob; } - return newError; } + exports.GoogleAuth = GoogleAuth; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/stscredentials.js -var require_stscredentials = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/iam.js +var require_iam = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.StsCredentials = undefined; - var gaxios_1 = require_src2(); - var authclient_1 = require_authclient(); - var oauth2common_1 = require_oauth2common(); - var util_1 = require_util2(); + exports.IAMAuth = undefined; - class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { - #tokenExchangeEndpoint; - constructor(options = { - tokenExchangeEndpoint: "" - }, clientAuthentication) { - if (typeof options !== "object" || options instanceof URL) { - options = { - tokenExchangeEndpoint: options, - clientAuthentication - }; - } - super(options); - this.#tokenExchangeEndpoint = options.tokenExchangeEndpoint; + class IAMAuth { + selector; + token; + constructor(selector, token) { + this.selector = selector; + this.token = token; + this.selector = selector; + this.token = token; } - async exchangeToken(stsCredentialsOptions, headers, options) { - const values = { - grant_type: stsCredentialsOptions.grantType, - resource: stsCredentialsOptions.resource, - audience: stsCredentialsOptions.audience, - scope: stsCredentialsOptions.scope?.join(" "), - requested_token_type: stsCredentialsOptions.requestedTokenType, - subject_token: stsCredentialsOptions.subjectToken, - subject_token_type: stsCredentialsOptions.subjectTokenType, - actor_token: stsCredentialsOptions.actingParty?.actorToken, - actor_token_type: stsCredentialsOptions.actingParty?.actorTokenType, - options: options && JSON.stringify(options) - }; - const opts = { - ...StsCredentials.RETRY_CONFIG, - url: this.#tokenExchangeEndpoint.toString(), - method: "POST", - headers, - data: new URLSearchParams((0, util_1.removeUndefinedValuesInObject)(values)), - responseType: "json" + getRequestHeaders() { + return { + "x-goog-iam-authority-selector": this.selector, + "x-goog-iam-authorization-token": this.token }; - authclient_1.AuthClient.setMethodName(opts, "exchangeToken"); - this.applyClientAuthenticationOptions(opts); - try { - const response = await this.transporter.request(opts); - const stsSuccessfulResponse = response.data; - stsSuccessfulResponse.res = response; - return stsSuccessfulResponse; - } catch (error) { - if (error instanceof gaxios_1.GaxiosError && error.response) { - throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, error); - } - throw error; - } } } - exports.StsCredentials = StsCredentials; + exports.IAMAuth = IAMAuth; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/baseexternalclient.js -var require_baseexternalclient = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/downscopedclient.js +var require_downscopedclient = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.BaseExternalAccountClient = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = undefined; + exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = undefined; var gaxios_1 = require_src2(); var stream = __require("stream"); var authclient_1 = require_authclient(); var sts = require_stscredentials(); - var util_1 = require_util2(); - var shared_cjs_1 = require_shared2(); var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; - var DEFAULT_OAUTH_SCOPE = "https://www.googleapis.com/auth/cloud-platform"; - var DEFAULT_TOKEN_LIFESPAN = 3600; + var STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; + exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; - exports.EXTERNAL_ACCOUNT_TYPE = "external_account"; - exports.CLOUD_RESOURCE_MANAGER = "https://cloudresourcemanager.googleapis.com/v1/projects/"; - var WORKFORCE_AUDIENCE_PATTERN = "//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+"; - var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/token"; - class BaseExternalAccountClient extends authclient_1.AuthClient { - scopes; - projectNumber; - audience; - subjectTokenType; + class DownscopedClient extends authclient_1.AuthClient { + authClient; + credentialAccessBoundary; + cachedDownscopedAccessToken; stsCredential; - clientAuth; - credentialSourceType; - cachedAccessToken; - serviceAccountImpersonationUrl; - serviceAccountImpersonationLifetime; - workforcePoolUserProject; - configLifetimeRequested; - tokenUrl; - cloudResourceManagerURL; - supplierContext; - #pendingAccessToken = null; - constructor(options) { - super(options); - const opts = (0, util_1.originalOrCamelOptions)(options); - const type = opts.get("type"); - if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { - throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + `received "${options.type}"`); - } - const clientId = opts.get("client_id"); - const clientSecret = opts.get("client_secret"); - this.tokenUrl = opts.get("token_url") ?? DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain); - const subjectTokenType = opts.get("subject_token_type"); - const workforcePoolUserProject = opts.get("workforce_pool_user_project"); - const serviceAccountImpersonationUrl = opts.get("service_account_impersonation_url"); - const serviceAccountImpersonation = opts.get("service_account_impersonation"); - const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get("token_lifetime_seconds"); - this.cloudResourceManagerURL = new URL(opts.get("cloud_resource_manager_url") || `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); - if (clientId) { - this.clientAuth = { - confidentialClientType: "basic", - clientId, - clientSecret - }; - } - this.stsCredential = new sts.StsCredentials({ - tokenExchangeEndpoint: this.tokenUrl, - clientAuthentication: this.clientAuth - }); - this.scopes = opts.get("scopes") || [DEFAULT_OAUTH_SCOPE]; - this.cachedAccessToken = null; - this.audience = opts.get("audience"); - this.subjectTokenType = subjectTokenType; - this.workforcePoolUserProject = workforcePoolUserProject; - const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); - if (this.workforcePoolUserProject && !this.audience.match(workforceAudiencePattern)) { - throw new Error("workforcePoolUserProject should not be set for non-workforce pool " + "credentials."); + constructor(options, credentialAccessBoundary = { + accessBoundary: { + accessBoundaryRules: [] } - this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; - this.serviceAccountImpersonationLifetime = serviceAccountImpersonationLifetime; - if (this.serviceAccountImpersonationLifetime) { - this.configLifetimeRequested = true; + }) { + super(options instanceof authclient_1.AuthClient ? {} : options); + if (options instanceof authclient_1.AuthClient) { + this.authClient = options; + this.credentialAccessBoundary = credentialAccessBoundary; } else { - this.configLifetimeRequested = false; - this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; + this.authClient = options.authClient; + this.credentialAccessBoundary = options.credentialAccessBoundary; } - this.projectNumber = this.getProjectNumber(this.audience); - this.supplierContext = { - audience: this.audience, - subjectTokenType: this.subjectTokenType, - transporter: this.transporter - }; - } - getServiceAccountEmail() { - if (this.serviceAccountImpersonationUrl) { - if (this.serviceAccountImpersonationUrl.length > 256) { - throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); + if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { + throw new Error("At least one access boundary rule needs to be defined."); + } else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { + throw new Error("The provided access boundary has more than " + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); + } + for (const rule of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules) { + if (rule.availablePermissions.length === 0) { + throw new Error("At least one permission should be defined in access boundary rules."); } - const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; - const result = re.exec(this.serviceAccountImpersonationUrl); - return result?.groups?.email || null; } - return null; + this.stsCredential = new sts.StsCredentials({ + tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token` + }); + this.cachedDownscopedAccessToken = null; } setCredentials(credentials) { + if (!credentials.expiry_date) { + throw new Error("The access token expiry_date field is missing in the provided " + "credentials."); + } super.setCredentials(credentials); - this.cachedAccessToken = credentials; + this.cachedDownscopedAccessToken = credentials; } async getAccessToken() { - if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { + if (!this.cachedDownscopedAccessToken || this.isExpired(this.cachedDownscopedAccessToken)) { await this.refreshAccessTokenAsync(); } return { - token: this.cachedAccessToken.access_token, - res: this.cachedAccessToken.res + token: this.cachedDownscopedAccessToken.access_token, + expirationTime: this.cachedDownscopedAccessToken.expiry_date, + res: this.cachedDownscopedAccessToken.res }; } async getRequestHeaders() { @@ -80147,25 +71094,6 @@ var require_baseexternalclient = __commonJS((exports) => { return this.requestAsync(opts); } } - async getProjectId() { - const projectNumber = this.projectNumber || this.workforcePoolUserProject; - if (this.projectId) { - return this.projectId; - } else if (projectNumber) { - const headers = await this.getRequestHeaders(); - const opts = { - ...BaseExternalAccountClient.RETRY_CONFIG, - headers, - url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, - responseType: "json" - }; - authclient_1.AuthClient.setMethodName(opts, "getProjectId"); - const response = await this.transporter.request(opts); - this.projectId = response.data.projectId; - return this.projectId; - } - return null; - } async requestAsync(opts, reAuthRetried = false) { let response; try { @@ -80189,3051 +71117,1135 @@ var require_baseexternalclient = __commonJS((exports) => { return response; } async refreshAccessTokenAsync() { - this.#pendingAccessToken = this.#pendingAccessToken || this.#internalRefreshAccessTokenAsync(); - try { - return await this.#pendingAccessToken; - } finally { - this.#pendingAccessToken = null; - } - } - async#internalRefreshAccessTokenAsync() { - const subjectToken = await this.retrieveSubjectToken(); + const subjectToken = (await this.authClient.getAccessToken()).token; const stsCredentialsOptions = { grantType: STS_GRANT_TYPE, - audience: this.audience, requestedTokenType: STS_REQUEST_TOKEN_TYPE, subjectToken, - subjectTokenType: this.subjectTokenType, - scope: this.serviceAccountImpersonationUrl ? [DEFAULT_OAUTH_SCOPE] : this.getScopesArray() + subjectTokenType: STS_SUBJECT_TOKEN_TYPE + }; + const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); + const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null; + const expiryDate = stsResponse.expires_in ? new Date().getTime() + stsResponse.expires_in * 1000 : sourceCredExpireDate; + this.cachedDownscopedAccessToken = { + access_token: stsResponse.access_token, + expiry_date: expiryDate, + res: stsResponse.res }; - const additionalOptions = !this.clientAuth && this.workforcePoolUserProject ? { userProject: this.workforcePoolUserProject } : undefined; - const additionalHeaders = new Headers({ - "x-goog-api-client": this.getMetricsHeaderValue() - }); - const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); - if (this.serviceAccountImpersonationUrl) { - this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); - } else if (stsResponse.expires_in) { - this.cachedAccessToken = { - access_token: stsResponse.access_token, - expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, - res: stsResponse.res - }; - } else { - this.cachedAccessToken = { - access_token: stsResponse.access_token, - res: stsResponse.res - }; - } this.credentials = {}; - Object.assign(this.credentials, this.cachedAccessToken); + Object.assign(this.credentials, this.cachedDownscopedAccessToken); delete this.credentials.res; this.emit("tokens", { refresh_token: null, - expiry_date: this.cachedAccessToken.expiry_date, - access_token: this.cachedAccessToken.access_token, + expiry_date: this.cachedDownscopedAccessToken.expiry_date, + access_token: this.cachedDownscopedAccessToken.access_token, token_type: "Bearer", id_token: null }); - return this.cachedAccessToken; - } - getProjectNumber(audience) { - const match = audience.match(/\/projects\/([^/]+)/); - if (!match) { - return null; - } - return match[1]; - } - async getImpersonatedAccessToken(token) { - const opts = { - ...BaseExternalAccountClient.RETRY_CONFIG, - url: this.serviceAccountImpersonationUrl, - method: "POST", - headers: { - "content-type": "application/json", - authorization: `Bearer ${token}` - }, - data: { - scope: this.getScopesArray(), - lifetime: this.serviceAccountImpersonationLifetime + "s" - }, - responseType: "json" - }; - authclient_1.AuthClient.setMethodName(opts, "getImpersonatedAccessToken"); - const response = await this.transporter.request(opts); - const successResponse = response.data; - return { - access_token: successResponse.accessToken, - expiry_date: new Date(successResponse.expireTime).getTime(), - res: response - }; + return this.cachedDownscopedAccessToken; } - isExpired(accessToken) { + isExpired(downscopedAccessToken) { const now = new Date().getTime(); - return accessToken.expiry_date ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis : false; - } - getScopesArray() { - if (typeof this.scopes === "string") { - return [this.scopes]; - } - return this.scopes || [DEFAULT_OAUTH_SCOPE]; - } - getMetricsHeaderValue() { - const nodeVersion = process.version.replace(/^v/, ""); - const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; - const credentialSourceType = this.credentialSourceType ? this.credentialSourceType : "unknown"; - return `gl-node/${nodeVersion} auth/${shared_cjs_1.pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; - } - getTokenUrl() { - return this.tokenUrl; + return downscopedAccessToken.expiry_date ? now >= downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis : false; } } - exports.BaseExternalAccountClient = BaseExternalAccountClient; + exports.DownscopedClient = DownscopedClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js -var require_filesubjecttokensupplier = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/passthrough.js +var require_passthrough = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - exports.FileSubjectTokenSupplier = undefined; - var util_1 = __require("util"); - var fs = __require("fs"); - var readFile = (0, util_1.promisify)(fs.readFile ?? (() => {})); - var realpath = (0, util_1.promisify)(fs.realpath ?? (() => {})); - var lstat = (0, util_1.promisify)(fs.lstat ?? (() => {})); + exports.PassThroughClient = undefined; + var authclient_1 = require_authclient(); - class FileSubjectTokenSupplier { - filePath; - formatType; - subjectTokenFieldName; - constructor(opts) { - this.filePath = opts.filePath; - this.formatType = opts.formatType; - this.subjectTokenFieldName = opts.subjectTokenFieldName; + class PassThroughClient extends authclient_1.AuthClient { + async request(opts) { + return this.transporter.request(opts); } - async getSubjectToken() { - let parsedFilePath = this.filePath; - try { - parsedFilePath = await realpath(parsedFilePath); - if (!(await lstat(parsedFilePath)).isFile()) { - throw new Error; - } - } catch (err) { - if (err instanceof Error) { - err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; - } - throw err; - } - let subjectToken; - const rawText = await readFile(parsedFilePath, { encoding: "utf8" }); - if (this.formatType === "text") { - subjectToken = rawText; - } else if (this.formatType === "json" && this.subjectTokenFieldName) { - const json2 = JSON.parse(rawText); - subjectToken = json2[this.subjectTokenFieldName]; - } - if (!subjectToken) { - throw new Error("Unable to parse the subject_token from the credential_source file"); - } - return subjectToken; + async getAccessToken() { + return {}; + } + async getRequestHeaders() { + return new Headers; } } - exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; + exports.PassThroughClient = PassThroughClient; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js -var require_urlsubjecttokensupplier = __commonJS((exports) => { +// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/index.js +var require_src5 = __commonJS((exports) => { + var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + var desc2 = Object.getOwnPropertyDescriptor(m, k); + if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { + desc2 = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc2); + } : function(o, m, k, k2) { + if (k2 === undefined) + k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports && exports.__exportStar || function(m, exports2) { + for (var p in m) + if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) + __createBinding(exports2, m, p); + }; Object.defineProperty(exports, "__esModule", { value: true }); - exports.UrlSubjectTokenSupplier = undefined; + exports.GoogleAuth = exports.auth = exports.PassThroughClient = exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = undefined; + var googleauth_1 = require_googleauth(); + Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function() { + return googleauth_1.GoogleAuth; + } }); + exports.gcpMetadata = require_src4(); + exports.gaxios = require_src2(); var authclient_1 = require_authclient(); + Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function() { + return authclient_1.AuthClient; + } }); + Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function() { + return authclient_1.DEFAULT_UNIVERSE; + } }); + var computeclient_1 = require_computeclient(); + Object.defineProperty(exports, "Compute", { enumerable: true, get: function() { + return computeclient_1.Compute; + } }); + var envDetect_1 = require_envDetect(); + Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function() { + return envDetect_1.GCPEnv; + } }); + var iam_1 = require_iam(); + Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function() { + return iam_1.IAMAuth; + } }); + var idtokenclient_1 = require_idtokenclient(); + Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function() { + return idtokenclient_1.IdTokenClient; + } }); + var jwtaccess_1 = require_jwtaccess(); + Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function() { + return jwtaccess_1.JWTAccess; + } }); + var jwtclient_1 = require_jwtclient(); + Object.defineProperty(exports, "JWT", { enumerable: true, get: function() { + return jwtclient_1.JWT; + } }); + var impersonated_1 = require_impersonated(); + Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function() { + return impersonated_1.Impersonated; + } }); + var oauth2client_1 = require_oauth2client(); + Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function() { + return oauth2client_1.CodeChallengeMethod; + } }); + Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function() { + return oauth2client_1.OAuth2Client; + } }); + Object.defineProperty(exports, "ClientAuthentication", { enumerable: true, get: function() { + return oauth2client_1.ClientAuthentication; + } }); + var loginticket_1 = require_loginticket(); + Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function() { + return loginticket_1.LoginTicket; + } }); + var refreshclient_1 = require_refreshclient(); + Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function() { + return refreshclient_1.UserRefreshClient; + } }); + var awsclient_1 = require_awsclient(); + Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function() { + return awsclient_1.AwsClient; + } }); + var awsrequestsigner_1 = require_awsrequestsigner(); + Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function() { + return awsrequestsigner_1.AwsRequestSigner; + } }); + var identitypoolclient_1 = require_identitypoolclient(); + Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function() { + return identitypoolclient_1.IdentityPoolClient; + } }); + var externalclient_1 = require_externalclient(); + Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function() { + return externalclient_1.ExternalAccountClient; + } }); + var baseexternalclient_1 = require_baseexternalclient(); + Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function() { + return baseexternalclient_1.BaseExternalAccountClient; + } }); + var downscopedclient_1 = require_downscopedclient(); + Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function() { + return downscopedclient_1.DownscopedClient; + } }); + var pluggable_auth_client_1 = require_pluggable_auth_client(); + Object.defineProperty(exports, "PluggableAuthClient", { enumerable: true, get: function() { + return pluggable_auth_client_1.PluggableAuthClient; + } }); + Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function() { + return pluggable_auth_client_1.ExecutableError; + } }); + var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient(); + Object.defineProperty(exports, "EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE", { enumerable: true, get: function() { + return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; + } }); + Object.defineProperty(exports, "ExternalAccountAuthorizedUserClient", { enumerable: true, get: function() { + return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient; + } }); + var passthrough_1 = require_passthrough(); + Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function() { + return passthrough_1.PassThroughClient; + } }); + __exportStar(require_googleToken(), exports); + var auth = new googleauth_1.GoogleAuth; + exports.auth = auth; +}); - class UrlSubjectTokenSupplier { - url; - headers; - formatType; - subjectTokenFieldName; - additionalGaxiosOptions; - constructor(opts) { - this.url = opts.url; - this.formatType = opts.formatType; - this.subjectTokenFieldName = opts.subjectTokenFieldName; - this.headers = opts.headers; - this.additionalGaxiosOptions = opts.additionalGaxiosOptions; +// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/fetch/cookies.js +var require_cookies = __commonJS((exports, module) => { + var urllib = __require("url"); + var SESSION_TIMEOUT = 1800; + + class Cookies { + constructor(options) { + this.options = options || {}; + this.cookies = []; } - async getSubjectToken(context) { - const opts = { - ...this.additionalGaxiosOptions, - url: this.url, - method: "GET", - headers: this.headers, - responseType: this.formatType - }; - authclient_1.AuthClient.setMethodName(opts, "getSubjectToken"); - let subjectToken; - if (this.formatType === "text") { - const response = await context.transporter.request(opts); - subjectToken = response.data; - } else if (this.formatType === "json" && this.subjectTokenFieldName) { - const response = await context.transporter.request(opts); - subjectToken = response.data[this.subjectTokenFieldName]; + set(cookieStr, url) { + const urlparts = urllib.parse(url || ""); + const cookie = this.parse(cookieStr); + let domain; + if (cookie.domain) { + domain = cookie.domain.replace(/^\./, ""); + if (urlparts.hostname.length < domain.length || ("." + urlparts.hostname).substr(-domain.length + 1) !== "." + domain) { + cookie.domain = urlparts.hostname; + } + } else { + cookie.domain = urlparts.hostname; } - if (!subjectToken) { - throw new Error("Unable to parse the subject_token from the credential_source URL"); + if (!cookie.path) { + cookie.path = this.getPath(urlparts.pathname); } - return subjectToken; + if (!cookie.expires) { + cookie.expires = new Date(Date.now() + (Number(this.options.sessionTimeout || SESSION_TIMEOUT) || SESSION_TIMEOUT) * 1000); + } + return this.add(cookie); } - } - exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/certificatesubjecttokensupplier.js -var require_certificatesubjecttokensupplier = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CertificateSubjectTokenSupplier = exports.InvalidConfigurationError = exports.CertificateSourceUnavailableError = exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = undefined; - var util_1 = require_util2(); - var fs = __require("fs"); - var crypto_1 = __require("crypto"); - var https = __require("https"); - exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE = "GOOGLE_API_CERTIFICATE_CONFIG"; - - class CertificateSourceUnavailableError extends Error { - constructor(message) { - super(message); - this.name = "CertificateSourceUnavailableError"; - } - } - exports.CertificateSourceUnavailableError = CertificateSourceUnavailableError; - - class InvalidConfigurationError extends Error { - constructor(message) { - super(message); - this.name = "InvalidConfigurationError"; - } - } - exports.InvalidConfigurationError = InvalidConfigurationError; - - class CertificateSubjectTokenSupplier { - certificateConfigPath; - trustChainPath; - cert; - key; - constructor(opts) { - if (!opts.useDefaultCertificateConfig && !opts.certificateConfigLocation) { - throw new InvalidConfigurationError("Either `useDefaultCertificateConfig` must be true or a `certificateConfigLocation` must be provided."); - } - if (opts.useDefaultCertificateConfig && opts.certificateConfigLocation) { - throw new InvalidConfigurationError("Both `useDefaultCertificateConfig` and `certificateConfigLocation` cannot be provided."); - } - this.trustChainPath = opts.trustChainPath; - this.certificateConfigPath = opts.certificateConfigLocation ?? ""; - } - async createMtlsHttpsAgent() { - if (!this.key || !this.cert) { - throw new InvalidConfigurationError("Cannot create mTLS Agent with missing certificate or key"); - } - return new https.Agent({ key: this.key, cert: this.cert }); - } - async getSubjectToken() { - this.certificateConfigPath = await this.#resolveCertificateConfigFilePath(); - const { certPath, keyPath } = await this.#getCertAndKeyPaths(); - ({ cert: this.cert, key: this.key } = await this.#getKeyAndCert(certPath, keyPath)); - return await this.#processChainFromPaths(this.cert); + get(url) { + return this.list(url).map((cookie) => cookie.name + "=" + cookie.value).join("; "); } - async#resolveCertificateConfigFilePath() { - const overridePath = this.certificateConfigPath; - if (overridePath) { - if (await (0, util_1.isValidFile)(overridePath)) { - return overridePath; + list(url) { + const result = []; + for (let i = this.cookies.length - 1;i >= 0; i--) { + const cookie = this.cookies[i]; + if (this.isExpired(cookie)) { + this.cookies.splice(i, 1); + continue; } - throw new CertificateSourceUnavailableError(`Provided certificate config path is invalid: ${overridePath}`); - } - const envPath = process.env[exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE]; - if (envPath) { - if (await (0, util_1.isValidFile)(envPath)) { - return envPath; + if (this.match(cookie, url)) { + result.unshift(cookie); } - throw new CertificateSourceUnavailableError(`Path from environment variable "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" is invalid: ${envPath}`); - } - const wellKnownPath = (0, util_1.getWellKnownCertificateConfigFileLocation)(); - if (await (0, util_1.isValidFile)(wellKnownPath)) { - return wellKnownPath; } - throw new CertificateSourceUnavailableError("Could not find certificate configuration file. Searched override path, " + `the "${exports.CERTIFICATE_CONFIGURATION_ENV_VARIABLE}" env var, and the gcloud path (${wellKnownPath}).`); + return result; } - async#getCertAndKeyPaths() { - const configPath = this.certificateConfigPath; - let fileContents; - try { - fileContents = await fs.promises.readFile(configPath, "utf8"); - } catch (err) { - throw new CertificateSourceUnavailableError(`Failed to read certificate config file at: ${configPath}`); - } - try { - const config = JSON.parse(fileContents); - const certPath = config?.cert_configs?.workload?.cert_path; - const keyPath = config?.cert_configs?.workload?.key_path; - if (!certPath || !keyPath) { - throw new InvalidConfigurationError(`Certificate config file (${configPath}) is missing required "cert_path" or "key_path" in the workload config.`); + parse(cookieStr) { + const cookie = {}; + (cookieStr || "").toString().split(";").forEach((cookiePart) => { + const valueParts = cookiePart.split("="); + const key = valueParts.shift().trim().toLowerCase(); + let value = valueParts.join("=").trim(); + let domain; + if (!key) { + return; } - return { certPath, keyPath }; - } catch (e2) { - if (e2 instanceof InvalidConfigurationError) - throw e2; - throw new InvalidConfigurationError(`Failed to parse certificate config from ${configPath}: ${e2.message}`); - } + switch (key) { + case "expires": + value = new Date(value); + if (value.toString() !== "Invalid Date") { + cookie.expires = value; + } + break; + case "path": + cookie.path = value; + break; + case "domain": + domain = value.toLowerCase(); + if (domain.length && domain.charAt(0) !== ".") { + domain = "." + domain; + } + cookie.domain = domain; + break; + case "max-age": + cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000); + break; + case "secure": + cookie.secure = true; + break; + case "httponly": + cookie.httponly = true; + break; + default: + if (!cookie.name) { + cookie.name = key; + cookie.value = value; + } + } + }); + return cookie; } - async#getKeyAndCert(certPath, keyPath) { - let cert, key; - try { - cert = await fs.promises.readFile(certPath); - new crypto_1.X509Certificate(cert); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - throw new CertificateSourceUnavailableError(`Failed to read certificate file at ${certPath}: ${message}`); + match(cookie, url) { + const urlparts = urllib.parse(url || ""); + if (urlparts.hostname !== cookie.domain && (cookie.domain.charAt(0) !== "." || ("." + urlparts.hostname).substr(-cookie.domain.length) !== cookie.domain)) { + return false; } - try { - key = await fs.promises.readFile(keyPath); - (0, crypto_1.createPrivateKey)(key); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - throw new CertificateSourceUnavailableError(`Failed to read private key file at ${keyPath}: ${message}`); + const path2 = this.getPath(urlparts.pathname); + if (path2.substr(0, cookie.path.length) !== cookie.path) { + return false; } - return { cert, key }; + if (cookie.secure && urlparts.protocol !== "https:") { + return false; + } + return true; } - async#processChainFromPaths(leafCertBuffer) { - const leafCert = new crypto_1.X509Certificate(leafCertBuffer); - if (!this.trustChainPath) { - return JSON.stringify([leafCert.raw.toString("base64")]); + add(cookie) { + if (!cookie || !cookie.name) { + return false; } - try { - const chainPems = await fs.promises.readFile(this.trustChainPath, "utf8"); - const pemBlocks = chainPems.match(/-----BEGIN CERTIFICATE-----[^-]+-----END CERTIFICATE-----/g) ?? []; - const chainCerts = pemBlocks.map((pem, index2) => { - try { - return new crypto_1.X509Certificate(pem); - } catch (err) { - const message = err instanceof Error ? err.message : String(err); - throw new InvalidConfigurationError(`Failed to parse certificate at index ${index2} in trust chain file ${this.trustChainPath}: ${message}`); + for (let i = 0, len = this.cookies.length;i < len; i++) { + if (this.compare(this.cookies[i], cookie)) { + if (this.isExpired(cookie)) { + this.cookies.splice(i, 1); + return false; } - }); - const leafIndex = chainCerts.findIndex((chainCert) => leafCert.raw.equals(chainCert.raw)); - let finalChain; - if (leafIndex === -1) { - finalChain = [leafCert, ...chainCerts]; - } else if (leafIndex === 0) { - finalChain = chainCerts; - } else { - throw new InvalidConfigurationError(`Leaf certificate exists in the trust chain but is not the first entry (found at index ${leafIndex}).`); + this.cookies[i] = cookie; + return true; } - return JSON.stringify(finalChain.map((cert) => cert.raw.toString("base64"))); - } catch (err) { - if (err instanceof InvalidConfigurationError) - throw err; - const message = err instanceof Error ? err.message : String(err); - throw new CertificateSourceUnavailableError(`Failed to process certificate chain from ${this.trustChainPath}: ${message}`); - } - } - } - exports.CertificateSubjectTokenSupplier = CertificateSubjectTokenSupplier; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/identitypoolclient.js -var require_identitypoolclient = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IdentityPoolClient = undefined; - var baseexternalclient_1 = require_baseexternalclient(); - var util_1 = require_util2(); - var filesubjecttokensupplier_1 = require_filesubjecttokensupplier(); - var urlsubjecttokensupplier_1 = require_urlsubjecttokensupplier(); - var certificatesubjecttokensupplier_1 = require_certificatesubjecttokensupplier(); - var stscredentials_1 = require_stscredentials(); - var gaxios_1 = require_src2(); - - class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { - subjectTokenSupplier; - constructor(options) { - super(options); - const opts = (0, util_1.originalOrCamelOptions)(options); - const credentialSource = opts.get("credential_source"); - const subjectTokenSupplier = opts.get("subject_token_supplier"); - if (!credentialSource && !subjectTokenSupplier) { - throw new Error("A credential source or subject token supplier must be specified."); - } - if (credentialSource && subjectTokenSupplier) { - throw new Error("Only one of credential source or subject token supplier can be specified."); } - if (subjectTokenSupplier) { - this.subjectTokenSupplier = subjectTokenSupplier; - this.credentialSourceType = "programmatic"; - } else { - const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); - const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get("format")); - const formatType = formatOpts.get("type") || "text"; - const formatSubjectTokenFieldName = formatOpts.get("subject_token_field_name"); - if (formatType !== "json" && formatType !== "text") { - throw new Error(`Invalid credential_source format "${formatType}"`); - } - if (formatType === "json" && !formatSubjectTokenFieldName) { - throw new Error("Missing subject_token_field_name for JSON credential_source format"); - } - const file = credentialSourceOpts.get("file"); - const url = credentialSourceOpts.get("url"); - const certificate = credentialSourceOpts.get("certificate"); - const headers = credentialSourceOpts.get("headers"); - if (file && url || url && certificate || file && certificate) { - throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); - } else if (file) { - this.credentialSourceType = "file"; - this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ - filePath: file, - formatType, - subjectTokenFieldName: formatSubjectTokenFieldName - }); - } else if (url) { - this.credentialSourceType = "url"; - this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ - url, - formatType, - subjectTokenFieldName: formatSubjectTokenFieldName, - headers, - additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG - }); - } else if (certificate) { - this.credentialSourceType = "certificate"; - const certificateSubjecttokensupplier = new certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier({ - useDefaultCertificateConfig: certificate.use_default_certificate_config, - certificateConfigLocation: certificate.certificate_config_location, - trustChainPath: certificate.trust_chain_path - }); - this.subjectTokenSupplier = certificateSubjecttokensupplier; - } else { - throw new Error('No valid Identity Pool "credential_source" provided, must be either file, url, or certificate.'); - } + if (!this.isExpired(cookie)) { + this.cookies.push(cookie); } + return true; } - async retrieveSubjectToken() { - const subjectToken = await this.subjectTokenSupplier.getSubjectToken(this.supplierContext); - if (this.subjectTokenSupplier instanceof certificatesubjecttokensupplier_1.CertificateSubjectTokenSupplier) { - const mtlsAgent = await this.subjectTokenSupplier.createMtlsHttpsAgent(); - this.stsCredential = new stscredentials_1.StsCredentials({ - tokenExchangeEndpoint: this.getTokenUrl(), - clientAuthentication: this.clientAuth, - transporter: new gaxios_1.Gaxios({ agent: mtlsAgent }) - }); - this.transporter = new gaxios_1.Gaxios({ - ...this.transporter.defaults || {}, - agent: mtlsAgent - }); - } - return subjectToken; + compare(a, b) { + return a.name === b.name && a.path === b.path && a.domain === b.domain && a.secure === b.secure && a.httponly === b.httponly; } - } - exports.IdentityPoolClient = IdentityPoolClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js -var require_awsrequestsigner = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AwsRequestSigner = undefined; - var gaxios_1 = require_src2(); - var crypto_1 = require_crypto3(); - var AWS_ALGORITHM = "AWS4-HMAC-SHA256"; - var AWS_REQUEST_TYPE = "aws4_request"; - - class AwsRequestSigner { - getCredentials; - region; - crypto; - constructor(getCredentials, region) { - this.getCredentials = getCredentials; - this.region = region; - this.crypto = (0, crypto_1.createCrypto)(); + isExpired(cookie) { + return cookie.expires && cookie.expires < new Date || !cookie.value; } - async getRequestOptions(amzOptions) { - if (!amzOptions.url) { - throw new RangeError('"url" is required in "amzOptions"'); - } - const requestPayloadData = typeof amzOptions.data === "object" ? JSON.stringify(amzOptions.data) : amzOptions.data; - const url = amzOptions.url; - const method = amzOptions.method || "GET"; - const requestPayload = amzOptions.body || requestPayloadData; - const additionalAmzHeaders = amzOptions.headers; - const awsSecurityCredentials = await this.getCredentials(); - const uri = new URL(url); - if (typeof requestPayload !== "string" && requestPayload !== undefined) { - throw new TypeError(`'requestPayload' is expected to be a string if provided. Got: ${requestPayload}`); - } - const headerMap = await generateAuthenticationHeaderMap({ - crypto: this.crypto, - host: uri.host, - canonicalUri: uri.pathname, - canonicalQuerystring: uri.search.slice(1), - method, - region: this.region, - securityCredentials: awsSecurityCredentials, - requestPayload, - additionalAmzHeaders - }); - const headers = gaxios_1.Gaxios.mergeHeaders(headerMap.amzDate ? { "x-amz-date": headerMap.amzDate } : {}, { - authorization: headerMap.authorizationHeader, - host: uri.host - }, additionalAmzHeaders || {}); - if (awsSecurityCredentials.token) { - gaxios_1.Gaxios.mergeHeaders(headers, { - "x-amz-security-token": awsSecurityCredentials.token - }); + getPath(pathname) { + let path2 = (pathname || "/").split("/"); + path2.pop(); + path2 = path2.join("/").trim(); + if (path2.charAt(0) !== "/") { + path2 = "/" + path2; } - const awsSignedReq = { - url, - method, - headers - }; - if (requestPayload !== undefined) { - awsSignedReq.body = requestPayload; + if (path2.substr(-1) !== "/") { + path2 += "/"; } - return awsSignedReq; + return path2; } } - exports.AwsRequestSigner = AwsRequestSigner; - async function sign(crypto2, key, msg) { - return await crypto2.signWithHmacSha256(key, msg); - } - async function getSigningKey(crypto2, key, dateStamp, region, serviceName) { - const kDate = await sign(crypto2, `AWS4${key}`, dateStamp); - const kRegion = await sign(crypto2, kDate, region); - const kService = await sign(crypto2, kRegion, serviceName); - const kSigning = await sign(crypto2, kService, "aws4_request"); - return kSigning; - } - async function generateAuthenticationHeaderMap(options) { - const additionalAmzHeaders = gaxios_1.Gaxios.mergeHeaders(options.additionalAmzHeaders); - const requestPayload = options.requestPayload || ""; - const serviceName = options.host.split(".")[0]; - const now = new Date; - const amzDate = now.toISOString().replace(/[-:]/g, "").replace(/\.[0-9]+/, ""); - const dateStamp = now.toISOString().replace(/[-]/g, "").replace(/T.*/, ""); - if (options.securityCredentials.token) { - additionalAmzHeaders.set("x-amz-security-token", options.securityCredentials.token); + module.exports = Cookies; +}); + +// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/package.json +var require_package5 = __commonJS((exports, module) => { + module.exports = { + name: "nodemailer", + version: "8.0.5", + description: "Easy as cake e-mail sending from your Node.js applications", + main: "lib/nodemailer.js", + scripts: { + test: "node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js", + "test:coverage": "c8 node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js", + format: 'prettier --write "**/*.{js,json,md}"', + "format:check": 'prettier --check "**/*.{js,json,md}"', + lint: "eslint .", + "lint:fix": "eslint . --fix", + update: "rm -rf node_modules/ package-lock.json && ncu -u && npm install", + "test:syntax": 'docker run --rm -v "$PWD:/app:ro" -w /app node:6-alpine node test/syntax-compat.js' + }, + repository: { + type: "git", + url: "https://github.com/nodemailer/nodemailer.git" + }, + keywords: [ + "Nodemailer" + ], + author: "Andris Reinman", + license: "MIT-0", + bugs: { + url: "https://github.com/nodemailer/nodemailer/issues" + }, + homepage: "https://nodemailer.com/", + devDependencies: { + "@aws-sdk/client-sesv2": "3.1025.0", + bunyan: "1.8.15", + c8: "11.0.0", + eslint: "10.2.0", + "eslint-config-prettier": "10.1.8", + globals: "17.4.0", + libbase64: "1.3.0", + libmime: "5.3.7", + libqp: "2.1.1", + "nodemailer-ntlm-auth": "1.0.4", + prettier: "3.8.1", + proxy: "1.0.2", + "proxy-test-server": "1.0.0", + "smtp-server": "3.18.3" + }, + engines: { + node: ">=6.0.0" } - const amzHeaders = gaxios_1.Gaxios.mergeHeaders({ - host: options.host - }, additionalAmzHeaders.has("date") ? {} : { "x-amz-date": amzDate }, additionalAmzHeaders); - let canonicalHeaders = ""; - const signedHeadersList = [ - ...amzHeaders.keys() - ].sort(); - signedHeadersList.forEach((key) => { - canonicalHeaders += `${key}:${amzHeaders.get(key)} -`; - }); - const signedHeaders = signedHeadersList.join(";"); - const payloadHash = await options.crypto.sha256DigestHex(requestPayload); - const canonicalRequest = `${options.method.toUpperCase()} -` + `${options.canonicalUri} -` + `${options.canonicalQuerystring} -` + `${canonicalHeaders} -` + `${signedHeaders} -` + `${payloadHash}`; - const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; - const stringToSign = `${AWS_ALGORITHM} -` + `${amzDate} -` + `${credentialScope} -` + await options.crypto.sha256DigestHex(canonicalRequest); - const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); - const signature = await sign(options.crypto, signingKey, stringToSign); - const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + `${credentialScope}, SignedHeaders=${signedHeaders}, ` + `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; - return { - amzDate: additionalAmzHeaders.has("date") ? undefined : amzDate, - authorizationHeader, - canonicalQuerystring: options.canonicalQuerystring - }; - } + }; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js -var require_defaultawssecuritycredentialssupplier = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DefaultAwsSecurityCredentialsSupplier = undefined; - var authclient_1 = require_authclient(); +// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/errors.js +var require_errors3 = __commonJS((exports, module) => { + var ERROR_CODES = { + ECONNECTION: "Connection closed unexpectedly", + ETIMEDOUT: "Connection or operation timed out", + ESOCKET: "Socket-level error", + EDNS: "DNS resolution failed", + ETLS: "TLS handshake or STARTTLS failed", + EREQUIRETLS: "REQUIRETLS not supported by server (RFC 8689)", + EPROTOCOL: "Invalid SMTP server response", + EENVELOPE: "Invalid mail envelope (sender or recipients)", + EMESSAGE: "Message delivery error", + ESTREAM: "Stream processing error", + EAUTH: "Authentication failed", + ENOAUTH: "Authentication credentials not provided", + EOAUTH2: "OAuth2 token generation or refresh error", + EMAXLIMIT: "Pool resource limit reached (max messages per connection)", + ESENDMAIL: "Sendmail command error", + ESES: "AWS SES transport error", + ECONFIG: "Invalid configuration", + EPROXY: "Proxy connection error", + EFILEACCESS: "File access rejected (disableFileAccess is set)", + EURLACCESS: "URL access rejected (disableUrlAccess is set)", + EFETCH: "HTTP fetch error" + }; + module.exports = { ERROR_CODES }; + for (const code of Object.keys(ERROR_CODES)) { + module.exports[code] = code; + } +}); - class DefaultAwsSecurityCredentialsSupplier { - regionUrl; - securityCredentialsUrl; - imdsV2SessionTokenUrl; - additionalGaxiosOptions; - constructor(opts) { - this.regionUrl = opts.regionUrl; - this.securityCredentialsUrl = opts.securityCredentialsUrl; - this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; - this.additionalGaxiosOptions = opts.additionalGaxiosOptions; +// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/fetch/index.js +var require_fetch = __commonJS((exports, module) => { + var http = __require("http"); + var https = __require("https"); + var urllib = __require("url"); + var zlib = __require("zlib"); + var { PassThrough } = __require("stream"); + var Cookies = require_cookies(); + var packageData = require_package5(); + var net = __require("net"); + var errors = require_errors3(); + var MAX_REDIRECTS = 5; + module.exports = function(url, options) { + return nmfetch(url, options); + }; + module.exports.Cookies = Cookies; + function nmfetch(url, options) { + options = options || {}; + options.fetchRes = options.fetchRes || new PassThrough; + options.cookies = options.cookies || new Cookies; + options.redirects = options.redirects || 0; + options.maxRedirects = isNaN(options.maxRedirects) ? MAX_REDIRECTS : options.maxRedirects; + if (options.cookie) { + [].concat(options.cookie || []).forEach((cookie) => { + options.cookies.set(cookie, url); + }); + options.cookie = false; } - async getAwsRegion(context) { - if (this.#regionFromEnv) { - return this.#regionFromEnv; - } - const metadataHeaders = new Headers; - if (!this.#regionFromEnv && this.imdsV2SessionTokenUrl) { - metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context.transporter)); - } - if (!this.regionUrl) { - throw new RangeError("Unable to determine AWS region due to missing " + '"options.credential_source.region_url"'); - } - const opts = { - ...this.additionalGaxiosOptions, - url: this.regionUrl, - method: "GET", - responseType: "text", - headers: metadataHeaders - }; - authclient_1.AuthClient.setMethodName(opts, "getAwsRegion"); - const response = await context.transporter.request(opts); - return response.data.substr(0, response.data.length - 1); + const fetchRes = options.fetchRes; + const parsed = urllib.parse(url); + let method = (options.method || "").toString().trim().toUpperCase() || "GET"; + let finished = false; + let cookies; + let body; + const handler = parsed.protocol === "https:" ? https : http; + const headers = { + "accept-encoding": "gzip,deflate", + "user-agent": "nodemailer/" + packageData.version + }; + Object.keys(options.headers || {}).forEach((key) => { + headers[key.toLowerCase().trim()] = options.headers[key]; + }); + if (options.userAgent) { + headers["user-agent"] = options.userAgent; } - async getAwsSecurityCredentials(context) { - if (this.#securityCredentialsFromEnv) { - return this.#securityCredentialsFromEnv; + if (parsed.auth) { + headers.Authorization = "Basic " + Buffer.from(parsed.auth).toString("base64"); + } + if (cookies = options.cookies.get(url)) { + headers.cookie = cookies; + } + if (options.body) { + if (options.contentType !== false) { + headers["Content-Type"] = options.contentType || "application/x-www-form-urlencoded"; } - const metadataHeaders = new Headers; - if (this.imdsV2SessionTokenUrl) { - metadataHeaders.set("x-aws-ec2-metadata-token", await this.#getImdsV2SessionToken(context.transporter)); + if (typeof options.body.pipe === "function") { + headers["Transfer-Encoding"] = "chunked"; + body = options.body; + body.on("error", (err) => { + if (finished) { + return; + } + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + }); + } else { + if (options.body instanceof Buffer) { + body = options.body; + } else if (typeof options.body === "object") { + try { + body = Buffer.from(Object.keys(options.body).map((key) => { + const value = options.body[key].toString().trim(); + return encodeURIComponent(key) + "=" + encodeURIComponent(value); + }).join("&")); + } catch (E2) { + if (finished) { + return; + } + finished = true; + E2.code = errors.EFETCH; + E2.sourceUrl = url; + fetchRes.emit("error", E2); + return; + } + } else { + body = Buffer.from(options.body.toString().trim()); + } + headers["Content-Type"] = options.contentType || "application/x-www-form-urlencoded"; + headers["Content-Length"] = body.length; } - const roleName = await this.#getAwsRoleName(metadataHeaders, context.transporter); - const awsCreds = await this.#retrieveAwsSecurityCredentials(roleName, metadataHeaders, context.transporter); - return { - accessKeyId: awsCreds.AccessKeyId, - secretAccessKey: awsCreds.SecretAccessKey, - token: awsCreds.Token - }; + method = (options.method || "").toString().trim().toUpperCase() || "POST"; } - async#getImdsV2SessionToken(transporter) { - const opts = { - ...this.additionalGaxiosOptions, - url: this.imdsV2SessionTokenUrl, - method: "PUT", - responseType: "text", - headers: { "x-aws-ec2-metadata-token-ttl-seconds": "300" } - }; - authclient_1.AuthClient.setMethodName(opts, "#getImdsV2SessionToken"); - const response = await transporter.request(opts); - return response.data; + let req; + const reqOptions = { + method, + host: parsed.hostname, + path: parsed.path, + port: parsed.port ? parsed.port : parsed.protocol === "https:" ? 443 : 80, + headers, + rejectUnauthorized: false, + agent: false + }; + if (options.tls) { + Object.assign(reqOptions, options.tls); } - async#getAwsRoleName(headers, transporter) { - if (!this.securityCredentialsUrl) { - throw new Error("Unable to determine AWS role name due to missing " + '"options.credential_source.url"'); - } - const opts = { - ...this.additionalGaxiosOptions, - url: this.securityCredentialsUrl, - method: "GET", - responseType: "text", - headers - }; - authclient_1.AuthClient.setMethodName(opts, "#getAwsRoleName"); - const response = await transporter.request(opts); - return response.data; + if (parsed.protocol === "https:" && parsed.hostname && parsed.hostname !== reqOptions.host && !net.isIP(parsed.hostname) && !reqOptions.servername) { + reqOptions.servername = parsed.hostname; } - async#retrieveAwsSecurityCredentials(roleName, headers, transporter) { - const opts = { - ...this.additionalGaxiosOptions, - url: `${this.securityCredentialsUrl}/${roleName}`, - headers, - responseType: "json" - }; - authclient_1.AuthClient.setMethodName(opts, "#retrieveAwsSecurityCredentials"); - const response = await transporter.request(opts); - return response.data; + try { + req = handler.request(reqOptions); + } catch (E2) { + finished = true; + setImmediate(() => { + E2.code = errors.EFETCH; + E2.sourceUrl = url; + fetchRes.emit("error", E2); + }); + return fetchRes; } - get #regionFromEnv() { - return process.env["AWS_REGION"] || process.env["AWS_DEFAULT_REGION"] || null; + if (options.timeout) { + req.setTimeout(options.timeout, () => { + if (finished) { + return; + } + finished = true; + req.abort(); + const err = new Error("Request Timeout"); + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + }); } - get #securityCredentialsFromEnv() { - if (process.env["AWS_ACCESS_KEY_ID"] && process.env["AWS_SECRET_ACCESS_KEY"]) { - return { - accessKeyId: process.env["AWS_ACCESS_KEY_ID"], - secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"], - token: process.env["AWS_SESSION_TOKEN"] - }; + req.on("error", (err) => { + if (finished) { + return; } - return null; - } - } - exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/awsclient.js -var require_awsclient = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.AwsClient = undefined; - var awsrequestsigner_1 = require_awsrequestsigner(); - var baseexternalclient_1 = require_baseexternalclient(); - var defaultawssecuritycredentialssupplier_1 = require_defaultawssecuritycredentialssupplier(); - var util_1 = require_util2(); - var gaxios_1 = require_src2(); - - class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { - environmentId; - awsSecurityCredentialsSupplier; - regionalCredVerificationUrl; - awsRequestSigner; - region; - static #DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = "https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15"; - static AWS_EC2_METADATA_IPV4_ADDRESS = "169.254.169.254"; - static AWS_EC2_METADATA_IPV6_ADDRESS = "fd00:ec2::254"; - constructor(options) { - super(options); - const opts = (0, util_1.originalOrCamelOptions)(options); - const credentialSource = opts.get("credential_source"); - const awsSecurityCredentialsSupplier = opts.get("aws_security_credentials_supplier"); - if (!credentialSource && !awsSecurityCredentialsSupplier) { - throw new Error("A credential source or AWS security credentials supplier must be specified."); + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + }); + req.on("response", (res) => { + let inflate; + if (finished) { + return; } - if (credentialSource && awsSecurityCredentialsSupplier) { - throw new Error("Only one of credential source or AWS security credentials supplier can be specified."); + switch (res.headers["content-encoding"]) { + case "gzip": + case "deflate": + inflate = zlib.createUnzip(); + break; } - if (awsSecurityCredentialsSupplier) { - this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; - this.regionalCredVerificationUrl = AwsClient.#DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; - this.credentialSourceType = "programmatic"; - } else { - const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); - this.environmentId = credentialSourceOpts.get("environment_id"); - const regionUrl = credentialSourceOpts.get("region_url"); - const securityCredentialsUrl = credentialSourceOpts.get("url"); - const imdsV2SessionTokenUrl = credentialSourceOpts.get("imdsv2_session_token_url"); - this.awsSecurityCredentialsSupplier = new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ - regionUrl, - securityCredentialsUrl, - imdsV2SessionTokenUrl + if (res.headers["set-cookie"]) { + [].concat(res.headers["set-cookie"] || []).forEach((cookie) => { + options.cookies.set(cookie, url); }); - this.regionalCredVerificationUrl = credentialSourceOpts.get("regional_cred_verification_url"); - this.credentialSourceType = "aws"; - this.validateEnvironmentId(); - } - this.awsRequestSigner = null; - this.region = ""; - } - validateEnvironmentId() { - const match = this.environmentId?.match(/^(aws)(\d+)$/); - if (!match || !this.regionalCredVerificationUrl) { - throw new Error('No valid AWS "credential_source" provided'); - } else if (parseInt(match[2], 10) !== 1) { - throw new Error(`aws version "${match[2]}" is not supported in the current build.`); - } - } - async retrieveSubjectToken() { - if (!this.awsRequestSigner) { - this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); - this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { - return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); - }, this.region); } - const options = await this.awsRequestSigner.getRequestOptions({ - ...AwsClient.RETRY_CONFIG, - url: this.regionalCredVerificationUrl.replace("{region}", this.region), - method: "POST" - }); - const reformattedHeader = []; - const extendedHeaders = gaxios_1.Gaxios.mergeHeaders({ - "x-goog-cloud-target-resource": this.audience - }, options.headers); - extendedHeaders.forEach((value, key) => reformattedHeader.push({ key, value })); - return encodeURIComponent(JSON.stringify({ - url: options.url, - method: options.method, - headers: reformattedHeader - })); - } - } - exports.AwsClient = AwsClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/executable-response.js -var require_executable_response = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = undefined; - var SAML_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:saml2"; - var OIDC_SUBJECT_TOKEN_TYPE1 = "urn:ietf:params:oauth:token-type:id_token"; - var OIDC_SUBJECT_TOKEN_TYPE2 = "urn:ietf:params:oauth:token-type:jwt"; - - class ExecutableResponse { - version; - success; - expirationTime; - tokenType; - errorCode; - errorMessage; - subjectToken; - constructor(responseJson) { - if (!responseJson.version) { - throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); + if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) { + options.redirects++; + if (options.redirects > options.maxRedirects) { + finished = true; + const err = new Error("Maximum redirect count exceeded"); + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + req.abort(); + return; + } + options.method = "GET"; + options.body = false; + return nmfetch(urllib.resolve(url, res.headers.location), options); } - if (responseJson.success === undefined) { - throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); + fetchRes.statusCode = res.statusCode; + fetchRes.headers = res.headers; + if (res.statusCode >= 300 && !options.allowErrorResponse) { + finished = true; + const err = new Error("Invalid status code " + res.statusCode); + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + req.abort(); + return; } - this.version = responseJson.version; - this.success = responseJson.success; - if (this.success) { - this.expirationTime = responseJson.expiration_time; - this.tokenType = responseJson.token_type; - if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { - throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); + res.on("error", (err) => { + if (finished) { + return; } - if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { - if (!responseJson.saml_response) { - throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); - } - this.subjectToken = responseJson.saml_response; - } else { - if (!responseJson.id_token) { - throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + req.abort(); + }); + if (inflate) { + res.pipe(inflate).pipe(fetchRes); + inflate.on("error", (err) => { + if (finished) { + return; } - this.subjectToken = responseJson.id_token; - } + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + req.abort(); + }); } else { - if (!responseJson.code) { - throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); - } - if (!responseJson.message) { - throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); + res.pipe(fetchRes); + } + }); + setImmediate(() => { + if (body) { + try { + if (typeof body.pipe === "function") { + return body.pipe(req); + } + req.write(body); + } catch (err) { + finished = true; + err.code = errors.EFETCH; + err.sourceUrl = url; + fetchRes.emit("error", err); + return; } - this.errorCode = responseJson.code; - this.errorMessage = responseJson.message; } - } - isValid() { - return !this.isExpired() && this.success; - } - isExpired() { - return this.expirationTime !== undefined && this.expirationTime < Math.round(Date.now() / 1000); - } - } - exports.ExecutableResponse = ExecutableResponse; - - class ExecutableResponseError extends Error { - constructor(message) { - super(message); - Object.setPrototypeOf(this, new.target.prototype); - } - } - exports.ExecutableResponseError = ExecutableResponseError; - - class InvalidVersionFieldError extends ExecutableResponseError { - } - exports.InvalidVersionFieldError = InvalidVersionFieldError; - - class InvalidSuccessFieldError extends ExecutableResponseError { - } - exports.InvalidSuccessFieldError = InvalidSuccessFieldError; - - class InvalidExpirationTimeFieldError extends ExecutableResponseError { - } - exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; - - class InvalidTokenTypeFieldError extends ExecutableResponseError { - } - exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; - - class InvalidCodeFieldError extends ExecutableResponseError { - } - exports.InvalidCodeFieldError = InvalidCodeFieldError; - - class InvalidMessageFieldError extends ExecutableResponseError { - } - exports.InvalidMessageFieldError = InvalidMessageFieldError; - - class InvalidSubjectTokenError extends ExecutableResponseError { + req.end(); + }); + return fetchRes; } - exports.InvalidSubjectTokenError = InvalidSubjectTokenError; }); -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js -var require_pluggable_auth_handler = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PluggableAuthHandler = exports.ExecutableError = undefined; - var executable_response_1 = require_executable_response(); - var childProcess = __require("child_process"); +// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/shared/index.js +var require_shared3 = __commonJS((exports, module) => { + var urllib = __require("url"); + var util = __require("util"); var fs = __require("fs"); - - class ExecutableError extends Error { - code; - constructor(message, code) { - super(`The executable failed with exit code: ${code} and error message: ${message}.`); - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } - } - exports.ExecutableError = ExecutableError; - - class PluggableAuthHandler { - commandComponents; - timeoutMillis; - outputFile; - constructor(options) { - if (!options.command) { - throw new Error("No command provided."); - } - this.commandComponents = PluggableAuthHandler.parseCommand(options.command); - this.timeoutMillis = options.timeoutMillis; - if (!this.timeoutMillis) { - throw new Error("No timeoutMillis provided."); - } - this.outputFile = options.outputFile; + var nmfetch = require_fetch(); + var dns = __require("dns"); + var net = __require("net"); + var os = __require("os"); + var DNS_TTL = 5 * 60 * 1000; + var CACHE_CLEANUP_INTERVAL = 30 * 1000; + var MAX_CACHE_SIZE = 1000; + var lastCacheCleanup = 0; + exports._lastCacheCleanup = () => lastCacheCleanup; + exports._resetCacheCleanup = () => { + lastCacheCleanup = 0; + }; + var networkInterfaces; + try { + networkInterfaces = os.networkInterfaces(); + } catch (_err) {} + exports.networkInterfaces = networkInterfaces; + var isFamilySupported = (family, allowInternal) => { + const ifaces = exports.networkInterfaces; + if (!ifaces) { + return true; } - retrieveResponseFromExecutable(envMap) { - return new Promise((resolve, reject) => { - const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { - env: { ...process.env, ...Object.fromEntries(envMap) } - }); - let output = ""; - child.stdout.on("data", (data) => { - output += data; - }); - child.stderr.on("data", (err) => { - output += err; - }); - const timeout = setTimeout(() => { - child.removeAllListeners(); - child.kill(); - return reject(new Error("The executable failed to finish within the timeout specified.")); - }, this.timeoutMillis); - child.on("close", (code) => { - clearTimeout(timeout); - if (code === 0) { - try { - const responseJson = JSON.parse(output); - const response = new executable_response_1.ExecutableResponse(responseJson); - return resolve(response); - } catch (error) { - if (error instanceof executable_response_1.ExecutableResponseError) { - return reject(error); - } - return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); - } - } else { - return reject(new ExecutableError(output, code.toString())); - } - }); - }); + return Object.keys(ifaces).map((key) => ifaces[key]).reduce((acc, val) => acc.concat(val), []).filter((i) => !i.internal || allowInternal).some((i) => i.family === "IPv" + family || i.family === family); + }; + var resolve = (family, hostname, options, callback) => { + options = options || {}; + if (!isFamilySupported(family, options.allowInternalNetworkInterfaces)) { + return callback(null, []); } - async retrieveCachedResponse() { - if (!this.outputFile || this.outputFile.length === 0) { - return; - } - let filePath; - try { - filePath = await fs.promises.realpath(this.outputFile); - } catch { - return; - } - if (!(await fs.promises.lstat(filePath)).isFile()) { - return; - } - const responseString = await fs.promises.readFile(filePath, { - encoding: "utf8" - }); - if (responseString === "") { - return; - } - try { - const responseJson = JSON.parse(responseString); - const response = new executable_response_1.ExecutableResponse(responseJson); - if (response.isValid()) { - return new executable_response_1.ExecutableResponse(responseJson); - } - return; - } catch (error) { - if (error instanceof executable_response_1.ExecutableResponseError) { - throw error; + const dnsResolver = dns.Resolver ? new dns.Resolver(options) : dns; + dnsResolver["resolve" + family](hostname, (err, addresses) => { + if (err) { + switch (err.code) { + case dns.NODATA: + case dns.NOTFOUND: + case dns.NOTIMP: + case dns.SERVFAIL: + case dns.CONNREFUSED: + case dns.REFUSED: + case "EAI_AGAIN": + return callback(null, []); } - throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); + return callback(err); } + return callback(null, Array.isArray(addresses) ? addresses : [].concat(addresses || [])); + }); + }; + var dnsCache = exports.dnsCache = new Map; + var formatDNSValue = (value, extra) => { + if (!value) { + return Object.assign({}, extra || {}); } - static parseCommand(command) { - const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); - if (!components) { - throw new Error(`Provided command: "${command}" could not be parsed.`); - } - for (let i = 0;i < components.length; i++) { - if (components[i][0] === '"' && components[i].slice(-1) === '"') { - components[i] = components[i].slice(1, -1); - } - } - return components; + const addresses = value.addresses || []; + const host = addresses.length > 0 ? addresses[Math.floor(Math.random() * addresses.length)] : null; + return Object.assign({ + servername: value.servername, + host, + _addresses: addresses + }, extra || {}); + }; + exports.resolveHostname = (options, callback) => { + options = options || {}; + if (!options.host && options.servername) { + options.host = options.servername; } - } - exports.PluggableAuthHandler = PluggableAuthHandler; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js -var require_pluggable_auth_client = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PluggableAuthClient = exports.ExecutableError = undefined; - var baseexternalclient_1 = require_baseexternalclient(); - var executable_response_1 = require_executable_response(); - var pluggable_auth_handler_1 = require_pluggable_auth_handler(); - var pluggable_auth_handler_2 = require_pluggable_auth_handler(); - Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function() { - return pluggable_auth_handler_2.ExecutableError; - } }); - var DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; - var MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; - var MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; - var GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = "GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES"; - var MAXIMUM_EXECUTABLE_VERSION = 1; - - class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { - command; - timeoutMillis; - outputFile; - handler; - constructor(options) { - super(options); - if (!options.credential_source.executable) { - throw new Error('No valid Pluggable Auth "credential_source" provided.'); - } - this.command = options.credential_source.executable.command; - if (!this.command) { - throw new Error('No valid Pluggable Auth "credential_source" provided.'); - } - if (options.credential_source.executable.timeout_millis === undefined) { - this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; - } else { - this.timeoutMillis = options.credential_source.executable.timeout_millis; - if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { - throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); - } - } - this.outputFile = options.credential_source.executable.output_file; - this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ - command: this.command, - timeoutMillis: this.timeoutMillis, - outputFile: this.outputFile - }); - this.credentialSourceType = "executable"; + if (!options.host || net.isIP(options.host)) { + const value = { + addresses: [options.host], + servername: options.servername || false + }; + return callback(null, formatDNSValue(value, { + cached: false + })); } - async retrieveSubjectToken() { - if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== "1") { - throw new Error("Pluggable Auth executables need to be explicitly allowed to run by " + "setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment " + "Variable to 1."); - } - let executableResponse = undefined; - if (this.outputFile) { - executableResponse = await this.handler.retrieveCachedResponse(); - } - if (!executableResponse) { - const envMap = new Map; - envMap.set("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE", this.audience); - envMap.set("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE", this.subjectTokenType); - envMap.set("GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE", "0"); - if (this.outputFile) { - envMap.set("GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE", this.outputFile); - } - const serviceAccountEmail = this.getServiceAccountEmail(); - if (serviceAccountEmail) { - envMap.set("GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL", serviceAccountEmail); + let cached; + if (dnsCache.has(options.host)) { + cached = dnsCache.get(options.host); + const now = Date.now(); + if (now - lastCacheCleanup > CACHE_CLEANUP_INTERVAL) { + lastCacheCleanup = now; + for (const [host, entry] of dnsCache.entries()) { + if (entry.expires && entry.expires < now) { + dnsCache.delete(host); + } } - executableResponse = await this.handler.retrieveResponseFromExecutable(envMap); - } - if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { - throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); - } - if (!executableResponse.success) { - throw new pluggable_auth_handler_1.ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); - } - if (this.outputFile) { - if (!executableResponse.expirationTime) { - throw new executable_response_1.InvalidExpirationTimeFieldError("The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration."); + if (dnsCache.size > MAX_CACHE_SIZE) { + const toDelete = Math.floor(MAX_CACHE_SIZE * 0.1); + const keys = Array.from(dnsCache.keys()).slice(0, toDelete); + keys.forEach((key) => dnsCache.delete(key)); } } - if (executableResponse.isExpired()) { - throw new Error("Executable response is expired."); + if (!cached.expires || cached.expires >= now) { + return callback(null, formatDNSValue(cached.value, { + cached: true + })); } - return executableResponse.subjectToken; - } - } - exports.PluggableAuthClient = PluggableAuthClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/externalclient.js -var require_externalclient = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ExternalAccountClient = undefined; - var baseexternalclient_1 = require_baseexternalclient(); - var identitypoolclient_1 = require_identitypoolclient(); - var awsclient_1 = require_awsclient(); - var pluggable_auth_client_1 = require_pluggable_auth_client(); - - class ExternalAccountClient { - constructor() { - throw new Error("ExternalAccountClients should be initialized via: " + "ExternalAccountClient.fromJSON(), " + "directly via explicit constructors, eg. " + "new AwsClient(options), new IdentityPoolClient(options), new" + "PluggableAuthClientOptions, or via " + "new GoogleAuth(options).getClient()"); } - static fromJSON(options) { - if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { - if (options.credential_source?.environment_id) { - return new awsclient_1.AwsClient(options); - } else if (options.credential_source?.executable) { - return new pluggable_auth_client_1.PluggableAuthClient(options); - } else { - return new identitypoolclient_1.IdentityPoolClient(options); - } + let ipv4Addresses = []; + let ipv6Addresses = []; + let ipv4Error = null; + let ipv6Error = null; + resolve(4, options.host, options, (err, addresses) => { + if (err) { + ipv4Error = err; } else { - return null; + ipv4Addresses = addresses || []; } + resolve(6, options.host, options, (err2, addresses2) => { + if (err2) { + ipv6Error = err2; + } else { + ipv6Addresses = addresses2 || []; + } + const allAddresses = ipv4Addresses.concat(ipv6Addresses); + if (allAddresses.length) { + const value = { + addresses: allAddresses, + servername: options.servername || options.host + }; + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + return callback(null, formatDNSValue(value, { + cached: false + })); + } + if (ipv4Error && ipv6Error) { + if (cached) { + dnsCache.set(options.host, { + value: cached.value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + return callback(null, formatDNSValue(cached.value, { + cached: true, + error: ipv4Error + })); + } + } + try { + dns.lookup(options.host, { all: true }, (err3, addresses3) => { + if (err3) { + if (cached) { + dnsCache.set(options.host, { + value: cached.value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + return callback(null, formatDNSValue(cached.value, { + cached: true, + error: err3 + })); + } + return callback(err3); + } + const supportedAddresses = addresses3 ? addresses3.filter((addr) => isFamilySupported(addr.family)).map((addr) => addr.address) : []; + if (addresses3 && addresses3.length && !supportedAddresses.length) { + console.warn(`Failed to resolve IPv${addresses3[0].family} addresses with current network`); + } + if (!supportedAddresses.length && cached) { + return callback(null, formatDNSValue(cached.value, { + cached: true + })); + } + const value = { + addresses: supportedAddresses.length ? supportedAddresses : [options.host], + servername: options.servername || options.host + }; + dnsCache.set(options.host, { + value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + return callback(null, formatDNSValue(value, { + cached: false + })); + }); + } catch (lookupErr) { + if (cached) { + dnsCache.set(options.host, { + value: cached.value, + expires: Date.now() + (options.dnsTtl || DNS_TTL) + }); + return callback(null, formatDNSValue(cached.value, { + cached: true, + error: lookupErr + })); + } + return callback(ipv4Error || ipv6Error || lookupErr); + } + }); + }); + }; + exports.parseConnectionUrl = (str) => { + str = str || ""; + const options = {}; + const url = urllib.parse(str, true); + switch (url.protocol) { + case "smtp:": + options.secure = false; + break; + case "smtps:": + options.secure = true; + break; + case "direct:": + options.direct = true; + break; } - } - exports.ExternalAccountClient = ExternalAccountClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js -var require_externalAccountAuthorizedUserClient = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = undefined; - var authclient_1 = require_authclient(); - var oauth2common_1 = require_oauth2common(); - var gaxios_1 = require_src2(); - var stream = __require("stream"); - var baseexternalclient_1 = require_baseexternalclient(); - exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = "external_account_authorized_user"; - var DEFAULT_TOKEN_URL = "https://sts.{universeDomain}/v1/oauthtoken"; - - class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { - #tokenRefreshEndpoint; - constructor(options) { - super(options); - this.#tokenRefreshEndpoint = options.tokenRefreshEndpoint; + if (!isNaN(url.port) && Number(url.port)) { + options.port = Number(url.port); } - async refreshToken(refreshToken, headers) { - const opts = { - ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, - url: this.#tokenRefreshEndpoint, - method: "POST", - headers, - data: new URLSearchParams({ - grant_type: "refresh_token", - refresh_token: refreshToken - }), - responseType: "json" - }; - authclient_1.AuthClient.setMethodName(opts, "refreshToken"); - this.applyClientAuthenticationOptions(opts); - try { - const response = await this.transporter.request(opts); - const tokenRefreshResponse = response.data; - tokenRefreshResponse.res = response; - return tokenRefreshResponse; - } catch (error) { - if (error instanceof gaxios_1.GaxiosError && error.response) { - throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, error); - } - throw error; - } + if (url.hostname) { + options.host = url.hostname; } - } - - class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { - cachedAccessToken; - externalAccountAuthorizedUserHandler; - refreshToken; - constructor(options) { - super(options); - if (options.universe_domain) { - this.universeDomain = options.universe_domain; - } - this.refreshToken = options.refresh_token; - const clientAuthentication = { - confidentialClientType: "basic", - clientId: options.client_id, - clientSecret: options.client_secret + if (url.auth) { + const auth = url.auth.split(":"); + options.auth = { + user: auth.shift(), + pass: auth.join(":") }; - this.externalAccountAuthorizedUserHandler = new ExternalAccountAuthorizedUserHandler({ - tokenRefreshEndpoint: options.token_url ?? DEFAULT_TOKEN_URL.replace("{universeDomain}", this.universeDomain), - transporter: this.transporter, - clientAuthentication - }); - this.cachedAccessToken = null; - this.quotaProjectId = options.quota_project_id; - if (typeof options?.eagerRefreshThresholdMillis !== "number") { - this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; - } else { - this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis; - } - this.forceRefreshOnFailure = !!options?.forceRefreshOnFailure; } - async getAccessToken() { - if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { - await this.refreshAccessTokenAsync(); + Object.keys(url.query || {}).forEach((key) => { + let obj = options; + let lKey = key; + let value = url.query[key]; + if (!isNaN(value)) { + value = Number(value); } - return { - token: this.cachedAccessToken.access_token, - res: this.cachedAccessToken.res - }; - } - async getRequestHeaders() { - const accessTokenResponse = await this.getAccessToken(); - const headers = new Headers({ - authorization: `Bearer ${accessTokenResponse.token}` - }); - return this.addSharedMetadataHeaders(headers); - } - request(opts, callback) { - if (callback) { - this.requestAsync(opts).then((r) => callback(null, r), (e2) => { - return callback(e2, e2.response); - }); - } else { - return this.requestAsync(opts); + switch (value) { + case "true": + value = true; + break; + case "false": + value = false; + break; } - } - async requestAsync(opts, reAuthRetried = false) { - let response; - try { - const requestHeaders = await this.getRequestHeaders(); - opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); - this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); - response = await this.transporter.request(opts); - } catch (e2) { - const res = e2.response; - if (res) { - const statusCode = res.status; - const isReadableStream = res.config.data instanceof stream.Readable; - const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { - await this.refreshAccessTokenAsync(); - return await this.requestAsync(opts, true); - } + if (key.indexOf("tls.") === 0) { + lKey = key.substr(4); + if (!options.tls) { + options.tls = {}; } - throw e2; + obj = options.tls; + } else if (key.indexOf(".") >= 0) { + return; } + if (!(lKey in obj)) { + obj[lKey] = value; + } + }); + return options; + }; + exports._logFunc = (logger, level, defaults2, data, message, ...args) => { + const entry = Object.assign({}, defaults2 || {}, data || {}); + delete entry.level; + logger[level](entry, message, ...args); + }; + exports.getLogger = (options, defaults2) => { + options = options || {}; + const response = {}; + const levels = ["trace", "debug", "info", "warn", "error", "fatal"]; + if (!options.logger) { + levels.forEach((level) => { + response[level] = () => false; + }); return response; } - async refreshAccessTokenAsync() { - const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); - this.cachedAccessToken = { - access_token: refreshResponse.access_token, - expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, - res: refreshResponse.res + const logger = options.logger === true ? createDefaultLogger(levels) : options.logger; + levels.forEach((level) => { + response[level] = (data, message, ...args) => { + exports._logFunc(logger, level, defaults2, data, message, ...args); }; - if (refreshResponse.refresh_token !== undefined) { - this.refreshToken = refreshResponse.refresh_token; - } - return this.cachedAccessToken; - } - isExpired(credentials) { - const now = new Date().getTime(); - return credentials.expiry_date ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis : false; + }); + return response; + }; + exports.callbackPromise = (resolve2, reject) => function() { + const args = Array.from(arguments); + const err = args.shift(); + if (err) { + reject(err); + } else { + resolve2(...args); } - } - exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/googleauth.js -var require_googleauth = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GoogleAuth = exports.GoogleAuthExceptionMessages = undefined; - var child_process_1 = __require("child_process"); - var fs = __require("fs"); - var gaxios_1 = require_src2(); - var gcpMetadata = require_src4(); - var os = __require("os"); - var path2 = __require("path"); - var crypto_1 = require_crypto3(); - var computeclient_1 = require_computeclient(); - var idtokenclient_1 = require_idtokenclient(); - var envDetect_1 = require_envDetect(); - var jwtclient_1 = require_jwtclient(); - var refreshclient_1 = require_refreshclient(); - var impersonated_1 = require_impersonated(); - var externalclient_1 = require_externalclient(); - var baseexternalclient_1 = require_baseexternalclient(); - var authclient_1 = require_authclient(); - var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient(); - var util_1 = require_util2(); - exports.GoogleAuthExceptionMessages = { - API_KEY_WITH_CREDENTIALS: "API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.", - NO_PROJECT_ID_FOUND: `Unable to detect a Project Id in the current environment. -` + `To learn more about authentication and Google APIs, visit: -` + "https://cloud.google.com/docs/authentication/getting-started", - NO_CREDENTIALS_FOUND: `Unable to find credentials in current environment. -` + `To learn more about authentication and Google APIs, visit: -` + "https://cloud.google.com/docs/authentication/getting-started", - NO_ADC_FOUND: "Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.", - NO_UNIVERSE_DOMAIN_FOUND: `Unable to detect a Universe Domain in the current environment. -` + `To learn more about Universe Domain retrieval, visit: -` + "https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys" }; - - class GoogleAuth { - checkIsGCE = undefined; - useJWTAccessWithScope; - defaultServicePath; - get isGCE() { - return this.checkIsGCE; + exports.parseDataURI = (uri) => { + if (typeof uri !== "string") { + return null; } - _findProjectIdPromise; - _cachedProjectId; - jsonContent = null; - apiKey; - cachedCredential = null; - #pendingAuthClient = null; - defaultScopes; - keyFilename; - scopes; - clientOptions = {}; - constructor(opts = {}) { - this._cachedProjectId = opts.projectId || null; - this.cachedCredential = opts.authClient || null; - this.keyFilename = opts.keyFilename || opts.keyFile; - this.scopes = opts.scopes; - this.clientOptions = opts.clientOptions || {}; - this.jsonContent = opts.credentials || null; - this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; - if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { - throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); - } - if (opts.universeDomain) { - this.clientOptions.universeDomain = opts.universeDomain; - } + if (!uri.startsWith("data:")) { + return null; } - setGapicJWTValues(client) { - client.defaultServicePath = this.defaultServicePath; - client.useJWTAccessWithScope = this.useJWTAccessWithScope; - client.defaultScopes = this.defaultScopes; + const commaPos = uri.indexOf(","); + if (commaPos === -1) { + return null; } - getProjectId(callback) { - if (callback) { - this.getProjectIdAsync().then((r) => callback(null, r), callback); - } else { - return this.getProjectIdAsync(); + const data = uri.substring(commaPos + 1); + const metaStr = uri.substring("data:".length, commaPos); + let encoding; + const metaEntries = metaStr.split(";"); + if (metaEntries.length > 0) { + const lastEntry = metaEntries[metaEntries.length - 1].toLowerCase().trim(); + if (["base64", "utf8", "utf-8"].includes(lastEntry) && lastEntry.indexOf("=") === -1) { + encoding = lastEntry; + metaEntries.pop(); } } - async getProjectIdOptional() { - try { - return await this.getProjectId(); - } catch (e2) { - if (e2 instanceof Error && e2.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { - return null; - } else { - throw e2; + const contentType = metaEntries.length > 0 ? metaEntries.shift() : "application/octet-stream"; + const params = {}; + for (let i = 0;i < metaEntries.length; i++) { + const entry = metaEntries[i]; + const sepPos = entry.indexOf("="); + if (sepPos > 0) { + const key = entry.substring(0, sepPos).trim(); + const value = entry.substring(sepPos + 1).trim(); + if (key) { + params[key] = value; } } } - async findAndCacheProjectId() { - let projectId = null; - projectId ||= await this.getProductionProjectId(); - projectId ||= await this.getFileProjectId(); - projectId ||= await this.getDefaultServiceProjectId(); - projectId ||= await this.getGCEProjectId(); - projectId ||= await this.getExternalAccountClientProjectId(); - if (projectId) { - this._cachedProjectId = projectId; - return projectId; + let bufferData; + try { + if (encoding === "base64") { + bufferData = Buffer.from(data, "base64"); } else { - throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); + try { + bufferData = Buffer.from(decodeURIComponent(data)); + } catch (_decodeError) { + bufferData = Buffer.from(data); + } } + } catch (_bufferError) { + bufferData = Buffer.alloc(0); } - async getProjectIdAsync() { - if (this._cachedProjectId) { - return this._cachedProjectId; - } - if (!this._findProjectIdPromise) { - this._findProjectIdPromise = this.findAndCacheProjectId(); - } - return this._findProjectIdPromise; + return { + data: bufferData, + encoding: encoding || null, + contentType: contentType || "application/octet-stream", + params + }; + }; + exports.resolveContent = (data, key, callback) => { + let promise; + if (!callback) { + promise = new Promise((resolve2, reject) => { + callback = exports.callbackPromise(resolve2, reject); + }); } - async getUniverseDomainFromMetadataServer() { - let universeDomain; - try { - universeDomain = await gcpMetadata.universe("universe-domain"); - universeDomain ||= authclient_1.DEFAULT_UNIVERSE; - } catch (e2) { - if (e2 && e2?.response?.status === 404) { - universeDomain = authclient_1.DEFAULT_UNIVERSE; - } else { - throw e2; + let content = data && data[key] && data[key].content || data[key]; + const encoding = (typeof data[key] === "object" && data[key].encoding || "utf8").toString().toLowerCase().replace(/[-_\s]/g, ""); + if (!content) { + return callback(null, content); + } + if (typeof content === "object") { + if (typeof content.pipe === "function") { + return resolveStream(content, (err, value) => { + if (err) { + return callback(err); + } + if (data[key].content) { + data[key].content = value; + } else { + data[key] = value; + } + callback(null, value); + }); + } else if (/^https?:\/\//i.test(content.path || content.href)) { + return resolveStream(nmfetch(content.path || content.href), callback); + } else if (/^data:/i.test(content.path || content.href)) { + const parsedDataUri = exports.parseDataURI(content.path || content.href); + if (!parsedDataUri || !parsedDataUri.data) { + return callback(null, Buffer.from(0)); } + return callback(null, parsedDataUri.data); + } else if (content.path) { + return resolveStream(fs.createReadStream(content.path), callback); } - return universeDomain; } - async getUniverseDomain() { - let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get("universe_domain"); - try { - universeDomain ??= (await this.getClient()).universeDomain; - } catch { - universeDomain ??= authclient_1.DEFAULT_UNIVERSE; - } - return universeDomain; + if (typeof data[key].content === "string" && !["utf8", "usascii", "ascii"].includes(encoding)) { + content = Buffer.from(data[key].content, encoding); } - getAnyScopes() { - return this.scopes || this.defaultScopes; + setImmediate(() => callback(null, content)); + return promise; + }; + exports.assign = function() { + const args = Array.from(arguments); + const target = args.shift() || {}; + args.forEach((source) => { + Object.keys(source || {}).forEach((key) => { + if (["tls", "auth"].includes(key) && source[key] && typeof source[key] === "object") { + target[key] = Object.assign(target[key] || {}, source[key]); + } else { + target[key] = source[key]; + } + }); + }); + return target; + }; + exports.encodeXText = (str) => { + if (!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(str)) { + return str; } - getApplicationDefault(optionsOrCallback = {}, callback) { - let options; - if (typeof optionsOrCallback === "function") { - callback = optionsOrCallback; - } else { - options = optionsOrCallback; - } - if (callback) { - this.getApplicationDefaultAsync(options).then((r) => callback(null, r.credential, r.projectId), callback); + const buf = Buffer.from(str); + let result = ""; + for (let i = 0, len = buf.length;i < len; i++) { + const c = buf[i]; + if (c < 33 || c > 126 || c === 43 || c === 61) { + result += "+" + (c < 16 ? "0" : "") + c.toString(16).toUpperCase(); } else { - return this.getApplicationDefaultAsync(options); - } - } - async getApplicationDefaultAsync(options = {}) { - if (this.cachedCredential) { - return await this.#prepareAndCacheClient(this.cachedCredential, null); - } - let credential; - credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); - if (credential) { - if (credential instanceof jwtclient_1.JWT) { - credential.scopes = this.scopes; - } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { - credential.scopes = this.getAnyScopes(); - } - return await this.#prepareAndCacheClient(credential); - } - credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options); - if (credential) { - if (credential instanceof jwtclient_1.JWT) { - credential.scopes = this.scopes; - } else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { - credential.scopes = this.getAnyScopes(); - } - return await this.#prepareAndCacheClient(credential); - } - if (await this._checkIsGCE()) { - options.scopes = this.getAnyScopes(); - return await this.#prepareAndCacheClient(new computeclient_1.Compute(options)); + result += String.fromCharCode(c); } - throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); } - async#prepareAndCacheClient(credential, quotaProjectIdOverride = process.env["GOOGLE_CLOUD_QUOTA_PROJECT"] || null) { - const projectId = await this.getProjectIdOptional(); - if (quotaProjectIdOverride) { - credential.quotaProjectId = quotaProjectIdOverride; + return result; + }; + function resolveStream(stream, callback) { + let responded = false; + const chunks = []; + let chunklen = 0; + stream.on("error", (err) => { + if (responded) { + return; } - this.cachedCredential = credential; - return { credential, projectId }; - } - async _checkIsGCE() { - if (this.checkIsGCE === undefined) { - this.checkIsGCE = gcpMetadata.getGCPResidency() || await gcpMetadata.isAvailable(); + responded = true; + callback(err); + }); + stream.on("readable", () => { + let chunk; + while ((chunk = stream.read()) !== null) { + chunks.push(chunk); + chunklen += chunk.length; } - return this.checkIsGCE; - } - async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { - const credentialsPath = process.env["GOOGLE_APPLICATION_CREDENTIALS"] || process.env["google_application_credentials"]; - if (!credentialsPath || credentialsPath.length === 0) { - return null; + }); + stream.on("end", () => { + if (responded) { + return; } + responded = true; + let value; try { - return this._getApplicationCredentialsFromFilePath(credentialsPath, options); - } catch (e2) { - if (e2 instanceof Error) { - e2.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e2.message}`; - } - throw e2; + value = Buffer.concat(chunks, chunklen); + } catch (E2) { + return callback(E2); } - } - async _tryGetApplicationCredentialsFromWellKnownFile(options) { - let location = null; - if (this._isWindows()) { - location = process.env["APPDATA"]; - } else { - const home = process.env["HOME"]; - if (home) { - location = path2.join(home, ".config"); - } + callback(null, value); + }); + } + function createDefaultLogger(levels) { + const levelMaxLen = levels.reduce((max, level) => Math.max(max, level.length), 0); + const levelNames = new Map; + levels.forEach((level) => { + let levelName = level.toUpperCase(); + if (levelName.length < levelMaxLen) { + levelName += " ".repeat(levelMaxLen - levelName.length); } - if (location) { - location = path2.join(location, "gcloud", "application_default_credentials.json"); - if (!fs.existsSync(location)) { - location = null; + levelNames.set(level, levelName); + }); + const print = (level, entry, message, ...args) => { + let prefix = ""; + if (entry) { + if (entry.tnx === "server") { + prefix = "S: "; + } else if (entry.tnx === "client") { + prefix = "C: "; } - } - if (!location) { - return null; - } - const client = await this._getApplicationCredentialsFromFilePath(location, options); - return client; - } - async _getApplicationCredentialsFromFilePath(filePath, options = {}) { - if (!filePath || filePath.length === 0) { - throw new Error("The file path is invalid."); - } - try { - filePath = fs.realpathSync(filePath); - if (!fs.lstatSync(filePath).isFile()) { - throw new Error; + if (entry.sid) { + prefix = "[" + entry.sid + "] " + prefix; } - } catch (err) { - if (err instanceof Error) { - err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; + if (entry.cid) { + prefix = "[#" + entry.cid + "] " + prefix; } - throw err; - } - const readStream = fs.createReadStream(filePath); - return this.fromStream(readStream, options); - } - fromImpersonatedJSON(json2) { - if (!json2) { - throw new Error("Must pass in a JSON object containing an impersonated refresh token"); - } - if (json2.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { - throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); - } - if (!json2.source_credentials) { - throw new Error("The incoming JSON object does not contain a source_credentials field"); - } - if (!json2.service_account_impersonation_url) { - throw new Error("The incoming JSON object does not contain a service_account_impersonation_url field"); - } - const sourceClient = this.fromJSON(json2.source_credentials); - if (json2.service_account_impersonation_url?.length > 256) { - throw new RangeError(`Target principal is too long: ${json2.service_account_impersonation_url}`); - } - const targetPrincipal = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json2.service_account_impersonation_url)?.groups?.target; - if (!targetPrincipal) { - throw new RangeError(`Cannot extract target principal from ${json2.service_account_impersonation_url}`); } - const targetScopes = (this.scopes || json2.scopes || this.defaultScopes) ?? []; - return new impersonated_1.Impersonated({ - ...json2, - sourceClient, - targetPrincipal, - targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes] + message = util.format(message, ...args); + message.split(/\r?\n/).forEach((line3) => { + console.log("[%s] %s %s", new Date().toISOString().substr(0, 19).replace(/T/, " "), levelNames.get(level), prefix + line3); }); - } - fromJSON(json2, options = {}) { - let client; - const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get("universe_domain"); - if (json2.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { - client = new refreshclient_1.UserRefreshClient(options); - client.fromJSON(json2); - } else if (json2.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { - client = this.fromImpersonatedJSON(json2); - } else if (json2.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { - client = externalclient_1.ExternalAccountClient.fromJSON({ - ...json2, - ...options - }); - client.scopes = this.getAnyScopes(); - } else if (json2.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { - client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient({ - ...json2, - ...options - }); - } else { - options.scopes = this.scopes; - client = new jwtclient_1.JWT(options); - this.setGapicJWTValues(client); - client.fromJSON(json2); - } - if (preferredUniverseDomain) { - client.universeDomain = preferredUniverseDomain; - } - return client; - } - _cacheClientFromJSON(json2, options) { - const client = this.fromJSON(json2, options); - this.jsonContent = json2; - this.cachedCredential = client; - return client; - } - fromStream(inputStream, optionsOrCallback = {}, callback) { - let options = {}; - if (typeof optionsOrCallback === "function") { - callback = optionsOrCallback; - } else { - options = optionsOrCallback; - } - if (callback) { - this.fromStreamAsync(inputStream, options).then((r) => callback(null, r), callback); - } else { - return this.fromStreamAsync(inputStream, options); - } - } - fromStreamAsync(inputStream, options) { - return new Promise((resolve, reject) => { - if (!inputStream) { - throw new Error("Must pass in a stream containing the Google auth settings."); - } - const chunks = []; - inputStream.setEncoding("utf8").on("error", reject).on("data", (chunk) => chunks.push(chunk)).on("end", () => { - try { - try { - const data = JSON.parse(chunks.join("")); - const r = this._cacheClientFromJSON(data, options); - return resolve(r); - } catch (err) { - if (!this.keyFilename) - throw err; - const client = new jwtclient_1.JWT({ - ...this.clientOptions, - keyFile: this.keyFilename - }); - this.cachedCredential = client; - this.setGapicJWTValues(client); - return resolve(client); - } - } catch (err) { - return reject(err); - } - }); - }); - } - fromAPIKey(apiKey, options = {}) { - return new jwtclient_1.JWT({ ...options, apiKey }); - } - _isWindows() { - const sys = os.platform(); - if (sys && sys.length >= 3) { - if (sys.substring(0, 3).toLowerCase() === "win") { - return true; - } - } - return false; - } - async getDefaultServiceProjectId() { - return new Promise((resolve) => { - (0, child_process_1.exec)("gcloud config config-helper --format json", (err, stdout) => { - if (!err && stdout) { - try { - const projectId = JSON.parse(stdout).configuration.properties.core.project; - resolve(projectId); - return; - } catch (e2) {} - } - resolve(null); - }); - }); - } - getProductionProjectId() { - return process.env["GCLOUD_PROJECT"] || process.env["GOOGLE_CLOUD_PROJECT"] || process.env["gcloud_project"] || process.env["google_cloud_project"]; - } - async getFileProjectId() { - if (this.cachedCredential) { - return this.cachedCredential.projectId; - } - if (this.keyFilename) { - const creds = await this.getClient(); - if (creds && creds.projectId) { - return creds.projectId; - } - } - const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); - if (r) { - return r.projectId; - } else { - return null; - } - } - async getExternalAccountClientProjectId() { - if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { - return null; - } - const creds = await this.getClient(); - return await creds.getProjectId(); - } - async getGCEProjectId() { - try { - const r = await gcpMetadata.project("project-id"); - return r; - } catch (e2) { - return null; - } - } - getCredentials(callback) { - if (callback) { - this.getCredentialsAsync().then((r) => callback(null, r), callback); - } else { - return this.getCredentialsAsync(); - } - } - async getCredentialsAsync() { - const client = await this.getClient(); - if (client instanceof impersonated_1.Impersonated) { - return { client_email: client.getTargetPrincipal() }; - } - if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { - const serviceAccountEmail = client.getServiceAccountEmail(); - if (serviceAccountEmail) { - return { - client_email: serviceAccountEmail, - universe_domain: client.universeDomain - }; - } - } - if (this.jsonContent) { - return { - client_email: this.jsonContent.client_email, - private_key: this.jsonContent.private_key, - universe_domain: this.jsonContent.universe_domain - }; - } - if (await this._checkIsGCE()) { - const [client_email, universe_domain] = await Promise.all([ - gcpMetadata.instance("service-accounts/default/email"), - this.getUniverseDomain() - ]); - return { client_email, universe_domain }; - } - throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); - } - async getClient() { - if (this.cachedCredential) { - return this.cachedCredential; - } - this.#pendingAuthClient = this.#pendingAuthClient || this.#determineClient(); - try { - return await this.#pendingAuthClient; - } finally { - this.#pendingAuthClient = null; - } - } - async#determineClient() { - if (this.jsonContent) { - return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); - } else if (this.keyFilename) { - const filePath = path2.resolve(this.keyFilename); - const stream = fs.createReadStream(filePath); - return await this.fromStreamAsync(stream, this.clientOptions); - } else if (this.apiKey) { - const client = await this.fromAPIKey(this.apiKey, this.clientOptions); - client.scopes = this.scopes; - const { credential } = await this.#prepareAndCacheClient(client); - return credential; - } else { - const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); - return credential; - } - } - async getIdTokenClient(targetAudience) { - const client = await this.getClient(); - if (!("fetchIdToken" in client)) { - throw new Error("Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file."); - } - return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); - } - async getAccessToken() { - const client = await this.getClient(); - return (await client.getAccessToken()).token; - } - async getRequestHeaders(url) { - const client = await this.getClient(); - return client.getRequestHeaders(url); - } - async authorizeRequest(opts = {}) { - const url = opts.url; - const client = await this.getClient(); - const headers = await client.getRequestHeaders(url); - opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers, headers); - return opts; - } - async fetch(...args) { - const client = await this.getClient(); - return client.fetch(...args); - } - async request(opts) { - const client = await this.getClient(); - return client.request(opts); - } - getEnv() { - return (0, envDetect_1.getEnv)(); - } - async sign(data, endpoint) { - const client = await this.getClient(); - const universe = await this.getUniverseDomain(); - endpoint = endpoint || `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; - if (client instanceof impersonated_1.Impersonated) { - const signed = await client.sign(data); - return signed.signedBlob; - } - const crypto2 = (0, crypto_1.createCrypto)(); - if (client instanceof jwtclient_1.JWT && client.key) { - const sign = await crypto2.sign(client.key, data); - return sign; - } - const creds = await this.getCredentials(); - if (!creds.client_email) { - throw new Error("Cannot sign data without `client_email`."); - } - return this.signBlob(crypto2, creds.client_email, data, endpoint); - } - async signBlob(crypto2, emailOrUniqueId, data, endpoint) { - const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); - const res = await this.request({ - method: "POST", - url: url.href, - data: { - payload: crypto2.encodeBase64StringUtf8(data) - }, - retry: true, - retryConfig: { - httpMethodsToRetry: ["POST"] - } - }); - return res.data.signedBlob; - } - } - exports.GoogleAuth = GoogleAuth; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/iam.js -var require_iam = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.IAMAuth = undefined; - - class IAMAuth { - selector; - token; - constructor(selector, token) { - this.selector = selector; - this.token = token; - this.selector = selector; - this.token = token; - } - getRequestHeaders() { - return { - "x-goog-iam-authority-selector": this.selector, - "x-goog-iam-authorization-token": this.token - }; - } - } - exports.IAMAuth = IAMAuth; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/downscopedclient.js -var require_downscopedclient = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = undefined; - var gaxios_1 = require_src2(); - var stream = __require("stream"); - var authclient_1 = require_authclient(); - var sts = require_stscredentials(); - var STS_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:token-exchange"; - var STS_REQUEST_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; - var STS_SUBJECT_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token"; - exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; - exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; - - class DownscopedClient extends authclient_1.AuthClient { - authClient; - credentialAccessBoundary; - cachedDownscopedAccessToken; - stsCredential; - constructor(options, credentialAccessBoundary = { - accessBoundary: { - accessBoundaryRules: [] - } - }) { - super(options instanceof authclient_1.AuthClient ? {} : options); - if (options instanceof authclient_1.AuthClient) { - this.authClient = options; - this.credentialAccessBoundary = credentialAccessBoundary; - } else { - this.authClient = options.authClient; - this.credentialAccessBoundary = options.credentialAccessBoundary; - } - if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { - throw new Error("At least one access boundary rule needs to be defined."); - } else if (this.credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { - throw new Error("The provided access boundary has more than " + `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); - } - for (const rule of this.credentialAccessBoundary.accessBoundary.accessBoundaryRules) { - if (rule.availablePermissions.length === 0) { - throw new Error("At least one permission should be defined in access boundary rules."); - } - } - this.stsCredential = new sts.StsCredentials({ - tokenExchangeEndpoint: `https://sts.${this.universeDomain}/v1/token` - }); - this.cachedDownscopedAccessToken = null; - } - setCredentials(credentials) { - if (!credentials.expiry_date) { - throw new Error("The access token expiry_date field is missing in the provided " + "credentials."); - } - super.setCredentials(credentials); - this.cachedDownscopedAccessToken = credentials; - } - async getAccessToken() { - if (!this.cachedDownscopedAccessToken || this.isExpired(this.cachedDownscopedAccessToken)) { - await this.refreshAccessTokenAsync(); - } - return { - token: this.cachedDownscopedAccessToken.access_token, - expirationTime: this.cachedDownscopedAccessToken.expiry_date, - res: this.cachedDownscopedAccessToken.res - }; - } - async getRequestHeaders() { - const accessTokenResponse = await this.getAccessToken(); - const headers = new Headers({ - authorization: `Bearer ${accessTokenResponse.token}` - }); - return this.addSharedMetadataHeaders(headers); - } - request(opts, callback) { - if (callback) { - this.requestAsync(opts).then((r) => callback(null, r), (e2) => { - return callback(e2, e2.response); - }); - } else { - return this.requestAsync(opts); - } - } - async requestAsync(opts, reAuthRetried = false) { - let response; - try { - const requestHeaders = await this.getRequestHeaders(); - opts.headers = gaxios_1.Gaxios.mergeHeaders(opts.headers); - this.addUserProjectAndAuthHeaders(opts.headers, requestHeaders); - response = await this.transporter.request(opts); - } catch (e2) { - const res = e2.response; - if (res) { - const statusCode = res.status; - const isReadableStream = res.config.data instanceof stream.Readable; - const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && isAuthErr && !isReadableStream && this.forceRefreshOnFailure) { - await this.refreshAccessTokenAsync(); - return await this.requestAsync(opts, true); - } - } - throw e2; - } - return response; - } - async refreshAccessTokenAsync() { - const subjectToken = (await this.authClient.getAccessToken()).token; - const stsCredentialsOptions = { - grantType: STS_GRANT_TYPE, - requestedTokenType: STS_REQUEST_TOKEN_TYPE, - subjectToken, - subjectTokenType: STS_SUBJECT_TOKEN_TYPE - }; - const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); - const sourceCredExpireDate = this.authClient.credentials?.expiry_date || null; - const expiryDate = stsResponse.expires_in ? new Date().getTime() + stsResponse.expires_in * 1000 : sourceCredExpireDate; - this.cachedDownscopedAccessToken = { - access_token: stsResponse.access_token, - expiry_date: expiryDate, - res: stsResponse.res - }; - this.credentials = {}; - Object.assign(this.credentials, this.cachedDownscopedAccessToken); - delete this.credentials.res; - this.emit("tokens", { - refresh_token: null, - expiry_date: this.cachedDownscopedAccessToken.expiry_date, - access_token: this.cachedDownscopedAccessToken.access_token, - token_type: "Bearer", - id_token: null - }); - return this.cachedDownscopedAccessToken; - } - isExpired(downscopedAccessToken) { - const now = new Date().getTime(); - return downscopedAccessToken.expiry_date ? now >= downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis : false; - } - } - exports.DownscopedClient = DownscopedClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/auth/passthrough.js -var require_passthrough = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.PassThroughClient = undefined; - var authclient_1 = require_authclient(); - - class PassThroughClient extends authclient_1.AuthClient { - async request(opts) { - return this.transporter.request(opts); - } - async getAccessToken() { - return {}; - } - async getRequestHeaders() { - return new Headers; - } - } - exports.PassThroughClient = PassThroughClient; -}); - -// node_modules/.pnpm/google-auth-library@10.6.2/node_modules/google-auth-library/build/src/index.js -var require_src5 = __commonJS((exports) => { - var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - var desc2 = Object.getOwnPropertyDescriptor(m, k); - if (!desc2 || ("get" in desc2 ? !m.__esModule : desc2.writable || desc2.configurable)) { - desc2 = { enumerable: true, get: function() { - return m[k]; - } }; - } - Object.defineProperty(o, k2, desc2); - } : function(o, m, k, k2) { - if (k2 === undefined) - k2 = k; - o[k2] = m[k]; - }); - var __exportStar = exports && exports.__exportStar || function(m, exports2) { - for (var p in m) - if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) - __createBinding(exports2, m, p); - }; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.GoogleAuth = exports.auth = exports.PassThroughClient = exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = undefined; - var googleauth_1 = require_googleauth(); - Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function() { - return googleauth_1.GoogleAuth; - } }); - exports.gcpMetadata = require_src4(); - exports.gaxios = require_src2(); - var authclient_1 = require_authclient(); - Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function() { - return authclient_1.AuthClient; - } }); - Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function() { - return authclient_1.DEFAULT_UNIVERSE; - } }); - var computeclient_1 = require_computeclient(); - Object.defineProperty(exports, "Compute", { enumerable: true, get: function() { - return computeclient_1.Compute; - } }); - var envDetect_1 = require_envDetect(); - Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function() { - return envDetect_1.GCPEnv; - } }); - var iam_1 = require_iam(); - Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function() { - return iam_1.IAMAuth; - } }); - var idtokenclient_1 = require_idtokenclient(); - Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function() { - return idtokenclient_1.IdTokenClient; - } }); - var jwtaccess_1 = require_jwtaccess(); - Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function() { - return jwtaccess_1.JWTAccess; - } }); - var jwtclient_1 = require_jwtclient(); - Object.defineProperty(exports, "JWT", { enumerable: true, get: function() { - return jwtclient_1.JWT; - } }); - var impersonated_1 = require_impersonated(); - Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function() { - return impersonated_1.Impersonated; - } }); - var oauth2client_1 = require_oauth2client(); - Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function() { - return oauth2client_1.CodeChallengeMethod; - } }); - Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function() { - return oauth2client_1.OAuth2Client; - } }); - Object.defineProperty(exports, "ClientAuthentication", { enumerable: true, get: function() { - return oauth2client_1.ClientAuthentication; - } }); - var loginticket_1 = require_loginticket(); - Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function() { - return loginticket_1.LoginTicket; - } }); - var refreshclient_1 = require_refreshclient(); - Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function() { - return refreshclient_1.UserRefreshClient; - } }); - var awsclient_1 = require_awsclient(); - Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function() { - return awsclient_1.AwsClient; - } }); - var awsrequestsigner_1 = require_awsrequestsigner(); - Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function() { - return awsrequestsigner_1.AwsRequestSigner; - } }); - var identitypoolclient_1 = require_identitypoolclient(); - Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function() { - return identitypoolclient_1.IdentityPoolClient; - } }); - var externalclient_1 = require_externalclient(); - Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function() { - return externalclient_1.ExternalAccountClient; - } }); - var baseexternalclient_1 = require_baseexternalclient(); - Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function() { - return baseexternalclient_1.BaseExternalAccountClient; - } }); - var downscopedclient_1 = require_downscopedclient(); - Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function() { - return downscopedclient_1.DownscopedClient; - } }); - var pluggable_auth_client_1 = require_pluggable_auth_client(); - Object.defineProperty(exports, "PluggableAuthClient", { enumerable: true, get: function() { - return pluggable_auth_client_1.PluggableAuthClient; - } }); - Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function() { - return pluggable_auth_client_1.ExecutableError; - } }); - var externalAccountAuthorizedUserClient_1 = require_externalAccountAuthorizedUserClient(); - Object.defineProperty(exports, "EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE", { enumerable: true, get: function() { - return externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE; - } }); - Object.defineProperty(exports, "ExternalAccountAuthorizedUserClient", { enumerable: true, get: function() { - return externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient; - } }); - var passthrough_1 = require_passthrough(); - Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function() { - return passthrough_1.PassThroughClient; - } }); - __exportStar(require_googleToken(), exports); - var auth = new googleauth_1.GoogleAuth; - exports.auth = auth; -}); - -// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/fetch/cookies.js -var require_cookies = __commonJS((exports, module) => { - var urllib = __require("url"); - var SESSION_TIMEOUT = 1800; - - class Cookies { - constructor(options) { - this.options = options || {}; - this.cookies = []; - } - set(cookieStr, url) { - const urlparts = urllib.parse(url || ""); - const cookie = this.parse(cookieStr); - let domain; - if (cookie.domain) { - domain = cookie.domain.replace(/^\./, ""); - if (urlparts.hostname.length < domain.length || ("." + urlparts.hostname).substr(-domain.length + 1) !== "." + domain) { - cookie.domain = urlparts.hostname; - } - } else { - cookie.domain = urlparts.hostname; - } - if (!cookie.path) { - cookie.path = this.getPath(urlparts.pathname); - } - if (!cookie.expires) { - cookie.expires = new Date(Date.now() + (Number(this.options.sessionTimeout || SESSION_TIMEOUT) || SESSION_TIMEOUT) * 1000); - } - return this.add(cookie); - } - get(url) { - return this.list(url).map((cookie) => cookie.name + "=" + cookie.value).join("; "); - } - list(url) { - const result = []; - for (let i = this.cookies.length - 1;i >= 0; i--) { - const cookie = this.cookies[i]; - if (this.isExpired(cookie)) { - this.cookies.splice(i, 1); - continue; - } - if (this.match(cookie, url)) { - result.unshift(cookie); - } - } - return result; - } - parse(cookieStr) { - const cookie = {}; - (cookieStr || "").toString().split(";").forEach((cookiePart) => { - const valueParts = cookiePart.split("="); - const key = valueParts.shift().trim().toLowerCase(); - let value = valueParts.join("=").trim(); - let domain; - if (!key) { - return; - } - switch (key) { - case "expires": - value = new Date(value); - if (value.toString() !== "Invalid Date") { - cookie.expires = value; - } - break; - case "path": - cookie.path = value; - break; - case "domain": - domain = value.toLowerCase(); - if (domain.length && domain.charAt(0) !== ".") { - domain = "." + domain; - } - cookie.domain = domain; - break; - case "max-age": - cookie.expires = new Date(Date.now() + (Number(value) || 0) * 1000); - break; - case "secure": - cookie.secure = true; - break; - case "httponly": - cookie.httponly = true; - break; - default: - if (!cookie.name) { - cookie.name = key; - cookie.value = value; - } - } - }); - return cookie; - } - match(cookie, url) { - const urlparts = urllib.parse(url || ""); - if (urlparts.hostname !== cookie.domain && (cookie.domain.charAt(0) !== "." || ("." + urlparts.hostname).substr(-cookie.domain.length) !== cookie.domain)) { - return false; - } - const path2 = this.getPath(urlparts.pathname); - if (path2.substr(0, cookie.path.length) !== cookie.path) { - return false; - } - if (cookie.secure && urlparts.protocol !== "https:") { - return false; - } - return true; - } - add(cookie) { - if (!cookie || !cookie.name) { - return false; - } - for (let i = 0, len = this.cookies.length;i < len; i++) { - if (this.compare(this.cookies[i], cookie)) { - if (this.isExpired(cookie)) { - this.cookies.splice(i, 1); - return false; - } - this.cookies[i] = cookie; - return true; - } - } - if (!this.isExpired(cookie)) { - this.cookies.push(cookie); - } - return true; - } - compare(a, b) { - return a.name === b.name && a.path === b.path && a.domain === b.domain && a.secure === b.secure && a.httponly === b.httponly; - } - isExpired(cookie) { - return cookie.expires && cookie.expires < new Date || !cookie.value; - } - getPath(pathname) { - let path2 = (pathname || "/").split("/"); - path2.pop(); - path2 = path2.join("/").trim(); - if (path2.charAt(0) !== "/") { - path2 = "/" + path2; - } - if (path2.substr(-1) !== "/") { - path2 += "/"; - } - return path2; - } - } - module.exports = Cookies; -}); - -// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/package.json -var require_package5 = __commonJS((exports, module) => { - module.exports = { - name: "nodemailer", - version: "8.0.5", - description: "Easy as cake e-mail sending from your Node.js applications", - main: "lib/nodemailer.js", - scripts: { - test: "node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js", - "test:coverage": "c8 node --test --test-concurrency=1 test/**/*.test.js test/**/*-test.js", - format: 'prettier --write "**/*.{js,json,md}"', - "format:check": 'prettier --check "**/*.{js,json,md}"', - lint: "eslint .", - "lint:fix": "eslint . --fix", - update: "rm -rf node_modules/ package-lock.json && ncu -u && npm install", - "test:syntax": 'docker run --rm -v "$PWD:/app:ro" -w /app node:6-alpine node test/syntax-compat.js' - }, - repository: { - type: "git", - url: "https://github.com/nodemailer/nodemailer.git" - }, - keywords: [ - "Nodemailer" - ], - author: "Andris Reinman", - license: "MIT-0", - bugs: { - url: "https://github.com/nodemailer/nodemailer/issues" - }, - homepage: "https://nodemailer.com/", - devDependencies: { - "@aws-sdk/client-sesv2": "3.1025.0", - bunyan: "1.8.15", - c8: "11.0.0", - eslint: "10.2.0", - "eslint-config-prettier": "10.1.8", - globals: "17.4.0", - libbase64: "1.3.0", - libmime: "5.3.7", - libqp: "2.1.1", - "nodemailer-ntlm-auth": "1.0.4", - prettier: "3.8.1", - proxy: "1.0.2", - "proxy-test-server": "1.0.0", - "smtp-server": "3.18.3" - }, - engines: { - node: ">=6.0.0" - } - }; -}); - -// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/errors.js -var require_errors5 = __commonJS((exports, module) => { - var ERROR_CODES = { - ECONNECTION: "Connection closed unexpectedly", - ETIMEDOUT: "Connection or operation timed out", - ESOCKET: "Socket-level error", - EDNS: "DNS resolution failed", - ETLS: "TLS handshake or STARTTLS failed", - EREQUIRETLS: "REQUIRETLS not supported by server (RFC 8689)", - EPROTOCOL: "Invalid SMTP server response", - EENVELOPE: "Invalid mail envelope (sender or recipients)", - EMESSAGE: "Message delivery error", - ESTREAM: "Stream processing error", - EAUTH: "Authentication failed", - ENOAUTH: "Authentication credentials not provided", - EOAUTH2: "OAuth2 token generation or refresh error", - EMAXLIMIT: "Pool resource limit reached (max messages per connection)", - ESENDMAIL: "Sendmail command error", - ESES: "AWS SES transport error", - ECONFIG: "Invalid configuration", - EPROXY: "Proxy connection error", - EFILEACCESS: "File access rejected (disableFileAccess is set)", - EURLACCESS: "URL access rejected (disableUrlAccess is set)", - EFETCH: "HTTP fetch error" - }; - module.exports = { ERROR_CODES }; - for (const code of Object.keys(ERROR_CODES)) { - module.exports[code] = code; - } -}); - -// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/fetch/index.js -var require_fetch = __commonJS((exports, module) => { - var http = __require("http"); - var https = __require("https"); - var urllib = __require("url"); - var zlib = __require("zlib"); - var { PassThrough } = __require("stream"); - var Cookies = require_cookies(); - var packageData = require_package5(); - var net = __require("net"); - var errors = require_errors5(); - var MAX_REDIRECTS = 5; - module.exports = function(url, options) { - return nmfetch(url, options); - }; - module.exports.Cookies = Cookies; - function nmfetch(url, options) { - options = options || {}; - options.fetchRes = options.fetchRes || new PassThrough; - options.cookies = options.cookies || new Cookies; - options.redirects = options.redirects || 0; - options.maxRedirects = isNaN(options.maxRedirects) ? MAX_REDIRECTS : options.maxRedirects; - if (options.cookie) { - [].concat(options.cookie || []).forEach((cookie) => { - options.cookies.set(cookie, url); - }); - options.cookie = false; - } - const fetchRes = options.fetchRes; - const parsed = urllib.parse(url); - let method = (options.method || "").toString().trim().toUpperCase() || "GET"; - let finished = false; - let cookies; - let body; - const handler = parsed.protocol === "https:" ? https : http; - const headers = { - "accept-encoding": "gzip,deflate", - "user-agent": "nodemailer/" + packageData.version - }; - Object.keys(options.headers || {}).forEach((key) => { - headers[key.toLowerCase().trim()] = options.headers[key]; - }); - if (options.userAgent) { - headers["user-agent"] = options.userAgent; - } - if (parsed.auth) { - headers.Authorization = "Basic " + Buffer.from(parsed.auth).toString("base64"); - } - if (cookies = options.cookies.get(url)) { - headers.cookie = cookies; - } - if (options.body) { - if (options.contentType !== false) { - headers["Content-Type"] = options.contentType || "application/x-www-form-urlencoded"; - } - if (typeof options.body.pipe === "function") { - headers["Transfer-Encoding"] = "chunked"; - body = options.body; - body.on("error", (err) => { - if (finished) { - return; - } - finished = true; - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - }); - } else { - if (options.body instanceof Buffer) { - body = options.body; - } else if (typeof options.body === "object") { - try { - body = Buffer.from(Object.keys(options.body).map((key) => { - const value = options.body[key].toString().trim(); - return encodeURIComponent(key) + "=" + encodeURIComponent(value); - }).join("&")); - } catch (E2) { - if (finished) { - return; - } - finished = true; - E2.code = errors.EFETCH; - E2.sourceUrl = url; - fetchRes.emit("error", E2); - return; - } - } else { - body = Buffer.from(options.body.toString().trim()); - } - headers["Content-Type"] = options.contentType || "application/x-www-form-urlencoded"; - headers["Content-Length"] = body.length; - } - method = (options.method || "").toString().trim().toUpperCase() || "POST"; - } - let req; - const reqOptions = { - method, - host: parsed.hostname, - path: parsed.path, - port: parsed.port ? parsed.port : parsed.protocol === "https:" ? 443 : 80, - headers, - rejectUnauthorized: false, - agent: false }; - if (options.tls) { - Object.assign(reqOptions, options.tls); - } - if (parsed.protocol === "https:" && parsed.hostname && parsed.hostname !== reqOptions.host && !net.isIP(parsed.hostname) && !reqOptions.servername) { - reqOptions.servername = parsed.hostname; - } - try { - req = handler.request(reqOptions); - } catch (E2) { - finished = true; - setImmediate(() => { - E2.code = errors.EFETCH; - E2.sourceUrl = url; - fetchRes.emit("error", E2); - }); - return fetchRes; - } - if (options.timeout) { - req.setTimeout(options.timeout, () => { - if (finished) { - return; - } - finished = true; - req.abort(); - const err = new Error("Request Timeout"); - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - }); - } - req.on("error", (err) => { - if (finished) { - return; - } - finished = true; - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - }); - req.on("response", (res) => { - let inflate; - if (finished) { - return; - } - switch (res.headers["content-encoding"]) { - case "gzip": - case "deflate": - inflate = zlib.createUnzip(); - break; - } - if (res.headers["set-cookie"]) { - [].concat(res.headers["set-cookie"] || []).forEach((cookie) => { - options.cookies.set(cookie, url); - }); - } - if ([301, 302, 303, 307, 308].includes(res.statusCode) && res.headers.location) { - options.redirects++; - if (options.redirects > options.maxRedirects) { - finished = true; - const err = new Error("Maximum redirect count exceeded"); - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - req.abort(); - return; - } - options.method = "GET"; - options.body = false; - return nmfetch(urllib.resolve(url, res.headers.location), options); - } - fetchRes.statusCode = res.statusCode; - fetchRes.headers = res.headers; - if (res.statusCode >= 300 && !options.allowErrorResponse) { - finished = true; - const err = new Error("Invalid status code " + res.statusCode); - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - req.abort(); - return; - } - res.on("error", (err) => { - if (finished) { - return; - } - finished = true; - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - req.abort(); - }); - if (inflate) { - res.pipe(inflate).pipe(fetchRes); - inflate.on("error", (err) => { - if (finished) { - return; - } - finished = true; - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - req.abort(); - }); - } else { - res.pipe(fetchRes); - } - }); - setImmediate(() => { - if (body) { - try { - if (typeof body.pipe === "function") { - return body.pipe(req); - } - req.write(body); - } catch (err) { - finished = true; - err.code = errors.EFETCH; - err.sourceUrl = url; - fetchRes.emit("error", err); - return; - } - } - req.end(); + const logger = {}; + levels.forEach((level) => { + logger[level] = print.bind(null, level); }); - return fetchRes; - } -}); - -// node_modules/.pnpm/nodemailer@8.0.5/node_modules/nodemailer/lib/shared/index.js -var require_shared3 = __commonJS((exports, module) => { - var urllib = __require("url"); - var util = __require("util"); - var fs = __require("fs"); - var nmfetch = require_fetch(); - var dns = __require("dns"); - var net = __require("net"); - var os = __require("os"); - var DNS_TTL = 5 * 60 * 1000; - var CACHE_CLEANUP_INTERVAL = 30 * 1000; - var MAX_CACHE_SIZE = 1000; - var lastCacheCleanup = 0; - exports._lastCacheCleanup = () => lastCacheCleanup; - exports._resetCacheCleanup = () => { - lastCacheCleanup = 0; - }; - var networkInterfaces; - try { - networkInterfaces = os.networkInterfaces(); - } catch (_err) {} - exports.networkInterfaces = networkInterfaces; - var isFamilySupported = (family, allowInternal) => { - const ifaces = exports.networkInterfaces; - if (!ifaces) { - return true; - } - return Object.keys(ifaces).map((key) => ifaces[key]).reduce((acc, val) => acc.concat(val), []).filter((i) => !i.internal || allowInternal).some((i) => i.family === "IPv" + family || i.family === family); - }; - var resolve = (family, hostname, options, callback) => { - options = options || {}; - if (!isFamilySupported(family, options.allowInternalNetworkInterfaces)) { - return callback(null, []); - } - const dnsResolver = dns.Resolver ? new dns.Resolver(options) : dns; - dnsResolver["resolve" + family](hostname, (err, addresses) => { - if (err) { - switch (err.code) { - case dns.NODATA: - case dns.NOTFOUND: - case dns.NOTIMP: - case dns.SERVFAIL: - case dns.CONNREFUSED: - case dns.REFUSED: - case "EAI_AGAIN": - return callback(null, []); - } - return callback(err); - } - return callback(null, Array.isArray(addresses) ? addresses : [].concat(addresses || [])); - }); - }; - var dnsCache = exports.dnsCache = new Map; - var formatDNSValue = (value, extra) => { - if (!value) { - return Object.assign({}, extra || {}); - } - const addresses = value.addresses || []; - const host = addresses.length > 0 ? addresses[Math.floor(Math.random() * addresses.length)] : null; - return Object.assign({ - servername: value.servername, - host, - _addresses: addresses - }, extra || {}); - }; - exports.resolveHostname = (options, callback) => { - options = options || {}; - if (!options.host && options.servername) { - options.host = options.servername; - } - if (!options.host || net.isIP(options.host)) { - const value = { - addresses: [options.host], - servername: options.servername || false - }; - return callback(null, formatDNSValue(value, { - cached: false - })); - } - let cached; - if (dnsCache.has(options.host)) { - cached = dnsCache.get(options.host); - const now = Date.now(); - if (now - lastCacheCleanup > CACHE_CLEANUP_INTERVAL) { - lastCacheCleanup = now; - for (const [host, entry] of dnsCache.entries()) { - if (entry.expires && entry.expires < now) { - dnsCache.delete(host); - } - } - if (dnsCache.size > MAX_CACHE_SIZE) { - const toDelete = Math.floor(MAX_CACHE_SIZE * 0.1); - const keys = Array.from(dnsCache.keys()).slice(0, toDelete); - keys.forEach((key) => dnsCache.delete(key)); - } - } - if (!cached.expires || cached.expires >= now) { - return callback(null, formatDNSValue(cached.value, { - cached: true - })); - } - } - let ipv4Addresses = []; - let ipv6Addresses = []; - let ipv4Error = null; - let ipv6Error = null; - resolve(4, options.host, options, (err, addresses) => { - if (err) { - ipv4Error = err; - } else { - ipv4Addresses = addresses || []; - } - resolve(6, options.host, options, (err2, addresses2) => { - if (err2) { - ipv6Error = err2; - } else { - ipv6Addresses = addresses2 || []; - } - const allAddresses = ipv4Addresses.concat(ipv6Addresses); - if (allAddresses.length) { - const value = { - addresses: allAddresses, - servername: options.servername || options.host - }; - dnsCache.set(options.host, { - value, - expires: Date.now() + (options.dnsTtl || DNS_TTL) - }); - return callback(null, formatDNSValue(value, { - cached: false - })); - } - if (ipv4Error && ipv6Error) { - if (cached) { - dnsCache.set(options.host, { - value: cached.value, - expires: Date.now() + (options.dnsTtl || DNS_TTL) - }); - return callback(null, formatDNSValue(cached.value, { - cached: true, - error: ipv4Error - })); - } - } - try { - dns.lookup(options.host, { all: true }, (err3, addresses3) => { - if (err3) { - if (cached) { - dnsCache.set(options.host, { - value: cached.value, - expires: Date.now() + (options.dnsTtl || DNS_TTL) - }); - return callback(null, formatDNSValue(cached.value, { - cached: true, - error: err3 - })); - } - return callback(err3); - } - const supportedAddresses = addresses3 ? addresses3.filter((addr) => isFamilySupported(addr.family)).map((addr) => addr.address) : []; - if (addresses3 && addresses3.length && !supportedAddresses.length) { - console.warn(`Failed to resolve IPv${addresses3[0].family} addresses with current network`); - } - if (!supportedAddresses.length && cached) { - return callback(null, formatDNSValue(cached.value, { - cached: true - })); - } - const value = { - addresses: supportedAddresses.length ? supportedAddresses : [options.host], - servername: options.servername || options.host - }; - dnsCache.set(options.host, { - value, - expires: Date.now() + (options.dnsTtl || DNS_TTL) - }); - return callback(null, formatDNSValue(value, { - cached: false - })); - }); - } catch (lookupErr) { - if (cached) { - dnsCache.set(options.host, { - value: cached.value, - expires: Date.now() + (options.dnsTtl || DNS_TTL) - }); - return callback(null, formatDNSValue(cached.value, { - cached: true, - error: lookupErr - })); - } - return callback(ipv4Error || ipv6Error || lookupErr); - } - }); - }); - }; - exports.parseConnectionUrl = (str) => { - str = str || ""; - const options = {}; - const url = urllib.parse(str, true); - switch (url.protocol) { - case "smtp:": - options.secure = false; - break; - case "smtps:": - options.secure = true; - break; - case "direct:": - options.direct = true; - break; - } - if (!isNaN(url.port) && Number(url.port)) { - options.port = Number(url.port); - } - if (url.hostname) { - options.host = url.hostname; - } - if (url.auth) { - const auth = url.auth.split(":"); - options.auth = { - user: auth.shift(), - pass: auth.join(":") - }; - } - Object.keys(url.query || {}).forEach((key) => { - let obj = options; - let lKey = key; - let value = url.query[key]; - if (!isNaN(value)) { - value = Number(value); - } - switch (value) { - case "true": - value = true; - break; - case "false": - value = false; - break; - } - if (key.indexOf("tls.") === 0) { - lKey = key.substr(4); - if (!options.tls) { - options.tls = {}; - } - obj = options.tls; - } else if (key.indexOf(".") >= 0) { - return; - } - if (!(lKey in obj)) { - obj[lKey] = value; - } - }); - return options; - }; - exports._logFunc = (logger, level, defaults2, data, message, ...args) => { - const entry = Object.assign({}, defaults2 || {}, data || {}); - delete entry.level; - logger[level](entry, message, ...args); - }; - exports.getLogger = (options, defaults2) => { - options = options || {}; - const response = {}; - const levels = ["trace", "debug", "info", "warn", "error", "fatal"]; - if (!options.logger) { - levels.forEach((level) => { - response[level] = () => false; - }); - return response; - } - const logger = options.logger === true ? createDefaultLogger(levels) : options.logger; - levels.forEach((level) => { - response[level] = (data, message, ...args) => { - exports._logFunc(logger, level, defaults2, data, message, ...args); - }; - }); - return response; - }; - exports.callbackPromise = (resolve2, reject) => function() { - const args = Array.from(arguments); - const err = args.shift(); - if (err) { - reject(err); - } else { - resolve2(...args); - } - }; - exports.parseDataURI = (uri) => { - if (typeof uri !== "string") { - return null; - } - if (!uri.startsWith("data:")) { - return null; - } - const commaPos = uri.indexOf(","); - if (commaPos === -1) { - return null; - } - const data = uri.substring(commaPos + 1); - const metaStr = uri.substring("data:".length, commaPos); - let encoding; - const metaEntries = metaStr.split(";"); - if (metaEntries.length > 0) { - const lastEntry = metaEntries[metaEntries.length - 1].toLowerCase().trim(); - if (["base64", "utf8", "utf-8"].includes(lastEntry) && lastEntry.indexOf("=") === -1) { - encoding = lastEntry; - metaEntries.pop(); - } - } - const contentType = metaEntries.length > 0 ? metaEntries.shift() : "application/octet-stream"; - const params = {}; - for (let i = 0;i < metaEntries.length; i++) { - const entry = metaEntries[i]; - const sepPos = entry.indexOf("="); - if (sepPos > 0) { - const key = entry.substring(0, sepPos).trim(); - const value = entry.substring(sepPos + 1).trim(); - if (key) { - params[key] = value; - } - } - } - let bufferData; - try { - if (encoding === "base64") { - bufferData = Buffer.from(data, "base64"); - } else { - try { - bufferData = Buffer.from(decodeURIComponent(data)); - } catch (_decodeError) { - bufferData = Buffer.from(data); - } - } - } catch (_bufferError) { - bufferData = Buffer.alloc(0); - } - return { - data: bufferData, - encoding: encoding || null, - contentType: contentType || "application/octet-stream", - params - }; - }; - exports.resolveContent = (data, key, callback) => { - let promise; - if (!callback) { - promise = new Promise((resolve2, reject) => { - callback = exports.callbackPromise(resolve2, reject); - }); - } - let content = data && data[key] && data[key].content || data[key]; - const encoding = (typeof data[key] === "object" && data[key].encoding || "utf8").toString().toLowerCase().replace(/[-_\s]/g, ""); - if (!content) { - return callback(null, content); - } - if (typeof content === "object") { - if (typeof content.pipe === "function") { - return resolveStream(content, (err, value) => { - if (err) { - return callback(err); - } - if (data[key].content) { - data[key].content = value; - } else { - data[key] = value; - } - callback(null, value); - }); - } else if (/^https?:\/\//i.test(content.path || content.href)) { - return resolveStream(nmfetch(content.path || content.href), callback); - } else if (/^data:/i.test(content.path || content.href)) { - const parsedDataUri = exports.parseDataURI(content.path || content.href); - if (!parsedDataUri || !parsedDataUri.data) { - return callback(null, Buffer.from(0)); - } - return callback(null, parsedDataUri.data); - } else if (content.path) { - return resolveStream(fs.createReadStream(content.path), callback); - } - } - if (typeof data[key].content === "string" && !["utf8", "usascii", "ascii"].includes(encoding)) { - content = Buffer.from(data[key].content, encoding); - } - setImmediate(() => callback(null, content)); - return promise; - }; - exports.assign = function() { - const args = Array.from(arguments); - const target = args.shift() || {}; - args.forEach((source) => { - Object.keys(source || {}).forEach((key) => { - if (["tls", "auth"].includes(key) && source[key] && typeof source[key] === "object") { - target[key] = Object.assign(target[key] || {}, source[key]); - } else { - target[key] = source[key]; - } - }); - }); - return target; - }; - exports.encodeXText = (str) => { - if (!/[^\x21-\x2A\x2C-\x3C\x3E-\x7E]/.test(str)) { - return str; - } - const buf = Buffer.from(str); - let result = ""; - for (let i = 0, len = buf.length;i < len; i++) { - const c = buf[i]; - if (c < 33 || c > 126 || c === 43 || c === 61) { - result += "+" + (c < 16 ? "0" : "") + c.toString(16).toUpperCase(); - } else { - result += String.fromCharCode(c); - } - } - return result; - }; - function resolveStream(stream, callback) { - let responded = false; - const chunks = []; - let chunklen = 0; - stream.on("error", (err) => { - if (responded) { - return; - } - responded = true; - callback(err); - }); - stream.on("readable", () => { - let chunk; - while ((chunk = stream.read()) !== null) { - chunks.push(chunk); - chunklen += chunk.length; - } - }); - stream.on("end", () => { - if (responded) { - return; - } - responded = true; - let value; - try { - value = Buffer.concat(chunks, chunklen); - } catch (E2) { - return callback(E2); - } - callback(null, value); - }); - } - function createDefaultLogger(levels) { - const levelMaxLen = levels.reduce((max, level) => Math.max(max, level.length), 0); - const levelNames = new Map; - levels.forEach((level) => { - let levelName = level.toUpperCase(); - if (levelName.length < levelMaxLen) { - levelName += " ".repeat(levelMaxLen - levelName.length); - } - levelNames.set(level, levelName); - }); - const print = (level, entry, message, ...args) => { - let prefix = ""; - if (entry) { - if (entry.tnx === "server") { - prefix = "S: "; - } else if (entry.tnx === "client") { - prefix = "C: "; - } - if (entry.sid) { - prefix = "[" + entry.sid + "] " + prefix; - } - if (entry.cid) { - prefix = "[#" + entry.cid + "] " + prefix; - } - } - message = util.format(message, ...args); - message.split(/\r?\n/).forEach((line2) => { - console.log("[%s] %s %s", new Date().toISOString().substr(0, 19).replace(/T/, " "), levelNames.get(level), prefix + line2); - }); - }; - const logger = {}; - levels.forEach((level) => { - logger[level] = print.bind(null, level); - }); - return logger; + return logger; } }); @@ -85444,13 +74456,13 @@ var require_punycode = __commonJS((exports, module) => { } output.push(input.charCodeAt(j)); } - for (let index2 = basic > 0 ? basic + 1 : 0;index2 < inputLength; ) { + for (let index3 = basic > 0 ? basic + 1 : 0;index3 < inputLength; ) { const oldi = i; for (let w = 1, k = base;; k += base) { - if (index2 >= inputLength) { + if (index3 >= inputLength) { error("invalid-input"); } - const digit = basicToDigit(input.charCodeAt(index2++)); + const digit = basicToDigit(input.charCodeAt(index3++)); if (digit >= base) { error("invalid-input"); } @@ -85697,60 +74709,60 @@ var require_qp = __commonJS((exports, module) => { } let pos = 0; const len = str.length; - let match, code, line2; + let match, code, line3; const lineMargin = Math.floor(lineLength / 3); let result = ""; while (pos < len) { - line2 = str.substr(pos, lineLength); - if (match = line2.match(/\r\n/)) { - line2 = line2.substr(0, match.index + match[0].length); - result += line2; - pos += line2.length; + line3 = str.substr(pos, lineLength); + if (match = line3.match(/\r\n/)) { + line3 = line3.substr(0, match.index + match[0].length); + result += line3; + pos += line3.length; continue; } - if (line2.substr(-1) === ` + if (line3.substr(-1) === ` `) { - result += line2; - pos += line2.length; + result += line3; + pos += line3.length; continue; } - if (match = line2.substr(-lineMargin).match(/\n.*?$/)) { - line2 = line2.substr(0, line2.length - (match[0].length - 1)); - result += line2; - pos += line2.length; + if (match = line3.substr(-lineMargin).match(/\n.*?$/)) { + line3 = line3.substr(0, line3.length - (match[0].length - 1)); + result += line3; + pos += line3.length; continue; } - if (line2.length > lineLength - lineMargin && (match = line2.substr(-lineMargin).match(/[ \t.,!?][^ \t.,!?]*$/))) { - line2 = line2.substr(0, line2.length - (match[0].length - 1)); - } else if (line2.match(/[=][\da-f]{0,2}$/i)) { - if (match = line2.match(/[=][\da-f]{0,1}$/i)) { - line2 = line2.substr(0, line2.length - match[0].length); + if (line3.length > lineLength - lineMargin && (match = line3.substr(-lineMargin).match(/[ \t.,!?][^ \t.,!?]*$/))) { + line3 = line3.substr(0, line3.length - (match[0].length - 1)); + } else if (line3.match(/[=][\da-f]{0,2}$/i)) { + if (match = line3.match(/[=][\da-f]{0,1}$/i)) { + line3 = line3.substr(0, line3.length - match[0].length); } - while (line2.length > 3 && line2.length < len - pos && !line2.match(/^(?:=[\da-f]{2}){1,4}$/i) && (match = line2.match(/[=][\da-f]{2}$/gi))) { + while (line3.length > 3 && line3.length < len - pos && !line3.match(/^(?:=[\da-f]{2}){1,4}$/i) && (match = line3.match(/[=][\da-f]{2}$/gi))) { code = parseInt(match[0].substr(1, 2), 16); if (code < 128) { break; } - line2 = line2.substr(0, line2.length - 3); + line3 = line3.substr(0, line3.length - 3); if (code >= 192) { break; } } } - if (pos + line2.length < len && line2.substr(-1) !== ` + if (pos + line3.length < len && line3.substr(-1) !== ` `) { - if (line2.length === lineLength && line2.match(/[=][\da-f]{2}$/i)) { - line2 = line2.substr(0, line2.length - 3); - } else if (line2.length === lineLength) { - line2 = line2.substr(0, line2.length - 1); + if (line3.length === lineLength && line3.match(/[=][\da-f]{2}$/i)) { + line3 = line3.substr(0, line3.length - 3); + } else if (line3.length === lineLength) { + line3 = line3.substr(0, line3.length - 1); } - pos += line2.length; - line2 += `=\r + pos += line3.length; + line3 += `=\r `; } else { - pos += line2.length; + pos += line3.length; } - result += line2; + result += line3; } return result; } @@ -85934,7 +74946,7 @@ var require_mime_funcs = __commonJS((exports, module) => { const list = []; let encodedStr = typeof data === "string" ? data : (data || "").toString(); let chr, ord; - let line2; + let line3; let startPos = 0; let i, len; maxLength = maxLength || 50; @@ -85974,7 +74986,7 @@ var require_mime_funcs = __commonJS((exports, module) => { } encodedStr = encodedStrArr; } - line2 = "utf-8''"; + line3 = "utf-8''"; let encoded = true; startPos = 0; for (i = 0, len = encodedStr.length;i < len; i++) { @@ -85984,27 +74996,27 @@ var require_mime_funcs = __commonJS((exports, module) => { } else { chr = chr === " " ? chr : this.safeEncodeURIComponent(chr); if (chr !== encodedStr[i]) { - if ((this.safeEncodeURIComponent(line2) + chr).length >= maxLength) { + if ((this.safeEncodeURIComponent(line3) + chr).length >= maxLength) { list.push({ - line: line2, + line: line3, encoded }); - line2 = ""; + line3 = ""; startPos = i - 1; } else { encoded = true; i = startPos; - line2 = ""; + line3 = ""; continue; } } } - if ((line2 + chr).length >= maxLength) { + if ((line3 + chr).length >= maxLength) { list.push({ - line: line2, + line: line3, encoded }); - line2 = chr = encodedStr[i] === " " ? " " : this.safeEncodeURIComponent(encodedStr[i]); + line3 = chr = encodedStr[i] === " " ? " " : this.safeEncodeURIComponent(encodedStr[i]); if (chr === encodedStr[i]) { encoded = false; startPos = i - 1; @@ -86012,12 +75024,12 @@ var require_mime_funcs = __commonJS((exports, module) => { encoded = true; } } else { - line2 += chr; + line3 += chr; } } - if (line2) { + if (line3) { list.push({ - line: line2, + line: line3, encoded }); } @@ -86128,25 +75140,25 @@ var require_mime_funcs = __commonJS((exports, module) => { let pos = 0; const len = str.length; let result = ""; - let line2, match; + let line3, match; while (pos < len) { - line2 = str.substr(pos, lineLength); - if (line2.length < lineLength) { - result += line2; + line3 = str.substr(pos, lineLength); + if (line3.length < lineLength) { + result += line3; break; } - if (match = line2.match(/^[^\n\r]*(\r?\n|\r)/)) { - line2 = match[0]; - result += line2; - pos += line2.length; + if (match = line3.match(/^[^\n\r]*(\r?\n|\r)/)) { + line3 = match[0]; + result += line3; + pos += line3.length; continue; - } else if ((match = line2.match(/(\s+)[^\s]*$/)) && match[0].length - (afterSpace ? (match[1] || "").length : 0) < line2.length) { - line2 = line2.substr(0, line2.length - (match[0].length - (afterSpace ? (match[1] || "").length : 0))); - } else if (match = str.substr(pos + line2.length).match(/^[^\s]+(\s*)/)) { - line2 = line2 + match[0].substr(0, match[0].length - (!afterSpace ? (match[1] || "").length : 0)); + } else if ((match = line3.match(/(\s+)[^\s]*$/)) && match[0].length - (afterSpace ? (match[1] || "").length : 0) < line3.length) { + line3 = line3.substr(0, line3.length - (match[0].length - (afterSpace ? (match[1] || "").length : 0))); + } else if (match = str.substr(pos + line3.length).match(/^[^\s]+(\s*)/)) { + line3 = line3 + match[0].substr(0, match[0].length - (!afterSpace ? (match[1] || "").length : 0)); } - result += line2; - pos += line2.length; + result += line3; + pos += line3.length; if (pos < len) { result += `\r `; @@ -86588,7 +75600,7 @@ var require_mime_node = __commonJS((exports, module) => { var base64 = require_base64(); var addressparser = require_addressparser(); var nmfetch = require_fetch(); - var errors = require_errors5(); + var errors = require_errors3(); var LastNewline = require_last_newline(); var LeWindows = require_le_windows(); var LeUnix = require_le_unix(); @@ -87320,21 +76332,21 @@ var require_mime_node = __commonJS((exports, module) => { if (lastAt < 0) { return address; } - let user2 = address.substr(0, lastAt); + let user3 = address.substr(0, lastAt); const domain = address.substr(lastAt + 1); let encodedDomain; try { encodedDomain = punycode.toASCII(domain.toLowerCase()); } catch (_err) {} - if (user2.indexOf(" ") >= 0) { - if (user2.charAt(0) !== '"') { - user2 = '"' + user2; + if (user3.indexOf(" ") >= 0) { + if (user3.charAt(0) !== '"') { + user3 = '"' + user3; } - if (user2.substr(-1) !== '"') { - user2 = user2 + '"'; + if (user3.substr(-1) !== '"') { + user3 = user3 + '"'; } } - return `${user2}@${encodedDomain}`; + return `${user3}@${encodedDomain}`; } _encodeAddressName(name) { if (!/^[\w ]*$/.test(name)) { @@ -87510,16 +76522,16 @@ var require_mail_composer = __commonJS((exports, module) => { } getAlternatives() { const alternatives = []; - let text2, html, watchHtml, amp, icalEvent, eventObject; + let text3, html, watchHtml, amp, icalEvent, eventObject; if (this.mail.text) { if (typeof this.mail.text === "object" && (this.mail.text.content || this.mail.text.path || this.mail.text.href || this.mail.text.raw)) { - text2 = this.mail.text; + text3 = this.mail.text; } else { - text2 = { + text3 = { content: this.mail.text }; } - text2.contentType = "text/plain; charset=utf-8"; + text3.contentType = "text/plain; charset=utf-8"; } if (this.mail.watchHtml) { if (typeof this.mail.watchHtml === "object" && (this.mail.watchHtml.content || this.mail.watchHtml.path || this.mail.watchHtml.href || this.mail.watchHtml.raw)) { @@ -87569,7 +76581,7 @@ var require_mail_composer = __commonJS((exports, module) => { } html.contentType = "text/html; charset=utf-8"; } - [].concat(text2 || []).concat(watchHtml || []).concat(amp || []).concat(html || []).concat(eventObject || []).concat(this.mail.alternatives || []).forEach((alternative) => { + [].concat(text3 || []).concat(watchHtml || []).concat(amp || []).concat(html || []).concat(eventObject || []).concat(this.mail.alternatives || []).forEach((alternative) => { if (/^data:/i.test(alternative.path || alternative.href)) { alternative = this._processDataUrl(alternative); } @@ -87877,9 +76889,9 @@ var require_message_parser = __commonJS((exports, module) => { lines.splice(i, 1); } } - return lines.filter((line2) => line2.trim()).map((line2) => ({ - key: line2.substr(0, line2.indexOf(":")).trim().toLowerCase(), - line: line2 + return lines.filter((line3) => line3.trim()).map((line3) => ({ + key: line3.substr(0, line3.indexOf(":")).trim().toLowerCase(), + line: line3 })); } } @@ -88044,9 +77056,9 @@ var require_sign3 = __commonJS((exports, module) => { includedFields.add(field.trim()); }); for (let i = headers.length - 1;i >= 0; i--) { - const line2 = headers[i]; - if (includedFields.has(line2.key) && !headerFields.has(line2.key)) { - headerFields.set(line2.key, relaxedHeaderLine(line2.line)); + const line3 = headers[i]; + if (includedFields.has(line3.key) && !headerFields.has(line3.key)) { + headerFields.set(line3.key, relaxedHeaderLine(line3.line)); } } const headersList = []; @@ -88064,8 +77076,8 @@ var require_sign3 = __commonJS((exports, module) => { fieldNames: fields.join(":") }; } - function relaxedHeaderLine(line2) { - return line2.substr(line2.indexOf(":") + 1).replace(/\r?\n/g, "").replace(/\s+/g, " ").trim(); + function relaxedHeaderLine(line3) { + return line3.substr(line3.indexOf(":") + 1).replace(/\r?\n/g, "").replace(/\s+/g, " ").trim(); } }); @@ -88266,7 +77278,7 @@ var require_http_proxy_client = __commonJS((exports, module) => { var net = __require("net"); var tls = __require("tls"); var urllib = __require("url"); - var errors = require_errors5(); + var errors = require_errors3(); function httpProxyClient(proxyUrl, destinationPort, destinationHost, callback) { const proxy = urllib.parse(proxyUrl); const options = { @@ -88619,7 +77631,7 @@ var require_mailer = __commonJS((exports, module) => { var MailComposer = require_mail_composer(); var DKIM = require_dkim(); var httpProxyClient = require_http_proxy_client(); - var errors = require_errors5(); + var errors = require_errors3(); var util = __require("util"); var urllib = __require("url"); var packageData = require_package5(); @@ -89844,7 +78856,7 @@ var require_smtp_connection = __commonJS((exports, module) => { this._sendCommand("HELO " + this.name); return; } - this._ehloLines = str.split(/\r?\n/).map((line2) => line2.replace(/^\d+[ -]/, "").trim()).filter((line2) => line2).slice(1); + this._ehloLines = str.split(/\r?\n/).map((line3) => line3.replace(/^\d+[ -]/, "").trim()).filter((line3) => line3).slice(1); if (!this.secure && !this.options.ignoreTLS && (/[ -]STARTTLS\b/im.test(str) || this.options.requireTLS)) { this._sendCommand("STARTTLS"); this._responseActions.push(this._actionSTARTTLS); @@ -90152,7 +79164,7 @@ var require_xoauth2 = __commonJS((exports, module) => { var nmfetch = require_fetch(); var crypto3 = __require("crypto"); var shared = require_shared3(); - var errors = require_errors5(); + var errors = require_errors3(); class XOAuth2 extends Stream { constructor(options, logger) { @@ -90421,7 +79433,7 @@ var require_pool_resource = __commonJS((exports, module) => { var SMTPConnection = require_smtp_connection(); var assign = require_shared3().assign; var XOAuth2 = require_xoauth2(); - var errors = require_errors5(); + var errors = require_errors3(); var EventEmitter = __require("events"); class PoolResource extends EventEmitter { @@ -91185,7 +80197,7 @@ var require_smtp_pool = __commonJS((exports, module) => { var SMTPConnection = require_smtp_connection(); var wellKnown = require_well_known(); var shared = require_shared3(); - var errors = require_errors5(); + var errors = require_errors3(); var packageData = require_package5(); class SMTPPool extends EventEmitter { @@ -91471,9 +80483,9 @@ var require_smtp_pool = __commonJS((exports, module) => { } } _removeConnection(connection) { - const index2 = this._connections.indexOf(connection); - if (index2 !== -1) { - this._connections.splice(index2, 1); + const index3 = this._connections.indexOf(connection); + if (index3 !== -1) { + this._connections.splice(index3, 1); } } _checkRateLimit(callback) { @@ -91595,7 +80607,7 @@ var require_smtp_transport = __commonJS((exports, module) => { var wellKnown = require_well_known(); var shared = require_shared3(); var XOAuth2 = require_xoauth2(); - var errors = require_errors5(); + var errors = require_errors3(); var packageData = require_package5(); class SMTPTransport extends EventEmitter { @@ -91873,7 +80885,7 @@ var require_sendmail_transport = __commonJS((exports, module) => { var { spawn } = __require("child_process"); var packageData = require_package5(); var shared = require_shared3(); - var errors = require_errors5(); + var errors = require_errors3(); class SendmailTransport { constructor(options) { @@ -92298,7 +81310,7 @@ var require_nodemailer = __commonJS((exports, module) => { var StreamTransport = require_stream_transport(); var JSONTransport = require_json_transport(); var SESTransport = require_ses_transport(); - var errors = require_errors5(); + var errors = require_errors3(); var nmfetch = require_fetch(); var packageData = require_package5(); var ETHEREAL_API = (process.env.ETHEREAL_API || "https://api.nodemailer.com").replace(/\/+$/, ""); @@ -92658,11 +81670,11 @@ var require_client3 = __commonJS((exports) => { var state = { warningEmitted: false }; - var emitWarningIfUnsupportedVersion = (version2) => { - if (version2 && !state.warningEmitted && parseInt(version2.substring(1, version2.indexOf("."))) < 20) { + var emitWarningIfUnsupportedVersion = (version3) => { + if (version3 && !state.warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 20) { state.warningEmitted = true; process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js ${version2} in January 2026. +no longer support Node.js ${version3} in January 2026. To continue receiving updates to AWS services, bug fixes, and security updates please upgrade to a supported Node.js LTS version. @@ -93586,8 +82598,8 @@ var require_dist_cjs9 = __commonJS((exports) => { if (typeof maxSockets !== "number" || maxSockets === Infinity) { return socketWarningTimestamp; } - const interval2 = 15000; - if (Date.now() - interval2 < socketWarningTimestamp) { + const interval3 = 15000; + if (Date.now() - interval3 < socketWarningTimestamp) { return socketWarningTimestamp; } if (sockets && requests) { @@ -93789,23 +82801,23 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf return this.sessions.shift(); } } - offerLast(session2) { - this.sessions.push(session2); + offerLast(session3) { + this.sessions.push(session3); } - contains(session2) { - return this.sessions.includes(session2); + contains(session3) { + return this.sessions.includes(session3); } - remove(session2) { - this.sessions = this.sessions.filter((s) => s !== session2); + remove(session3) { + this.sessions = this.sessions.filter((s) => s !== session3); } [Symbol.iterator]() { return this.sessions[Symbol.iterator](); } destroy(connection) { - for (const session2 of this.sessions) { - if (session2 === connection) { - if (!session2.destroyed) { - session2.destroy(); + for (const session3 of this.sessions) { + if (session3 === connection) { + if (!session3.destroyed) { + session3.destroy(); } } } @@ -93830,53 +82842,53 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf return existingSession; } } - const session2 = http2.connect(url); + const session3 = http2.connect(url); if (this.config.maxConcurrency) { - session2.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { + session3.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { if (err) { throw new Error("Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString()); } }); } - session2.unref(); + session3.unref(); const destroySessionCb = () => { - session2.destroy(); - this.deleteSession(url, session2); + session3.destroy(); + this.deleteSession(url, session3); }; - session2.on("goaway", destroySessionCb); - session2.on("error", destroySessionCb); - session2.on("frameError", destroySessionCb); - session2.on("close", () => this.deleteSession(url, session2)); + session3.on("goaway", destroySessionCb); + session3.on("error", destroySessionCb); + session3.on("frameError", destroySessionCb); + session3.on("close", () => this.deleteSession(url, session3)); if (connectionConfiguration.requestTimeout) { - session2.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); + session3.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); } const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool; - connectionPool.offerLast(session2); + connectionPool.offerLast(session3); this.sessionCache.set(url, connectionPool); - return session2; + return session3; } - deleteSession(authority, session2) { + deleteSession(authority, session3) { const existingConnectionPool = this.sessionCache.get(authority); if (!existingConnectionPool) { return; } - if (!existingConnectionPool.contains(session2)) { + if (!existingConnectionPool.contains(session3)) { return; } - existingConnectionPool.remove(session2); + existingConnectionPool.remove(session3); this.sessionCache.set(authority, existingConnectionPool); } - release(requestContext, session2) { + release(requestContext, session3) { const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session2); + this.sessionCache.get(cacheKey)?.offerLast(session3); } destroy() { for (const [key, connectionPool] of this.sessionCache) { - for (const session2 of connectionPool) { - if (!session2.destroyed) { - session2.destroy(); + for (const session3 of connectionPool) { + if (!session3.destroyed) { + session3.destroy(); } - connectionPool.remove(session2); + connectionPool.remove(session3); } this.sessionCache.delete(key); } @@ -93956,13 +82968,13 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf } const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; const requestContext = { destination: new URL(authority) }; - const session2 = this.connectionManager.lease(requestContext, { + const session3 = this.connectionManager.lease(requestContext, { requestTimeout: this.config?.sessionTimeout, isEventStream }); const rejectWithDestroy = (err) => { if (disableConcurrentStreams) { - this.destroySession(session2); + this.destroySession(session3); } fulfilled = true; reject(err); @@ -93975,12 +82987,12 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf if (request.fragment) { path2 += `#${request.fragment}`; } - const req = session2.request({ + const req = session3.request({ ...request.headers, [http2.constants.HTTP2_HEADER_PATH]: path2, [http2.constants.HTTP2_HEADER_METHOD]: method }); - session2.ref(); + session3.ref(); req.on("response", (headers) => { const httpResponse = new protocolHttp.HttpResponse({ statusCode: headers[":status"] ?? -1, @@ -93990,8 +83002,8 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf fulfilled = true; resolve({ response: httpResponse }); if (disableConcurrentStreams) { - session2.close(); - this.connectionManager.deleteSession(authority, session2); + session3.close(); + this.connectionManager.deleteSession(authority, session3); } }); if (effectiveRequestTimeout) { @@ -94024,9 +83036,9 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); }); req.on("close", () => { - session2.unref(); + session3.unref(); if (disableConcurrentStreams) { - session2.destroy(); + session3.destroy(); } if (!fulfilled) { rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); @@ -94047,9 +83059,9 @@ or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler conf httpHandlerConfigs() { return this.config ?? {}; } - destroySession(session2) { - if (!session2.destroyed) { - session2.destroy(); + destroySession(session3) { + if (!session3.destroyed) { + session3.destroy(); } } } @@ -94638,8 +83650,8 @@ var require_tslib = __commonJS((exports, module) => { var __spread; var __spreadArrays; var __spreadArray; - var __await; - var __asyncGenerator; + var __await2; + var __asyncGenerator2; var __asyncDelegator; var __asyncValues; var __makeTemplateObject; @@ -94973,10 +83985,10 @@ var require_tslib = __commonJS((exports, module) => { } return to.concat(ar || Array.prototype.slice.call(from)); }; - __await = function(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); + __await2 = function(v) { + return this instanceof __await2 ? (this.v = v, this) : new __await2(v); }; - __asyncGenerator = function(thisArg, _arguments, generator) { + __asyncGenerator2 = function(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; @@ -95007,7 +84019,7 @@ var require_tslib = __commonJS((exports, module) => { } } function step(r) { - r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + r.value instanceof __await2 ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); @@ -95029,7 +84041,7 @@ var require_tslib = __commonJS((exports, module) => { }, 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; + return (p = !p) ? { value: __await2(o[n](v)), done: false } : f ? f(v) : v; } : f; } }; @@ -95207,8 +84219,8 @@ var require_tslib = __commonJS((exports, module) => { exporter("__spread", __spread); exporter("__spreadArrays", __spreadArrays); exporter("__spreadArray", __spreadArray); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); + exporter("__await", __await2); + exporter("__asyncGenerator", __asyncGenerator2); exporter("__asyncDelegator", __asyncDelegator); exporter("__asyncValues", __asyncValues); exporter("__makeTemplateObject", __makeTemplateObject); @@ -95843,7 +84855,7 @@ var require_endpoints = __commonJS((exports) => { }); // node_modules/.pnpm/@smithy+core@3.23.15/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js -var require_schema3 = __commonJS((exports) => { +var require_schema = __commonJS((exports) => { var protocolHttp = require_dist_cjs2(); var utilMiddleware = require_dist_cjs13(); var endpoints = require_endpoints(); @@ -95881,15 +84893,15 @@ var require_schema3 = __commonJS((exports) => { configurable: false }); if (!("$metadata" in error2)) { - const hint2 = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + const hint3 = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; try { error2.message += ` - ` + hint2; + ` + hint3; } catch (e2) { if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint2); + console.warn(hint3); } else { - context.logger?.warn?.(hint2); + context.logger?.warn?.(hint3); } } if (typeof error2.$responseBodyText !== "undefined") { @@ -95954,7 +84966,7 @@ var require_schema3 = __commonJS((exports) => { }; } - class Schema3 { + class Schema4 { name; namespace; traits; @@ -95975,21 +84987,21 @@ var require_schema3 = __commonJS((exports) => { } } - class ListSchema extends Schema3 { + class ListSchema extends Schema4 { static symbol = Symbol.for("@smithy/lis"); name; traits; valueSchema; symbol = ListSchema.symbol; } - var list = (namespace, name, traits, valueSchema) => Schema3.assign(new ListSchema, { + var list = (namespace, name, traits, valueSchema) => Schema4.assign(new ListSchema, { name, namespace, traits, valueSchema }); - class MapSchema extends Schema3 { + class MapSchema extends Schema4 { static symbol = Symbol.for("@smithy/map"); name; traits; @@ -95997,7 +85009,7 @@ var require_schema3 = __commonJS((exports) => { valueSchema; symbol = MapSchema.symbol; } - var map = (namespace, name, traits, keySchema, valueSchema) => Schema3.assign(new MapSchema, { + var map = (namespace, name, traits, keySchema, valueSchema) => Schema4.assign(new MapSchema, { name, namespace, traits, @@ -96005,7 +85017,7 @@ var require_schema3 = __commonJS((exports) => { valueSchema }); - class OperationSchema extends Schema3 { + class OperationSchema extends Schema4 { static symbol = Symbol.for("@smithy/ope"); name; traits; @@ -96013,7 +85025,7 @@ var require_schema3 = __commonJS((exports) => { output; symbol = OperationSchema.symbol; } - var op = (namespace, name, traits, input, output) => Schema3.assign(new OperationSchema, { + var op = (namespace, name, traits, input, output) => Schema4.assign(new OperationSchema, { name, namespace, traits, @@ -96021,7 +85033,7 @@ var require_schema3 = __commonJS((exports) => { output }); - class StructureSchema extends Schema3 { + class StructureSchema extends Schema4 { static symbol = Symbol.for("@smithy/str"); name; traits; @@ -96029,7 +85041,7 @@ var require_schema3 = __commonJS((exports) => { memberList; symbol = StructureSchema.symbol; } - var struct = (namespace, name, traits, memberNames, memberList) => Schema3.assign(new StructureSchema, { + var struct = (namespace, name, traits, memberNames, memberList) => Schema4.assign(new StructureSchema, { name, namespace, traits, @@ -96042,7 +85054,7 @@ var require_schema3 = __commonJS((exports) => { ctor; symbol = ErrorSchema.symbol; } - var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema3.assign(new ErrorSchema, { + var error = (namespace, name, traits, memberNames, memberList, ctor) => Schema4.assign(new ErrorSchema, { name, namespace, traits, @@ -96357,20 +85369,20 @@ var require_schema3 = __commonJS((exports) => { var isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; var isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; - class SimpleSchema extends Schema3 { + class SimpleSchema extends Schema4 { static symbol = Symbol.for("@smithy/sim"); name; schemaRef; traits; symbol = SimpleSchema.symbol; } - var sim = (namespace, name, schemaRef, traits) => Schema3.assign(new SimpleSchema, { + var sim = (namespace, name, schemaRef, traits) => Schema4.assign(new SimpleSchema, { name, namespace, traits, schemaRef }); - var simAdapter = (namespace, name, traits, schemaRef) => Schema3.assign(new SimpleSchema, { + var simAdapter = (namespace, name, traits, schemaRef) => Schema4.assign(new SimpleSchema, { name, namespace, traits, @@ -96483,7 +85495,7 @@ var require_schema3 = __commonJS((exports) => { exports.NormalizedSchema = NormalizedSchema; exports.OperationSchema = OperationSchema; exports.SCHEMA = SCHEMA; - exports.Schema = Schema3; + exports.Schema = Schema4; exports.SimpleSchema = SimpleSchema; exports.StructureSchema = StructureSchema; exports.TypeRegistry = TypeRegistry; @@ -96534,7 +85546,7 @@ var require_dist_cjs20 = __commonJS((exports) => { // node_modules/.pnpm/@smithy+core@3.23.15/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js var require_serde = __commonJS((exports) => { - var uuid2 = require_dist_cjs20(); + var uuid3 = require_dist_cjs20(); var copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; var parseBoolean = (value) => { switch (value) { @@ -96764,14 +85776,14 @@ var require_serde = __commonJS((exports) => { }; var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - function dateToUtcString(date4) { - const year2 = date4.getUTCFullYear(); - const month = date4.getUTCMonth(); - const dayOfWeek = date4.getUTCDay(); - const dayOfMonthInt = date4.getUTCDate(); - const hoursInt = date4.getUTCHours(); - const minutesInt = date4.getUTCMinutes(); - const secondsInt = date4.getUTCSeconds(); + function dateToUtcString(date5) { + const year2 = date5.getUTCFullYear(); + const month = date5.getUTCMonth(); + const dayOfWeek = date5.getUTCDay(); + const dayOfMonthInt = date5.getUTCDate(); + const hoursInt = date5.getUTCHours(); + const minutesInt = date5.getUTCMinutes(); + const secondsInt = date5.getUTCSeconds(); const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; @@ -96812,11 +85824,11 @@ var require_serde = __commonJS((exports) => { const year2 = strictParseShort(stripLeadingZeroes(yearStr)); const month = parseDateValue(monthStr, "month", 1, 12); const day = parseDateValue(dayStr, "day", 1, 31); - const date4 = buildDate(year2, month, day, { hours, minutes, seconds, fractionalMilliseconds }); + const date5 = buildDate(year2, month, day, { hours, minutes, seconds, fractionalMilliseconds }); if (offsetStr.toUpperCase() != "Z") { - date4.setTime(date4.getTime() - parseOffsetToMilliseconds(offsetStr)); + date5.setTime(date5.getTime() - parseOffsetToMilliseconds(offsetStr)); } - return date4; + return date5; }; var IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); var RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); @@ -96869,10 +85881,10 @@ var require_serde = __commonJS((exports) => { } return new Date(Math.round(valueAsDouble * 1000)); }; - var buildDate = (year2, month, day, time3) => { + var buildDate = (year2, month, day, time4) => { const adjustedMonth = month - 1; validateDayOfMonth(year2, adjustedMonth, day); - return new Date(Date.UTC(year2, adjustedMonth, day, parseDateValue(time3.hours, "hour", 0, 23), parseDateValue(time3.minutes, "minute", 0, 59), parseDateValue(time3.seconds, "seconds", 0, 60), parseMilliseconds(time3.fractionalMilliseconds))); + return new Date(Date.UTC(year2, adjustedMonth, day, parseDateValue(time4.hours, "hour", 0, 23), parseDateValue(time4.minutes, "minute", 0, 59), parseDateValue(time4.seconds, "seconds", 0, 60), parseMilliseconds(time4.fractionalMilliseconds))); }; var parseTwoDigitYear = (value) => { const thisYear = new Date().getUTCFullYear(); @@ -96977,13 +85989,13 @@ var require_serde = __commonJS((exports) => { } var ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; var mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; - var time2 = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; - var date3 = `(\\d?\\d)`; + var time3 = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; + var date4 = `(\\d?\\d)`; var year = `(\\d{4})`; var RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); - var IMF_FIXDATE = new RegExp(`^${ddd}, ${date3} ${mmm} ${year} ${time2} GMT$`); - var RFC_850_DATE = new RegExp(`^${ddd}, ${date3}-${mmm}-(\\d\\d) ${time2} GMT$`); - var ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time2} ${year}$`); + var IMF_FIXDATE = new RegExp(`^${ddd}, ${date4} ${mmm} ${year} ${time3} GMT$`); + var RFC_850_DATE = new RegExp(`^${ddd}, ${date4}-${mmm}-(\\d\\d) ${time3} GMT$`); + var ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time3} ${year}$`); var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var _parseEpochTimestamp = (value) => { if (value == null) { @@ -97022,14 +86034,14 @@ var require_serde = __commonJS((exports) => { range(hours, 0, 23); range(minutes, 0, 59); range(seconds, 0, 60); - const date4 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0)); - date4.setUTCFullYear(Number(yearStr)); + const date5 = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0)); + date5.setUTCFullYear(Number(yearStr)); if (offsetStr.toUpperCase() != "Z") { const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [undefined, "+", 0, 0]; const scalar = sign === "-" ? 1 : -1; - date4.setTime(date4.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); + date5.setTime(date5.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); } - return date4; + return date5; }; var _parseRfc7231DateTime = (value) => { if (value == null) { @@ -97055,14 +86067,14 @@ var require_serde = __commonJS((exports) => { [, month, day, hour, minute, second, fraction, year2] = matches; } if (year2 && second) { - const timestamp2 = Date.UTC(Number(year2), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); + const timestamp3 = Date.UTC(Number(year2), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); range(day, 1, 31); range(hour, 0, 23); range(minute, 0, 59); range(second, 0, 60); - const date4 = new Date(timestamp2); - date4.setUTCFullYear(Number(year2)); - return date4; + const date5 = new Date(timestamp3); + date5.setUTCFullYear(Number(year2)); + return date5; } throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); }; @@ -97105,8 +86117,8 @@ var require_serde = __commonJS((exports) => { let prevChar = undefined; let anchor = 0; for (let i = 0;i < z; ++i) { - const char2 = value[i]; - switch (char2) { + const char3 = value[i]; + switch (char3) { case `"`: if (prevChar !== "\\") { withinQuotes = !withinQuotes; @@ -97119,7 +86131,7 @@ var require_serde = __commonJS((exports) => { } break; } - prevChar = char2; + prevChar = char3; } values.push(value.slice(anchor)); return values.map((v) => { @@ -97160,7 +86172,7 @@ var require_serde = __commonJS((exports) => { function nv(input) { return new NumericValue(String(input), "bigDecimal"); } - exports.generateIdempotencyToken = uuid2.v4; + exports.generateIdempotencyToken = uuid3.v4; exports.LazyJsonString = LazyJsonString; exports.NumericValue = NumericValue; exports._parseEpochTimestamp = _parseEpochTimestamp; @@ -97448,7 +86460,7 @@ var require_event_streams = __commonJS((exports) => { // node_modules/.pnpm/@smithy+core@3.23.15/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js var require_protocols = __commonJS((exports) => { var utilStream = require_dist_cjs12(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var serde = require_serde(); var protocolHttp = require_dist_cjs2(); var utilBase64 = require_dist_cjs6(); @@ -98279,7 +87291,7 @@ var require_protocols = __commonJS((exports) => { var require_dist_cjs21 = __commonJS((exports) => { var middlewareStack = require_dist_cjs17(); var types3 = require_dist_cjs(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var serde = require_serde(); var protocols = require_protocols(); @@ -98629,8 +87641,8 @@ var require_dist_cjs21 = __commonJS((exports) => { } }; var warningEmitted = false; - var emitWarningIfUnsupportedVersion = (version2) => { - if (version2 && !warningEmitted && parseInt(version2.substring(1, version2.indexOf("."))) < 16) { + var emitWarningIfUnsupportedVersion = (version3) => { + if (version3 && !warningEmitted && parseInt(version3.substring(1, version3.indexOf("."))) < 16) { warningEmitted = true; } }; @@ -98824,7 +87836,7 @@ var require_dist_cjs21 = __commonJS((exports) => { return value; } }; - var serializeDateTime = (date3) => date3.toISOString().replace(".000Z", "Z"); + var serializeDateTime = (date4) => date4.toISOString().replace(".000Z", "Z"); var _json = (obj) => { if (obj == null) { return {}; @@ -99169,18 +88181,18 @@ var require_dist_cjs22 = __commonJS((exports) => { } return keys.sort().map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); }; - var iso8601 = (time2) => toDate(time2).toISOString().replace(/\.\d{3}Z$/, "Z"); - var toDate = (time2) => { - if (typeof time2 === "number") { - return new Date(time2 * 1000); + var iso8601 = (time3) => toDate(time3).toISOString().replace(/\.\d{3}Z$/, "Z"); + var toDate = (time3) => { + if (typeof time3 === "number") { + return new Date(time3 * 1000); } - if (typeof time2 === "string") { - if (Number(time2)) { - return new Date(Number(time2) * 1000); + if (typeof time3 === "string") { + if (Number(time3)) { + return new Date(Number(time3) * 1000); } - return new Date(time2); + return new Date(time3); } - return time2; + return time3; }; class SignatureV4Base { @@ -99814,7 +88826,7 @@ var require_cbor = __commonJS((exports) => { var protocols = require_protocols(); var protocolHttp = require_dist_cjs2(); var utilBodyLengthBrowser = require_dist_cjs25(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var utilMiddleware = require_dist_cjs13(); var utilBase64 = require_dist_cjs6(); var majorUint64 = 0; @@ -99838,7 +88850,7 @@ var require_cbor = __commonJS((exports) => { return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); } var tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); - function tag2(data2) { + function tag3(data2) { data2[tagSymbol] = true; return data2; } @@ -99938,7 +88950,7 @@ var require_cbor = __commonJS((exports) => { const value = decode(at + offset, to); const valueOffset = _offset; _offset = offset + valueOffset; - return tag2({ tag: castBigInt(unsignedInt), value }); + return tag3({ tag: castBigInt(unsignedInt), value }); } } case majorUtf8String: @@ -100058,11 +89070,11 @@ var require_cbor = __commonJS((exports) => { } function decodeUtf8StringIndefinite(at, to) { at += 1; - const vector2 = []; + const vector3 = []; for (const base = at;at < to; ) { if (payload[at] === 255) { - const data2 = alloc(vector2.length); - data2.set(vector2, 0); + const data2 = alloc(vector3.length); + data2.set(vector3, 0); _offset = at - base + 2; return bytesToUtf8(data2, 0, data2.length); } @@ -100078,7 +89090,7 @@ var require_cbor = __commonJS((exports) => { const length = _offset; at += length; for (let i = 0;i < bytes.length; ++i) { - vector2.push(bytes[i]); + vector3.push(bytes[i]); } } throw new Error("expected break marker."); @@ -100096,11 +89108,11 @@ var require_cbor = __commonJS((exports) => { } function decodeUnstructuredByteStringIndefinite(at, to) { at += 1; - const vector2 = []; + const vector3 = []; for (const base = at;at < to; ) { if (payload[at] === 255) { - const data2 = alloc(vector2.length); - data2.set(vector2, 0); + const data2 = alloc(vector3.length); + data2.set(vector3, 0); _offset = at - base + 2; return data2; } @@ -100116,7 +89128,7 @@ var require_cbor = __commonJS((exports) => { const length = _offset; at += length; for (let i = 0;i < bytes.length; ++i) { - vector2.push(bytes[i]); + vector3.push(bytes[i]); } } throw new Error("expected break marker."); @@ -100468,10 +89480,10 @@ var require_cbor = __commonJS((exports) => { return {}; }); }; - var dateToTag = (date3) => { - return tag2({ + var dateToTag = (date4) => { + return tag3({ tag: 1, - value: date3.getTime() / 1000 + value: date4.getTime() / 1000 }); }; var parseCborErrorBody = async (errorBody, context) => { @@ -100828,7 +89840,7 @@ var require_cbor = __commonJS((exports) => { exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode; exports.parseCborBody = parseCborBody; exports.parseCborErrorBody = parseCborErrorBody; - exports.tag = tag2; + exports.tag = tag3; exports.tagSymbol = tagSymbol; }); @@ -102544,7 +91556,7 @@ var require_dist_cjs26 = __commonJS((exports) => { // node_modules/.pnpm/@aws-sdk+core@3.974.1/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js var require_protocols2 = __commonJS((exports) => { var cbor = require_cbor(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var smithyClient = require_dist_cjs21(); var protocols = require_protocols(); var serde = require_serde(); @@ -103052,7 +92064,7 @@ var require_protocols2 = __commonJS((exports) => { return value; }; } - replaceInJson(json2) { + replaceInJson(json3) { if (this.stage === 0) { throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); } @@ -103061,12 +92073,12 @@ var require_protocols2 = __commonJS((exports) => { } this.stage = 2; if (this.counter === 0) { - return json2; + return json3; } for (const [key, value] of this.values) { - json2 = json2.replace(key, value); + json3 = json3.replace(key, value); } - return json2; + return json3; } } @@ -104482,14 +93494,14 @@ var require_dist_cjs27 = __commonJS((exports) => { } return pathList; }; - var getAttr = (value, path2) => getAttrPathList(path2).reduce((acc, index2) => { + var getAttr = (value, path2) => getAttrPathList(path2).reduce((acc, index3) => { if (typeof acc !== "object") { - throw new EndpointError(`Index '${index2}' in '${path2}' not found in '${JSON.stringify(value)}'`); + throw new EndpointError(`Index '${index3}' in '${path2}' not found in '${JSON.stringify(value)}'`); } else if (Array.isArray(acc)) { - const i = parseInt(index2); + const i = parseInt(index3); return acc[i < 0 ? acc.length + i : i]; } - return acc[index2]; + return acc[index3]; }, value); var isSet = (value) => value != null; var VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); @@ -105194,10 +94206,10 @@ var require_dist_cjs28 = __commonJS((exports) => { } } ]; - var version2 = "1.1"; + var version3 = "1.1"; var partitionsInfo = { partitions, - version: version2 + version: version3 }; var selectedPartitionsInfo = partitionsInfo; var selectedUserAgentPrefix = ""; @@ -105419,14 +94431,14 @@ var require_dist_cjs30 = __commonJS((exports) => { this.availableTokens = this.availableTokens - amount; } refillTokenBucket() { - const timestamp2 = this.getCurrentTimeInSeconds(); + const timestamp3 = this.getCurrentTimeInSeconds(); if (!this.lastTimestamp) { - this.lastTimestamp = timestamp2; + this.lastTimestamp = timestamp3; return; } - const fillAmount = (timestamp2 - this.lastTimestamp) * this.fillRate; + const fillAmount = (timestamp3 - this.lastTimestamp) * this.fillRate; this.availableTokens = Math.min(this.maxCapacity, this.availableTokens + fillAmount); - this.lastTimestamp = timestamp2; + this.lastTimestamp = timestamp3; } calculateTimeWindow() { this.timeWindow = this.getPrecise(Math.pow(this.lastMaxRate * (1 - this.beta) / this.scaleConstant, 1 / 3)); @@ -105434,8 +94446,8 @@ var require_dist_cjs30 = __commonJS((exports) => { cubicThrottle(rateToUse) { return this.getPrecise(rateToUse * this.beta); } - cubicSuccess(timestamp2) { - return this.getPrecise(this.scaleConstant * Math.pow(timestamp2 - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); + cubicSuccess(timestamp3) { + return this.getPrecise(this.scaleConstant * Math.pow(timestamp3 - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); } enableTokenBucket() { this.enabled = true; @@ -105508,9 +94520,9 @@ var require_dist_cjs30 = __commonJS((exports) => { count; cost; longPoll; - constructor(delay, count, cost, longPoll) { + constructor(delay, count2, cost, longPoll) { this.delay = delay; - this.count = count; + this.count = count2; this.cost = cost; this.longPoll = longPoll; } @@ -105805,15 +94817,15 @@ var require_dist_cjs31 = __commonJS((exports) => { }; var escapeUserAgent = (userAgentPair) => { const name = userAgentPair[0].split(UA_NAME_SEPARATOR).map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)).join(UA_NAME_SEPARATOR); - const version2 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); + const version3 = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); const prefix = name.substring(0, prefixSeparatorIndex); let uaName = name.substring(prefixSeparatorIndex + 1); if (prefix === "api") { uaName = uaName.toLowerCase(); } - return [prefix, uaName, version2].filter((item) => item && item.length > 0).reduce((acc, item, index2) => { - switch (index2) { + return [prefix, uaName, version3].filter((item) => item && item.length > 0).reduce((acc, item, index3) => { + switch (index3) { case 0: return item; case 1: @@ -106533,15 +95545,15 @@ var require_dist_cjs37 = __commonJS((exports) => { configurable: false }); if (!("$metadata" in error)) { - const hint2 = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; + const hint3 = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; try { error.message += ` - ` + hint2; + ` + hint3; } catch (e2) { if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint2); + console.warn(hint3); } else { - context.logger?.warn?.(hint2); + context.logger?.warn?.(hint3); } } if (typeof error.$responseBodyText !== "undefined") { @@ -106874,7 +95886,7 @@ var require_dist_cjs39 = __commonJS((exports) => { var utilRetry = require_dist_cjs30(); var protocolHttp = require_dist_cjs2(); var serviceErrorClassification = require_dist_cjs29(); - var uuid2 = require_dist_cjs20(); + var uuid3 = require_dist_cjs20(); var utilMiddleware = require_dist_cjs13(); var smithyClient = require_dist_cjs21(); var isStreamingPayload = require_isStreamingPayload(); @@ -106953,7 +95965,7 @@ var require_dist_cjs39 = __commonJS((exports) => { const maxAttempts = await this.getMaxAttempts(); const { request } = args; if (protocolHttp.HttpRequest.isInstance(request)) { - request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid2.v4(); + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid3.v4(); } while (true) { try { @@ -107099,8 +96111,8 @@ var require_dist_cjs39 = __commonJS((exports) => { let retryAfterSeconds = NaN; if (retryAfter.endsWith("GMT")) { try { - const date3 = serde.parseRfc7231DateTime(retryAfter); - retryAfterSeconds = (date3.getTime() - Date.now()) / 1000; + const date4 = serde.parseRfc7231DateTime(retryAfter); + retryAfterSeconds = (date4.getTime() - Date.now()) / 1000; } catch (e2) { logger?.trace?.("Failed to parse retry-after header"); logger?.trace?.(e2); @@ -107142,7 +96154,7 @@ var require_dist_cjs39 = __commonJS((exports) => { const { request } = args; const isRequest = protocolHttp.HttpRequest.isInstance(request); if (isRequest) { - request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid2.v4(); + request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid3.v4(); } while (true) { try { @@ -108359,7 +97371,7 @@ var require_package6 = __commonJS((exports, module) => { // node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.17/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js var require_dist_cjs40 = __commonJS((exports) => { - var __dirname = "/Users/shivamverma/Desktop/CodeSM/backend/node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.17/node_modules/@aws-sdk/util-user-agent-node/dist-cjs"; + var __dirname = "/home/kmadhav824/Desktop/CodeSM/backend/node_modules/.pnpm/@aws-sdk+util-user-agent-node@3.973.17/node_modules/@aws-sdk/util-user-agent-node/dist-cjs"; var node_os = __require("os"); var node_process = __require("process"); var utilConfigProvider = require_dist_cjs23(); @@ -108390,8 +97402,8 @@ var require_dist_cjs40 = __commonJS((exports) => { return [parentDir, cwd]; }; var SEMVER_REGEX = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/; - var getSanitizedTypeScriptVersion = (version2 = "") => { - const match = version2.match(SEMVER_REGEX); + var getSanitizedTypeScriptVersion = (version3 = "") => { + const match = version3.match(SEMVER_REGEX); if (!match) { return; } @@ -108400,12 +97412,12 @@ var require_dist_cjs40 = __commonJS((exports) => { }; var ALLOWED_PREFIXES = ["^", "~", ">=", "<=", ">", "<"]; var ALLOWED_DIST_TAGS = ["latest", "beta", "dev", "rc", "insiders", "next"]; - var getSanitizedDevTypeScriptVersion = (version2 = "") => { - if (ALLOWED_DIST_TAGS.includes(version2)) { - return version2; + var getSanitizedDevTypeScriptVersion = (version3 = "") => { + if (ALLOWED_DIST_TAGS.includes(version3)) { + return version3; } - const prefix = ALLOWED_PREFIXES.find((p2) => version2.startsWith(p2)) ?? ""; - const sanitizedTypeScriptVersion = getSanitizedTypeScriptVersion(version2.slice(prefix.length)); + const prefix = ALLOWED_PREFIXES.find((p2) => version3.startsWith(p2)) ?? ""; + const sanitizedTypeScriptVersion = getSanitizedTypeScriptVersion(version3.slice(prefix.length)); if (!sanitizedTypeScriptVersion) { return; } @@ -108435,11 +97447,11 @@ var require_dist_cjs40 = __commonJS((exports) => { const appPackageJsonPath = node_path.join(nodeModulesParentDir, "package.json"); const packageJson = await promises.readFile(appPackageJsonPath, "utf-8"); const { dependencies, devDependencies } = JSON.parse(packageJson); - const version2 = devDependencies?.typescript ?? dependencies?.typescript; - if (typeof version2 !== "string") { + const version3 = devDependencies?.typescript ?? dependencies?.typescript; + if (typeof version3 !== "string") { continue; } - versionFromApp = version2; + versionFromApp = version3; break; } catch {} } @@ -108452,8 +97464,8 @@ var require_dist_cjs40 = __commonJS((exports) => { try { const tsPackageJsonPath = node_path.join(nodeModulesParentDir, TS_PACKAGE_JSON); const packageJson = await promises.readFile(tsPackageJsonPath, "utf-8"); - const { version: version2 } = JSON.parse(packageJson); - const sanitizedVersion2 = getSanitizedTypeScriptVersion(version2); + const { version: version3 } = JSON.parse(packageJson); + const sanitizedVersion2 = getSanitizedTypeScriptVersion(version3); if (typeof sanitizedVersion2 !== "string") { continue; } @@ -108836,7 +97848,7 @@ var require_SSOOIDCServiceException = __commonJS((exports) => { }); // node_modules/.pnpm/@aws-sdk+nested-clients@3.996.21/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/models/errors.js -var require_errors6 = __commonJS((exports) => { +var require_errors4 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.UnsupportedGrantTypeException = exports.UnauthorizedClientException = exports.SlowDownException = exports.InvalidScopeException = exports.InvalidRequestException = exports.InvalidGrantException = exports.InvalidClientException = exports.InternalServerException = exports.ExpiredTokenException = exports.AuthorizationPendingException = exports.AccessDeniedException = undefined; var SSOOIDCServiceException_1 = require_SSOOIDCServiceException(); @@ -109089,8 +98101,8 @@ var require_schemas_0 = __commonJS((exports) => { var _se = "server"; var _tT = "tokenType"; var n02 = "com.amazonaws.ssooidc"; - var schema_1 = require_schema3(); - var errors_1 = require_errors6(); + var schema_1 = require_schema(); + var errors_1 = require_errors4(); var SSOOIDCServiceException_1 = require_SSOOIDCServiceException(); var _s_registry2 = schema_1.TypeRegistry.for(_s2); exports.SSOOIDCServiceException$ = [-3, _s2, "SSOOIDCServiceException", 0, [], []]; @@ -109360,7 +98372,7 @@ var require_sso_oidc = __commonJS((exports) => { var middlewareUserAgent = require_dist_cjs31(); var configResolver = require_dist_cjs32(); var core = require_dist_cjs24(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var middlewareContentLength = require_dist_cjs33(); var middlewareEndpoint = require_dist_cjs38(); var middlewareRetry = require_dist_cjs39(); @@ -109370,7 +98382,7 @@ var require_sso_oidc = __commonJS((exports) => { var regionConfigResolver = require_dist_cjs44(); var protocolHttp = require_dist_cjs2(); var schemas_0 = require_schemas_0(); - var errors = require_errors6(); + var errors = require_errors4(); var SSOOIDCServiceException = require_SSOOIDCServiceException(); var resolveClientEndpointParameters2 = (options) => { return Object.assign(options, { @@ -109391,11 +98403,11 @@ var require_sso_oidc = __commonJS((exports) => { let _credentials = runtimeConfig2.credentials; return { setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { + const index3 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index3 === -1) { _httpAuthSchemes.push(httpAuthScheme); } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + _httpAuthSchemes.splice(index3, 1, httpAuthScheme); } }, httpAuthSchemes() { @@ -109891,7 +98903,7 @@ var require_SSOServiceException = __commonJS((exports) => { }); // node_modules/.pnpm/@aws-sdk+nested-clients@3.996.21/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso/models/errors.js -var require_errors7 = __commonJS((exports) => { +var require_errors5 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.UnauthorizedException = exports.TooManyRequestsException = exports.ResourceNotFoundException = exports.InvalidRequestException = undefined; var SSOServiceException_1 = require_SSOServiceException(); @@ -109988,8 +99000,8 @@ var require_schemas_02 = __commonJS((exports) => { var _sT = "sessionToken"; var _xasbt = "x-amz-sso_bearer_token"; var n02 = "com.amazonaws.sso"; - var schema_1 = require_schema3(); - var errors_1 = require_errors7(); + var schema_1 = require_schema(); + var errors_1 = require_errors5(); var SSOServiceException_1 = require_SSOServiceException(); var _s_registry2 = schema_1.TypeRegistry.for(_s2); exports.SSOServiceException$ = [-3, _s2, "SSOServiceException", 0, [], []]; @@ -110160,7 +99172,7 @@ var require_sso = __commonJS((exports) => { var middlewareUserAgent = require_dist_cjs31(); var configResolver = require_dist_cjs32(); var core = require_dist_cjs24(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var middlewareContentLength = require_dist_cjs33(); var middlewareEndpoint = require_dist_cjs38(); var middlewareRetry = require_dist_cjs39(); @@ -110170,7 +99182,7 @@ var require_sso = __commonJS((exports) => { var regionConfigResolver = require_dist_cjs44(); var protocolHttp = require_dist_cjs2(); var schemas_0 = require_schemas_02(); - var errors = require_errors7(); + var errors = require_errors5(); var SSOServiceException = require_SSOServiceException(); var resolveClientEndpointParameters2 = (options) => { return Object.assign(options, { @@ -110191,11 +99203,11 @@ var require_sso = __commonJS((exports) => { let _credentials = runtimeConfig2.credentials; return { setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { + const index3 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index3 === -1) { _httpAuthSchemes.push(httpAuthScheme); } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + _httpAuthSchemes.splice(index3, 1, httpAuthScheme); } }, httpAuthSchemes() { @@ -110430,22 +99442,22 @@ var import_property_provider15, import_shared_ini_file_loader4, fromSSO = (init3 } if (profile?.sso_session) { const ssoSessions = await import_shared_ini_file_loader4.loadSsoSessionData(init3); - const session2 = ssoSessions[profile.sso_session]; + const session3 = ssoSessions[profile.sso_session]; const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; - if (ssoRegion && ssoRegion !== session2.sso_region) { + if (ssoRegion && ssoRegion !== session3.sso_region) { throw new import_property_provider15.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { tryNextLink: false, logger: init3.logger }); } - if (ssoStartUrl && ssoStartUrl !== session2.sso_start_url) { + if (ssoStartUrl && ssoStartUrl !== session3.sso_start_url) { throw new import_property_provider15.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { tryNextLink: false, logger: init3.logger }); } - profile.sso_region = session2.sso_region; - profile.sso_start_url = session2.sso_start_url; + profile.sso_region = session3.sso_region; + profile.sso_start_url = session3.sso_start_url; } const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init3.logger); return resolveSSOCredentials({ @@ -110847,7 +99859,7 @@ var require_STSServiceException = __commonJS((exports) => { }); // node_modules/.pnpm/@aws-sdk+nested-clients@3.996.21/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/models/errors.js -var require_errors8 = __commonJS((exports) => { +var require_errors6 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.IDPCommunicationErrorException = exports.InvalidIdentityTokenException = exports.IDPRejectedClaimException = exports.RegionDisabledException = exports.PackedPolicyTooLargeException = exports.MalformedPolicyDocumentException = exports.ExpiredTokenException = undefined; var STSServiceException_1 = require_STSServiceException(); @@ -111014,8 +100026,8 @@ var require_schemas_03 = __commonJS((exports) => { var _s2 = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; var _tLT = "tagListType"; var n02 = "com.amazonaws.sts"; - var schema_1 = require_schema3(); - var errors_1 = require_errors8(); + var schema_1 = require_schema(); + var errors_1 = require_errors6(); var STSServiceException_1 = require_STSServiceException(); var _s_registry2 = schema_1.TypeRegistry.for(_s2); exports.STSServiceException$ = [-3, _s2, "STSServiceException", 0, [], []]; @@ -111279,11 +100291,11 @@ var require_httpAuthExtensionConfiguration = __commonJS((exports) => { let _credentials = runtimeConfig.credentials; return { setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { + const index3 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index3 === -1) { _httpAuthSchemes.push(httpAuthScheme); } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + _httpAuthSchemes.splice(index3, 1, httpAuthScheme); } }, httpAuthSchemes() { @@ -111340,7 +100352,7 @@ var require_STSClient = __commonJS((exports) => { var middleware_user_agent_1 = require_dist_cjs31(); var config_resolver_1 = require_dist_cjs32(); var core_1 = require_dist_cjs24(); - var schema_1 = require_schema3(); + var schema_1 = require_schema(); var middleware_content_length_1 = require_dist_cjs33(); var middleware_endpoint_1 = require_dist_cjs38(); var middleware_retry_1 = require_dist_cjs39(); @@ -111397,7 +100409,7 @@ var require_sts = __commonJS((exports) => { var middlewareEndpoint = require_dist_cjs38(); var EndpointParameters = require_EndpointParameters(); var schemas_0 = require_schemas_03(); - var errors = require_errors8(); + var errors = require_errors6(); var client = require_client3(); var regionConfigResolver = require_dist_cjs44(); var STSServiceException = require_STSServiceException(); @@ -111896,7 +100908,7 @@ var require_SigninServiceException = __commonJS((exports) => { }); // node_modules/.pnpm/@aws-sdk+nested-clients@3.996.21/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/models/errors.js -var require_errors9 = __commonJS((exports) => { +var require_errors7 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidationException = exports.TooManyRequestsError = exports.InternalServerException = exports.AccessDeniedException = undefined; var SigninServiceException_1 = require_SigninServiceException(); @@ -112005,8 +101017,8 @@ var require_schemas_04 = __commonJS((exports) => { var _tO = "tokenOutput"; var _tT = "tokenType"; var n02 = "com.amazonaws.signin"; - var schema_1 = require_schema3(); - var errors_1 = require_errors9(); + var schema_1 = require_schema(); + var errors_1 = require_errors7(); var SigninServiceException_1 = require_SigninServiceException(); var _s_registry2 = schema_1.TypeRegistry.for(_s2); exports.SigninServiceException$ = [-3, _s2, "SigninServiceException", 0, [], []]; @@ -112208,7 +101220,7 @@ var require_signin = __commonJS((exports) => { var middlewareUserAgent = require_dist_cjs31(); var configResolver = require_dist_cjs32(); var core = require_dist_cjs24(); - var schema2 = require_schema3(); + var schema2 = require_schema(); var middlewareContentLength = require_dist_cjs33(); var middlewareEndpoint = require_dist_cjs38(); var middlewareRetry = require_dist_cjs39(); @@ -112218,7 +101230,7 @@ var require_signin = __commonJS((exports) => { var regionConfigResolver = require_dist_cjs44(); var protocolHttp = require_dist_cjs2(); var schemas_0 = require_schemas_04(); - var errors = require_errors9(); + var errors = require_errors7(); var SigninServiceException = require_SigninServiceException(); var resolveClientEndpointParameters2 = (options) => { return Object.assign(options, { @@ -112239,11 +101251,11 @@ var require_signin = __commonJS((exports) => { let _credentials = runtimeConfig2.credentials; return { setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { + const index3 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index3 === -1) { _httpAuthSchemes.push(httpAuthScheme); } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + _httpAuthSchemes.splice(index3, 1, httpAuthScheme); } }, httpAuthSchemes() { @@ -115704,7 +104716,7 @@ var require_built = __commonJS((exports) => { }); // node_modules/.pnpm/standard-as-callback@2.1.0/node_modules/standard-as-callback/built/utils.js -var require_utils10 = __commonJS((exports) => { +var require_utils6 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.tryCatch = exports.errorObj = undefined; exports.errorObj = { e: {} }; @@ -115729,7 +104741,7 @@ var require_utils10 = __commonJS((exports) => { // node_modules/.pnpm/standard-as-callback@2.1.0/node_modules/standard-as-callback/built/index.js var require_built2 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - var utils_1 = require_utils10(); + var utils_1 = require_utils6(); function throwLater(e3) { setTimeout(function() { throw e3; @@ -116182,34 +105194,34 @@ var require_lib6 = __commonJS((exports, module) => { 7920 ]; var toUTF8Array = function toUTF8Array2(str) { - var char2; + var char3; var i2 = 0; var p2 = 0; var utf8 = []; var len = str.length; for (;i2 < len; i2++) { - char2 = str.charCodeAt(i2); - if (char2 < 128) { - utf8[p2++] = char2; - } else if (char2 < 2048) { - utf8[p2++] = char2 >> 6 | 192; - utf8[p2++] = char2 & 63 | 128; - } else if ((char2 & 64512) === 55296 && i2 + 1 < str.length && (str.charCodeAt(i2 + 1) & 64512) === 56320) { - char2 = 65536 + ((char2 & 1023) << 10) + (str.charCodeAt(++i2) & 1023); - utf8[p2++] = char2 >> 18 | 240; - utf8[p2++] = char2 >> 12 & 63 | 128; - utf8[p2++] = char2 >> 6 & 63 | 128; - utf8[p2++] = char2 & 63 | 128; + char3 = str.charCodeAt(i2); + if (char3 < 128) { + utf8[p2++] = char3; + } else if (char3 < 2048) { + utf8[p2++] = char3 >> 6 | 192; + utf8[p2++] = char3 & 63 | 128; + } else if ((char3 & 64512) === 55296 && i2 + 1 < str.length && (str.charCodeAt(i2 + 1) & 64512) === 56320) { + char3 = 65536 + ((char3 & 1023) << 10) + (str.charCodeAt(++i2) & 1023); + utf8[p2++] = char3 >> 18 | 240; + utf8[p2++] = char3 >> 12 & 63 | 128; + utf8[p2++] = char3 >> 6 & 63 | 128; + utf8[p2++] = char3 & 63 | 128; } else { - utf8[p2++] = char2 >> 12 | 224; - utf8[p2++] = char2 >> 6 & 63 | 128; - utf8[p2++] = char2 & 63 | 128; + utf8[p2++] = char3 >> 12 | 224; + utf8[p2++] = char3 >> 6 & 63 | 128; + utf8[p2++] = char3 & 63 | 128; } } return utf8; }; var generate = module.exports = function generate2(str) { - var char2; + var char3; var i2 = 0; var start = -1; var result = 0; @@ -116217,17 +105229,17 @@ var require_lib6 = __commonJS((exports, module) => { var utf8 = typeof str === "string" ? toUTF8Array(str) : str; var len = utf8.length; while (i2 < len) { - char2 = utf8[i2++]; + char3 = utf8[i2++]; if (start === -1) { - if (char2 === 123) { + if (char3 === 123) { start = i2; } - } else if (char2 !== 125) { - resultHash = lookup[(char2 ^ resultHash >> 8) & 255] ^ resultHash << 8; + } else if (char3 !== 125) { + resultHash = lookup[(char3 ^ resultHash >> 8) & 255] ^ resultHash << 8; } else if (i2 - 1 !== start) { return resultHash & 16383; } - result = lookup[(char2 ^ result >> 8) & 255] ^ result << 8; + result = lookup[(char3 ^ result >> 8) & 255] ^ result << 8; } return result & 16383; }; @@ -116264,9 +105276,9 @@ var require_lodash8 = __commonJS((exports, module) => { return func.apply(thisArg, args); } function baseTimes(n2, iteratee) { - var index2 = -1, result = Array(n2); - while (++index2 < n2) { - result[index2] = iteratee(index2); + var index3 = -1, result = Array(n2); + while (++index3 < n2) { + result[index3] = iteratee(index3); } return result; } @@ -116312,14 +105324,14 @@ var require_lodash8 = __commonJS((exports, module) => { function baseRest(func, start) { start = nativeMax(start === undefined ? func.length - 1 : start, 0); return function() { - var args = arguments, index2 = -1, length = nativeMax(args.length - start, 0), array2 = Array(length); - while (++index2 < length) { - array2[index2] = args[start + index2]; + var args = arguments, index3 = -1, length = nativeMax(args.length - start, 0), array2 = Array(length); + while (++index3 < length) { + array2[index3] = args[start + index3]; } - index2 = -1; + index3 = -1; var otherArgs = Array(start + 1); - while (++index2 < start) { - otherArgs[index2] = args[index2]; + while (++index3 < start) { + otherArgs[index3] = args[index3]; } otherArgs[start] = array2; return apply(func, this, otherArgs); @@ -116327,9 +105339,9 @@ var require_lodash8 = __commonJS((exports, module) => { } function copyObject(source, props, object2, customizer) { object2 || (object2 = {}); - var index2 = -1, length = props.length; - while (++index2 < length) { - var key = props[index2]; + var index3 = -1, length = props.length; + while (++index3 < length) { + var key = props[index3]; var newValue = customizer ? customizer(object2[key], source[key], key, object2, source) : undefined; assignValue(object2, key, newValue === undefined ? source[key] : newValue); } @@ -116337,17 +105349,17 @@ var require_lodash8 = __commonJS((exports, module) => { } function createAssigner(assigner) { return baseRest(function(object2, sources) { - var index2 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; + var index3 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object2 = Object(object2); - while (++index2 < length) { - var source = sources[index2]; + while (++index3 < length) { + var source = sources[index3]; if (source) { - assigner(object2, source, index2, customizer); + assigner(object2, source, index3, customizer); } } return object2; @@ -116357,13 +105369,13 @@ var require_lodash8 = __commonJS((exports, module) => { length = length == null ? MAX_SAFE_INTEGER3 : length; return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } - function isIterateeCall(value, index2, object2) { + function isIterateeCall(value, index3, object2) { if (!isObject2(object2)) { return false; } - var type = typeof index2; - if (type == "number" ? isArrayLike(object2) && isIndex(index2, object2.length) : type == "string" && (index2 in object2)) { - return eq2(object2[index2], value); + var type = typeof index3; + if (type == "number" ? isArrayLike(object2) && isIndex(index3, object2.length) : type == "string" && (index3 in object2)) { + return eq2(object2[index3], value); } return false; } @@ -116394,8 +105406,8 @@ var require_lodash8 = __commonJS((exports, module) => { return isObjectLike(value) && isArrayLike(value); } function isFunction(value) { - var tag2 = isObject2(value) ? objectToString.call(value) : ""; - return tag2 == funcTag || tag2 == genTag; + var tag3 = isObject2(value) ? objectToString.call(value) : ""; + return tag3 == funcTag || tag3 == genTag; } function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER3; @@ -116440,8 +105452,8 @@ var require_lodash9 = __commonJS((exports, module) => { return isObjectLike(value) && isArrayLike(value); } function isFunction(value) { - var tag2 = isObject2(value) ? objectToString.call(value) : ""; - return tag2 == funcTag || tag2 == genTag; + var tag3 = isObject2(value) ? objectToString.call(value) : ""; + return tag3 == funcTag || tag3 == genTag; } function isLength(value) { return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER3; @@ -116701,8 +105713,8 @@ WD9f }); // node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/utils/index.js -var require_utils11 = __commonJS((exports) => { - var __dirname = "/Users/shivamverma/Desktop/CodeSM/backend/node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/utils"; +var require_utils7 = __commonJS((exports) => { + var __dirname = "/home/kmadhav824/Desktop/CodeSM/backend/node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/utils"; Object.defineProperty(exports, "__esModule", { value: true }); exports.noop = exports.defaults = exports.Debug = exports.getPackageMeta = exports.zipMap = exports.CONNECTION_CLOSED_ERROR_MSG = exports.shuffle = exports.sample = exports.resolveTLSProfile = exports.parseURL = exports.optimizeErrorStack = exports.toArg = exports.convertMapToArray = exports.convertObjectToArray = exports.timeout = exports.packObject = exports.isInt = exports.wrapMultiResult = exports.convertBufferToString = undefined; var fs_1 = __require("fs"); @@ -116838,9 +105850,9 @@ var require_utils11 = __commonJS((exports) => { const options = parsed.query || {}; const result = {}; if (parsed.auth) { - const index2 = parsed.auth.indexOf(":"); - result.username = index2 === -1 ? parsed.auth : parsed.auth.slice(0, index2); - result.password = index2 === -1 ? "" : parsed.auth.slice(index2 + 1); + const index3 = parsed.auth.indexOf(":"); + result.username = index3 === -1 ? parsed.auth : parsed.auth.slice(0, index3); + result.password = index3 === -1 ? "" : parsed.auth.slice(index3 + 1); } if (parsed.pathname) { if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { @@ -116891,9 +105903,9 @@ var require_utils11 = __commonJS((exports) => { function shuffle(array2) { let counter = array2.length; while (counter > 0) { - const index2 = Math.floor(Math.random() * counter); + const index3 = Math.floor(Math.random() * counter); counter--; - [array2[counter], array2[index2]] = [array2[index2], array2[counter]]; + [array2[counter], array2[index3]] = [array2[index3], array2[counter]]; } return array2; } @@ -116901,8 +105913,8 @@ var require_utils11 = __commonJS((exports) => { exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; function zipMap(keys, values) { const map = new Map; - keys.forEach((key, index2) => { - map.set(key, values[index2]); + keys.forEach((key, index3) => { + map.set(key, values[index3]); }); return map; } @@ -116988,12 +106000,12 @@ var require_argumentParsers = __commonJS((exports) => { // node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/Command.js var require_Command = __commonJS((exports) => { - var __dirname = "/Users/shivamverma/Desktop/CodeSM/backend/node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built"; + var __dirname = "/home/kmadhav824/Desktop/CodeSM/backend/node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built"; Object.defineProperty(exports, "__esModule", { value: true }); var commands_1 = require_built(); var calculateSlot = require_lib6(); var standard_as_callback_1 = require_built2(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var argumentParsers_1 = require_argumentParsers(); class Command { @@ -117212,9 +106224,9 @@ $` + Buffer.byteLength(this.name) + `\r const keyIndexes = (0, commands_1.getKeyIndexes)(this.name, this.args, { nameCaseInsensitive: true }); - for (const index2 of keyIndexes) { - this.args[index2] = transform(this.args[index2]); - this.keys.push(this.args[index2]); + for (const index3 of keyIndexes) { + this.args[index3] = transform(this.args[index3]); + this.keys.push(this.args[index3]); } } } @@ -117704,7 +106716,7 @@ var require_Pipeline = __commonJS((exports) => { var standard_as_callback_1 = require_built2(); var util_1 = __require("util"); var Command_1 = require_Command(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var Commander_1 = require_Commander(); function generateMultiWithNodes(redis, keys) { const slot = calculateSlot(keys[0]); @@ -118008,7 +107020,7 @@ var require_Pipeline = __commonJS((exports) => { var require_transaction = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.addTransactionSupport = undefined; - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var standard_as_callback_1 = require_built2(); var Pipeline_1 = require_Pipeline(); function addTransactionSupport(redis) { @@ -118134,7 +107146,7 @@ var require_ClusterOptions = __commonJS((exports) => { var require_util3 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.getConnectionName = exports.weightSrvRecords = exports.groupSrvRecords = exports.getUniqueHostnamesFromOptions = exports.normalizeNodeOptions = exports.nodeKeyToRedisOptions = exports.getNodeKey = undefined; - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var net_1 = __require("net"); function getNodeKey(node) { node.port = node.port || 6379; @@ -118231,7 +107243,7 @@ var require_util3 = __commonJS((exports) => { var require_ClusterSubscriber = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util3(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var Redis_1 = require_Redis(); var debug = (0, utils_1.Debug)("cluster:subscriber"); @@ -118403,7 +107415,7 @@ var require_ClusterSubscriber = __commonJS((exports) => { var require_ConnectionPool = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); var events_1 = __require("events"); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var util_1 = require_util3(); var Redis_1 = require_Redis(); var debug = (0, utils_1.Debug)("cluster:connectionPool"); @@ -118539,8 +107551,8 @@ var require_denque = __commonJS((exports, module) => { this._list = new Array(4); } } - Denque.prototype.peekAt = function peekAt(index2) { - var i2 = index2; + Denque.prototype.peekAt = function peekAt(index3) { + var i2 = index3; if (i2 !== (i2 | 0)) { return; } @@ -118634,8 +107646,8 @@ var require_denque = __commonJS((exports, module) => { this._shrinkArray(); return item; }; - Denque.prototype.removeOne = function removeOne(index2) { - var i2 = index2; + Denque.prototype.removeOne = function removeOne(index3) { + var i2 = index3; if (i2 !== (i2 | 0)) { return; } @@ -118650,14 +107662,14 @@ var require_denque = __commonJS((exports, module) => { i2 = this._head + i2 & this._capacityMask; var item = this._list[i2]; var k2; - if (index2 < size / 2) { - for (k2 = index2;k2 > 0; k2--) { + if (index3 < size / 2) { + for (k2 = index3;k2 > 0; k2--) { this._list[i2] = this._list[i2 = i2 - 1 + len & this._capacityMask]; } this._list[i2] = undefined; this._head = this._head + 1 + len & this._capacityMask; } else { - for (k2 = size - 1 - index2;k2 > 0; k2--) { + for (k2 = size - 1 - index3;k2 > 0; k2--) { this._list[i2] = this._list[i2 = i2 + 1 + len & this._capacityMask]; } this._list[i2] = undefined; @@ -118665,10 +107677,10 @@ var require_denque = __commonJS((exports, module) => { } return item; }; - Denque.prototype.remove = function remove(index2, count) { - var i2 = index2; + Denque.prototype.remove = function remove(index3, count2) { + var i2 = index3; var removed; - var del_count = count; + var del_count = count2; if (i2 !== (i2 | 0)) { return; } @@ -118676,45 +107688,45 @@ var require_denque = __commonJS((exports, module) => { return; var size = this.size(); var len = this._list.length; - if (i2 >= size || i2 < -size || count < 1) + if (i2 >= size || i2 < -size || count2 < 1) return; if (i2 < 0) i2 += size; - if (count === 1 || !count) { + if (count2 === 1 || !count2) { removed = new Array(1); removed[0] = this.removeOne(i2); return removed; } - if (i2 === 0 && i2 + count >= size) { + if (i2 === 0 && i2 + count2 >= size) { removed = this.toArray(); this.clear(); return removed; } - if (i2 + count > size) - count = size - i2; + if (i2 + count2 > size) + count2 = size - i2; var k2; - removed = new Array(count); - for (k2 = 0;k2 < count; k2++) { + removed = new Array(count2); + for (k2 = 0;k2 < count2; k2++) { removed[k2] = this._list[this._head + i2 + k2 & this._capacityMask]; } i2 = this._head + i2 & this._capacityMask; - if (index2 + count === size) { - this._tail = this._tail - count + len & this._capacityMask; - for (k2 = count;k2 > 0; k2--) { + if (index3 + count2 === size) { + this._tail = this._tail - count2 + len & this._capacityMask; + for (k2 = count2;k2 > 0; k2--) { this._list[i2 = i2 + 1 + len & this._capacityMask] = undefined; } return removed; } - if (index2 === 0) { - this._head = this._head + count + len & this._capacityMask; - for (k2 = count - 1;k2 > 0; k2--) { + if (index3 === 0) { + this._head = this._head + count2 + len & this._capacityMask; + for (k2 = count2 - 1;k2 > 0; k2--) { this._list[i2 = i2 + 1 + len & this._capacityMask] = undefined; } return removed; } if (i2 < size / 2) { - this._head = this._head + index2 + count + len & this._capacityMask; - for (k2 = index2;k2 > 0; k2--) { + this._head = this._head + index3 + count2 + len & this._capacityMask; + for (k2 = index3;k2 > 0; k2--) { this.unshift(this._list[i2 = i2 - 1 + len & this._capacityMask]); } i2 = this._head - 1 + len & this._capacityMask; @@ -118722,12 +107734,12 @@ var require_denque = __commonJS((exports, module) => { this._list[i2 = i2 - 1 + len & this._capacityMask] = undefined; del_count--; } - if (index2 < 0) + if (index3 < 0) this._tail = i2; } else { this._tail = i2; - i2 = i2 + count + len & this._capacityMask; - for (k2 = size - (count + index2);k2 > 0; k2--) { + i2 = i2 + count2 + len & this._capacityMask; + for (k2 = size - (count2 + index3);k2 > 0; k2--) { this.push(this._list[i2++]); } i2 = this._tail; @@ -118740,8 +107752,8 @@ var require_denque = __commonJS((exports, module) => { this._shrinkArray(); return removed; }; - Denque.prototype.splice = function splice(index2, count) { - var i2 = index2; + Denque.prototype.splice = function splice(index3, count2) { + var i2 = index3; if (i2 !== (i2 | 0)) { return; } @@ -118762,13 +107774,13 @@ var require_denque = __commonJS((exports, module) => { for (k2 = 0;k2 < i2; k2++) { temp[k2] = this._list[this._head + k2 & this._capacityMask]; } - if (count === 0) { + if (count2 === 0) { removed = []; if (i2 > 0) { this._head = this._head + i2 + len & this._capacityMask; } } else { - removed = this.remove(i2, count); + removed = this.remove(i2, count2); this._head = this._head + i2 + len & this._capacityMask; } while (arg_len > arguments_index) { @@ -118778,18 +107790,18 @@ var require_denque = __commonJS((exports, module) => { this.unshift(temp[k2 - 1]); } } else { - temp = new Array(size - (i2 + count)); + temp = new Array(size - (i2 + count2)); var leng = temp.length; for (k2 = 0;k2 < leng; k2++) { - temp[k2] = this._list[this._head + i2 + count + k2 & this._capacityMask]; + temp[k2] = this._list[this._head + i2 + count2 + k2 & this._capacityMask]; } - if (count === 0) { + if (count2 === 0) { removed = []; if (i2 != size) { this._tail = this._head + i2 + len & this._capacityMask; } } else { - removed = this.remove(i2, count); + removed = this.remove(i2, count2); this._tail = this._tail - leng + len & this._capacityMask; } while (arguments_index < arg_len) { @@ -118801,7 +107813,7 @@ var require_denque = __commonJS((exports, module) => { } return removed; } else { - return this.remove(i2, count); + return this.remove(i2, count2); } }; Denque.prototype.clear = function clear() { @@ -118873,7 +107885,7 @@ var require_denque = __commonJS((exports, module) => { // node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/cluster/DelayQueue.js var require_DelayQueue = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var Deque = require_denque(); var debug = (0, utils_1.Debug)("delayqueue"); @@ -118921,7 +107933,7 @@ var require_DelayQueue = __commonJS((exports) => { var require_ShardedSubscriber = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util3(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var Redis_1 = require_Redis(); var debug = (0, utils_1.Debug)("cluster:subscriberGroup:shardedSubscriber"); var SubscriberStatus = { @@ -119059,7 +108071,7 @@ var require_ShardedSubscriber = __commonJS((exports) => { // node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/cluster/ClusterSubscriberGroup.js var require_ClusterSubscriberGroup = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var util_1 = require_util3(); var calculateSlot = require_lib6(); var ShardedSubscriber_1 = require_ShardedSubscriber(); @@ -119324,7 +108336,7 @@ var require_cluster = __commonJS((exports) => { var Redis_1 = require_Redis(); var ScanStream_1 = require_ScanStream(); var transaction_1 = require_transaction(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var applyMixin_1 = require_applyMixin(); var Commander_1 = require_Commander(); var ClusterOptions_1 = require_ClusterOptions(); @@ -119564,12 +108576,12 @@ var require_cluster = __commonJS((exports) => { }; const nodes = (0, utils_1.shuffle)(this.connectionPool.getNodes()); let lastNodeError = null; - function tryNode(index2) { - if (index2 === nodes.length) { + function tryNode(index3) { + if (index3 === nodes.length) { const error = new ClusterAllFailedError_1.default(ClusterAllFailedError_1.default.defaultMessage, lastNodeError); return wrapper(error); } - const node = nodes[index2]; + const node = nodes[index3]; const key = `${node.options.host}:${node.options.port}`; debug("getting slot cache from %s", key); _this.getInfoFromNode(node, function(err) { @@ -119583,7 +108595,7 @@ var require_cluster = __commonJS((exports) => { if (err) { _this.emit("node error", err, key); lastNodeError = err; - tryNode(index2 + 1); + tryNode(index3 + 1); } else { _this.emit("refresh"); wrapper(); @@ -120097,7 +109109,7 @@ var require_cluster = __commonJS((exports) => { // node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/connectors/AbstractConnector.js var require_AbstractConnector = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var debug = (0, utils_1.Debug)("AbstractConnector"); class AbstractConnector { @@ -120129,7 +109141,7 @@ var require_StandaloneConnector = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); var net_1 = __require("net"); var tls_1 = __require("tls"); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var AbstractConnector_1 = require_AbstractConnector(); class StandaloneConnector extends AbstractConnector_1.default { @@ -120229,7 +109241,7 @@ var require_SentinelIterator = __commonJS((exports) => { var require_FailoverDetector = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.FailoverDetector = undefined; - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var debug = (0, utils_1.Debug)("FailoverDetector"); var CHANNEL_NAME = "+switch-master"; @@ -120275,7 +109287,7 @@ var require_SentinelConnector = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.SentinelIterator = undefined; var net_1 = __require("net"); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var tls_1 = __require("tls"); var SentinelIterator_1 = require_SentinelIterator(); exports.SentinelIterator = SentinelIterator_1.default; @@ -120558,7 +109570,7 @@ var require_MaxRetriesPerRequestError = __commonJS((exports) => { }); // node_modules/.pnpm/ioredis@5.10.1/node_modules/ioredis/built/errors/index.js -var require_errors10 = __commonJS((exports) => { +var require_errors8 = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); exports.MaxRetriesPerRequestError = undefined; var MaxRetriesPerRequestError_1 = require_MaxRetriesPerRequestError(); @@ -120575,7 +109587,7 @@ var require_parser2 = __commonJS((exports, module) => { var ParserError = errors.ParserError; var bufferPool = Buffer4.allocUnsafe(32 * 1024); var bufferOffset = 0; - var interval2 = null; + var interval3 = null; var counter = 0; var notDecreased = 0; function parseSimpleNumbers(parser) { @@ -120770,10 +109782,10 @@ var require_parser2 = __commonJS((exports, module) => { counter--; } } else { - clearInterval(interval2); + clearInterval(interval3); counter = 0; notDecreased = 0; - interval2 = null; + interval3 = null; } } function resizeBuffer(length) { @@ -120785,8 +109797,8 @@ var require_parser2 = __commonJS((exports, module) => { bufferPool = Buffer4.allocUnsafe(length * multiplier + bufferOffset); bufferOffset = 0; counter++; - if (interval2 === null) { - interval2 = setInterval(decreaseBufferPool, 50); + if (interval3 === null) { + interval3 = setInterval(decreaseBufferPool, 50); } } } @@ -120977,7 +109989,7 @@ var require_SubscriptionSet = __commonJS((exports) => { var require_DataHandler = __commonJS((exports) => { Object.defineProperty(exports, "__esModule", { value: true }); var Command_1 = require_Command(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var RedisParser = require_parser2(); var SubscriptionSet_1 = require_SubscriptionSet(); var debug = (0, utils_1.Debug)("dataHandler"); @@ -121096,15 +110108,15 @@ var require_DataHandler = __commonJS((exports) => { if (channel) { this.redis.condition.subscriber.del(replyType, channel); } - const count = reply[2]; - if (Number(count) === 0) { + const count2 = reply[2]; + if (Number(count2) === 0) { this.redis.condition.subscriber = false; } const item = this.shiftCommand(reply); if (!item) { return; } - if (!fillUnsubCommand(item.command, count)) { + if (!fillUnsubCommand(item.command, count2)) { this.redis.commandQueue.unshift(item); } break; @@ -121128,11 +110140,11 @@ var require_DataHandler = __commonJS((exports) => { return false; } const len = replyStr.indexOf(" "); - const timestamp2 = replyStr.slice(0, len); + const timestamp3 = replyStr.slice(0, len); const argIndex = replyStr.indexOf('"'); const args = replyStr.slice(argIndex + 1, -1).split('" "').map((elem) => elem.replace(/\\"/g, '"')); const dbAndSource = replyStr.slice(len + 2, argIndex - 2).split(" "); - this.redis.emit("monitor", timestamp2, args, dbAndSource[1], dbAndSource[0]); + this.redis.emit("monitor", timestamp3, args, dbAndSource[1], dbAndSource[0]); return true; } shiftCommand(reply) { @@ -121148,30 +110160,30 @@ var require_DataHandler = __commonJS((exports) => { } exports.default = DataHandler; var remainingRepliesMap = new WeakMap; - function fillSubCommand(command, count) { + function fillSubCommand(command, count2) { let remainingReplies = remainingRepliesMap.has(command) ? remainingRepliesMap.get(command) : command.args.length; remainingReplies -= 1; if (remainingReplies <= 0) { - command.resolve(count); + command.resolve(count2); remainingRepliesMap.delete(command); return true; } remainingRepliesMap.set(command, remainingReplies); return false; } - function fillUnsubCommand(command, count) { + function fillUnsubCommand(command, count2) { let remainingReplies = remainingRepliesMap.has(command) ? remainingRepliesMap.get(command) : command.args.length; if (remainingReplies === 0) { - if (Number(count) === 0) { + if (Number(count2) === 0) { remainingRepliesMap.delete(command); - command.resolve(count); + command.resolve(count2); return true; } return false; } remainingReplies -= 1; if (remainingReplies <= 0) { - command.resolve(count); + command.resolve(count2); return true; } remainingRepliesMap.set(command, remainingReplies); @@ -121185,8 +110197,8 @@ var require_event_handler = __commonJS((exports) => { exports.readyHandler = exports.errorHandler = exports.closeHandler = exports.connectHandler = undefined; var redis_errors_1 = require_redis_errors(); var Command_1 = require_Command(); - var errors_1 = require_errors10(); - var utils_1 = require_utils11(); + var errors_1 = require_errors8(); + var utils_1 = require_utils7(); var DataHandler_1 = require_DataHandler(); var debug = (0, utils_1.Debug)("connection"); function connectHandler(self2) { @@ -121522,7 +110534,7 @@ var require_Redis = __commonJS((exports) => { var RedisOptions_1 = require_RedisOptions(); var ScanStream_1 = require_ScanStream(); var transaction_1 = require_transaction(); - var utils_1 = require_utils11(); + var utils_1 = require_utils7(); var applyMixin_1 = require_applyMixin(); var Commander_1 = require_Commander(); var lodash_1 = require_lodash10(); @@ -122103,20156 +111115,6741 @@ var require_built3 = __commonJS((exports, module) => { exports.print = print; }); -// node_modules/.pnpm/lodash@4.18.1/node_modules/lodash/lodash.js -var require_lodash11 = __commonJS((exports, module) => { - (function() { - var undefined2; - var VERSION = "4.18.1"; - var LARGE_ARRAY_SIZE = 200; - var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`", INVALID_TEMPL_IMPORTS_ERROR_TEXT = "Invalid `imports` option passed into `_.template`"; - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - var MAX_MEMOIZE_SIZE = 500; - var PLACEHOLDER = "__lodash_placeholder__"; - var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; - var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; - var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; - var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; - var HOT_COUNT = 800, HOT_SPAN = 16; - var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; - var INFINITY = 1 / 0, MAX_SAFE_INTEGER3 = 9007199254740991, MAX_INTEGER = 179769313486231570000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000, NAN = 0 / 0; - var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - var wrapFlags = [ - ["ary", WRAP_ARY_FLAG], - ["bind", WRAP_BIND_FLAG], - ["bindKey", WRAP_BIND_KEY_FLAG], - ["curry", WRAP_CURRY_FLAG], - ["curryRight", WRAP_CURRY_RIGHT_FLAG], - ["flip", WRAP_FLIP_FLAG], - ["partial", WRAP_PARTIAL_FLAG], - ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], - ["rearg", WRAP_REARG_FLAG] - ]; - var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; - var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; - var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); - var reTrimStart = /^\s+/; - var reWhitespace = /\s/; - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - var reEscapeChar = /\\(\\)?/g; - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - var reFlags = /\w*$/; - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - var reIsBinary = /^0b[01]+$/i; - var reIsHostCtor = /^\[object .+?Constructor\]$/; - var reIsOctal = /^0o[0-7]+$/i; - var reIsUint = /^(?:0|[1-9]\d*)$/; - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - var reNoMatch = /($^)/; - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - var rsApos = "['\u2019]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; - var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; - var reApos = RegExp(rsApos, "g"); - var reComboMark = RegExp(rsCombo, "g"); - var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - var reUnicodeWord = RegExp([ - rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", - rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", - rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, - rsUpper + "+" + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join("|"), "g"); - var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - var contextProps = [ - "Array", - "Buffer", - "DataView", - "Date", - "Error", - "Float32Array", - "Float64Array", - "Function", - "Int8Array", - "Int16Array", - "Int32Array", - "Map", - "Math", - "Object", - "Promise", - "RegExp", - "Set", - "String", - "Symbol", - "TypeError", - "Uint8Array", - "Uint8ClampedArray", - "Uint16Array", - "Uint32Array", - "WeakMap", - "_", - "clearTimeout", - "isFinite", - "parseInt", - "setTimeout" - ]; - var templateCounter = -1; - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; - var deburredLetters = { - "\xC0": "A", - "\xC1": "A", - "\xC2": "A", - "\xC3": "A", - "\xC4": "A", - "\xC5": "A", - "\xE0": "a", - "\xE1": "a", - "\xE2": "a", - "\xE3": "a", - "\xE4": "a", - "\xE5": "a", - "\xC7": "C", - "\xE7": "c", - "\xD0": "D", - "\xF0": "d", - "\xC8": "E", - "\xC9": "E", - "\xCA": "E", - "\xCB": "E", - "\xE8": "e", - "\xE9": "e", - "\xEA": "e", - "\xEB": "e", - "\xCC": "I", - "\xCD": "I", - "\xCE": "I", - "\xCF": "I", - "\xEC": "i", - "\xED": "i", - "\xEE": "i", - "\xEF": "i", - "\xD1": "N", - "\xF1": "n", - "\xD2": "O", - "\xD3": "O", - "\xD4": "O", - "\xD5": "O", - "\xD6": "O", - "\xD8": "O", - "\xF2": "o", - "\xF3": "o", - "\xF4": "o", - "\xF5": "o", - "\xF6": "o", - "\xF8": "o", - "\xD9": "U", - "\xDA": "U", - "\xDB": "U", - "\xDC": "U", - "\xF9": "u", - "\xFA": "u", - "\xFB": "u", - "\xFC": "u", - "\xDD": "Y", - "\xFD": "y", - "\xFF": "y", - "\xC6": "Ae", - "\xE6": "ae", - "\xDE": "Th", - "\xFE": "th", - "\xDF": "ss", - "\u0100": "A", - "\u0102": "A", - "\u0104": "A", - "\u0101": "a", - "\u0103": "a", - "\u0105": "a", - "\u0106": "C", - "\u0108": "C", - "\u010A": "C", - "\u010C": "C", - "\u0107": "c", - "\u0109": "c", - "\u010B": "c", - "\u010D": "c", - "\u010E": "D", - "\u0110": "D", - "\u010F": "d", - "\u0111": "d", - "\u0112": "E", - "\u0114": "E", - "\u0116": "E", - "\u0118": "E", - "\u011A": "E", - "\u0113": "e", - "\u0115": "e", - "\u0117": "e", - "\u0119": "e", - "\u011B": "e", - "\u011C": "G", - "\u011E": "G", - "\u0120": "G", - "\u0122": "G", - "\u011D": "g", - "\u011F": "g", - "\u0121": "g", - "\u0123": "g", - "\u0124": "H", - "\u0126": "H", - "\u0125": "h", - "\u0127": "h", - "\u0128": "I", - "\u012A": "I", - "\u012C": "I", - "\u012E": "I", - "\u0130": "I", - "\u0129": "i", - "\u012B": "i", - "\u012D": "i", - "\u012F": "i", - "\u0131": "i", - "\u0134": "J", - "\u0135": "j", - "\u0136": "K", - "\u0137": "k", - "\u0138": "k", - "\u0139": "L", - "\u013B": "L", - "\u013D": "L", - "\u013F": "L", - "\u0141": "L", - "\u013A": "l", - "\u013C": "l", - "\u013E": "l", - "\u0140": "l", - "\u0142": "l", - "\u0143": "N", - "\u0145": "N", - "\u0147": "N", - "\u014A": "N", - "\u0144": "n", - "\u0146": "n", - "\u0148": "n", - "\u014B": "n", - "\u014C": "O", - "\u014E": "O", - "\u0150": "O", - "\u014D": "o", - "\u014F": "o", - "\u0151": "o", - "\u0154": "R", - "\u0156": "R", - "\u0158": "R", - "\u0155": "r", - "\u0157": "r", - "\u0159": "r", - "\u015A": "S", - "\u015C": "S", - "\u015E": "S", - "\u0160": "S", - "\u015B": "s", - "\u015D": "s", - "\u015F": "s", - "\u0161": "s", - "\u0162": "T", - "\u0164": "T", - "\u0166": "T", - "\u0163": "t", - "\u0165": "t", - "\u0167": "t", - "\u0168": "U", - "\u016A": "U", - "\u016C": "U", - "\u016E": "U", - "\u0170": "U", - "\u0172": "U", - "\u0169": "u", - "\u016B": "u", - "\u016D": "u", - "\u016F": "u", - "\u0171": "u", - "\u0173": "u", - "\u0174": "W", - "\u0175": "w", - "\u0176": "Y", - "\u0177": "y", - "\u0178": "Y", - "\u0179": "Z", - "\u017B": "Z", - "\u017D": "Z", - "\u017A": "z", - "\u017C": "z", - "\u017E": "z", - "\u0132": "IJ", - "\u0133": "ij", - "\u0152": "Oe", - "\u0153": "oe", - "\u0149": "'n", - "\u017F": "s" - }; - var htmlEscapes = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - var htmlUnescapes = { - "&": "&", - "<": "<", - ">": ">", - """: '"', - "'": "'" - }; - var stringEscapes = { - "\\": "\\", - "'": "'", - "\n": "n", - "\r": "r", - "\u2028": "u2028", - "\u2029": "u2029" - }; - var freeParseFloat = parseFloat, freeParseInt = parseInt; - var freeGlobal = typeof global == "object" && global && global.Object === Object && global; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports; - var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = function() { - try { - var types6 = freeModule && freeModule.require && freeModule.require("util").types; - if (types6) { - return types6; - } - return freeProcess && freeProcess.binding && freeProcess.binding("util"); - } catch (e3) {} - }(); - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - function apply(func, thisArg, args) { - switch (args.length) { - case 0: - return func.call(thisArg); - case 1: - return func.call(thisArg, args[0]); - case 2: - return func.call(thisArg, args[0], args[1]); - case 3: - return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); +// node_modules/.pnpm/node-abort-controller@3.1.1/node_modules/node-abort-controller/index.js +var require_node_abort_controller = __commonJS((exports, module) => { + var { EventEmitter } = __require("events"); + + class AbortSignal2 { + constructor() { + this.eventEmitter = new EventEmitter; + this.onabort = null; + this.aborted = false; + this.reason = undefined; } - function arrayAggregator(array2, setter, iteratee, accumulator) { - var index2 = -1, length = array2 == null ? 0 : array2.length; - while (++index2 < length) { - var value = array2[index2]; - setter(accumulator, value, iteratee(value), array2); - } - return accumulator; + toString() { + return "[object AbortSignal]"; } - function arrayEach(array2, iteratee) { - var index2 = -1, length = array2 == null ? 0 : array2.length; - while (++index2 < length) { - if (iteratee(array2[index2], index2, array2) === false) { - break; - } - } - return array2; + get [Symbol.toStringTag]() { + return "AbortSignal"; } - function arrayEachRight(array2, iteratee) { - var length = array2 == null ? 0 : array2.length; - while (length--) { - if (iteratee(array2[length], length, array2) === false) { - break; - } - } - return array2; + removeEventListener(name, handler) { + this.eventEmitter.removeListener(name, handler); } - function arrayEvery(array2, predicate) { - var index2 = -1, length = array2 == null ? 0 : array2.length; - while (++index2 < length) { - if (!predicate(array2[index2], index2, array2)) { - return false; - } - } - return true; + addEventListener(name, handler) { + this.eventEmitter.on(name, handler); } - function arrayFilter(array2, predicate) { - var index2 = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result = []; - while (++index2 < length) { - var value = array2[index2]; - if (predicate(value, index2, array2)) { - result[resIndex++] = value; - } + dispatchEvent(type) { + const event = { type, target: this }; + const handlerName = `on${type}`; + if (typeof this[handlerName] === "function") + this[handlerName](event); + this.eventEmitter.emit(type, event); + } + throwIfAborted() { + if (this.aborted) { + throw this.reason; } - return result; } - function arrayIncludes(array2, value) { - var length = array2 == null ? 0 : array2.length; - return !!length && baseIndexOf(array2, value, 0) > -1; + static abort(reason) { + const controller = new AbortController2; + controller.abort(); + return controller.signal; } - function arrayIncludesWith(array2, value, comparator) { - var index2 = -1, length = array2 == null ? 0 : array2.length; - while (++index2 < length) { - if (comparator(value, array2[index2])) { - return true; - } - } - return false; + static timeout(time3) { + const controller = new AbortController2; + setTimeout(() => controller.abort(new Error("TimeoutError")), time3); + return controller.signal; } - function arrayMap(array2, iteratee) { - var index2 = -1, length = array2 == null ? 0 : array2.length, result = Array(length); - while (++index2 < length) { - result[index2] = iteratee(array2[index2], index2, array2); - } - return result; + } + + class AbortController2 { + constructor() { + this.signal = new AbortSignal2; + } + abort(reason) { + if (this.signal.aborted) + return; + this.signal.aborted = true; + if (reason) + this.signal.reason = reason; + else + this.signal.reason = new Error("AbortError"); + this.signal.dispatchEvent("abort"); } - function arrayPush(array2, values) { - var index2 = -1, length = values.length, offset = array2.length; - while (++index2 < length) { - array2[offset + index2] = values[index2]; + toString() { + return "[object AbortController]"; + } + get [Symbol.toStringTag]() { + return "AbortController"; + } + } + module.exports = { AbortController: AbortController2, AbortSignal: AbortSignal2 }; +}); + +// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js +var require_process = __commonJS((exports, module) => { + var isLinux = () => process.platform === "linux"; + var report = null; + var getReport = () => { + if (!report) { + if (isLinux() && process.report) { + const orig = process.report.excludeNetwork; + process.report.excludeNetwork = true; + report = process.report.getReport(); + process.report.excludeNetwork = orig; + } else { + report = {}; } - return array2; } - function arrayReduce(array2, iteratee, accumulator, initAccum) { - var index2 = -1, length = array2 == null ? 0 : array2.length; - if (initAccum && length) { - accumulator = array2[++index2]; + return report; + }; + module.exports = { isLinux, getReport }; +}); + +// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/filesystem.js +var require_filesystem = __commonJS((exports, module) => { + var fs3 = __require("fs"); + var LDD_PATH = "/usr/bin/ldd"; + var SELF_PATH = "/proc/self/exe"; + var MAX_LENGTH = 2048; + var readFileSync2 = (path2) => { + const fd = fs3.openSync(path2, "r"); + const buffer = Buffer.alloc(MAX_LENGTH); + const bytesRead = fs3.readSync(fd, buffer, 0, MAX_LENGTH, 0); + fs3.close(fd, () => {}); + return buffer.subarray(0, bytesRead); + }; + var readFile2 = (path2) => new Promise((resolve, reject) => { + fs3.open(path2, "r", (err, fd) => { + if (err) { + reject(err); + } else { + const buffer = Buffer.alloc(MAX_LENGTH); + fs3.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => { + resolve(buffer.subarray(0, bytesRead)); + fs3.close(fd, () => {}); + }); } - while (++index2 < length) { - accumulator = iteratee(accumulator, array2[index2], index2, array2); + }); + }); + module.exports = { + LDD_PATH, + SELF_PATH, + readFileSync: readFileSync2, + readFile: readFile2 + }; +}); + +// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/elf.js +var require_elf = __commonJS((exports, module) => { + var interpreterPath = (elf) => { + if (elf.length < 64) { + return null; + } + if (elf.readUInt32BE(0) !== 2135247942) { + return null; + } + if (elf.readUInt8(4) !== 2) { + return null; + } + if (elf.readUInt8(5) !== 1) { + return null; + } + const offset = elf.readUInt32LE(32); + const size = elf.readUInt16LE(54); + const count2 = elf.readUInt16LE(56); + for (let i2 = 0;i2 < count2; i2++) { + const headerOffset = offset + i2 * size; + const type = elf.readUInt32LE(headerOffset); + if (type === 3) { + const fileOffset = elf.readUInt32LE(headerOffset + 8); + const fileSize = elf.readUInt32LE(headerOffset + 32); + return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\0.*$/g, ""); } - return accumulator; } - function arrayReduceRight(array2, iteratee, accumulator, initAccum) { - var length = array2 == null ? 0 : array2.length; - if (initAccum && length) { - accumulator = array2[--length]; + return null; + }; + module.exports = { + interpreterPath + }; +}); + +// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/detect-libc.js +var require_detect_libc = __commonJS((exports, module) => { + var childProcess = __require("child_process"); + var { isLinux, getReport } = require_process(); + var { LDD_PATH, SELF_PATH, readFile: readFile2, readFileSync: readFileSync2 } = require_filesystem(); + var { interpreterPath } = require_elf(); + var cachedFamilyInterpreter; + var cachedFamilyFilesystem; + var cachedVersionFilesystem; + var command = "getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true"; + var commandOut = ""; + var safeCommand = () => { + if (!commandOut) { + return new Promise((resolve) => { + childProcess.exec(command, (err, out) => { + commandOut = err ? " " : out; + resolve(commandOut); + }); + }); + } + return commandOut; + }; + var safeCommandSync = () => { + if (!commandOut) { + try { + commandOut = childProcess.execSync(command, { encoding: "utf8" }); + } catch (_err) { + commandOut = " "; } - while (length--) { - accumulator = iteratee(accumulator, array2[length], length, array2); + } + return commandOut; + }; + var GLIBC = "glibc"; + var RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i; + var MUSL = "musl"; + var isFileMusl = (f2) => f2.includes("libc.musl-") || f2.includes("ld-musl-"); + var familyFromReport = () => { + const report = getReport(); + if (report.header && report.header.glibcVersionRuntime) { + return GLIBC; + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return MUSL; } - return accumulator; } - function arraySome(array2, predicate) { - var index2 = -1, length = array2 == null ? 0 : array2.length; - while (++index2 < length) { - if (predicate(array2[index2], index2, array2)) { - return true; - } + return null; + }; + var familyFromCommand = (out) => { + const [getconf, ldd1] = out.split(/[\r\n]+/); + if (getconf && getconf.includes(GLIBC)) { + return GLIBC; + } + if (ldd1 && ldd1.includes(MUSL)) { + return MUSL; + } + return null; + }; + var familyFromInterpreterPath = (path2) => { + if (path2) { + if (path2.includes("/ld-musl-")) { + return MUSL; + } else if (path2.includes("/ld-linux-")) { + return GLIBC; } - return false; } - var asciiSize = baseProperty("length"); - function asciiToArray(string2) { - return string2.split(""); + return null; + }; + var getFamilyFromLddContent = (content) => { + content = content.toString(); + if (content.includes("musl")) { + return MUSL; } - function asciiWords(string2) { - return string2.match(reAsciiWord) || []; + if (content.includes("GNU C Library")) { + return GLIBC; } - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection2) { - if (predicate(value, key, collection2)) { - result = key; - return false; - } - }); - return result; + return null; + }; + var familyFromFilesystem = async () => { + if (cachedFamilyFilesystem !== undefined) { + return cachedFamilyFilesystem; } - function baseFindIndex(array2, predicate, fromIndex, fromRight) { - var length = array2.length, index2 = fromIndex + (fromRight ? 1 : -1); - while (fromRight ? index2-- : ++index2 < length) { - if (predicate(array2[index2], index2, array2)) { - return index2; + cachedFamilyFilesystem = null; + try { + const lddContent = await readFile2(LDD_PATH); + cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); + } catch (e3) {} + return cachedFamilyFilesystem; + }; + var familyFromFilesystemSync = () => { + if (cachedFamilyFilesystem !== undefined) { + return cachedFamilyFilesystem; + } + cachedFamilyFilesystem = null; + try { + const lddContent = readFileSync2(LDD_PATH); + cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); + } catch (e3) {} + return cachedFamilyFilesystem; + }; + var familyFromInterpreter = async () => { + if (cachedFamilyInterpreter !== undefined) { + return cachedFamilyInterpreter; + } + cachedFamilyInterpreter = null; + try { + const selfContent = await readFile2(SELF_PATH); + const path2 = interpreterPath(selfContent); + cachedFamilyInterpreter = familyFromInterpreterPath(path2); + } catch (e3) {} + return cachedFamilyInterpreter; + }; + var familyFromInterpreterSync = () => { + if (cachedFamilyInterpreter !== undefined) { + return cachedFamilyInterpreter; + } + cachedFamilyInterpreter = null; + try { + const selfContent = readFileSync2(SELF_PATH); + const path2 = interpreterPath(selfContent); + cachedFamilyInterpreter = familyFromInterpreterPath(path2); + } catch (e3) {} + return cachedFamilyInterpreter; + }; + var family = async () => { + let family2 = null; + if (isLinux()) { + family2 = await familyFromInterpreter(); + if (!family2) { + family2 = await familyFromFilesystem(); + if (!family2) { + family2 = familyFromReport(); + } + if (!family2) { + const out = await safeCommand(); + family2 = familyFromCommand(out); } } - return -1; } - function baseIndexOf(array2, value, fromIndex) { - return value === value ? strictIndexOf(array2, value, fromIndex) : baseFindIndex(array2, baseIsNaN, fromIndex); - } - function baseIndexOfWith(array2, value, fromIndex, comparator) { - var index2 = fromIndex - 1, length = array2.length; - while (++index2 < length) { - if (comparator(array2[index2], value)) { - return index2; + return family2; + }; + var familySync = () => { + let family2 = null; + if (isLinux()) { + family2 = familyFromInterpreterSync(); + if (!family2) { + family2 = familyFromFilesystemSync(); + if (!family2) { + family2 = familyFromReport(); + } + if (!family2) { + const out = safeCommandSync(); + family2 = familyFromCommand(out); } } - return -1; } - function baseIsNaN(value) { - return value !== value; + return family2; + }; + var isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; + var isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; + var versionFromFilesystem = async () => { + if (cachedVersionFilesystem !== undefined) { + return cachedVersionFilesystem; } - function baseMean(array2, iteratee) { - var length = array2 == null ? 0 : array2.length; - return length ? baseSum(array2, iteratee) / length : NAN; + cachedVersionFilesystem = null; + try { + const lddContent = await readFile2(LDD_PATH); + const versionMatch = lddContent.match(RE_GLIBC_VERSION); + if (versionMatch) { + cachedVersionFilesystem = versionMatch[1]; + } + } catch (e3) {} + return cachedVersionFilesystem; + }; + var versionFromFilesystemSync = () => { + if (cachedVersionFilesystem !== undefined) { + return cachedVersionFilesystem; } - function baseProperty(key) { - return function(object2) { - return object2 == null ? undefined2 : object2[key]; - }; + cachedVersionFilesystem = null; + try { + const lddContent = readFileSync2(LDD_PATH); + const versionMatch = lddContent.match(RE_GLIBC_VERSION); + if (versionMatch) { + cachedVersionFilesystem = versionMatch[1]; + } + } catch (e3) {} + return cachedVersionFilesystem; + }; + var versionFromReport = () => { + const report = getReport(); + if (report.header && report.header.glibcVersionRuntime) { + return report.header.glibcVersionRuntime; } - function basePropertyOf(object2) { - return function(key) { - return object2 == null ? undefined2 : object2[key]; - }; + return null; + }; + var versionSuffix = (s2) => s2.trim().split(/\s+/)[1]; + var versionFromCommand = (out) => { + const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); + if (getconf && getconf.includes(GLIBC)) { + return versionSuffix(getconf); } - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index2, collection2) { - accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index2, collection2); - }); - return accumulator; + if (ldd1 && ldd2 && ldd1.includes(MUSL)) { + return versionSuffix(ldd2); } - function baseSortBy(array2, comparer) { - var length = array2.length; - array2.sort(comparer); - while (length--) { - array2[length] = array2[length].value; + return null; + }; + var version3 = async () => { + let version4 = null; + if (isLinux()) { + version4 = await versionFromFilesystem(); + if (!version4) { + version4 = versionFromReport(); } - return array2; - } - function baseSum(array2, iteratee) { - var result, index2 = -1, length = array2.length; - while (++index2 < length) { - var current = iteratee(array2[index2]); - if (current !== undefined2) { - result = result === undefined2 ? current : result + current; - } + if (!version4) { + const out = await safeCommand(); + version4 = versionFromCommand(out); } - return result; } - function baseTimes(n2, iteratee) { - var index2 = -1, result = Array(n2); - while (++index2 < n2) { - result[index2] = iteratee(index2); + return version4; + }; + var versionSync = () => { + let version4 = null; + if (isLinux()) { + version4 = versionFromFilesystemSync(); + if (!version4) { + version4 = versionFromReport(); + } + if (!version4) { + const out = safeCommandSync(); + version4 = versionFromCommand(out); } - return result; } - function baseToPairs(object2, props) { - return arrayMap(props, function(key) { - return [key, object2[key]]; - }); + return version4; + }; + module.exports = { + GLIBC, + MUSL, + family, + familySync, + isNonGlibcLinux, + isNonGlibcLinuxSync, + version: version3, + versionSync + }; +}); + +// node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/node-gyp-build.js +var require_node_gyp_build = __commonJS((exports, module) => { + var fs3 = __require("fs"); + var path2 = __require("path"); + var url = __require("url"); + var os = __require("os"); + var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; + var vars = process.config && process.config.variables || {}; + var prebuildsOnly = !!process.env.PREBUILDS_ONLY; + var versions = process.versions; + var abi = versions.modules; + if (versions.deno || process.isBun) { + abi = "unsupported"; + } + var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node"; + var arch = process.env.npm_config_arch || os.arch(); + var platform = process.env.npm_config_platform || os.platform(); + var libc = process.env.LIBC || (isMusl(platform) ? "musl" : "glibc"); + var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || ""; + var uv = (versions.uv || "").split(".")[0]; + module.exports = load; + function load(dir) { + return runtimeRequire(load.resolve(dir)); + } + load.resolve = load.path = function(dir) { + dir = path2.resolve(dir || "."); + var packageName = ""; + var packageNameError; + try { + packageName = runtimeRequire(path2.join(dir, "package.json")).name; + var varName = packageName.toUpperCase().replace(/-/g, "_"); + if (process.env[varName + "_PREBUILD"]) + dir = process.env[varName + "_PREBUILD"]; + } catch (err) { + packageNameError = err; } - function baseTrim(string2) { - return string2 ? string2.slice(0, trimmedEndIndex(string2) + 1).replace(reTrimStart, "") : string2; + if (!prebuildsOnly) { + var release = getFirst(path2.join(dir, "build/Release"), matchBuild); + if (release) + return release; + var debug = getFirst(path2.join(dir, "build/Debug"), matchBuild); + if (debug) + return debug; } - function baseUnary(func) { - return function(value) { - return func(value); - }; + var prebuild = resolve(dir); + if (prebuild) + return prebuild; + var nearby = resolve(path2.dirname(process.execPath)); + if (nearby) + return nearby; + var platformPackage = (packageName[0] == "@" ? "" : "@" + packageName + "/") + packageName + "-" + platform + "-" + arch; + var packageResolutionError; + try { + var prebuildPackage = path2.dirname(__require("module").createRequire(url.pathToFileURL(path2.join(dir, "package.json"))).resolve(platformPackage)); + return resolveFile(prebuildPackage); + } catch (error) { + packageResolutionError = error; } - function baseValues(object2, props) { - return arrayMap(props, function(key) { - return object2[key]; - }); + var target2 = [ + "platform=" + platform, + "arch=" + arch, + "runtime=" + runtime, + "abi=" + abi, + "uv=" + uv, + armv ? "armv=" + armv : "", + "libc=" + libc, + "node=" + process.versions.node, + process.versions.electron ? "electron=" + process.versions.electron : "", + typeof __webpack_require__ === "function" ? "webpack=true" : "" + ].filter(Boolean).join(" "); + let errMessage = "No native build was found for " + target2 + ` + attempted loading from: ` + dir + " and package:" + " " + platformPackage + ` +`; + if (packageNameError) { + errMessage += "Error finding package.json: " + packageNameError.message + ` +`; } - function cacheHas(cache2, key) { - return cache2.has(key); + if (packageResolutionError) { + errMessage += "Error resolving package: " + packageResolutionError.message + ` +`; } - function charsStartIndex(strSymbols, chrSymbols) { - var index2 = -1, length = strSymbols.length; - while (++index2 < length && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {} - return index2; + throw new Error(errMessage); + function resolve(dir2) { + var tuples = readdirSync(path2.join(dir2, "prebuilds")).map(parseTuple); + var tuple2 = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]; + if (!tuple2) + return; + return resolveFile(path2.join(dir2, "prebuilds", tuple2.name)); } - function charsEndIndex(strSymbols, chrSymbols) { - var index2 = strSymbols.length; - while (index2-- && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {} - return index2; + function resolveFile(prebuilds) { + var parsed = readdirSync(prebuilds).map(parseTags); + var candidates = parsed.filter(matchTags(runtime, abi)); + var winner = candidates.sort(compareTags(runtime))[0]; + if (winner) + return path2.join(prebuilds, winner.file); } - function countHolders(array2, placeholder) { - var length = array2.length, result = 0; - while (length--) { - if (array2[length] === placeholder) { - ++result; - } + }; + function readdirSync(dir) { + try { + return fs3.readdirSync(dir); + } catch (err) { + return []; + } + } + function getFirst(dir, filter) { + var files = readdirSync(dir).filter(filter); + return files[0] && path2.join(dir, files[0]); + } + function matchBuild(name) { + return /\.node$/.test(name); + } + function parseTuple(name) { + var arr = name.split("-"); + if (arr.length !== 2) + return; + var platform2 = arr[0]; + var architectures = arr[1].split("+"); + if (!platform2) + return; + if (!architectures.length) + return; + if (!architectures.every(Boolean)) + return; + return { name, platform: platform2, architectures }; + } + function matchTuple(platform2, arch2) { + return function(tuple2) { + if (tuple2 == null) + return false; + if (tuple2.platform !== platform2) + return false; + return tuple2.architectures.includes(arch2); + }; + } + function compareTuples(a2, b2) { + return a2.architectures.length - b2.architectures.length; + } + function parseTags(file) { + var arr = file.split("."); + var extension = arr.pop(); + var tags = { file, specificity: 0 }; + if (extension !== "node") + return; + for (var i2 = 0;i2 < arr.length; i2++) { + var tag3 = arr[i2]; + if (tag3 === "node" || tag3 === "electron" || tag3 === "node-webkit") { + tags.runtime = tag3; + } else if (tag3 === "napi") { + tags.napi = true; + } else if (tag3.slice(0, 3) === "abi") { + tags.abi = tag3.slice(3); + } else if (tag3.slice(0, 2) === "uv") { + tags.uv = tag3.slice(2); + } else if (tag3.slice(0, 4) === "armv") { + tags.armv = tag3.slice(4); + } else if (tag3 === "glibc" || tag3 === "musl") { + tags.libc = tag3; + } else { + continue; } - return result; + tags.specificity++; } - var deburrLetter = basePropertyOf(deburredLetters); - var escapeHtmlChar = basePropertyOf(htmlEscapes); - function escapeStringChar(chr) { - return "\\" + stringEscapes[chr]; + return tags; + } + function matchTags(runtime2, abi2) { + return function(tags) { + if (tags == null) + return false; + if (tags.runtime !== runtime2 && !runtimeAgnostic(tags)) + return false; + if (tags.abi !== abi2 && !tags.napi) + return false; + if (tags.uv && tags.uv !== uv) + return false; + if (tags.armv && tags.armv !== armv) + return false; + if (tags.libc && tags.libc !== libc) + return false; + return true; + }; + } + function runtimeAgnostic(tags) { + return tags.runtime === "node" && tags.napi; + } + function compareTags(runtime2) { + return function(a2, b2) { + if (a2.runtime !== b2.runtime) { + return a2.runtime === runtime2 ? -1 : 1; + } else if (a2.abi !== b2.abi) { + return a2.abi ? -1 : 1; + } else if (a2.specificity !== b2.specificity) { + return a2.specificity > b2.specificity ? -1 : 1; + } else { + return 0; + } + }; + } + function isNwjs() { + return !!(process.versions && process.versions.nw); + } + function isElectron() { + if (process.versions && process.versions.electron) + return true; + if (process.env.ELECTRON_RUN_AS_NODE) + return true; + return typeof window !== "undefined" && window.process && window.process.type === "renderer"; + } + function isMusl(platform2) { + if (platform2 !== "linux") + return false; + const { familySync, MUSL } = require_detect_libc(); + return familySync() === MUSL; + } + load.parseTags = parseTags; + load.matchTags = matchTags; + load.compareTags = compareTags; + load.parseTuple = parseTuple; + load.matchTuple = matchTuple; + load.compareTuples = compareTuples; +}); + +// node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js +var require_node_gyp_build_optional_packages = __commonJS((exports, module) => { + var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; + if (typeof runtimeRequire.addon === "function") { + module.exports = runtimeRequire.addon.bind(runtimeRequire); + } else { + module.exports = require_node_gyp_build(); + } +}); + +// node_modules/.pnpm/msgpackr-extract@3.0.3/node_modules/msgpackr-extract/index.js +var require_msgpackr_extract = __commonJS((exports, module) => { + var __dirname = "/home/kmadhav824/Desktop/CodeSM/backend/node_modules/.pnpm/msgpackr-extract@3.0.3/node_modules/msgpackr-extract"; + module.exports = require_node_gyp_build_optional_packages()(__dirname); +}); + +// node_modules/.pnpm/luxon@3.7.2/node_modules/luxon/build/node/luxon.js +var require_luxon = __commonJS((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + + class LuxonError extends Error { + } + + class InvalidDateTimeError extends LuxonError { + constructor(reason) { + super(`Invalid DateTime: ${reason.toMessage()}`); } - function getValue(object2, key) { - return object2 == null ? undefined2 : object2[key]; + } + + class InvalidIntervalError extends LuxonError { + constructor(reason) { + super(`Invalid Interval: ${reason.toMessage()}`); } - function hasUnicode(string2) { - return reHasUnicode.test(string2); + } + + class InvalidDurationError extends LuxonError { + constructor(reason) { + super(`Invalid Duration: ${reason.toMessage()}`); } - function hasUnicodeWord(string2) { - return reHasUnicodeWord.test(string2); + } + + class ConflictingSpecificationError extends LuxonError { + } + + class InvalidUnitError extends LuxonError { + constructor(unit) { + super(`Invalid unit ${unit}`); } - function iteratorToArray(iterator) { - var data, result = []; - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; + } + + class InvalidArgumentError extends LuxonError { + } + + class ZoneIsAbstractError extends LuxonError { + constructor() { + super("Zone is an abstract class"); } - function mapToArray(map) { - var index2 = -1, result = Array(map.size); - map.forEach(function(value, key) { - result[++index2] = [key, value]; - }); - return result; + } + var n2 = "numeric"; + var s2 = "short"; + var l2 = "long"; + var DATE_SHORT = { + year: n2, + month: n2, + day: n2 + }; + var DATE_MED = { + year: n2, + month: s2, + day: n2 + }; + var DATE_MED_WITH_WEEKDAY = { + year: n2, + month: s2, + day: n2, + weekday: s2 + }; + var DATE_FULL = { + year: n2, + month: l2, + day: n2 + }; + var DATE_HUGE = { + year: n2, + month: l2, + day: n2, + weekday: l2 + }; + var TIME_SIMPLE = { + hour: n2, + minute: n2 + }; + var TIME_WITH_SECONDS = { + hour: n2, + minute: n2, + second: n2 + }; + var TIME_WITH_SHORT_OFFSET = { + hour: n2, + minute: n2, + second: n2, + timeZoneName: s2 + }; + var TIME_WITH_LONG_OFFSET = { + hour: n2, + minute: n2, + second: n2, + timeZoneName: l2 + }; + var TIME_24_SIMPLE = { + hour: n2, + minute: n2, + hourCycle: "h23" + }; + var TIME_24_WITH_SECONDS = { + hour: n2, + minute: n2, + second: n2, + hourCycle: "h23" + }; + var TIME_24_WITH_SHORT_OFFSET = { + hour: n2, + minute: n2, + second: n2, + hourCycle: "h23", + timeZoneName: s2 + }; + var TIME_24_WITH_LONG_OFFSET = { + hour: n2, + minute: n2, + second: n2, + hourCycle: "h23", + timeZoneName: l2 + }; + var DATETIME_SHORT = { + year: n2, + month: n2, + day: n2, + hour: n2, + minute: n2 + }; + var DATETIME_SHORT_WITH_SECONDS = { + year: n2, + month: n2, + day: n2, + hour: n2, + minute: n2, + second: n2 + }; + var DATETIME_MED = { + year: n2, + month: s2, + day: n2, + hour: n2, + minute: n2 + }; + var DATETIME_MED_WITH_SECONDS = { + year: n2, + month: s2, + day: n2, + hour: n2, + minute: n2, + second: n2 + }; + var DATETIME_MED_WITH_WEEKDAY = { + year: n2, + month: s2, + day: n2, + weekday: s2, + hour: n2, + minute: n2 + }; + var DATETIME_FULL = { + year: n2, + month: l2, + day: n2, + hour: n2, + minute: n2, + timeZoneName: s2 + }; + var DATETIME_FULL_WITH_SECONDS = { + year: n2, + month: l2, + day: n2, + hour: n2, + minute: n2, + second: n2, + timeZoneName: s2 + }; + var DATETIME_HUGE = { + year: n2, + month: l2, + day: n2, + weekday: l2, + hour: n2, + minute: n2, + timeZoneName: l2 + }; + var DATETIME_HUGE_WITH_SECONDS = { + year: n2, + month: l2, + day: n2, + weekday: l2, + hour: n2, + minute: n2, + second: n2, + timeZoneName: l2 + }; + + class Zone { + get type() { + throw new ZoneIsAbstractError; } - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; + get name() { + throw new ZoneIsAbstractError; } - function replaceHolders(array2, placeholder) { - var index2 = -1, length = array2.length, resIndex = 0, result = []; - while (++index2 < length) { - var value = array2[index2]; - if (value === placeholder || value === PLACEHOLDER) { - array2[index2] = PLACEHOLDER; - result[resIndex++] = index2; - } - } - return result; + get ianaName() { + return this.name; } - function setToArray(set) { - var index2 = -1, result = Array(set.size); - set.forEach(function(value) { - result[++index2] = value; - }); - return result; + get isUniversal() { + throw new ZoneIsAbstractError; } - function setToPairs(set) { - var index2 = -1, result = Array(set.size); - set.forEach(function(value) { - result[++index2] = [value, value]; - }); - return result; + offsetName(ts, opts) { + throw new ZoneIsAbstractError; } - function strictIndexOf(array2, value, fromIndex) { - var index2 = fromIndex - 1, length = array2.length; - while (++index2 < length) { - if (array2[index2] === value) { - return index2; - } - } - return -1; + formatOffset(ts, format) { + throw new ZoneIsAbstractError; } - function strictLastIndexOf(array2, value, fromIndex) { - var index2 = fromIndex + 1; - while (index2--) { - if (array2[index2] === value) { - return index2; - } + offset(ts) { + throw new ZoneIsAbstractError; + } + equals(otherZone) { + throw new ZoneIsAbstractError; + } + get isValid() { + throw new ZoneIsAbstractError; + } + } + var singleton$1 = null; + + class SystemZone extends Zone { + static get instance() { + if (singleton$1 === null) { + singleton$1 = new SystemZone; } - return index2; + return singleton$1; } - function stringSize(string2) { - return hasUnicode(string2) ? unicodeSize(string2) : asciiSize(string2); + get type() { + return "system"; } - function stringToArray(string2) { - return hasUnicode(string2) ? unicodeToArray(string2) : asciiToArray(string2); + get name() { + return new Intl.DateTimeFormat().resolvedOptions().timeZone; } - function trimmedEndIndex(string2) { - var index2 = string2.length; - while (index2-- && reWhitespace.test(string2.charAt(index2))) {} - return index2; + get isUniversal() { + return false; } - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - function unicodeSize(string2) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string2)) { - ++result; - } - return result; + offsetName(ts, { + format, + locale: locale2 + }) { + return parseZoneInfo(ts, format, locale2); } - function unicodeToArray(string2) { - return string2.match(reUnicode) || []; - } - function unicodeWords(string2) { - return string2.match(reUnicodeWord) || []; - } - var runInContext = function runInContext2(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - var { Array: Array2, Date: Date2, Error: Error2, Function: Function2, Math: Math2, Object: Object2, RegExp: RegExp2, String: String2, TypeError: TypeError2 } = context; - var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype; - var coreJsData = context["__core-js_shared__"]; - var funcToString = funcProto.toString; - var hasOwnProperty = objectProto.hasOwnProperty; - var idCounter = 0; - var maskSrcKey = function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); - return uid ? "Symbol(src)_1." + uid : ""; - }(); - var nativeObjectToString = objectProto.toString; - var objectCtorString = funcToString.call(Object2); - var oldDash = root._; - var reIsNative = RegExp2("^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"); - var Buffer4 = moduleExports ? context.Buffer : undefined2, Symbol2 = context.Symbol, Uint8Array2 = context.Uint8Array, allocUnsafe = Buffer4 ? Buffer4.allocUnsafe : undefined2, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined2, symIterator = Symbol2 ? Symbol2.iterator : undefined2, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined2; - var defineProperty = function() { - try { - var func = getNative(Object2, "defineProperty"); - func({}, "", {}); - return func; - } catch (e3) {} - }(); - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - var { ceil: nativeCeil, floor: nativeFloor } = Math2, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer4 ? Buffer4.isBuffer : undefined2, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse; - var DataView2 = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise2 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap2 = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create"); - var metaMap = WeakMap2 && new WeakMap2; - var realNames = {}; - var dataViewCtorString = toSource(DataView2), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap2); - var symbolProto = Symbol2 ? Symbol2.prototype : undefined2, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined2, symbolToString2 = symbolProto ? symbolProto.toString : undefined2; - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, "__wrapped__")) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } - var baseCreate = function() { - function object2() {} - return function(proto) { - if (!isObject2(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object2.prototype = proto; - var result2 = new object2; - object2.prototype = undefined2; - return result2; - }; - }(); - function baseLodash() {} - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined2; - } - lodash.templateSettings = { - escape: reEscape, - evaluate: reEvaluate, - interpolate: reInterpolate, - variable: "", - imports: { - _: lodash - } - }; - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - function lazyClone() { - var result2 = new LazyWrapper(this.__wrapped__); - result2.__actions__ = copyArray(this.__actions__); - result2.__dir__ = this.__dir__; - result2.__filtered__ = this.__filtered__; - result2.__iteratees__ = copyArray(this.__iteratees__); - result2.__takeCount__ = this.__takeCount__; - result2.__views__ = copyArray(this.__views__); - return result2; - } - function lazyReverse() { - if (this.__filtered__) { - var result2 = new LazyWrapper(this); - result2.__dir__ = -1; - result2.__filtered__ = true; - } else { - result2 = this.clone(); - result2.__dir__ *= -1; - } - return result2; - } - function lazyValue() { - var array2 = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array2), isRight = dir < 0, arrLength = isArr ? array2.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index2 = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); - if (!isArr || !isRight && arrLength == length && takeCount == length) { - return baseWrapperValue(array2, this.__actions__); - } - var result2 = []; - outer: - while (length-- && resIndex < takeCount) { - index2 += dir; - var iterIndex = -1, value = array2[index2]; - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], iteratee2 = data.iteratee, type = data.type, computed = iteratee2(value); - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result2[resIndex++] = value; - } - return result2; - } - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - function Hash2(entries) { - var index2 = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index2 < length) { - var entry = entries[index2]; - this.set(entry[0], entry[1]); - } - } - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - function hashDelete(key) { - var result2 = this.has(key) && delete this.__data__[key]; - this.size -= result2 ? 1 : 0; - return result2; - } - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result2 = data[key]; - return result2 === HASH_UNDEFINED ? undefined2 : result2; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined2; - } - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined2 : hasOwnProperty.call(data, key); - } - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = nativeCreate && value === undefined2 ? HASH_UNDEFINED : value; - return this; + formatOffset(ts, format) { + return formatOffset(this.offset(ts), format); + } + offset(ts) { + return -new Date(ts).getTimezoneOffset(); + } + equals(otherZone) { + return otherZone.type === "system"; + } + get isValid() { + return true; + } + } + var dtfCache = new Map; + function makeDTF(zoneName) { + let dtf = dtfCache.get(zoneName); + if (dtf === undefined) { + dtf = new Intl.DateTimeFormat("en-US", { + hour12: false, + timeZone: zoneName, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + era: "short" + }); + dtfCache.set(zoneName, dtf); + } + return dtf; + } + var typeToPos = { + year: 0, + month: 1, + day: 2, + era: 3, + hour: 4, + minute: 5, + second: 6 + }; + function hackyOffset(dtf, date4) { + const formatted = dtf.format(date4).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; + return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; + } + function partsOffset(dtf, date4) { + const formatted = dtf.formatToParts(date4); + const filled = []; + for (let i2 = 0;i2 < formatted.length; i2++) { + const { + type, + value + } = formatted[i2]; + const pos = typeToPos[type]; + if (type === "era") { + filled[pos] = value; + } else if (!isUndefined(pos)) { + filled[pos] = parseInt(value, 10); } - Hash2.prototype.clear = hashClear; - Hash2.prototype["delete"] = hashDelete; - Hash2.prototype.get = hashGet; - Hash2.prototype.has = hashHas; - Hash2.prototype.set = hashSet; - function ListCache(entries) { - var index2 = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index2 < length) { - var entry = entries[index2]; - this.set(entry[0], entry[1]); - } + } + return filled; + } + var ianaZoneCache = new Map; + + class IANAZone extends Zone { + static create(name) { + let zone = ianaZoneCache.get(name); + if (zone === undefined) { + ianaZoneCache.set(name, zone = new IANAZone(name)); } - function listCacheClear() { - this.__data__ = []; - this.size = 0; + return zone; + } + static resetCache() { + ianaZoneCache.clear(); + dtfCache.clear(); + } + static isValidSpecifier(s3) { + return this.isValidZone(s3); + } + static isValidZone(zone) { + if (!zone) { + return false; } - function listCacheDelete(key) { - var data = this.__data__, index2 = assocIndexOf(data, key); - if (index2 < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index2 == lastIndex) { - data.pop(); - } else { - splice.call(data, index2, 1); - } - --this.size; + try { + new Intl.DateTimeFormat("en-US", { + timeZone: zone + }).format(); return true; + } catch (e3) { + return false; } - function listCacheGet(key) { - var data = this.__data__, index2 = assocIndexOf(data, key); - return index2 < 0 ? undefined2 : data[index2][1]; - } - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - function listCacheSet(key, value) { - var data = this.__data__, index2 = assocIndexOf(data, key); - if (index2 < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index2][1] = value; - } - return this; - } - ListCache.prototype.clear = listCacheClear; - ListCache.prototype["delete"] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - function MapCache(entries) { - var index2 = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index2 < length) { - var entry = entries[index2]; - this.set(entry[0], entry[1]); - } - } - function mapCacheClear() { - this.size = 0; - this.__data__ = { - hash: new Hash2, - map: new (Map2 || ListCache), - string: new Hash2 - }; - } - function mapCacheDelete(key) { - var result2 = getMapData(this, key)["delete"](key); - this.size -= result2 ? 1 : 0; - return result2; - } - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - function mapCacheSet(key, value) { - var data = getMapData(this, key), size2 = data.size; - data.set(key, value); - this.size += data.size == size2 ? 0 : 1; - return this; - } - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype["delete"] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - function SetCache(values2) { - var index2 = -1, length = values2 == null ? 0 : values2.length; - this.__data__ = new MapCache; - while (++index2 < length) { - this.add(values2[index2]); - } - } - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; + } + constructor(name) { + super(); + this.zoneName = name; + this.valid = IANAZone.isValidZone(name); + } + get type() { + return "iana"; + } + get name() { + return this.zoneName; + } + get isUniversal() { + return false; + } + offsetName(ts, { + format, + locale: locale2 + }) { + return parseZoneInfo(ts, format, locale2, this.name); + } + formatOffset(ts, format) { + return formatOffset(this.offset(ts), format); + } + offset(ts) { + if (!this.valid) + return NaN; + const date4 = new Date(ts); + if (isNaN(date4)) + return NaN; + const dtf = makeDTF(this.name); + let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date4) : hackyOffset(dtf, date4); + if (adOrBc === "BC") { + year = -Math.abs(year) + 1; } - function setCacheHas(value) { - return this.__data__.has(value); - } - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } - function stackDelete(key) { - var data = this.__data__, result2 = data["delete"](key); - this.size = data.size; - return result2; - } - function stackGet(key) { - return this.__data__.get(key); - } - function stackHas(key) { - return this.__data__.has(key); - } - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } - Stack.prototype.clear = stackClear; - Stack.prototype["delete"] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String2) : [], length = result2.length; - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && (key == "length" || isBuff && (key == "offset" || key == "parent") || isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || isIndex(key, length)))) { - result2.push(key); - } - } - return result2; - } - function arraySample(array2) { - var length = array2.length; - return length ? array2[baseRandom(0, length - 1)] : undefined2; - } - function arraySampleSize(array2, n2) { - return shuffleSelf(copyArray(array2), baseClamp(n2, 0, array2.length)); - } - function arrayShuffle(array2) { - return shuffleSelf(copyArray(array2)); - } - function assignMergeValue(object2, key, value) { - if (value !== undefined2 && !eq2(object2[key], value) || value === undefined2 && !(key in object2)) { - baseAssignValue(object2, key, value); - } - } - function assignValue(object2, key, value) { - var objValue = object2[key]; - if (!(hasOwnProperty.call(object2, key) && eq2(objValue, value)) || value === undefined2 && !(key in object2)) { - baseAssignValue(object2, key, value); - } - } - function assocIndexOf(array2, key) { - var length = array2.length; - while (length--) { - if (eq2(array2[length][0], key)) { - return length; - } - } - return -1; - } - function baseAggregator(collection, setter, iteratee2, accumulator) { - baseEach(collection, function(value, key, collection2) { - setter(accumulator, value, iteratee2(value), collection2); - }); - return accumulator; - } - function baseAssign(object2, source) { - return object2 && copyObject(source, keys(source), object2); - } - function baseAssignIn(object2, source) { - return object2 && copyObject(source, keysIn(source), object2); - } - function baseAssignValue(object2, key, value) { - if (key == "__proto__" && defineProperty) { - defineProperty(object2, key, { - configurable: true, - enumerable: true, - value, - writable: true - }); - } else { - object2[key] = value; - } - } - function baseAt(object2, paths) { - var index2 = -1, length = paths.length, result2 = Array2(length), skip = object2 == null; - while (++index2 < length) { - result2[index2] = skip ? undefined2 : get(object2, paths[index2]); - } - return result2; - } - function baseClamp(number2, lower, upper) { - if (number2 === number2) { - if (upper !== undefined2) { - number2 = number2 <= upper ? number2 : upper; - } - if (lower !== undefined2) { - number2 = number2 >= lower ? number2 : lower; - } - } - return number2; - } - function baseClone(value, bitmask, customizer, key, object2, stack) { - var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; - if (customizer) { - result2 = object2 ? customizer(value, key, object2, stack) : customizer(value); - } - if (result2 !== undefined2) { - return result2; - } - if (!isObject2(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result2 = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result2); - } - } else { - var tag2 = getTag(value), isFunc = tag2 == funcTag || tag2 == genTag; - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag2 == objectTag || tag2 == argsTag || isFunc && !object2) { - result2 = isFlat || isFunc ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat ? copySymbolsIn(value, baseAssignIn(result2, value)) : copySymbols(value, baseAssign(result2, value)); - } - } else { - if (!cloneableTags[tag2]) { - return object2 ? value : {}; - } - result2 = initCloneByTag(value, tag2, isDeep); - } - } - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result2); - if (isSet(value)) { - value.forEach(function(subValue) { - result2.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key2) { - result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); - }); - } - var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys; - var props = isArr ? undefined2 : keysFunc(value); - arrayEach(props || value, function(subValue, key2) { - if (props) { - key2 = subValue; - subValue = value[key2]; - } - assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value, stack)); - }); - return result2; - } - function baseConforms(source) { - var props = keys(source); - return function(object2) { - return baseConformsTo(object2, source, props); + const adjustedHour = hour === 24 ? 0 : hour; + const asUTC = objToLocalTS({ + year, + month, + day, + hour: adjustedHour, + minute, + second, + millisecond: 0 + }); + let asTS = +date4; + const over = asTS % 1000; + asTS -= over >= 0 ? over : 1000 + over; + return (asUTC - asTS) / (60 * 1000); + } + equals(otherZone) { + return otherZone.type === "iana" && otherZone.name === this.name; + } + get isValid() { + return this.valid; + } + } + var intlLFCache = {}; + function getCachedLF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlLFCache[key]; + if (!dtf) { + dtf = new Intl.ListFormat(locString, opts); + intlLFCache[key] = dtf; + } + return dtf; + } + var intlDTCache = new Map; + function getCachedDTF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let dtf = intlDTCache.get(key); + if (dtf === undefined) { + dtf = new Intl.DateTimeFormat(locString, opts); + intlDTCache.set(key, dtf); + } + return dtf; + } + var intlNumCache = new Map; + function getCachedINF(locString, opts = {}) { + const key = JSON.stringify([locString, opts]); + let inf = intlNumCache.get(key); + if (inf === undefined) { + inf = new Intl.NumberFormat(locString, opts); + intlNumCache.set(key, inf); + } + return inf; + } + var intlRelCache = new Map; + function getCachedRTF(locString, opts = {}) { + const { + base, + ...cacheKeyOpts + } = opts; + const key = JSON.stringify([locString, cacheKeyOpts]); + let inf = intlRelCache.get(key); + if (inf === undefined) { + inf = new Intl.RelativeTimeFormat(locString, opts); + intlRelCache.set(key, inf); + } + return inf; + } + var sysLocaleCache = null; + function systemLocale() { + if (sysLocaleCache) { + return sysLocaleCache; + } else { + sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; + return sysLocaleCache; + } + } + var intlResolvedOptionsCache = new Map; + function getCachedIntResolvedOptions(locString) { + let opts = intlResolvedOptionsCache.get(locString); + if (opts === undefined) { + opts = new Intl.DateTimeFormat(locString).resolvedOptions(); + intlResolvedOptionsCache.set(locString, opts); + } + return opts; + } + var weekInfoCache = new Map; + function getCachedWeekInfo(locString) { + let data = weekInfoCache.get(locString); + if (!data) { + const locale2 = new Intl.Locale(locString); + data = "getWeekInfo" in locale2 ? locale2.getWeekInfo() : locale2.weekInfo; + if (!("minimalDays" in data)) { + data = { + ...fallbackWeekSettings, + ...data }; } - function baseConformsTo(object2, source, props) { - var length = props.length; - if (object2 == null) { - return !length; - } - object2 = Object2(object2); - while (length--) { - var key = props[length], predicate = source[key], value = object2[key]; - if (value === undefined2 && !(key in object2) || !predicate(value)) { - return false; - } - } - return true; - } - function baseDelay(func, wait, args) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return setTimeout2(function() { - func.apply(undefined2, args); - }, wait); - } - function baseDifference(array2, values2, iteratee2, comparator) { - var index2 = -1, includes2 = arrayIncludes, isCommon = true, length = array2.length, result2 = [], valuesLength = values2.length; - if (!length) { - return result2; - } - if (iteratee2) { - values2 = arrayMap(values2, baseUnary(iteratee2)); - } - if (comparator) { - includes2 = arrayIncludesWith; - isCommon = false; - } else if (values2.length >= LARGE_ARRAY_SIZE) { - includes2 = cacheHas; - isCommon = false; - values2 = new SetCache(values2); - } - outer: - while (++index2 < length) { - var value = array2[index2], computed = iteratee2 == null ? value : iteratee2(value); - value = comparator || value !== 0 ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values2[valuesIndex] === computed) { - continue outer; - } - } - result2.push(value); - } else if (!includes2(values2, computed, comparator)) { - result2.push(value); - } - } - return result2; - } - var baseEach = createBaseEach(baseForOwn); - var baseEachRight = createBaseEach(baseForOwnRight, true); - function baseEvery(collection, predicate) { - var result2 = true; - baseEach(collection, function(value, index2, collection2) { - result2 = !!predicate(value, index2, collection2); - return result2; - }); - return result2; - } - function baseExtremum(array2, iteratee2, comparator) { - var index2 = -1, length = array2.length; - while (++index2 < length) { - var value = array2[index2], current = iteratee2(value); - if (current != null && (computed === undefined2 ? current === current && !isSymbol(current) : comparator(current, computed))) { - var computed = current, result2 = value; - } - } - return result2; - } - function baseFill(array2, value, start, end) { - var length = array2.length; - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : length + start; - } - end = end === undefined2 || end > length ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array2[start++] = value; - } - return array2; - } - function baseFilter(collection, predicate) { - var result2 = []; - baseEach(collection, function(value, index2, collection2) { - if (predicate(value, index2, collection2)) { - result2.push(value); - } - }); - return result2; - } - function baseFlatten(array2, depth, predicate, isStrict, result2) { - var index2 = -1, length = array2.length; - predicate || (predicate = isFlattenable); - result2 || (result2 = []); - while (++index2 < length) { - var value = array2[index2]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - baseFlatten(value, depth - 1, predicate, isStrict, result2); - } else { - arrayPush(result2, value); - } - } else if (!isStrict) { - result2[result2.length] = value; - } - } - return result2; - } - var baseFor = createBaseFor(); - var baseForRight = createBaseFor(true); - function baseForOwn(object2, iteratee2) { - return object2 && baseFor(object2, iteratee2, keys); - } - function baseForOwnRight(object2, iteratee2) { - return object2 && baseForRight(object2, iteratee2, keys); - } - function baseFunctions(object2, props) { - return arrayFilter(props, function(key) { - return isFunction(object2[key]); - }); - } - function baseGet(object2, path2) { - path2 = castPath(path2, object2); - var index2 = 0, length = path2.length; - while (object2 != null && index2 < length) { - object2 = object2[toKey(path2[index2++])]; - } - return index2 && index2 == length ? object2 : undefined2; - } - function baseGetAllKeys(object2, keysFunc, symbolsFunc) { - var result2 = keysFunc(object2); - return isArray(object2) ? result2 : arrayPush(result2, symbolsFunc(object2)); - } - function baseGetTag(value) { - if (value == null) { - return value === undefined2 ? undefinedTag : nullTag; - } - return symToStringTag && symToStringTag in Object2(value) ? getRawTag(value) : objectToString(value); - } - function baseGt(value, other) { - return value > other; - } - function baseHas(object2, key) { - return object2 != null && hasOwnProperty.call(object2, key); - } - function baseHasIn(object2, key) { - return object2 != null && key in Object2(object2); - } - function baseInRange(number2, start, end) { - return number2 >= nativeMin(start, end) && number2 < nativeMax(start, end); - } - function baseIntersection(arrays, iteratee2, comparator) { - var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; - while (othIndex--) { - var array2 = arrays[othIndex]; - if (othIndex && iteratee2) { - array2 = arrayMap(array2, baseUnary(iteratee2)); - } - maxLength = nativeMin(array2.length, maxLength); - caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array2.length >= 120) ? new SetCache(othIndex && array2) : undefined2; - } - array2 = arrays[0]; - var index2 = -1, seen = caches[0]; - outer: - while (++index2 < length && result2.length < maxLength) { - var value = array2[index2], computed = iteratee2 ? iteratee2(value) : value; - value = comparator || value !== 0 ? value : 0; - if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) { - othIndex = othLength; - while (--othIndex) { - var cache2 = caches[othIndex]; - if (!(cache2 ? cacheHas(cache2, computed) : includes2(arrays[othIndex], computed, comparator))) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result2.push(value); - } - } - return result2; - } - function baseInverter(object2, setter, iteratee2, accumulator) { - baseForOwn(object2, function(value, key, object3) { - setter(accumulator, iteratee2(value), key, object3); - }); - return accumulator; - } - function baseInvoke(object2, path2, args) { - path2 = castPath(path2, object2); - object2 = parent(object2, path2); - var func = object2 == null ? object2 : object2[toKey(last(path2))]; - return func == null ? undefined2 : apply(func, object2, args); - } - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } - function baseIsEqualDeep(object2, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object2), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object2), othTag = othIsArr ? arrayTag : getTag(other); - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; - if (isSameTag && isBuffer(object2)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return objIsArr || isTypedArray(object2) ? equalArrays(object2, other, bitmask, customizer, equalFunc, stack) : equalByTag(object2, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object2, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__"); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object2.value() : object2, othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object2, other, bitmask, customizer, equalFunc, stack); - } - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } - function baseIsMatch(object2, source, matchData, customizer) { - var index2 = matchData.length, length = index2, noCustomizer = !customizer; - if (object2 == null) { - return !length; - } - object2 = Object2(object2); - while (index2--) { - var data = matchData[index2]; - if (noCustomizer && data[2] ? data[1] !== object2[data[0]] : !(data[0] in object2)) { - return false; - } - } - while (++index2 < length) { - data = matchData[index2]; - var key = data[0], objValue = object2[key], srcValue = data[1]; - if (noCustomizer && data[2]) { - if (objValue === undefined2 && !(key in object2)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result2 = customizer(objValue, srcValue, key, object2, source, stack); - } - if (!(result2 === undefined2 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) { - return false; - } - } - } - return true; - } - function baseIsNative(value) { - if (!isObject2(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - function baseIsTypedArray(value) { - return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } - function baseIteratee(value) { - if (typeof value == "function") { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == "object") { - return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); - } - return property(value); - } - function baseKeys(object2) { - if (!isPrototype(object2)) { - return nativeKeys(object2); - } - var result2 = []; - for (var key in Object2(object2)) { - if (hasOwnProperty.call(object2, key) && key != "constructor") { - result2.push(key); - } - } - return result2; - } - function baseKeysIn(object2) { - if (!isObject2(object2)) { - return nativeKeysIn(object2); - } - var isProto = isPrototype(object2), result2 = []; - for (var key in object2) { - if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object2, key)))) { - result2.push(key); - } - } - return result2; + weekInfoCache.set(locString, data); + } + return data; + } + function parseLocaleString(localeStr) { + const xIndex = localeStr.indexOf("-x-"); + if (xIndex !== -1) { + localeStr = localeStr.substring(0, xIndex); + } + const uIndex = localeStr.indexOf("-u-"); + if (uIndex === -1) { + return [localeStr]; + } else { + let options; + let selectedStr; + try { + options = getCachedDTF(localeStr).resolvedOptions(); + selectedStr = localeStr; + } catch (e3) { + const smaller = localeStr.substring(0, uIndex); + options = getCachedDTF(smaller).resolvedOptions(); + selectedStr = smaller; } - function baseLt(value, other) { - return value < other; + const { + numberingSystem, + calendar + } = options; + return [selectedStr, numberingSystem, calendar]; + } + } + function intlConfigString(localeStr, numberingSystem, outputCalendar) { + if (outputCalendar || numberingSystem) { + if (!localeStr.includes("-u-")) { + localeStr += "-u"; } - function baseMap(collection, iteratee2) { - var index2 = -1, result2 = isArrayLike(collection) ? Array2(collection.length) : []; - baseEach(collection, function(value, key, collection2) { - result2[++index2] = iteratee2(value, key, collection2); - }); - return result2; + if (outputCalendar) { + localeStr += `-ca-${outputCalendar}`; } - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object2) { - return object2 === source || baseIsMatch(object2, source, matchData); - }; + if (numberingSystem) { + localeStr += `-nu-${numberingSystem}`; } - function baseMatchesProperty(path2, srcValue) { - if (isKey(path2) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path2), srcValue); - } - return function(object2) { - var objValue = get(object2, path2); - return objValue === undefined2 && objValue === srcValue ? hasIn(object2, path2) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + return localeStr; + } else { + return localeStr; + } + } + function mapMonths(f2) { + const ms = []; + for (let i2 = 1;i2 <= 12; i2++) { + const dt = DateTime.utc(2009, i2, 1); + ms.push(f2(dt)); + } + return ms; + } + function mapWeekdays(f2) { + const ms = []; + for (let i2 = 1;i2 <= 7; i2++) { + const dt = DateTime.utc(2016, 11, 13 + i2); + ms.push(f2(dt)); + } + return ms; + } + function listStuff(loc, length, englishFn, intlFn) { + const mode = loc.listingMode(); + if (mode === "error") { + return null; + } else if (mode === "en") { + return englishFn(length); + } else { + return intlFn(length); + } + } + function supportsFastNumbers(loc) { + if (loc.numberingSystem && loc.numberingSystem !== "latn") { + return false; + } else { + return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || getCachedIntResolvedOptions(loc.locale).numberingSystem === "latn"; + } + } + + class PolyNumberFormatter { + constructor(intl, forceSimple, opts) { + this.padTo = opts.padTo || 0; + this.floor = opts.floor || false; + const { + padTo, + floor, + ...otherOpts + } = opts; + if (!forceSimple || Object.keys(otherOpts).length > 0) { + const intlOpts = { + useGrouping: false, + ...opts }; + if (opts.padTo > 0) + intlOpts.minimumIntegerDigits = opts.padTo; + this.inf = getCachedINF(intl, intlOpts); } - function baseMerge(object2, source, srcIndex, customizer, stack) { - if (object2 === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject2(srcValue)) { - baseMergeDeep(object2, source, key, srcIndex, baseMerge, customizer, stack); - } else { - var newValue = customizer ? customizer(safeGet(object2, key), srcValue, key + "", object2, source, stack) : undefined2; - if (newValue === undefined2) { - newValue = srcValue; - } - assignMergeValue(object2, key, newValue); - } - }, keysIn); - } - function baseMergeDeep(object2, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object2, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); - if (stacked) { - assignMergeValue(object2, key, stacked); - return; - } - var newValue = customizer ? customizer(objValue, srcValue, key + "", object2, source, stack) : undefined2; - var isCommon = newValue === undefined2; - if (isCommon) { - var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } else { - newValue = []; - } - } else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } else if (!isObject2(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } else { - isCommon = false; - } - } - if (isCommon) { - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack["delete"](srcValue); - } - assignMergeValue(object2, key, newValue); - } - function baseNth(array2, n2) { - var length = array2.length; - if (!length) { - return; - } - n2 += n2 < 0 ? length : 0; - return isIndex(n2, length) ? array2[n2] : undefined2; + } + format(i2) { + if (this.inf) { + const fixed = this.floor ? Math.floor(i2) : i2; + return this.inf.format(fixed); + } else { + const fixed = this.floor ? Math.floor(i2) : roundTo(i2, 3); + return padStart(fixed, this.padTo); } - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee2) { - if (isArray(iteratee2)) { - return function(value) { - return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2); - }; - } - return iteratee2; - }); + } + } + + class PolyDateFormatter { + constructor(dt, intl, opts) { + this.opts = opts; + this.originalZone = undefined; + let z2 = undefined; + if (this.opts.timeZone) { + this.dt = dt; + } else if (dt.zone.type === "fixed") { + const gmtOffset = -1 * (dt.offset / 60); + const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; + if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { + z2 = offsetZ; + this.dt = dt; } else { - iteratees = [identity]; - } - var index2 = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - var result2 = baseMap(collection, function(value, key, collection2) { - var criteria = arrayMap(iteratees, function(iteratee2) { - return iteratee2(value); + z2 = "UTC"; + this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ + minutes: dt.offset }); - return { criteria, index: ++index2, value }; - }); - return baseSortBy(result2, function(object2, other) { - return compareMultiple(object2, other, orders); - }); - } - function basePick(object2, paths) { - return basePickBy(object2, paths, function(value, path2) { - return hasIn(object2, path2); - }); - } - function basePickBy(object2, paths, predicate) { - var index2 = -1, length = paths.length, result2 = {}; - while (++index2 < length) { - var path2 = paths[index2], value = baseGet(object2, path2); - if (predicate(value, path2)) { - baseSet(result2, castPath(path2, object2), value); - } - } - return result2; - } - function basePropertyDeep(path2) { - return function(object2) { - return baseGet(object2, path2); - }; - } - function basePullAll(array2, values2, iteratee2, comparator) { - var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index2 = -1, length = values2.length, seen = array2; - if (array2 === values2) { - values2 = copyArray(values2); - } - if (iteratee2) { - seen = arrayMap(array2, baseUnary(iteratee2)); - } - while (++index2 < length) { - var fromIndex = 0, value = values2[index2], computed = iteratee2 ? iteratee2(value) : value; - while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array2) { - splice.call(seen, fromIndex, 1); - } - splice.call(array2, fromIndex, 1); - } - } - return array2; - } - function basePullAt(array2, indexes) { - var length = array2 ? indexes.length : 0, lastIndex = length - 1; - while (length--) { - var index2 = indexes[length]; - if (length == lastIndex || index2 !== previous) { - var previous = index2; - if (isIndex(index2)) { - splice.call(array2, index2, 1); - } else { - baseUnset(array2, index2); - } - } - } - return array2; - } - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - function baseRange(start, end, step, fromRight) { - var index2 = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result2 = Array2(length); - while (length--) { - result2[fromRight ? length : ++index2] = start; - start += step; - } - return result2; - } - function baseRepeat(string2, n2) { - var result2 = ""; - if (!string2 || n2 < 1 || n2 > MAX_SAFE_INTEGER3) { - return result2; - } - do { - if (n2 % 2) { - result2 += string2; - } - n2 = nativeFloor(n2 / 2); - if (n2) { - string2 += string2; - } - } while (n2); - return result2; - } - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ""); - } - function baseSample(collection) { - return arraySample(values(collection)); - } - function baseSampleSize(collection, n2) { - var array2 = values(collection); - return shuffleSelf(array2, baseClamp(n2, 0, array2.length)); - } - function baseSet(object2, path2, value, customizer) { - if (!isObject2(object2)) { - return object2; - } - path2 = castPath(path2, object2); - var index2 = -1, length = path2.length, lastIndex = length - 1, nested = object2; - while (nested != null && ++index2 < length) { - var key = toKey(path2[index2]), newValue = value; - if (key === "__proto__" || key === "constructor" || key === "prototype") { - return object2; - } - if (index2 != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined2; - if (newValue === undefined2) { - newValue = isObject2(objValue) ? objValue : isIndex(path2[index2 + 1]) ? [] : {}; - } - } - assignValue(nested, key, newValue); - nested = nested[key]; + this.originalZone = dt.zone; } - return object2; - } - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - var baseSetToString = !defineProperty ? identity : function(func, string2) { - return defineProperty(func, "toString", { - configurable: true, - enumerable: false, - value: constant(string2), - writable: true - }); - }; - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - function baseSlice(array2, start, end) { - var index2 = -1, length = array2.length; - if (start < 0) { - start = -start > length ? 0 : length + start; - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : end - start >>> 0; - start >>>= 0; - var result2 = Array2(length); - while (++index2 < length) { - result2[index2] = array2[index2 + start]; - } - return result2; - } - function baseSome(collection, predicate) { - var result2; - baseEach(collection, function(value, index2, collection2) { - result2 = predicate(value, index2, collection2); - return !result2; + } else if (dt.zone.type === "system") { + this.dt = dt; + } else if (dt.zone.type === "iana") { + this.dt = dt; + z2 = dt.zone.name; + } else { + z2 = "UTC"; + this.dt = dt.setZone("UTC").plus({ + minutes: dt.offset }); - return !!result2; - } - function baseSortedIndex(array2, value, retHighest) { - var low = 0, high = array2 == null ? low : array2.length; - if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = low + high >>> 1, computed = array2[mid]; - if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array2, value, identity, retHighest); - } - function baseSortedIndexBy(array2, value, iteratee2, retHighest) { - var low = 0, high = array2 == null ? 0 : array2.length; - if (high === 0) { - return 0; - } - value = iteratee2(value); - var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined2; - while (low < high) { - var mid = nativeFloor((low + high) / 2), computed = iteratee2(array2[mid]), othIsDefined = computed !== undefined2, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? computed <= value : computed < value; - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - function baseSortedUniq(array2, iteratee2) { - var index2 = -1, length = array2.length, resIndex = 0, result2 = []; - while (++index2 < length) { - var value = array2[index2], computed = iteratee2 ? iteratee2(value) : value; - if (!index2 || !eq2(computed, seen)) { - var seen = computed; - result2[resIndex++] = value === 0 ? 0 : value; - } - } - return result2; - } - function baseToNumber(value) { - if (typeof value == "number") { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } - function baseToString(value) { - if (typeof value == "string") { - return value; - } - if (isArray(value)) { - return arrayMap(value, baseToString) + ""; - } - if (isSymbol(value)) { - return symbolToString2 ? symbolToString2.call(value) : ""; - } - var result2 = value + ""; - return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2; - } - function baseUniq(array2, iteratee2, comparator) { - var index2 = -1, includes2 = arrayIncludes, length = array2.length, isCommon = true, result2 = [], seen = result2; - if (comparator) { - isCommon = false; - includes2 = arrayIncludesWith; - } else if (length >= LARGE_ARRAY_SIZE) { - var set2 = iteratee2 ? null : createSet(array2); - if (set2) { - return setToArray(set2); - } - isCommon = false; - includes2 = cacheHas; - seen = new SetCache; - } else { - seen = iteratee2 ? [] : result2; - } - outer: - while (++index2 < length) { - var value = array2[index2], computed = iteratee2 ? iteratee2(value) : value; - value = comparator || value !== 0 ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee2) { - seen.push(computed); - } - result2.push(value); - } else if (!includes2(seen, computed, comparator)) { - if (seen !== result2) { - seen.push(computed); - } - result2.push(value); - } - } - return result2; - } - function baseUnset(object2, path2) { - path2 = castPath(path2, object2); - var index2 = -1, length = path2.length; - if (!length) { - return true; - } - while (++index2 < length) { - var key = toKey(path2[index2]); - if (key === "__proto__" && !hasOwnProperty.call(object2, "__proto__")) { - return false; - } - if ((key === "constructor" || key === "prototype") && index2 < length - 1) { - return false; - } - } - var obj = parent(object2, path2); - return obj == null || delete obj[toKey(last(path2))]; - } - function baseUpdate(object2, path2, updater, customizer) { - return baseSet(object2, path2, updater(baseGet(object2, path2)), customizer); - } - function baseWhile(array2, predicate, isDrop, fromRight) { - var length = array2.length, index2 = fromRight ? length : -1; - while ((fromRight ? index2-- : ++index2 < length) && predicate(array2[index2], index2, array2)) {} - return isDrop ? baseSlice(array2, fromRight ? 0 : index2, fromRight ? index2 + 1 : length) : baseSlice(array2, fromRight ? index2 + 1 : 0, fromRight ? length : index2); - } - function baseWrapperValue(value, actions) { - var result2 = value; - if (result2 instanceof LazyWrapper) { - result2 = result2.value(); - } - return arrayReduce(actions, function(result3, action) { - return action.func.apply(action.thisArg, arrayPush([result3], action.args)); - }, result2); - } - function baseXor(arrays, iteratee2, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index2 = -1, result2 = Array2(length); - while (++index2 < length) { - var array2 = arrays[index2], othIndex = -1; - while (++othIndex < length) { - if (othIndex != index2) { - result2[index2] = baseDifference(result2[index2] || array2, arrays[othIndex], iteratee2, comparator); - } - } - } - return baseUniq(baseFlatten(result2, 1), iteratee2, comparator); - } - function baseZipObject(props, values2, assignFunc) { - var index2 = -1, length = props.length, valsLength = values2.length, result2 = {}; - while (++index2 < length) { - var value = index2 < valsLength ? values2[index2] : undefined2; - assignFunc(result2, props[index2], value); - } - return result2; - } - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } - function castFunction(value) { - return typeof value == "function" ? value : identity; - } - function castPath(value, object2) { - if (isArray(value)) { - return value; - } - return isKey(value, object2) ? [value] : stringToPath(toString2(value)); - } - var castRest = baseRest; - function castSlice(array2, start, end) { - var length = array2.length; - end = end === undefined2 ? length : end; - return !start && end >= length ? array2 : baseSlice(array2, start, end); + this.originalZone = dt.zone; } - var clearTimeout2 = ctxClearTimeout || function(id) { - return root.clearTimeout(id); + const intlOpts = { + ...this.opts }; - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - buffer.copy(result2); - return result2; - } - function cloneArrayBuffer(arrayBuffer) { - var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array2(result2).set(new Uint8Array2(arrayBuffer)); - return result2; - } - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - function cloneRegExp(regexp) { - var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result2.lastIndex = regexp.lastIndex; - return result2; - } - function cloneSymbol(symbol) { - return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {}; - } - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined2, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); - var othIsDefined = other !== undefined2, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); - if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { - return 1; - } - if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { - return -1; - } - } - return 0; - } - function compareMultiple(object2, other, orders) { - var index2 = -1, objCriteria = object2.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; - while (++index2 < length) { - var result2 = compareAscending(objCriteria[index2], othCriteria[index2]); - if (result2) { - if (index2 >= ordersLength) { - return result2; - } - var order = orders[index2]; - return result2 * (order == "desc" ? -1 : 1); - } - } - return object2.index - other.index; - } - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried; - while (++leftIndex < leftLength) { - result2[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result2[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result2[leftIndex++] = args[argsIndex++]; - } - return result2; - } - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried; - while (++argsIndex < rangeLength) { - result2[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result2[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result2[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result2; - } - function copyArray(source, array2) { - var index2 = -1, length = source.length; - array2 || (array2 = Array2(length)); - while (++index2 < length) { - array2[index2] = source[index2]; - } - return array2; + intlOpts.timeZone = intlOpts.timeZone || z2; + this.dtf = getCachedDTF(intl, intlOpts); + } + format() { + if (this.originalZone) { + return this.formatToParts().map(({ + value + }) => value).join(""); } - function copyObject(source, props, object2, customizer) { - var isNew = !object2; - object2 || (object2 = {}); - var index2 = -1, length = props.length; - while (++index2 < length) { - var key = props[index2]; - var newValue = customizer ? customizer(object2[key], source[key], key, object2, source) : undefined2; - if (newValue === undefined2) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object2, key, newValue); + return this.dtf.format(this.dt.toJSDate()); + } + formatToParts() { + const parts = this.dtf.formatToParts(this.dt.toJSDate()); + if (this.originalZone) { + return parts.map((part) => { + if (part.type === "timeZoneName") { + const offsetName = this.originalZone.offsetName(this.dt.ts, { + locale: this.dt.locale, + format: this.opts.timeZoneName + }); + return { + ...part, + value: offsetName + }; } else { - assignValue(object2, key, newValue); - } - } - return object2; - } - function copySymbols(source, object2) { - return copyObject(source, getSymbols(source), object2); - } - function copySymbolsIn(source, object2) { - return copyObject(source, getSymbolsIn(source), object2); - } - function createAggregator(setter, initializer) { - return function(collection, iteratee2) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; - return func(collection, setter, getIteratee(iteratee2, 2), accumulator); - }; - } - function createAssigner(assigner) { - return baseRest(function(object2, sources) { - var index2 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined2, guard = length > 2 ? sources[2] : undefined2; - customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined2; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined2 : customizer; - length = 1; - } - object2 = Object2(object2); - while (++index2 < length) { - var source = sources[index2]; - if (source) { - assigner(object2, source, index2, customizer); - } + return part; } - return object2; }); } - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee2) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee2); - } - var length = collection.length, index2 = fromRight ? length : -1, iterable = Object2(collection); - while (fromRight ? index2-- : ++index2 < length) { - if (iteratee2(iterable[index2], index2, iterable) === false) { - break; - } - } - return collection; - }; - } - function createBaseFor(fromRight) { - return function(object2, iteratee2, keysFunc) { - var index2 = -1, iterable = Object2(object2), props = keysFunc(object2), length = props.length; - while (length--) { - var key = props[fromRight ? length : ++index2]; - if (iteratee2(iterable[key], key, iterable) === false) { - break; - } - } - return object2; - }; - } - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); - function wrapper() { - var fn = this && this !== root && this instanceof wrapper ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - function createCaseFirst(methodName) { - return function(string2) { - string2 = toString2(string2); - var strSymbols = hasUnicode(string2) ? stringToArray(string2) : undefined2; - var chr = strSymbols ? strSymbols[0] : string2.charAt(0); - var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string2.slice(1); - return chr[methodName]() + trailing; - }; + return parts; + } + resolvedOptions() { + return this.dtf.resolvedOptions(); + } + } + + class PolyRelFormatter { + constructor(intl, isEnglish, opts) { + this.opts = { + style: "long", + ...opts + }; + if (!isEnglish && hasRelative()) { + this.rtf = getCachedRTF(intl, opts); } - function createCompounder(callback) { - return function(string2) { - return arrayReduce(words(deburr(string2).replace(reApos, "")), callback, ""); - }; + } + format(count2, unit) { + if (this.rtf) { + return this.rtf.format(count2, unit); + } else { + return formatRelativeTime(unit, count2, this.opts.numeric, this.opts.style !== "long"); } - function createCtor(Ctor) { - return function() { - var args = arguments; - switch (args.length) { - case 0: - return new Ctor; - case 1: - return new Ctor(args[0]); - case 2: - return new Ctor(args[0], args[1]); - case 3: - return new Ctor(args[0], args[1], args[2]); - case 4: - return new Ctor(args[0], args[1], args[2], args[3]); - case 5: - return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: - return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: - return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args); - return isObject2(result2) ? result2 : thisBinding; - }; + } + formatToParts(count2, unit) { + if (this.rtf) { + return this.rtf.formatToParts(count2, unit); + } else { + return []; } - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - function wrapper() { - var length = arguments.length, args = Array2(length), index2 = length, placeholder = getHolder(wrapper); - while (index2--) { - args[index2] = arguments[index2]; - } - var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); - length -= holders.length; - if (length < arity) { - return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, undefined2, args, holders, undefined2, undefined2, arity - length); - } - var fn = this && this !== root && this instanceof wrapper ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object2(collection); - if (!isArrayLike(collection)) { - var iteratee2 = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { - return iteratee2(iterable[key], key, iterable); - }; - } - var index2 = findIndexFunc(collection, predicate, fromIndex); - return index2 > -1 ? iterable[iteratee2 ? collection[index2] : index2] : undefined2; - }; + } + } + var fallbackWeekSettings = { + firstDay: 1, + minimalDays: 4, + weekend: [6, 7] + }; + + class Locale { + static fromOpts(opts) { + return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN); + } + static create(locale2, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) { + const specifiedLocale = locale2 || Settings.defaultLocale; + const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); + const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; + const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; + const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; + return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); + } + static resetCache() { + sysLocaleCache = null; + intlDTCache.clear(); + intlNumCache.clear(); + intlRelCache.clear(); + intlResolvedOptionsCache.clear(); + weekInfoCache.clear(); + } + static fromObject({ + locale: locale2, + numberingSystem, + outputCalendar, + weekSettings + } = {}) { + return Locale.create(locale2, numberingSystem, outputCalendar, weekSettings); + } + constructor(locale2, numbering, outputCalendar, weekSettings, specifiedLocale) { + const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale2); + this.locale = parsedLocale; + this.numberingSystem = numbering || parsedNumberingSystem || null; + this.outputCalendar = outputCalendar || parsedOutputCalendar || null; + this.weekSettings = weekSettings; + this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); + this.weekdaysCache = { + format: {}, + standalone: {} + }; + this.monthsCache = { + format: {}, + standalone: {} + }; + this.meridiemCache = null; + this.eraCache = {}; + this.specifiedLocale = specifiedLocale; + this.fastNumbersCached = null; + } + get fastNumbers() { + if (this.fastNumbersCached == null) { + this.fastNumbersCached = supportsFastNumbers(this); } - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, index2 = length, prereq = LodashWrapper.prototype.thru; - if (fromRight) { - funcs.reverse(); - } - while (index2--) { - var func = funcs[index2]; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == "wrapper") { - var wrapper = new LodashWrapper([], true); - } - } - index2 = wrapper ? index2 : length; - while (++index2 < length) { - func = funcs[index2]; - var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined2; - if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); - } - } - return function() { - var args = arguments, value = args[0]; - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index3 = 0, result2 = length ? funcs[index3].apply(this, args) : value; - while (++index3 < length) { - result2 = funcs[index3].call(this, result2); - } - return result2; - }; - }); + return this.fastNumbersCached; + } + listingMode() { + const isActuallyEn = this.isEnglish(); + const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); + return isActuallyEn && hasNoWeirdness ? "en" : "intl"; + } + clone(alts) { + if (!alts || Object.getOwnPropertyNames(alts).length === 0) { + return this; + } else { + return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false); } - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined2 : createCtor(func); - function wrapper() { - var length = arguments.length, args = Array2(length), index2 = length; - while (index2--) { - args[index2] = arguments[index2]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry(func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary2, arity - length); - } - var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary2 < length) { - args.length = ary2; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); + } + redefaultToEN(alts = {}) { + return this.clone({ + ...alts, + defaultToEN: true + }); + } + redefaultToSystem(alts = {}) { + return this.clone({ + ...alts, + defaultToEN: false + }); + } + months(length, format = false) { + return listStuff(this, length, months, () => { + const monthSpecialCase = this.intl === "ja" || this.intl.startsWith("ja-"); + format &= !monthSpecialCase; + const intl = format ? { + month: length, + day: "numeric" + } : { + month: length + }, formatStr = format ? "format" : "standalone"; + if (!this.monthsCache[formatStr][length]) { + const mapper = !monthSpecialCase ? (dt) => this.extract(dt, intl, "month") : (dt) => this.dtFormatter(dt, intl).format(); + this.monthsCache[formatStr][length] = mapMonths(mapper); } - return wrapper; - } - function createInverter(setter, toIteratee) { - return function(object2, iteratee2) { - return baseInverter(object2, setter, toIteratee(iteratee2), {}); - }; - } - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result2; - if (value === undefined2 && other === undefined2) { - return defaultValue; - } - if (value !== undefined2) { - result2 = value; - } - if (other !== undefined2) { - if (result2 === undefined2) { - return other; - } - if (typeof value == "string" || typeof other == "string") { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result2 = operator(value, other); - } - return result2; - }; - } - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee2) { - return apply(iteratee2, thisArg, args); - }); - }); - }); - } - function createPadding(length, chars) { - chars = chars === undefined2 ? " " : baseToString(chars); - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; + return this.monthsCache[formatStr][length]; + }); + } + weekdays(length, format = false) { + return listStuff(this, length, weekdays, () => { + const intl = format ? { + weekday: length, + year: "numeric", + month: "long", + day: "numeric" + } : { + weekday: length + }, formatStr = format ? "format" : "standalone"; + if (!this.weekdaysCache[formatStr][length]) { + this.weekdaysCache[formatStr][length] = mapWeekdays((dt) => this.extract(dt, intl, "weekday")); } - var result2 = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length); - } - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); - function wrapper() { - var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); + return this.weekdaysCache[formatStr][length]; + }); + } + meridiems() { + return listStuff(this, undefined, () => meridiems, () => { + if (!this.meridiemCache) { + const intl = { + hour: "numeric", + hourCycle: "h12" + }; + this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map((dt) => this.extract(dt, intl, "dayperiod")); } - return wrapper; - } - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != "number" && isIterateeCall(start, end, step)) { - end = step = undefined2; - } - start = toFinite(start); - if (end === undefined2) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined2 ? start < end ? 1 : -1 : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == "string" && typeof other == "string")) { - value = toNumber2(value); - other = toNumber2(other); - } - return operator(value, other); - }; - } - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined2, newHoldersRight = isCurry ? undefined2 : holders, newPartials = isCurry ? partials : undefined2, newPartialsRight = isCurry ? undefined2 : partials; - bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); - } - var newData = [ - func, - bitmask, - thisArg, - newPartials, - newHolders, - newPartialsRight, - newHoldersRight, - argPos, - ary2, - arity - ]; - var result2 = wrapFunc.apply(undefined2, newData); - if (isLaziable(func)) { - setData(result2, newData); - } - result2.placeholder = placeholder; - return setWrapToString(result2, func, bitmask); - } - function createRound(methodName) { - var func = Math2[methodName]; - return function(number2, precision) { - number2 = toNumber2(number2); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number2)) { - var pair = (toString2(number2) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision)); - pair = (toString2(value) + "e").split("e"); - return +(pair[0] + "e" + (+pair[1] - precision)); - } - return func(number2); - }; - } - var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop : function(values2) { - return new Set2(values2); - }; - function createToPairs(keysFunc) { - return function(object2) { - var tag2 = getTag(object2); - if (tag2 == mapTag) { - return mapToArray(object2); - } - if (tag2 == setTag) { - return setToPairs(object2); - } - return baseToPairs(object2, keysFunc(object2)); + return this.meridiemCache; + }); + } + eras(length) { + return listStuff(this, length, eras, () => { + const intl = { + era: length }; - } - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined2; - } - ary2 = ary2 === undefined2 ? ary2 : nativeMax(toInteger(ary2), 0); - arity = arity === undefined2 ? arity : toInteger(arity); - length -= holders ? holders.length : 0; - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, holdersRight = holders; - partials = holders = undefined2; - } - var data = isBindKey ? undefined2 : getData(func); - var newData = [ - func, - bitmask, - thisArg, - partials, - holders, - partialsRight, - holdersRight, - argPos, - ary2, - arity - ]; - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined2 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result2 = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result2 = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result2 = createPartial(func, bitmask, thisArg, partials); - } else { - result2 = createHybrid.apply(undefined2, newData); + if (!this.eraCache[length]) { + this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) => this.extract(dt, intl, "era")); } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result2, newData), func, bitmask); + return this.eraCache[length]; + }); + } + extract(dt, intlOpts, field) { + const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m2) => m2.type.toLowerCase() === field); + return matching ? matching.value : null; + } + numberFormatter(opts = {}) { + return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); + } + dtFormatter(dt, intlOpts = {}) { + return new PolyDateFormatter(dt, this.intl, intlOpts); + } + relFormatter(opts = {}) { + return new PolyRelFormatter(this.intl, this.isEnglish(), opts); + } + listFormatter(opts = {}) { + return getCachedLF(this.intl, opts); + } + isEnglish() { + return this.locale === "en" || this.locale.toLowerCase() === "en-us" || getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us"); + } + getWeekSettings() { + if (this.weekSettings) { + return this.weekSettings; + } else if (!hasLocaleWeekInfo()) { + return fallbackWeekSettings; + } else { + return getCachedWeekInfo(this.locale); } - function customDefaultsAssignIn(objValue, srcValue, key, object2) { - if (objValue === undefined2 || eq2(objValue, objectProto[key]) && !hasOwnProperty.call(object2, key)) { - return srcValue; - } - return objValue; + } + getStartOfWeek() { + return this.getWeekSettings().firstDay; + } + getMinDaysInFirstWeek() { + return this.getWeekSettings().minimalDays; + } + getWeekendDays() { + return this.getWeekSettings().weekend; + } + equals(other) { + return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; + } + toString() { + return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`; + } + } + var singleton = null; + + class FixedOffsetZone extends Zone { + static get utcInstance() { + if (singleton === null) { + singleton = new FixedOffsetZone(0); } - function customDefaultsMerge(objValue, srcValue, key, object2, source, stack) { - if (isObject2(objValue) && isObject2(srcValue)) { - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined2, customDefaultsMerge, stack); - stack["delete"](srcValue); + return singleton; + } + static instance(offset2) { + return offset2 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset2); + } + static parseSpecifier(s3) { + if (s3) { + const r2 = s3.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); + if (r2) { + return new FixedOffsetZone(signedOffset(r2[1], r2[2])); } - return objValue; } - function customOmitClone(value) { - return isPlainObject(value) ? undefined2 : value; + return null; + } + constructor(offset2) { + super(); + this.fixed = offset2; + } + get type() { + return "fixed"; + } + get name() { + return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; + } + get ianaName() { + if (this.fixed === 0) { + return "Etc/UTC"; + } else { + return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; } - function equalArrays(array2, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array2.length, othLength = other.length; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - var arrStacked = stack.get(array2); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array2; - } - var index2 = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache : undefined2; - stack.set(array2, other); - stack.set(other, array2); - while (++index2 < arrLength) { - var arrValue = array2[index2], othValue = other[index2]; - if (customizer) { - var compared = isPartial ? customizer(othValue, arrValue, index2, other, array2, stack) : customizer(arrValue, othValue, index2, array2, other, stack); - } - if (compared !== undefined2) { - if (compared) { - continue; - } - result2 = false; - break; - } - if (seen) { - if (!arraySome(other, function(othValue2, othIndex) { - if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result2 = false; - break; + } + offsetName() { + return this.name; + } + formatOffset(ts, format) { + return formatOffset(this.fixed, format); + } + get isUniversal() { + return true; + } + offset() { + return this.fixed; + } + equals(otherZone) { + return otherZone.type === "fixed" && otherZone.fixed === this.fixed; + } + get isValid() { + return true; + } + } + + class InvalidZone extends Zone { + constructor(zoneName) { + super(); + this.zoneName = zoneName; + } + get type() { + return "invalid"; + } + get name() { + return this.zoneName; + } + get isUniversal() { + return false; + } + offsetName() { + return null; + } + formatOffset() { + return ""; + } + offset() { + return NaN; + } + equals() { + return false; + } + get isValid() { + return false; + } + } + function normalizeZone(input, defaultZone2) { + if (isUndefined(input) || input === null) { + return defaultZone2; + } else if (input instanceof Zone) { + return input; + } else if (isString(input)) { + const lowered = input.toLowerCase(); + if (lowered === "default") + return defaultZone2; + else if (lowered === "local" || lowered === "system") + return SystemZone.instance; + else if (lowered === "utc" || lowered === "gmt") + return FixedOffsetZone.utcInstance; + else + return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); + } else if (isNumber(input)) { + return FixedOffsetZone.instance(input); + } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { + return input; + } else { + return new InvalidZone(input); + } + } + var numberingSystems = { + arab: "[\u0660-\u0669]", + arabext: "[\u06F0-\u06F9]", + bali: "[\u1B50-\u1B59]", + beng: "[\u09E6-\u09EF]", + deva: "[\u0966-\u096F]", + fullwide: "[\uFF10-\uFF19]", + gujr: "[\u0AE6-\u0AEF]", + hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", + khmr: "[\u17E0-\u17E9]", + knda: "[\u0CE6-\u0CEF]", + laoo: "[\u0ED0-\u0ED9]", + limb: "[\u1946-\u194F]", + mlym: "[\u0D66-\u0D6F]", + mong: "[\u1810-\u1819]", + mymr: "[\u1040-\u1049]", + orya: "[\u0B66-\u0B6F]", + tamldec: "[\u0BE6-\u0BEF]", + telu: "[\u0C66-\u0C6F]", + thai: "[\u0E50-\u0E59]", + tibt: "[\u0F20-\u0F29]", + latn: "\\d" + }; + var numberingSystemsUTF16 = { + arab: [1632, 1641], + arabext: [1776, 1785], + bali: [6992, 7001], + beng: [2534, 2543], + deva: [2406, 2415], + fullwide: [65296, 65303], + gujr: [2790, 2799], + khmr: [6112, 6121], + knda: [3302, 3311], + laoo: [3792, 3801], + limb: [6470, 6479], + mlym: [3430, 3439], + mong: [6160, 6169], + mymr: [4160, 4169], + orya: [2918, 2927], + tamldec: [3046, 3055], + telu: [3174, 3183], + thai: [3664, 3673], + tibt: [3872, 3881] + }; + var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); + function parseDigits(str) { + let value = parseInt(str, 10); + if (isNaN(value)) { + value = ""; + for (let i2 = 0;i2 < str.length; i2++) { + const code = str.charCodeAt(i2); + if (str[i2].search(numberingSystems.hanidec) !== -1) { + value += hanidecChars.indexOf(str[i2]); + } else { + for (const key in numberingSystemsUTF16) { + const [min, max] = numberingSystemsUTF16[key]; + if (code >= min && code <= max) { + value += code - min; } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - result2 = false; - break; } } - stack["delete"](array2); - stack["delete"](other); - return result2; } - function equalByTag(object2, other, tag2, bitmask, customizer, equalFunc, stack) { - switch (tag2) { - case dataViewTag: - if (object2.byteLength != other.byteLength || object2.byteOffset != other.byteOffset) { - return false; - } - object2 = object2.buffer; - other = other.buffer; - case arrayBufferTag: - if (object2.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object2), new Uint8Array2(other))) { - return false; - } - return true; - case boolTag: - case dateTag: - case numberTag: - return eq2(+object2, +other); - case errorTag: - return object2.name == other.name && object2.message == other.message; - case regexpTag: - case stringTag: - return object2 == other + ""; - case mapTag: - var convert = mapToArray; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - if (object2.size != other.size && !isPartial) { - return false; - } - var stacked = stack.get(object2); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - stack.set(object2, other); - var result2 = equalArrays(convert(object2), convert(other), bitmask, customizer, equalFunc, stack); - stack["delete"](object2); - return result2; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object2) == symbolValueOf.call(other); - } - } - return false; - } - function equalObjects(object2, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object2), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; - if (objLength != othLength && !isPartial) { - return false; - } - var index2 = objLength; - while (index2--) { - var key = objProps[index2]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - var objStacked = stack.get(object2); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object2; - } - var result2 = true; - stack.set(object2, other); - stack.set(other, object2); - var skipCtor = isPartial; - while (++index2 < objLength) { - key = objProps[index2]; - var objValue = object2[key], othValue = other[key]; - if (customizer) { - var compared = isPartial ? customizer(othValue, objValue, key, other, object2, stack) : customizer(objValue, othValue, key, object2, other, stack); - } - if (!(compared === undefined2 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { - result2 = false; - break; - } - skipCtor || (skipCtor = key == "constructor"); - } - if (result2 && !skipCtor) { - var objCtor = object2.constructor, othCtor = other.constructor; - if (objCtor != othCtor && (("constructor" in object2) && ("constructor" in other)) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { - result2 = false; - } - } - stack["delete"](object2); - stack["delete"](other); - return result2; - } - function flatRest(func) { - return setToString(overRest(func, undefined2, flatten), func + ""); - } - function getAllKeys(object2) { - return baseGetAllKeys(object2, keys, getSymbols); - } - function getAllKeysIn(object2) { - return baseGetAllKeys(object2, keysIn, getSymbolsIn); - } - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); - }; - function getFuncName(func) { - var result2 = func.name + "", array2 = realNames[result2], length = hasOwnProperty.call(realNames, result2) ? array2.length : 0; - while (length--) { - var data = array2[length], otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result2; - } - function getHolder(func) { - var object2 = hasOwnProperty.call(lodash, "placeholder") ? lodash : func; - return object2.placeholder; - } - function getIteratee() { - var result2 = lodash.iteratee || iteratee; - result2 = result2 === iteratee ? baseIteratee : result2; - return arguments.length ? result2(arguments[0], arguments[1]) : result2; - } - function getMapData(map2, key) { - var data = map2.__data__; - return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; - } - function getMatchData(object2) { - var result2 = keys(object2), length = result2.length; - while (length--) { - var key = result2[length], value = object2[key]; - result2[length] = [key, value, isStrictComparable(value)]; - } - return result2; - } - function getNative(object2, key) { - var value = getValue(object2, key); - return baseIsNative(value) ? value : undefined2; - } - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), tag2 = value[symToStringTag]; - try { - value[symToStringTag] = undefined2; - var unmasked = true; - } catch (e3) {} - var result2 = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag2; - } else { - delete value[symToStringTag]; - } - } - return result2; - } - var getSymbols = !nativeGetSymbols ? stubArray : function(object2) { - if (object2 == null) { - return []; - } - object2 = Object2(object2); - return arrayFilter(nativeGetSymbols(object2), function(symbol) { - return propertyIsEnumerable.call(object2, symbol); - }); - }; - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object2) { - var result2 = []; - while (object2) { - arrayPush(result2, getSymbols(object2)); - object2 = getPrototype(object2); - } - return result2; - }; - var getTag = baseGetTag; - if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2) != setTag || WeakMap2 && getTag(new WeakMap2) != weakMapTag) { - getTag = function(value) { - var result2 = baseGetTag(value), Ctor = result2 == objectTag ? value.constructor : undefined2, ctorString = Ctor ? toSource(Ctor) : ""; - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: - return dataViewTag; - case mapCtorString: - return mapTag; - case promiseCtorString: - return promiseTag; - case setCtorString: - return setTag; - case weakMapCtorString: - return weakMapTag; - } - } - return result2; - }; - } - function getView(start, end, transforms) { - var index2 = -1, length = transforms.length; - while (++index2 < length) { - var data = transforms[index2], size2 = data.size; - switch (data.type) { - case "drop": - start += size2; - break; - case "dropRight": - end -= size2; - break; - case "take": - end = nativeMin(end, start + size2); - break; - case "takeRight": - start = nativeMax(start, end - size2); - break; - } - } - return { start, end }; - } - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - function hasPath(object2, path2, hasFunc) { - path2 = castPath(path2, object2); - var index2 = -1, length = path2.length, result2 = false; - while (++index2 < length) { - var key = toKey(path2[index2]); - if (!(result2 = object2 != null && hasFunc(object2, key))) { - break; - } - object2 = object2[key]; - } - if (result2 || ++index2 != length) { - return result2; - } - length = object2 == null ? 0 : object2.length; - return !!length && isLength(length) && isIndex(key, length) && (isArray(object2) || isArguments(object2)); - } - function initCloneArray(array2) { - var length = array2.length, result2 = new array2.constructor(length); - if (length && typeof array2[0] == "string" && hasOwnProperty.call(array2, "index")) { - result2.index = array2.index; - result2.input = array2.input; - } - return result2; - } - function initCloneObject(object2) { - return typeof object2.constructor == "function" && !isPrototype(object2) ? baseCreate(getPrototype(object2)) : {}; - } - function initCloneByTag(object2, tag2, isDeep) { - var Ctor = object2.constructor; - switch (tag2) { - case arrayBufferTag: - return cloneArrayBuffer(object2); - case boolTag: - case dateTag: - return new Ctor(+object2); - case dataViewTag: - return cloneDataView(object2, isDeep); - case float32Tag: - case float64Tag: - case int8Tag: - case int16Tag: - case int32Tag: - case uint8Tag: - case uint8ClampedTag: - case uint16Tag: - case uint32Tag: - return cloneTypedArray(object2, isDeep); - case mapTag: - return new Ctor; - case numberTag: - case stringTag: - return new Ctor(object2); - case regexpTag: - return cloneRegExp(object2); - case setTag: - return new Ctor; - case symbolTag: - return cloneSymbol(object2); - } - } - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; - details = details.join(length > 2 ? ", " : " "); - return source.replace(reWrapComment, `{ -/* [wrapped with ` + details + `] */ -`); - } - function isFlattenable(value) { - return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); - } - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER3 : length; - return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); - } - function isIterateeCall(value, index2, object2) { - if (!isObject2(object2)) { - return false; - } - var type = typeof index2; - if (type == "number" ? isArrayLike(object2) && isIndex(index2, object2.length) : type == "string" && (index2 in object2)) { - return eq2(object2[index2], value); - } - return false; - } - function isKey(value, object2) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object2 != null && value in Object2(object2); - } - function isKeyable(value) { - var type = typeof value; - return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null; - } - function isLaziable(func) { - var funcName = getFuncName(func), other = lodash[funcName]; - if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - function isMasked(func) { - return !!maskSrcKey && maskSrcKey in func; - } - var isMaskable = coreJsData ? isFunction : stubFalse; - function isPrototype(value) { - var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; - return value === proto; - } - function isStrictComparable(value) { - return value === value && !isObject2(value); - } - function matchesStrictComparable(key, srcValue) { - return function(object2) { - if (object2 == null) { - return false; - } - return object2[key] === srcValue && (srcValue !== undefined2 || (key in Object2(object2))); - }; - } - function memoizeCapped(func) { - var result2 = memoize(func, function(key) { - if (cache2.size === MAX_MEMOIZE_SIZE) { - cache2.clear(); - } - return key; - }); - var cache2 = result2.cache; - return result2; - } - function mergeData(data, source) { - var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; - if (!(isCommon || isCombo)) { - return data; - } - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - value = source[7]; - if (value) { - data[7] = value; - } - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - if (data[9] == null) { - data[9] = source[9]; - } - data[0] = source[0]; - data[1] = newBitmask; - return data; - } - function nativeKeysIn(object2) { - var result2 = []; - if (object2 != null) { - for (var key in Object2(object2)) { - result2.push(key); - } - } - return result2; - } - function objectToString(value) { - return nativeObjectToString.call(value); - } - function overRest(func, start, transform2) { - start = nativeMax(start === undefined2 ? func.length - 1 : start, 0); - return function() { - var args = arguments, index2 = -1, length = nativeMax(args.length - start, 0), array2 = Array2(length); - while (++index2 < length) { - array2[index2] = args[start + index2]; - } - index2 = -1; - var otherArgs = Array2(start + 1); - while (++index2 < start) { - otherArgs[index2] = args[index2]; - } - otherArgs[start] = transform2(array2); - return apply(func, this, otherArgs); - }; - } - function parent(object2, path2) { - return path2.length < 2 ? object2 : baseGet(object2, baseSlice(path2, 0, -1)); - } - function reorder(array2, indexes) { - var arrLength = array2.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array2); - while (length--) { - var index2 = indexes[length]; - array2[length] = isIndex(index2, arrLength) ? oldArray[index2] : undefined2; - } - return array2; - } - function safeGet(object2, key) { - if (key === "constructor" && typeof object2[key] === "function") { - return; - } - if (key == "__proto__") { - return; - } - return object2[key]; - } - var setData = shortOut(baseSetData); - var setTimeout2 = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - var setToString = shortOut(baseSetToString); - function setWrapToString(wrapper, reference, bitmask) { - var source = reference + ""; - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - function shortOut(func) { - var count = 0, lastCalled = 0; - return function() { - var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined2, arguments); - }; - } - function shuffleSelf(array2, size2) { - var index2 = -1, length = array2.length, lastIndex = length - 1; - size2 = size2 === undefined2 ? length : size2; - while (++index2 < size2) { - var rand = baseRandom(index2, lastIndex), value = array2[rand]; - array2[rand] = array2[index2]; - array2[index2] = value; - } - array2.length = size2; - return array2; - } - var stringToPath = memoizeCapped(function(string2) { - var result2 = []; - if (string2.charCodeAt(0) === 46) { - result2.push(""); - } - string2.replace(rePropName, function(match, number2, quote, subString) { - result2.push(quote ? subString.replace(reEscapeChar, "$1") : number2 || match); - }); - return result2; - }); - function toKey(value) { - if (typeof value == "string" || isSymbol(value)) { - return value; - } - var result2 = value + ""; - return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2; - } - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e3) {} - try { - return func + ""; - } catch (e3) {} - } - return ""; - } - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = "_." + pair[0]; - if (bitmask & pair[1] && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); - } - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result2.__actions__ = copyArray(wrapper.__actions__); - result2.__index__ = wrapper.__index__; - result2.__values__ = wrapper.__values__; - return result2; - } - function chunk(array2, size2, guard) { - if (guard ? isIterateeCall(array2, size2, guard) : size2 === undefined2) { - size2 = 1; - } else { - size2 = nativeMax(toInteger(size2), 0); - } - var length = array2 == null ? 0 : array2.length; - if (!length || size2 < 1) { - return []; - } - var index2 = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2)); - while (index2 < length) { - result2[resIndex++] = baseSlice(array2, index2, index2 += size2); - } - return result2; - } - function compact(array2) { - var index2 = -1, length = array2 == null ? 0 : array2.length, resIndex = 0, result2 = []; - while (++index2 < length) { - var value = array2[index2]; - if (value) { - result2[resIndex++] = value; - } - } - return result2; - } - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array2(length - 1), array2 = arguments[0], index2 = length; - while (index2--) { - args[index2 - 1] = arguments[index2]; - } - return arrayPush(isArray(array2) ? copyArray(array2) : [array2], baseFlatten(args, 1)); - } - var difference = baseRest(function(array2, values2) { - return isArrayLikeObject(array2) ? baseDifference(array2, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; - }); - var differenceBy = baseRest(function(array2, values2) { - var iteratee2 = last(values2); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined2; - } - return isArrayLikeObject(array2) ? baseDifference(array2, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : []; - }); - var differenceWith = baseRest(function(array2, values2) { - var comparator = last(values2); - if (isArrayLikeObject(comparator)) { - comparator = undefined2; - } - return isArrayLikeObject(array2) ? baseDifference(array2, baseFlatten(values2, 1, isArrayLikeObject, true), undefined2, comparator) : []; - }); - function drop(array2, n2, guard) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - return baseSlice(array2, n2 < 0 ? 0 : n2, length); - } - function dropRight(array2, n2, guard) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - n2 = length - n2; - return baseSlice(array2, 0, n2 < 0 ? 0 : n2); - } - function dropRightWhile(array2, predicate) { - return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), true, true) : []; - } - function dropWhile(array2, predicate) { - return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), true) : []; - } - function fill(array2, value, start, end) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return []; - } - if (start && typeof start != "number" && isIterateeCall(array2, value, start)) { - start = 0; - end = length; - } - return baseFill(array2, value, start, end); - } - function findIndex2(array2, predicate, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return -1; - } - var index2 = fromIndex == null ? 0 : toInteger(fromIndex); - if (index2 < 0) { - index2 = nativeMax(length + index2, 0); - } - return baseFindIndex(array2, getIteratee(predicate, 3), index2); - } - function findLastIndex(array2, predicate, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return -1; - } - var index2 = length - 1; - if (fromIndex !== undefined2) { - index2 = toInteger(fromIndex); - index2 = fromIndex < 0 ? nativeMax(length + index2, 0) : nativeMin(index2, length - 1); - } - return baseFindIndex(array2, getIteratee(predicate, 3), index2, true); - } - function flatten(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseFlatten(array2, 1) : []; - } - function flattenDeep(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseFlatten(array2, INFINITY) : []; - } - function flattenDepth(array2, depth) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return []; - } - depth = depth === undefined2 ? 1 : toInteger(depth); - return baseFlatten(array2, depth); - } - function fromPairs(pairs) { - var index2 = -1, length = pairs == null ? 0 : pairs.length, result2 = {}; - while (++index2 < length) { - var pair = pairs[index2]; - baseAssignValue(result2, pair[0], pair[1]); - } - return result2; - } - function head(array2) { - return array2 && array2.length ? array2[0] : undefined2; - } - function indexOf(array2, value, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return -1; - } - var index2 = fromIndex == null ? 0 : toInteger(fromIndex); - if (index2 < 0) { - index2 = nativeMax(length + index2, 0); - } - return baseIndexOf(array2, value, index2); - } - function initial(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseSlice(array2, 0, -1) : []; - } - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; - }); - var intersectionBy = baseRest(function(arrays) { - var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); - if (iteratee2 === last(mapped)) { - iteratee2 = undefined2; - } else { - mapped.pop(); - } - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : []; - }); - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); - comparator = typeof comparator == "function" ? comparator : undefined2; - if (comparator) { - mapped.pop(); - } - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined2, comparator) : []; - }); - function join3(array2, separator) { - return array2 == null ? "" : nativeJoin.call(array2, separator); - } - function last(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? array2[length - 1] : undefined2; - } - function lastIndexOf(array2, value, fromIndex) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return -1; - } - var index2 = length; - if (fromIndex !== undefined2) { - index2 = toInteger(fromIndex); - index2 = index2 < 0 ? nativeMax(length + index2, 0) : nativeMin(index2, length - 1); - } - return value === value ? strictLastIndexOf(array2, value, index2) : baseFindIndex(array2, baseIsNaN, index2, true); - } - function nth(array2, n2) { - return array2 && array2.length ? baseNth(array2, toInteger(n2)) : undefined2; - } - var pull = baseRest(pullAll); - function pullAll(array2, values2) { - return array2 && array2.length && values2 && values2.length ? basePullAll(array2, values2) : array2; - } - function pullAllBy(array2, values2, iteratee2) { - return array2 && array2.length && values2 && values2.length ? basePullAll(array2, values2, getIteratee(iteratee2, 2)) : array2; - } - function pullAllWith(array2, values2, comparator) { - return array2 && array2.length && values2 && values2.length ? basePullAll(array2, values2, undefined2, comparator) : array2; - } - var pullAt = flatRest(function(array2, indexes) { - var length = array2 == null ? 0 : array2.length, result2 = baseAt(array2, indexes); - basePullAt(array2, arrayMap(indexes, function(index2) { - return isIndex(index2, length) ? +index2 : index2; - }).sort(compareAscending)); - return result2; - }); - function remove(array2, predicate) { - var result2 = []; - if (!(array2 && array2.length)) { - return result2; - } - var index2 = -1, indexes = [], length = array2.length; - predicate = getIteratee(predicate, 3); - while (++index2 < length) { - var value = array2[index2]; - if (predicate(value, index2, array2)) { - result2.push(value); - indexes.push(index2); - } - } - basePullAt(array2, indexes); - return result2; - } - function reverse(array2) { - return array2 == null ? array2 : nativeReverse.call(array2); - } - function slice(array2, start, end) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return []; - } - if (end && typeof end != "number" && isIterateeCall(array2, start, end)) { - start = 0; - end = length; - } else { - start = start == null ? 0 : toInteger(start); - end = end === undefined2 ? length : toInteger(end); - } - return baseSlice(array2, start, end); - } - function sortedIndex(array2, value) { - return baseSortedIndex(array2, value); - } - function sortedIndexBy(array2, value, iteratee2) { - return baseSortedIndexBy(array2, value, getIteratee(iteratee2, 2)); - } - function sortedIndexOf(array2, value) { - var length = array2 == null ? 0 : array2.length; - if (length) { - var index2 = baseSortedIndex(array2, value); - if (index2 < length && eq2(array2[index2], value)) { - return index2; - } - } - return -1; - } - function sortedLastIndex(array2, value) { - return baseSortedIndex(array2, value, true); - } - function sortedLastIndexBy(array2, value, iteratee2) { - return baseSortedIndexBy(array2, value, getIteratee(iteratee2, 2), true); - } - function sortedLastIndexOf(array2, value) { - var length = array2 == null ? 0 : array2.length; - if (length) { - var index2 = baseSortedIndex(array2, value, true) - 1; - if (eq2(array2[index2], value)) { - return index2; - } - } - return -1; - } - function sortedUniq(array2) { - return array2 && array2.length ? baseSortedUniq(array2) : []; - } - function sortedUniqBy(array2, iteratee2) { - return array2 && array2.length ? baseSortedUniq(array2, getIteratee(iteratee2, 2)) : []; - } - function tail(array2) { - var length = array2 == null ? 0 : array2.length; - return length ? baseSlice(array2, 1, length) : []; - } - function take(array2, n2, guard) { - if (!(array2 && array2.length)) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - return baseSlice(array2, 0, n2 < 0 ? 0 : n2); - } - function takeRight(array2, n2, guard) { - var length = array2 == null ? 0 : array2.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined2 ? 1 : toInteger(n2); - n2 = length - n2; - return baseSlice(array2, n2 < 0 ? 0 : n2, length); - } - function takeRightWhile(array2, predicate) { - return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3), false, true) : []; - } - function takeWhile(array2, predicate) { - return array2 && array2.length ? baseWhile(array2, getIteratee(predicate, 3)) : []; - } - var union2 = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - var unionBy = baseRest(function(arrays) { - var iteratee2 = last(arrays); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined2; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)); - }); - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == "function" ? comparator : undefined2; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined2, comparator); - }); - function uniq(array2) { - return array2 && array2.length ? baseUniq(array2) : []; - } - function uniqBy(array2, iteratee2) { - return array2 && array2.length ? baseUniq(array2, getIteratee(iteratee2, 2)) : []; - } - function uniqWith(array2, comparator) { - comparator = typeof comparator == "function" ? comparator : undefined2; - return array2 && array2.length ? baseUniq(array2, undefined2, comparator) : []; - } - function unzip(array2) { - if (!(array2 && array2.length)) { - return []; - } - var length = 0; - array2 = arrayFilter(array2, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index2) { - return arrayMap(array2, baseProperty(index2)); - }); - } - function unzipWith(array2, iteratee2) { - if (!(array2 && array2.length)) { - return []; - } - var result2 = unzip(array2); - if (iteratee2 == null) { - return result2; - } - return arrayMap(result2, function(group) { - return apply(iteratee2, undefined2, group); - }); - } - var without = baseRest(function(array2, values2) { - return isArrayLikeObject(array2) ? baseDifference(array2, values2) : []; - }); - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - var xorBy = baseRest(function(arrays) { - var iteratee2 = last(arrays); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined2; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2)); - }); - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == "function" ? comparator : undefined2; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined2, comparator); - }); - var zip = baseRest(unzip); - function zipObject(props, values2) { - return baseZipObject(props || [], values2 || [], assignValue); - } - function zipObjectDeep(props, values2) { - return baseZipObject(props || [], values2 || [], baseSet); - } - var zipWith = baseRest(function(arrays) { - var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined2; - iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined2; - return unzipWith(arrays, iteratee2); - }); - function chain3(value) { - var result2 = lodash(value); - result2.__chain__ = true; - return result2; - } - function tap(value, interceptor) { - interceptor(value); - return value; - } - function thru(value, interceptor) { - return interceptor(value); - } - var wrapperAt = flatRest(function(paths) { - var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object2) { - return baseAt(object2, paths); - }; - if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - func: thru, - args: [interceptor], - thisArg: undefined2 - }); - return new LodashWrapper(value, this.__chain__).thru(function(array2) { - if (length && !array2.length) { - array2.push(undefined2); - } - return array2; - }); - }); - function wrapperChain() { - return chain3(this); - } - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - function wrapperNext() { - if (this.__values__ === undefined2) { - this.__values__ = toArray2(this.value()); - } - var done = this.__index__ >= this.__values__.length, value = done ? undefined2 : this.__values__[this.__index__++]; - return { done, value }; - } - function wrapperToIterator() { - return this; - } - function wrapperPlant(value) { - var result2, parent2 = this; - while (parent2 instanceof baseLodash) { - var clone5 = wrapperClone(parent2); - clone5.__index__ = 0; - clone5.__values__ = undefined2; - if (result2) { - previous.__wrapped__ = clone5; - } else { - result2 = clone5; - } - var previous = clone5; - parent2 = parent2.__wrapped__; - } - previous.__wrapped__ = value; - return result2; - } - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - func: thru, - args: [reverse], - thisArg: undefined2 - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - var countBy = createAggregator(function(result2, value, key) { - if (hasOwnProperty.call(result2, key)) { - ++result2[key]; - } else { - baseAssignValue(result2, key, 1); - } - }); - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined2; - } - return func(collection, getIteratee(predicate, 3)); - } - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - var find = createFind(findIndex2); - var findLast = createFind(findLastIndex); - function flatMap(collection, iteratee2) { - return baseFlatten(map(collection, iteratee2), 1); - } - function flatMapDeep(collection, iteratee2) { - return baseFlatten(map(collection, iteratee2), INFINITY); - } - function flatMapDepth(collection, iteratee2, depth) { - depth = depth === undefined2 ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee2), depth); - } - function forEach2(collection, iteratee2) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee2, 3)); - } - function forEachRight(collection, iteratee2) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee2, 3)); - } - var groupBy = createAggregator(function(result2, value, key) { - if (hasOwnProperty.call(result2, key)) { - result2[key].push(value); - } else { - baseAssignValue(result2, key, [value]); - } - }); - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0; - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1; - } - var invokeMap = baseRest(function(collection, path2, args) { - var index2 = -1, isFunc = typeof path2 == "function", result2 = isArrayLike(collection) ? Array2(collection.length) : []; - baseEach(collection, function(value) { - result2[++index2] = isFunc ? apply(path2, value, args) : baseInvoke(value, path2, args); - }); - return result2; - }); - var keyBy = createAggregator(function(result2, value, key) { - baseAssignValue(result2, key, value); - }); - function map(collection, iteratee2) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee2, 3)); - } - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined2 : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - var partition = createAggregator(function(result2, value, key) { - result2[key ? 0 : 1].push(value); - }, function() { - return [[], []]; - }); - function reduce(collection, iteratee2, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach); - } - function reduceRight(collection, iteratee2, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight); - } - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate2(getIteratee(predicate, 3))); - } - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); - } - function sampleSize(collection, n2, guard) { - if (guard ? isIterateeCall(collection, n2, guard) : n2 === undefined2) { - n2 = 1; - } else { - n2 = toInteger(n2); - } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n2); - } - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; - } - var tag2 = getTag(collection); - if (tag2 == mapTag || tag2 == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined2; - } - return func(collection, getIteratee(predicate, 3)); - } - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - var now = ctxNow || function() { - return root.Date.now(); - }; - function after(n2, func) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - n2 = toInteger(n2); - return function() { - if (--n2 < 1) { - return func.apply(this, arguments); - } - }; - } - function ary(func, n2, guard) { - n2 = guard ? undefined2 : n2; - n2 = func && n2 == null ? func.length : n2; - return createWrap(func, WRAP_ARY_FLAG, undefined2, undefined2, undefined2, undefined2, n2); - } - function before(n2, func) { - var result2; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - n2 = toInteger(n2); - return function() { - if (--n2 > 0) { - result2 = func.apply(this, arguments); - } - if (n2 <= 1) { - func = undefined2; - } - return result2; - }; - } - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - var bindKey = baseRest(function(object2, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object2, partials, holders); - }); - function curry(func, arity, guard) { - arity = guard ? undefined2 : arity; - var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined2, undefined2, undefined2, undefined2, undefined2, arity); - result2.placeholder = curry.placeholder; - return result2; - } - function curryRight(func, arity, guard) { - arity = guard ? undefined2 : arity; - var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined2, undefined2, undefined2, undefined2, undefined2, arity); - result2.placeholder = curryRight.placeholder; - return result2; - } - function debounce(func, wait, options) { - var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - wait = toNumber2(wait) || 0; - if (isObject2(options)) { - leading = !!options.leading; - maxing = "maxWait" in options; - maxWait = maxing ? nativeMax(toNumber2(options.maxWait) || 0, wait) : maxWait; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - function invokeFunc(time2) { - var args = lastArgs, thisArg = lastThis; - lastArgs = lastThis = undefined2; - lastInvokeTime = time2; - result2 = func.apply(thisArg, args); - return result2; - } - function leadingEdge(time2) { - lastInvokeTime = time2; - timerId = setTimeout2(timerExpired, wait); - return leading ? invokeFunc(time2) : result2; - } - function remainingWait(time2) { - var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; - return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; - } - function shouldInvoke(time2) { - var timeSinceLastCall = time2 - lastCallTime, timeSinceLastInvoke = time2 - lastInvokeTime; - return lastCallTime === undefined2 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; - } - function timerExpired() { - var time2 = now(); - if (shouldInvoke(time2)) { - return trailingEdge(time2); - } - timerId = setTimeout2(timerExpired, remainingWait(time2)); - } - function trailingEdge(time2) { - timerId = undefined2; - if (trailing && lastArgs) { - return invokeFunc(time2); - } - lastArgs = lastThis = undefined2; - return result2; - } - function cancel() { - if (timerId !== undefined2) { - clearTimeout2(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined2; - } - function flush() { - return timerId === undefined2 ? result2 : trailingEdge(now()); - } - function debounced() { - var time2 = now(), isInvoking = shouldInvoke(time2); - lastArgs = arguments; - lastThis = this; - lastCallTime = time2; - if (isInvoking) { - if (timerId === undefined2) { - return leadingEdge(lastCallTime); - } - if (maxing) { - clearTimeout2(timerId); - timerId = setTimeout2(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined2) { - timerId = setTimeout2(timerExpired, wait); - } - return result2; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber2(wait) || 0, args); - }); - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - function memoize(func, resolver) { - if (typeof func != "function" || resolver != null && typeof resolver != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache2 = memoized.cache; - if (cache2.has(key)) { - return cache2.get(key); - } - var result2 = func.apply(this, args); - memoized.cache = cache2.set(key, result2) || cache2; - return result2; - }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; - } - memoize.Cache = MapCache; - function negate2(predicate) { - if (typeof predicate != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: - return !predicate.call(this); - case 1: - return !predicate.call(this, args[0]); - case 2: - return !predicate.call(this, args[0], args[1]); - case 3: - return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - function once(func) { - return before(2, func); - } - var overArgs = castRest(function(func, transforms) { - transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - var funcsLength = transforms.length; - return baseRest(function(args) { - var index2 = -1, length = nativeMin(args.length, funcsLength); - while (++index2 < length) { - args[index2] = transforms[index2].call(this, args[index2]); - } - return apply(func, this, args); - }); - }); - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined2, partials, holders); - }); - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined2, partials, holders); - }); - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined2, undefined2, undefined2, indexes); - }); - function rest(func, start) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - start = start === undefined2 ? start : toInteger(start); - return baseRest(func, start); - } - function spread(func, start) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array2 = args[start], otherArgs = castSlice(args, 0, start); - if (array2) { - arrayPush(otherArgs, array2); - } - return apply(func, this, otherArgs); - }); - } - function throttle(func, wait, options) { - var leading = true, trailing = true; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - if (isObject2(options)) { - leading = "leading" in options ? !!options.leading : leading; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - leading, - maxWait: wait, - trailing - }); - } - function unary(func) { - return ary(func, 1); - } - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); - } - function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray(value) ? value : [value]; - } - function clone4(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); - } - function cloneWith(value, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - function conformsTo(object2, source) { - return source == null || baseConformsTo(object2, source, keys(source)); - } - function eq2(value, other) { - return value === other || value !== value && other !== other; - } - var gt2 = createRelationalOperation(baseGt); - var gte2 = createRelationalOperation(function(value, other) { - return value >= other; - }); - var isArguments = baseIsArguments(function() { - return arguments; - }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee"); - }; - var isArray = Array2.isArray; - var isArrayBuffer3 = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); - } - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); - } - function isBoolean(value) { - return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag; - } - var isBuffer = nativeIsBuffer || stubFalse; - var isDate2 = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); - } - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag2 = getTag(value); - if (tag2 == mapTag || tag2 == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; - } - } - return true; - } - function isEqual(value, other) { - return baseIsEqual(value, other); - } - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - var result2 = customizer ? customizer(value, other) : undefined2; - return result2 === undefined2 ? baseIsEqual(value, other, undefined2, customizer) : !!result2; - } - function isError(value) { - if (!isObjectLike(value)) { - return false; - } - var tag2 = baseGetTag(value); - return tag2 == errorTag || tag2 == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value); - } - function isFinite2(value) { - return typeof value == "number" && nativeIsFinite(value); - } - function isFunction(value) { - if (!isObject2(value)) { - return false; - } - var tag2 = baseGetTag(value); - return tag2 == funcTag || tag2 == genTag || tag2 == asyncTag || tag2 == proxyTag; - } - function isInteger(value) { - return typeof value == "number" && value == toInteger(value); - } - function isLength(value) { - return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER3; - } - function isObject2(value) { - var type = typeof value; - return value != null && (type == "object" || type == "function"); - } - function isObjectLike(value) { - return value != null && typeof value == "object"; - } - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - function isMatch(object2, source) { - return object2 === source || baseIsMatch(object2, source, getMatchData(source)); - } - function isMatchWith(object2, source, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return baseIsMatch(object2, source, getMatchData(source), customizer); - } - function isNaN2(value) { - return isNumber(value) && value != +value; - } - function isNative(value) { - if (isMaskable(value)) { - throw new Error2(CORE_ERROR_TEXT); - } - return baseIsNative(value); - } - function isNull2(value) { - return value === null; - } - function isNil(value) { - return value == null; - } - function isNumber(value) { - return typeof value == "number" || isObjectLike(value) && baseGetTag(value) == numberTag; - } - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; - } - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER3 && value <= MAX_SAFE_INTEGER3; - } - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - function isString(value) { - return typeof value == "string" || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag; - } - function isSymbol(value) { - return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag; - } - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - function isUndefined(value) { - return value === undefined2; - } - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } - var lt2 = createRelationalOperation(baseLt); - var lte2 = createRelationalOperation(function(value, other) { - return value <= other; - }); - function toArray2(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag2 = getTag(value), func = tag2 == mapTag ? mapToArray : tag2 == setTag ? setToArray : values; - return func(value); - } - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber2(value); - if (value === INFINITY || value === -INFINITY) { - var sign2 = value < 0 ? -1 : 1; - return sign2 * MAX_INTEGER; - } - return value === value ? value : 0; - } - function toInteger(value) { - var result2 = toFinite(value), remainder = result2 % 1; - return result2 === result2 ? remainder ? result2 - remainder : result2 : 0; - } - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; - } - function toNumber2(value) { - if (typeof value == "number") { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject2(value)) { - var other = typeof value.valueOf == "function" ? value.valueOf() : value; - value = isObject2(other) ? other + "" : other; - } - if (typeof value != "string") { - return value === 0 ? value : +value; - } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value; - } - function toPlainObject(value) { - return copyObject(value, keysIn(value)); - } - function toSafeInteger(value) { - return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER3, MAX_SAFE_INTEGER3) : value === 0 ? value : 0; - } - function toString2(value) { - return value == null ? "" : baseToString(value); - } - var assign = createAssigner(function(object2, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object2); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object2, key, source[key]); - } - } - }); - var assignIn = createAssigner(function(object2, source) { - copyObject(source, keysIn(source), object2); - }); - var assignInWith = createAssigner(function(object2, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object2, customizer); - }); - var assignWith = createAssigner(function(object2, source, srcIndex, customizer) { - copyObject(source, keys(source), object2, customizer); - }); - var at2 = flatRest(baseAt); - function create(prototype, properties) { - var result2 = baseCreate(prototype); - return properties == null ? result2 : baseAssign(result2, properties); - } - var defaults2 = baseRest(function(object2, sources) { - object2 = Object2(object2); - var index2 = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined2; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - while (++index2 < length) { - var source = sources[index2]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object2[key]; - if (value === undefined2 || eq2(value, objectProto[key]) && !hasOwnProperty.call(object2, key)) { - object2[key] = source[key]; - } - } - } - return object2; - }); - var defaultsDeep = baseRest(function(args) { - args.push(undefined2, customDefaultsMerge); - return apply(mergeWith, undefined2, args); - }); - function findKey(object2, predicate) { - return baseFindKey(object2, getIteratee(predicate, 3), baseForOwn); - } - function findLastKey(object2, predicate) { - return baseFindKey(object2, getIteratee(predicate, 3), baseForOwnRight); - } - function forIn(object2, iteratee2) { - return object2 == null ? object2 : baseFor(object2, getIteratee(iteratee2, 3), keysIn); - } - function forInRight(object2, iteratee2) { - return object2 == null ? object2 : baseForRight(object2, getIteratee(iteratee2, 3), keysIn); - } - function forOwn(object2, iteratee2) { - return object2 && baseForOwn(object2, getIteratee(iteratee2, 3)); - } - function forOwnRight(object2, iteratee2) { - return object2 && baseForOwnRight(object2, getIteratee(iteratee2, 3)); - } - function functions(object2) { - return object2 == null ? [] : baseFunctions(object2, keys(object2)); - } - function functionsIn(object2) { - return object2 == null ? [] : baseFunctions(object2, keysIn(object2)); - } - function get(object2, path2, defaultValue) { - var result2 = object2 == null ? undefined2 : baseGet(object2, path2); - return result2 === undefined2 ? defaultValue : result2; - } - function has(object2, path2) { - return object2 != null && hasPath(object2, path2, baseHas); - } - function hasIn(object2, path2) { - return object2 != null && hasPath(object2, path2, baseHasIn); - } - var invert = createInverter(function(result2, value, key) { - if (value != null && typeof value.toString != "function") { - value = nativeObjectToString.call(value); - } - result2[value] = key; - }, constant(identity)); - var invertBy = createInverter(function(result2, value, key) { - if (value != null && typeof value.toString != "function") { - value = nativeObjectToString.call(value); - } - if (hasOwnProperty.call(result2, value)) { - result2[value].push(key); - } else { - result2[value] = [key]; - } - }, getIteratee); - var invoke = baseRest(baseInvoke); - function keys(object2) { - return isArrayLike(object2) ? arrayLikeKeys(object2) : baseKeys(object2); - } - function keysIn(object2) { - return isArrayLike(object2) ? arrayLikeKeys(object2, true) : baseKeysIn(object2); - } - function mapKeys(object2, iteratee2) { - var result2 = {}; - iteratee2 = getIteratee(iteratee2, 3); - baseForOwn(object2, function(value, key, object3) { - baseAssignValue(result2, iteratee2(value, key, object3), value); - }); - return result2; - } - function mapValues(object2, iteratee2) { - var result2 = {}; - iteratee2 = getIteratee(iteratee2, 3); - baseForOwn(object2, function(value, key, object3) { - baseAssignValue(result2, key, iteratee2(value, key, object3)); - }); - return result2; - } - var merge = createAssigner(function(object2, source, srcIndex) { - baseMerge(object2, source, srcIndex); - }); - var mergeWith = createAssigner(function(object2, source, srcIndex, customizer) { - baseMerge(object2, source, srcIndex, customizer); - }); - var omit = flatRest(function(object2, paths) { - var result2 = {}; - if (object2 == null) { - return result2; - } - var isDeep = false; - paths = arrayMap(paths, function(path2) { - path2 = castPath(path2, object2); - isDeep || (isDeep = path2.length > 1); - return path2; - }); - copyObject(object2, getAllKeysIn(object2), result2); - if (isDeep) { - result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result2, paths[length]); - } - return result2; - }); - function omitBy(object2, predicate) { - return pickBy(object2, negate2(getIteratee(predicate))); - } - var pick = flatRest(function(object2, paths) { - return object2 == null ? {} : basePick(object2, paths); - }); - function pickBy(object2, predicate) { - if (object2 == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object2), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object2, props, function(value, path2) { - return predicate(value, path2[0]); - }); - } - function result(object2, path2, defaultValue) { - path2 = castPath(path2, object2); - var index2 = -1, length = path2.length; - if (!length) { - length = 1; - object2 = undefined2; - } - while (++index2 < length) { - var value = object2 == null ? undefined2 : object2[toKey(path2[index2])]; - if (value === undefined2) { - index2 = length; - value = defaultValue; - } - object2 = isFunction(value) ? value.call(object2) : value; - } - return object2; - } - function set(object2, path2, value) { - return object2 == null ? object2 : baseSet(object2, path2, value); - } - function setWith(object2, path2, value, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return object2 == null ? object2 : baseSet(object2, path2, value, customizer); - } - var toPairs = createToPairs(keys); - var toPairsIn = createToPairs(keysIn); - function transform(object2, iteratee2, accumulator) { - var isArr = isArray(object2), isArrLike = isArr || isBuffer(object2) || isTypedArray(object2); - iteratee2 = getIteratee(iteratee2, 4); - if (accumulator == null) { - var Ctor = object2 && object2.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } else if (isObject2(object2)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object2)) : {}; - } else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object2, function(value, index2, object3) { - return iteratee2(accumulator, value, index2, object3); - }); - return accumulator; - } - function unset(object2, path2) { - return object2 == null ? true : baseUnset(object2, path2); - } - function update(object2, path2, updater) { - return object2 == null ? object2 : baseUpdate(object2, path2, castFunction(updater)); - } - function updateWith(object2, path2, updater, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined2; - return object2 == null ? object2 : baseUpdate(object2, path2, castFunction(updater), customizer); - } - function values(object2) { - return object2 == null ? [] : baseValues(object2, keys(object2)); - } - function valuesIn(object2) { - return object2 == null ? [] : baseValues(object2, keysIn(object2)); - } - function clamp(number2, lower, upper) { - if (upper === undefined2) { - upper = lower; - lower = undefined2; - } - if (upper !== undefined2) { - upper = toNumber2(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined2) { - lower = toNumber2(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber2(number2), lower, upper); - } - function inRange(number2, start, end) { - start = toFinite(start); - if (end === undefined2) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number2 = toNumber2(number2); - return baseInRange(number2, start, end); - } - function random3(lower, upper, floating) { - if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined2; - } - if (floating === undefined2) { - if (typeof upper == "boolean") { - floating = upper; - upper = undefined2; - } else if (typeof lower == "boolean") { - floating = lower; - lower = undefined2; - } - } - if (lower === undefined2 && upper === undefined2) { - lower = 0; - upper = 1; - } else { - lower = toFinite(lower); - if (upper === undefined2) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper); - } - return baseRandom(lower, upper); - } - var camelCase2 = createCompounder(function(result2, word, index2) { - word = word.toLowerCase(); - return result2 + (index2 ? capitalize(word) : word); - }); - function capitalize(string2) { - return upperFirst(toString2(string2).toLowerCase()); - } - function deburr(string2) { - string2 = toString2(string2); - return string2 && string2.replace(reLatin, deburrLetter).replace(reComboMark, ""); - } - function endsWith(string2, target, position) { - string2 = toString2(string2); - target = baseToString(target); - var length = string2.length; - position = position === undefined2 ? length : baseClamp(toInteger(position), 0, length); - var end = position; - position -= target.length; - return position >= 0 && string2.slice(position, end) == target; - } - function escape2(string2) { - string2 = toString2(string2); - return string2 && reHasUnescapedHtml.test(string2) ? string2.replace(reUnescapedHtml, escapeHtmlChar) : string2; - } - function escapeRegExp(string2) { - string2 = toString2(string2); - return string2 && reHasRegExpChar.test(string2) ? string2.replace(reRegExpChar, "\\$&") : string2; - } - var kebabCase = createCompounder(function(result2, word, index2) { - return result2 + (index2 ? "-" : "") + word.toLowerCase(); - }); - var lowerCase = createCompounder(function(result2, word, index2) { - return result2 + (index2 ? " " : "") + word.toLowerCase(); - }); - var lowerFirst = createCaseFirst("toLowerCase"); - function pad(string2, length, chars) { - string2 = toString2(string2); - length = toInteger(length); - var strLength = length ? stringSize(string2) : 0; - if (!length || strLength >= length) { - return string2; - } - var mid = (length - strLength) / 2; - return createPadding(nativeFloor(mid), chars) + string2 + createPadding(nativeCeil(mid), chars); - } - function padEnd(string2, length, chars) { - string2 = toString2(string2); - length = toInteger(length); - var strLength = length ? stringSize(string2) : 0; - return length && strLength < length ? string2 + createPadding(length - strLength, chars) : string2; - } - function padStart(string2, length, chars) { - string2 = toString2(string2); - length = toInteger(length); - var strLength = length ? stringSize(string2) : 0; - return length && strLength < length ? createPadding(length - strLength, chars) + string2 : string2; - } - function parseInt2(string2, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString2(string2).replace(reTrimStart, ""), radix || 0); - } - function repeat(string2, n2, guard) { - if (guard ? isIterateeCall(string2, n2, guard) : n2 === undefined2) { - n2 = 1; - } else { - n2 = toInteger(n2); - } - return baseRepeat(toString2(string2), n2); - } - function replace() { - var args = arguments, string2 = toString2(args[0]); - return args.length < 3 ? string2 : string2.replace(args[1], args[2]); - } - var snakeCase2 = createCompounder(function(result2, word, index2) { - return result2 + (index2 ? "_" : "") + word.toLowerCase(); - }); - function split4(string2, separator, limit) { - if (limit && typeof limit != "number" && isIterateeCall(string2, separator, limit)) { - separator = limit = undefined2; - } - limit = limit === undefined2 ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string2 = toString2(string2); - if (string2 && (typeof separator == "string" || separator != null && !isRegExp(separator))) { - separator = baseToString(separator); - if (!separator && hasUnicode(string2)) { - return castSlice(stringToArray(string2), 0, limit); - } - } - return string2.split(separator, limit); - } - var startCase = createCompounder(function(result2, word, index2) { - return result2 + (index2 ? " " : "") + upperFirst(word); - }); - function startsWith(string2, target, position) { - string2 = toString2(string2); - position = position == null ? 0 : baseClamp(toInteger(position), 0, string2.length); - target = baseToString(target); - return string2.slice(position, position + target.length) == target; - } - function template(string2, options, guard) { - var settings = lodash.templateSettings; - if (guard && isIterateeCall(string2, options, guard)) { - options = undefined2; - } - string2 = toString2(string2); - options = assignWith({}, options, settings, customDefaultsAssignIn); - var imports = assignWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); - arrayEach(importsKeys, function(key) { - if (reForbiddenIdentifierChars.test(key)) { - throw new Error2(INVALID_TEMPL_IMPORTS_ERROR_TEXT); - } - }); - var isEscaping, isEvaluating, index2 = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; - var reDelimiters = RegExp2((options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", "g"); - var sourceURL = "//# sourceURL=" + (hasOwnProperty.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + ` -`; - string2.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { - interpolateValue || (interpolateValue = esTemplateValue); - source += string2.slice(index2, offset).replace(reUnescapedString, escapeStringChar); - if (escapeValue) { - isEscaping = true; - source += `' + -__e(` + escapeValue + `) + -'`; - } - if (evaluateValue) { - isEvaluating = true; - source += `'; -` + evaluateValue + `; -__p += '`; - } - if (interpolateValue) { - source += `' + -((__t = (` + interpolateValue + `)) == null ? '' : __t) + -'`; - } - index2 = offset + match.length; - return match; - }); - source += `'; -`; - var variable = hasOwnProperty.call(options, "variable") && options.variable; - if (!variable) { - source = `with (obj) { -` + source + ` -} -`; - } else if (reForbiddenIdentifierChars.test(variable)) { - throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT); - } - source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); - source = "function(" + (variable || "obj") + `) { -` + (variable ? "" : `obj || (obj = {}); -`) + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? `, __j = Array.prototype.join; -` + `function print() { __p += __j.call(arguments, '') } -` : `; -`) + source + `return __p -}`; - var result2 = attempt(function() { - return Function2(importsKeys, sourceURL + "return " + source).apply(undefined2, importsValues); - }); - result2.source = source; - if (isError(result2)) { - throw result2; - } - return result2; - } - function toLower(value) { - return toString2(value).toLowerCase(); - } - function toUpper(value) { - return toString2(value).toUpperCase(); - } - function trim(string2, chars, guard) { - string2 = toString2(string2); - if (string2 && (guard || chars === undefined2)) { - return baseTrim(string2); - } - if (!string2 || !(chars = baseToString(chars))) { - return string2; - } - var strSymbols = stringToArray(string2), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; - return castSlice(strSymbols, start, end).join(""); - } - function trimEnd(string2, chars, guard) { - string2 = toString2(string2); - if (string2 && (guard || chars === undefined2)) { - return string2.slice(0, trimmedEndIndex(string2) + 1); - } - if (!string2 || !(chars = baseToString(chars))) { - return string2; - } - var strSymbols = stringToArray(string2), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; - return castSlice(strSymbols, 0, end).join(""); - } - function trimStart(string2, chars, guard) { - string2 = toString2(string2); - if (string2 && (guard || chars === undefined2)) { - return string2.replace(reTrimStart, ""); - } - if (!string2 || !(chars = baseToString(chars))) { - return string2; - } - var strSymbols = stringToArray(string2), start = charsStartIndex(strSymbols, stringToArray(chars)); - return castSlice(strSymbols, start).join(""); - } - function truncate(string2, options) { - var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; - if (isObject2(options)) { - var separator = "separator" in options ? options.separator : separator; - length = "length" in options ? toInteger(options.length) : length; - omission = "omission" in options ? baseToString(options.omission) : omission; - } - string2 = toString2(string2); - var strLength = string2.length; - if (hasUnicode(string2)) { - var strSymbols = stringToArray(string2); - strLength = strSymbols.length; - } - if (length >= strLength) { - return string2; - } - var end = length - stringSize(omission); - if (end < 1) { - return omission; - } - var result2 = strSymbols ? castSlice(strSymbols, 0, end).join("") : string2.slice(0, end); - if (separator === undefined2) { - return result2 + omission; - } - if (strSymbols) { - end += result2.length - end; - } - if (isRegExp(separator)) { - if (string2.slice(end).search(separator)) { - var match, substring = result2; - if (!separator.global) { - separator = RegExp2(separator.source, toString2(reFlags.exec(separator)) + "g"); - } - separator.lastIndex = 0; - while (match = separator.exec(substring)) { - var newEnd = match.index; - } - result2 = result2.slice(0, newEnd === undefined2 ? end : newEnd); - } - } else if (string2.indexOf(baseToString(separator), end) != end) { - var index2 = result2.lastIndexOf(separator); - if (index2 > -1) { - result2 = result2.slice(0, index2); - } - } - return result2 + omission; - } - function unescape2(string2) { - string2 = toString2(string2); - return string2 && reHasEscapedHtml.test(string2) ? string2.replace(reEscapedHtml, unescapeHtmlChar) : string2; - } - var upperCase = createCompounder(function(result2, word, index2) { - return result2 + (index2 ? " " : "") + word.toUpperCase(); - }); - var upperFirst = createCaseFirst("toUpperCase"); - function words(string2, pattern, guard) { - string2 = toString2(string2); - pattern = guard ? undefined2 : pattern; - if (pattern === undefined2) { - return hasUnicodeWord(string2) ? unicodeWords(string2) : asciiWords(string2); - } - return string2.match(pattern) || []; - } - var attempt = baseRest(function(func, args) { - try { - return apply(func, undefined2, args); - } catch (e3) { - return isError(e3) ? e3 : new Error2(e3); - } - }); - var bindAll = flatRest(function(object2, methodNames) { - arrayEach(methodNames, function(key) { - key = toKey(key); - baseAssignValue(object2, key, bind(object2[key], object2)); - }); - return object2; - }); - function cond(pairs) { - var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); - pairs = !length ? [] : arrayMap(pairs, function(pair) { - if (typeof pair[1] != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return [toIteratee(pair[0]), pair[1]]; - }); - return baseRest(function(args) { - var index2 = -1; - while (++index2 < length) { - var pair = pairs[index2]; - if (apply(pair[0], this, args)) { - return apply(pair[1], this, args); - } - } - }); - } - function conforms(source) { - return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); - } - function constant(value) { - return function() { - return value; - }; - } - function defaultTo(value, defaultValue) { - return value == null || value !== value ? defaultValue : value; - } - var flow = createFlow(); - var flowRight = createFlow(true); - function identity(value) { - return value; - } - function iteratee(func) { - return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG)); - } - function matches(source) { - return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); - } - function matchesProperty(path2, srcValue) { - return baseMatchesProperty(path2, baseClone(srcValue, CLONE_DEEP_FLAG)); - } - var method = baseRest(function(path2, args) { - return function(object2) { - return baseInvoke(object2, path2, args); - }; - }); - var methodOf = baseRest(function(object2, args) { - return function(path2) { - return baseInvoke(object2, path2, args); - }; - }); - function mixin(object2, source, options) { - var props = keys(source), methodNames = baseFunctions(source, props); - if (options == null && !(isObject2(source) && (methodNames.length || !props.length))) { - options = source; - source = object2; - object2 = this; - methodNames = baseFunctions(source, keys(source)); - } - var chain4 = !(isObject2(options) && ("chain" in options)) || !!options.chain, isFunc = isFunction(object2); - arrayEach(methodNames, function(methodName) { - var func = source[methodName]; - object2[methodName] = func; - if (isFunc) { - object2.prototype[methodName] = function() { - var chainAll = this.__chain__; - if (chain4 || chainAll) { - var result2 = object2(this.__wrapped__), actions = result2.__actions__ = copyArray(this.__actions__); - actions.push({ func, args: arguments, thisArg: object2 }); - result2.__chain__ = chainAll; - return result2; - } - return func.apply(object2, arrayPush([this.value()], arguments)); - }; - } - }); - return object2; - } - function noConflict() { - if (root._ === this) { - root._ = oldDash; - } - return this; - } - function noop() {} - function nthArg(n2) { - n2 = toInteger(n2); - return baseRest(function(args) { - return baseNth(args, n2); - }); - } - var over = createOver(arrayMap); - var overEvery = createOver(arrayEvery); - var overSome = createOver(arraySome); - function property(path2) { - return isKey(path2) ? baseProperty(toKey(path2)) : basePropertyDeep(path2); - } - function propertyOf(object2) { - return function(path2) { - return object2 == null ? undefined2 : baseGet(object2, path2); - }; - } - var range = createRange(); - var rangeRight = createRange(true); - function stubArray() { - return []; - } - function stubFalse() { - return false; - } - function stubObject() { - return {}; - } - function stubString() { - return ""; - } - function stubTrue() { - return true; - } - function times(n2, iteratee2) { - n2 = toInteger(n2); - if (n2 < 1 || n2 > MAX_SAFE_INTEGER3) { - return []; - } - var index2 = MAX_ARRAY_LENGTH, length = nativeMin(n2, MAX_ARRAY_LENGTH); - iteratee2 = getIteratee(iteratee2); - n2 -= MAX_ARRAY_LENGTH; - var result2 = baseTimes(length, iteratee2); - while (++index2 < n2) { - iteratee2(index2); - } - return result2; - } - function toPath(value) { - if (isArray(value)) { - return arrayMap(value, toKey); - } - return isSymbol(value) ? [value] : copyArray(stringToPath(toString2(value))); - } - function uniqueId(prefix) { - var id = ++idCounter; - return toString2(prefix) + id; - } - var add = createMathOperation(function(augend, addend) { - return augend + addend; - }, 0); - var ceil = createRound("ceil"); - var divide = createMathOperation(function(dividend, divisor) { - return dividend / divisor; - }, 1); - var floor = createRound("floor"); - function max(array2) { - return array2 && array2.length ? baseExtremum(array2, identity, baseGt) : undefined2; - } - function maxBy(array2, iteratee2) { - return array2 && array2.length ? baseExtremum(array2, getIteratee(iteratee2, 2), baseGt) : undefined2; - } - function mean(array2) { - return baseMean(array2, identity); - } - function meanBy(array2, iteratee2) { - return baseMean(array2, getIteratee(iteratee2, 2)); - } - function min(array2) { - return array2 && array2.length ? baseExtremum(array2, identity, baseLt) : undefined2; - } - function minBy(array2, iteratee2) { - return array2 && array2.length ? baseExtremum(array2, getIteratee(iteratee2, 2), baseLt) : undefined2; - } - var multiply = createMathOperation(function(multiplier, multiplicand) { - return multiplier * multiplicand; - }, 1); - var round = createRound("round"); - var subtract = createMathOperation(function(minuend, subtrahend) { - return minuend - subtrahend; - }, 0); - function sum(array2) { - return array2 && array2.length ? baseSum(array2, identity) : 0; - } - function sumBy(array2, iteratee2) { - return array2 && array2.length ? baseSum(array2, getIteratee(iteratee2, 2)) : 0; - } - lodash.after = after; - lodash.ary = ary; - lodash.assign = assign; - lodash.assignIn = assignIn; - lodash.assignInWith = assignInWith; - lodash.assignWith = assignWith; - lodash.at = at2; - lodash.before = before; - lodash.bind = bind; - lodash.bindAll = bindAll; - lodash.bindKey = bindKey; - lodash.castArray = castArray; - lodash.chain = chain3; - lodash.chunk = chunk; - lodash.compact = compact; - lodash.concat = concat; - lodash.cond = cond; - lodash.conforms = conforms; - lodash.constant = constant; - lodash.countBy = countBy; - lodash.create = create; - lodash.curry = curry; - lodash.curryRight = curryRight; - lodash.debounce = debounce; - lodash.defaults = defaults2; - lodash.defaultsDeep = defaultsDeep; - lodash.defer = defer; - lodash.delay = delay; - lodash.difference = difference; - lodash.differenceBy = differenceBy; - lodash.differenceWith = differenceWith; - lodash.drop = drop; - lodash.dropRight = dropRight; - lodash.dropRightWhile = dropRightWhile; - lodash.dropWhile = dropWhile; - lodash.fill = fill; - lodash.filter = filter; - lodash.flatMap = flatMap; - lodash.flatMapDeep = flatMapDeep; - lodash.flatMapDepth = flatMapDepth; - lodash.flatten = flatten; - lodash.flattenDeep = flattenDeep; - lodash.flattenDepth = flattenDepth; - lodash.flip = flip; - lodash.flow = flow; - lodash.flowRight = flowRight; - lodash.fromPairs = fromPairs; - lodash.functions = functions; - lodash.functionsIn = functionsIn; - lodash.groupBy = groupBy; - lodash.initial = initial; - lodash.intersection = intersection; - lodash.intersectionBy = intersectionBy; - lodash.intersectionWith = intersectionWith; - lodash.invert = invert; - lodash.invertBy = invertBy; - lodash.invokeMap = invokeMap; - lodash.iteratee = iteratee; - lodash.keyBy = keyBy; - lodash.keys = keys; - lodash.keysIn = keysIn; - lodash.map = map; - lodash.mapKeys = mapKeys; - lodash.mapValues = mapValues; - lodash.matches = matches; - lodash.matchesProperty = matchesProperty; - lodash.memoize = memoize; - lodash.merge = merge; - lodash.mergeWith = mergeWith; - lodash.method = method; - lodash.methodOf = methodOf; - lodash.mixin = mixin; - lodash.negate = negate2; - lodash.nthArg = nthArg; - lodash.omit = omit; - lodash.omitBy = omitBy; - lodash.once = once; - lodash.orderBy = orderBy; - lodash.over = over; - lodash.overArgs = overArgs; - lodash.overEvery = overEvery; - lodash.overSome = overSome; - lodash.partial = partial; - lodash.partialRight = partialRight; - lodash.partition = partition; - lodash.pick = pick; - lodash.pickBy = pickBy; - lodash.property = property; - lodash.propertyOf = propertyOf; - lodash.pull = pull; - lodash.pullAll = pullAll; - lodash.pullAllBy = pullAllBy; - lodash.pullAllWith = pullAllWith; - lodash.pullAt = pullAt; - lodash.range = range; - lodash.rangeRight = rangeRight; - lodash.rearg = rearg; - lodash.reject = reject; - lodash.remove = remove; - lodash.rest = rest; - lodash.reverse = reverse; - lodash.sampleSize = sampleSize; - lodash.set = set; - lodash.setWith = setWith; - lodash.shuffle = shuffle; - lodash.slice = slice; - lodash.sortBy = sortBy; - lodash.sortedUniq = sortedUniq; - lodash.sortedUniqBy = sortedUniqBy; - lodash.split = split4; - lodash.spread = spread; - lodash.tail = tail; - lodash.take = take; - lodash.takeRight = takeRight; - lodash.takeRightWhile = takeRightWhile; - lodash.takeWhile = takeWhile; - lodash.tap = tap; - lodash.throttle = throttle; - lodash.thru = thru; - lodash.toArray = toArray2; - lodash.toPairs = toPairs; - lodash.toPairsIn = toPairsIn; - lodash.toPath = toPath; - lodash.toPlainObject = toPlainObject; - lodash.transform = transform; - lodash.unary = unary; - lodash.union = union2; - lodash.unionBy = unionBy; - lodash.unionWith = unionWith; - lodash.uniq = uniq; - lodash.uniqBy = uniqBy; - lodash.uniqWith = uniqWith; - lodash.unset = unset; - lodash.unzip = unzip; - lodash.unzipWith = unzipWith; - lodash.update = update; - lodash.updateWith = updateWith; - lodash.values = values; - lodash.valuesIn = valuesIn; - lodash.without = without; - lodash.words = words; - lodash.wrap = wrap; - lodash.xor = xor; - lodash.xorBy = xorBy; - lodash.xorWith = xorWith; - lodash.zip = zip; - lodash.zipObject = zipObject; - lodash.zipObjectDeep = zipObjectDeep; - lodash.zipWith = zipWith; - lodash.entries = toPairs; - lodash.entriesIn = toPairsIn; - lodash.extend = assignIn; - lodash.extendWith = assignInWith; - mixin(lodash, lodash); - lodash.add = add; - lodash.attempt = attempt; - lodash.camelCase = camelCase2; - lodash.capitalize = capitalize; - lodash.ceil = ceil; - lodash.clamp = clamp; - lodash.clone = clone4; - lodash.cloneDeep = cloneDeep; - lodash.cloneDeepWith = cloneDeepWith; - lodash.cloneWith = cloneWith; - lodash.conformsTo = conformsTo; - lodash.deburr = deburr; - lodash.defaultTo = defaultTo; - lodash.divide = divide; - lodash.endsWith = endsWith; - lodash.eq = eq2; - lodash.escape = escape2; - lodash.escapeRegExp = escapeRegExp; - lodash.every = every; - lodash.find = find; - lodash.findIndex = findIndex2; - lodash.findKey = findKey; - lodash.findLast = findLast; - lodash.findLastIndex = findLastIndex; - lodash.findLastKey = findLastKey; - lodash.floor = floor; - lodash.forEach = forEach2; - lodash.forEachRight = forEachRight; - lodash.forIn = forIn; - lodash.forInRight = forInRight; - lodash.forOwn = forOwn; - lodash.forOwnRight = forOwnRight; - lodash.get = get; - lodash.gt = gt2; - lodash.gte = gte2; - lodash.has = has; - lodash.hasIn = hasIn; - lodash.head = head; - lodash.identity = identity; - lodash.includes = includes; - lodash.indexOf = indexOf; - lodash.inRange = inRange; - lodash.invoke = invoke; - lodash.isArguments = isArguments; - lodash.isArray = isArray; - lodash.isArrayBuffer = isArrayBuffer3; - lodash.isArrayLike = isArrayLike; - lodash.isArrayLikeObject = isArrayLikeObject; - lodash.isBoolean = isBoolean; - lodash.isBuffer = isBuffer; - lodash.isDate = isDate2; - lodash.isElement = isElement; - lodash.isEmpty = isEmpty; - lodash.isEqual = isEqual; - lodash.isEqualWith = isEqualWith; - lodash.isError = isError; - lodash.isFinite = isFinite2; - lodash.isFunction = isFunction; - lodash.isInteger = isInteger; - lodash.isLength = isLength; - lodash.isMap = isMap; - lodash.isMatch = isMatch; - lodash.isMatchWith = isMatchWith; - lodash.isNaN = isNaN2; - lodash.isNative = isNative; - lodash.isNil = isNil; - lodash.isNull = isNull2; - lodash.isNumber = isNumber; - lodash.isObject = isObject2; - lodash.isObjectLike = isObjectLike; - lodash.isPlainObject = isPlainObject; - lodash.isRegExp = isRegExp; - lodash.isSafeInteger = isSafeInteger; - lodash.isSet = isSet; - lodash.isString = isString; - lodash.isSymbol = isSymbol; - lodash.isTypedArray = isTypedArray; - lodash.isUndefined = isUndefined; - lodash.isWeakMap = isWeakMap; - lodash.isWeakSet = isWeakSet; - lodash.join = join3; - lodash.kebabCase = kebabCase; - lodash.last = last; - lodash.lastIndexOf = lastIndexOf; - lodash.lowerCase = lowerCase; - lodash.lowerFirst = lowerFirst; - lodash.lt = lt2; - lodash.lte = lte2; - lodash.max = max; - lodash.maxBy = maxBy; - lodash.mean = mean; - lodash.meanBy = meanBy; - lodash.min = min; - lodash.minBy = minBy; - lodash.stubArray = stubArray; - lodash.stubFalse = stubFalse; - lodash.stubObject = stubObject; - lodash.stubString = stubString; - lodash.stubTrue = stubTrue; - lodash.multiply = multiply; - lodash.nth = nth; - lodash.noConflict = noConflict; - lodash.noop = noop; - lodash.now = now; - lodash.pad = pad; - lodash.padEnd = padEnd; - lodash.padStart = padStart; - lodash.parseInt = parseInt2; - lodash.random = random3; - lodash.reduce = reduce; - lodash.reduceRight = reduceRight; - lodash.repeat = repeat; - lodash.replace = replace; - lodash.result = result; - lodash.round = round; - lodash.runInContext = runInContext2; - lodash.sample = sample; - lodash.size = size; - lodash.snakeCase = snakeCase2; - lodash.some = some; - lodash.sortedIndex = sortedIndex; - lodash.sortedIndexBy = sortedIndexBy; - lodash.sortedIndexOf = sortedIndexOf; - lodash.sortedLastIndex = sortedLastIndex; - lodash.sortedLastIndexBy = sortedLastIndexBy; - lodash.sortedLastIndexOf = sortedLastIndexOf; - lodash.startCase = startCase; - lodash.startsWith = startsWith; - lodash.subtract = subtract; - lodash.sum = sum; - lodash.sumBy = sumBy; - lodash.template = template; - lodash.times = times; - lodash.toFinite = toFinite; - lodash.toInteger = toInteger; - lodash.toLength = toLength; - lodash.toLower = toLower; - lodash.toNumber = toNumber2; - lodash.toSafeInteger = toSafeInteger; - lodash.toString = toString2; - lodash.toUpper = toUpper; - lodash.trim = trim; - lodash.trimEnd = trimEnd; - lodash.trimStart = trimStart; - lodash.truncate = truncate; - lodash.unescape = unescape2; - lodash.uniqueId = uniqueId; - lodash.upperCase = upperCase; - lodash.upperFirst = upperFirst; - lodash.each = forEach2; - lodash.eachRight = forEachRight; - lodash.first = head; - mixin(lodash, function() { - var source = {}; - baseForOwn(lodash, function(func, methodName) { - if (!hasOwnProperty.call(lodash.prototype, methodName)) { - source[methodName] = func; - } - }); - return source; - }(), { chain: false }); - lodash.VERSION = VERSION; - arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) { - lodash[methodName].placeholder = lodash; - }); - arrayEach(["drop", "take"], function(methodName, index2) { - LazyWrapper.prototype[methodName] = function(n2) { - n2 = n2 === undefined2 ? 1 : nativeMax(toInteger(n2), 0); - var result2 = this.__filtered__ && !index2 ? new LazyWrapper(this) : this.clone(); - if (result2.__filtered__) { - result2.__takeCount__ = nativeMin(n2, result2.__takeCount__); - } else { - result2.__views__.push({ - size: nativeMin(n2, MAX_ARRAY_LENGTH), - type: methodName + (result2.__dir__ < 0 ? "Right" : "") - }); - } - return result2; - }; - LazyWrapper.prototype[methodName + "Right"] = function(n2) { - return this.reverse()[methodName](n2).reverse(); - }; - }); - arrayEach(["filter", "map", "takeWhile"], function(methodName, index2) { - var type = index2 + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; - LazyWrapper.prototype[methodName] = function(iteratee2) { - var result2 = this.clone(); - result2.__iteratees__.push({ - iteratee: getIteratee(iteratee2, 3), - type - }); - result2.__filtered__ = result2.__filtered__ || isFilter; - return result2; - }; - }); - arrayEach(["head", "last"], function(methodName, index2) { - var takeName = "take" + (index2 ? "Right" : ""); - LazyWrapper.prototype[methodName] = function() { - return this[takeName](1).value()[0]; - }; - }); - arrayEach(["initial", "tail"], function(methodName, index2) { - var dropName = "drop" + (index2 ? "" : "Right"); - LazyWrapper.prototype[methodName] = function() { - return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); - }; - }); - LazyWrapper.prototype.compact = function() { - return this.filter(identity); - }; - LazyWrapper.prototype.find = function(predicate) { - return this.filter(predicate).head(); - }; - LazyWrapper.prototype.findLast = function(predicate) { - return this.reverse().find(predicate); - }; - LazyWrapper.prototype.invokeMap = baseRest(function(path2, args) { - if (typeof path2 == "function") { - return new LazyWrapper(this); - } - return this.map(function(value) { - return baseInvoke(value, path2, args); - }); - }); - LazyWrapper.prototype.reject = function(predicate) { - return this.filter(negate2(getIteratee(predicate))); - }; - LazyWrapper.prototype.slice = function(start, end) { - start = toInteger(start); - var result2 = this; - if (result2.__filtered__ && (start > 0 || end < 0)) { - return new LazyWrapper(result2); - } - if (start < 0) { - result2 = result2.takeRight(-start); - } else if (start) { - result2 = result2.drop(start); - } - if (end !== undefined2) { - end = toInteger(end); - result2 = end < 0 ? result2.dropRight(-end) : result2.take(end - start); - } - return result2; - }; - LazyWrapper.prototype.takeRightWhile = function(predicate) { - return this.reverse().takeWhile(predicate).reverse(); - }; - LazyWrapper.prototype.toArray = function() { - return this.take(MAX_ARRAY_LENGTH); - }; - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); - if (!lodashFunc) { - return; - } - lodash.prototype[methodName] = function() { - var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray(value); - var interceptor = function(value2) { - var result3 = lodashFunc.apply(lodash, arrayPush([value2], args)); - return isTaker && chainAll ? result3[0] : result3; - }; - if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) { - isLazy = useLazy = false; - } - var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; - if (!retUnwrapped && useLazy) { - value = onlyLazy ? value : new LazyWrapper(this); - var result2 = func.apply(value, args); - result2.__actions__.push({ func: thru, args: [interceptor], thisArg: undefined2 }); - return new LodashWrapper(result2, chainAll); - } - if (isUnwrapped && onlyLazy) { - return func.apply(this, args); - } - result2 = this.thru(interceptor); - return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2; - }; - }); - arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) { - var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); - lodash.prototype[methodName] = function() { - var args = arguments; - if (retUnwrapped && !this.__chain__) { - var value = this.value(); - return func.apply(isArray(value) ? value : [], args); - } - return this[chainName](function(value2) { - return func.apply(isArray(value2) ? value2 : [], args); - }); - }; - }); - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var lodashFunc = lodash[methodName]; - if (lodashFunc) { - var key = lodashFunc.name + ""; - if (!hasOwnProperty.call(realNames, key)) { - realNames[key] = []; - } - realNames[key].push({ name: methodName, func: lodashFunc }); - } - }); - realNames[createHybrid(undefined2, WRAP_BIND_KEY_FLAG).name] = [{ - name: "wrapper", - func: undefined2 - }]; - LazyWrapper.prototype.clone = lazyClone; - LazyWrapper.prototype.reverse = lazyReverse; - LazyWrapper.prototype.value = lazyValue; - lodash.prototype.at = wrapperAt; - lodash.prototype.chain = wrapperChain; - lodash.prototype.commit = wrapperCommit; - lodash.prototype.next = wrapperNext; - lodash.prototype.plant = wrapperPlant; - lodash.prototype.reverse = wrapperReverse; - lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; - lodash.prototype.first = lodash.prototype.head; - if (symIterator) { - lodash.prototype[symIterator] = wrapperToIterator; - } - return lodash; - }; - var _ = runInContext(); - if (typeof define == "function" && typeof define.amd == "object" && define.amd) { - root._ = _; - define(function() { - return _; - }); - } else if (freeModule) { - (freeModule.exports = _)._ = _; - freeExports._ = _; + return parseInt(value, 10); } else { - root._ = _; - } - }).call(exports); -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/utils.js -var require_utils12 = __commonJS((exports, module) => { - var errorObject = { value: null }; - function tryCatch(fn, ctx, args) { - try { - return fn.apply(ctx, args); - } catch (e3) { - errorObject.value = e3; - return errorObject; + return value; } } - function isRedisReady(client) { - return new Promise((resolve, reject) => { - if (client.status === "ready") { - resolve(); - } else { - let handleReady = function() { - client.removeListener("end", handleEnd); - client.removeListener("error", handleError); - resolve(); - }, handleError = function(err) { - lastError = err; - }, handleEnd = function() { - client.removeListener("ready", handleReady); - client.removeListener("error", handleError); - reject(lastError); - }; - let lastError; - client.once("ready", handleReady); - client.on("error", handleError); - client.once("end", handleEnd); - } - }); + var digitRegexCache = new Map; + function resetDigitRegexCache() { + digitRegexCache.clear(); } - exports.errorObject = errorObject; - exports.tryCatch = tryCatch; - exports.isRedisReady = isRedisReady; - exports.emitSafe = function(emitter, event, ...args) { - try { - return emitter.emit(event, ...args); - } catch (err) { - try { - return emitter.emit("error", err); - } catch (err2) { - console.error(err2); - } + function digitRegex({ + numberingSystem + }, append = "") { + const ns = numberingSystem || "latn"; + let appendCache = digitRegexCache.get(ns); + if (appendCache === undefined) { + appendCache = new Map; + digitRegexCache.set(ns, appendCache); } - }; - exports.MetricsTime = { - ONE_MINUTE: 1, - FIVE_MINUTES: 5, - FIFTEEN_MINUTES: 15, - THIRTY_MINUTES: 30, - ONE_HOUR: 60, - ONE_WEEK: 60 * 24 * 7, - TWO_WEEKS: 60 * 24 * 7 * 2, - ONE_MONTH: 60 * 24 * 7 * 2 * 4 - }; -}); - -// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/process.js -var require_process = __commonJS((exports, module) => { - var isLinux = () => process.platform === "linux"; - var report = null; - var getReport = () => { - if (!report) { - if (isLinux() && process.report) { - const orig = process.report.excludeNetwork; - process.report.excludeNetwork = true; - report = process.report.getReport(); - process.report.excludeNetwork = orig; - } else { - report = {}; - } + let regex = appendCache.get(append); + if (regex === undefined) { + regex = new RegExp(`${numberingSystems[ns]}${append}`); + appendCache.set(append, regex); } - return report; - }; - module.exports = { isLinux, getReport }; -}); - -// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/filesystem.js -var require_filesystem = __commonJS((exports, module) => { - var fs3 = __require("fs"); - var LDD_PATH = "/usr/bin/ldd"; - var SELF_PATH = "/proc/self/exe"; - var MAX_LENGTH = 2048; - var readFileSync2 = (path2) => { - const fd = fs3.openSync(path2, "r"); - const buffer = Buffer.alloc(MAX_LENGTH); - const bytesRead = fs3.readSync(fd, buffer, 0, MAX_LENGTH, 0); - fs3.close(fd, () => {}); - return buffer.subarray(0, bytesRead); - }; - var readFile2 = (path2) => new Promise((resolve, reject) => { - fs3.open(path2, "r", (err, fd) => { - if (err) { - reject(err); - } else { - const buffer = Buffer.alloc(MAX_LENGTH); - fs3.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => { - resolve(buffer.subarray(0, bytesRead)); - fs3.close(fd, () => {}); - }); - } - }); - }); - module.exports = { - LDD_PATH, - SELF_PATH, - readFileSync: readFileSync2, - readFile: readFile2 - }; -}); + return regex; + } + var now = () => Date.now(); + var defaultZone = "system"; + var defaultLocale = null; + var defaultNumberingSystem = null; + var defaultOutputCalendar = null; + var twoDigitCutoffYear = 60; + var throwOnInvalid; + var defaultWeekSettings = null; -// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/elf.js -var require_elf = __commonJS((exports, module) => { - var interpreterPath = (elf) => { - if (elf.length < 64) { - return null; - } - if (elf.readUInt32BE(0) !== 2135247942) { - return null; + class Settings { + static get now() { + return now; } - if (elf.readUInt8(4) !== 2) { - return null; + static set now(n3) { + now = n3; } - if (elf.readUInt8(5) !== 1) { - return null; + static set defaultZone(zone) { + defaultZone = zone; } - const offset = elf.readUInt32LE(32); - const size = elf.readUInt16LE(54); - const count = elf.readUInt16LE(56); - for (let i2 = 0;i2 < count; i2++) { - const headerOffset = offset + i2 * size; - const type = elf.readUInt32LE(headerOffset); - if (type === 3) { - const fileOffset = elf.readUInt32LE(headerOffset + 8); - const fileSize = elf.readUInt32LE(headerOffset + 32); - return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\0.*$/g, ""); - } + static get defaultZone() { + return normalizeZone(defaultZone, SystemZone.instance); } - return null; - }; - module.exports = { - interpreterPath - }; -}); - -// node_modules/.pnpm/detect-libc@2.1.2/node_modules/detect-libc/lib/detect-libc.js -var require_detect_libc = __commonJS((exports, module) => { - var childProcess = __require("child_process"); - var { isLinux, getReport } = require_process(); - var { LDD_PATH, SELF_PATH, readFile: readFile2, readFileSync: readFileSync2 } = require_filesystem(); - var { interpreterPath } = require_elf(); - var cachedFamilyInterpreter; - var cachedFamilyFilesystem; - var cachedVersionFilesystem; - var command = "getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true"; - var commandOut = ""; - var safeCommand = () => { - if (!commandOut) { - return new Promise((resolve) => { - childProcess.exec(command, (err, out) => { - commandOut = err ? " " : out; - resolve(commandOut); - }); - }); + static get defaultLocale() { + return defaultLocale; } - return commandOut; - }; - var safeCommandSync = () => { - if (!commandOut) { - try { - commandOut = childProcess.execSync(command, { encoding: "utf8" }); - } catch (_err) { - commandOut = " "; - } + static set defaultLocale(locale2) { + defaultLocale = locale2; } - return commandOut; - }; - var GLIBC = "glibc"; - var RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i; - var MUSL = "musl"; - var isFileMusl = (f2) => f2.includes("libc.musl-") || f2.includes("ld-musl-"); - var familyFromReport = () => { - const report = getReport(); - if (report.header && report.header.glibcVersionRuntime) { - return GLIBC; + static get defaultNumberingSystem() { + return defaultNumberingSystem; } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { - return MUSL; - } + static set defaultNumberingSystem(numberingSystem) { + defaultNumberingSystem = numberingSystem; } - return null; - }; - var familyFromCommand = (out) => { - const [getconf, ldd1] = out.split(/[\r\n]+/); - if (getconf && getconf.includes(GLIBC)) { - return GLIBC; + static get defaultOutputCalendar() { + return defaultOutputCalendar; } - if (ldd1 && ldd1.includes(MUSL)) { - return MUSL; + static set defaultOutputCalendar(outputCalendar) { + defaultOutputCalendar = outputCalendar; } - return null; - }; - var familyFromInterpreterPath = (path2) => { - if (path2) { - if (path2.includes("/ld-musl-")) { - return MUSL; - } else if (path2.includes("/ld-linux-")) { - return GLIBC; - } + static get defaultWeekSettings() { + return defaultWeekSettings; } - return null; - }; - var getFamilyFromLddContent = (content) => { - content = content.toString(); - if (content.includes("musl")) { - return MUSL; + static set defaultWeekSettings(weekSettings) { + defaultWeekSettings = validateWeekSettings(weekSettings); } - if (content.includes("GNU C Library")) { - return GLIBC; + static get twoDigitCutoffYear() { + return twoDigitCutoffYear; } - return null; - }; - var familyFromFilesystem = async () => { - if (cachedFamilyFilesystem !== undefined) { - return cachedFamilyFilesystem; + static set twoDigitCutoffYear(cutoffYear) { + twoDigitCutoffYear = cutoffYear % 100; } - cachedFamilyFilesystem = null; - try { - const lddContent = await readFile2(LDD_PATH); - cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); - } catch (e3) {} - return cachedFamilyFilesystem; - }; - var familyFromFilesystemSync = () => { - if (cachedFamilyFilesystem !== undefined) { - return cachedFamilyFilesystem; + static get throwOnInvalid() { + return throwOnInvalid; } - cachedFamilyFilesystem = null; - try { - const lddContent = readFileSync2(LDD_PATH); - cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); - } catch (e3) {} - return cachedFamilyFilesystem; - }; - var familyFromInterpreter = async () => { - if (cachedFamilyInterpreter !== undefined) { - return cachedFamilyInterpreter; + static set throwOnInvalid(t9) { + throwOnInvalid = t9; } - cachedFamilyInterpreter = null; - try { - const selfContent = await readFile2(SELF_PATH); - const path2 = interpreterPath(selfContent); - cachedFamilyInterpreter = familyFromInterpreterPath(path2); - } catch (e3) {} - return cachedFamilyInterpreter; - }; - var familyFromInterpreterSync = () => { - if (cachedFamilyInterpreter !== undefined) { - return cachedFamilyInterpreter; + static resetCaches() { + Locale.resetCache(); + IANAZone.resetCache(); + DateTime.resetCache(); + resetDigitRegexCache(); } - cachedFamilyInterpreter = null; - try { - const selfContent = readFileSync2(SELF_PATH); - const path2 = interpreterPath(selfContent); - cachedFamilyInterpreter = familyFromInterpreterPath(path2); - } catch (e3) {} - return cachedFamilyInterpreter; - }; - var family = async () => { - let family2 = null; - if (isLinux()) { - family2 = await familyFromInterpreter(); - if (!family2) { - family2 = await familyFromFilesystem(); - if (!family2) { - family2 = familyFromReport(); - } - if (!family2) { - const out = await safeCommand(); - family2 = familyFromCommand(out); - } - } + } + + class Invalid { + constructor(reason, explanation) { + this.reason = reason; + this.explanation = explanation; } - return family2; - }; - var familySync = () => { - let family2 = null; - if (isLinux()) { - family2 = familyFromInterpreterSync(); - if (!family2) { - family2 = familyFromFilesystemSync(); - if (!family2) { - family2 = familyFromReport(); - } - if (!family2) { - const out = safeCommandSync(); - family2 = familyFromCommand(out); - } + toMessage() { + if (this.explanation) { + return `${this.reason}: ${this.explanation}`; + } else { + return this.reason; } } - return family2; - }; - var isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; - var isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; - var versionFromFilesystem = async () => { - if (cachedVersionFilesystem !== undefined) { - return cachedVersionFilesystem; + } + var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; + function unitOutOfRange(unit, value) { + return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`); + } + function dayOfWeek(year, month, day) { + const d2 = new Date(Date.UTC(year, month - 1, day)); + if (year < 100 && year >= 0) { + d2.setUTCFullYear(d2.getUTCFullYear() - 1900); } - cachedVersionFilesystem = null; - try { - const lddContent = await readFile2(LDD_PATH); - const versionMatch = lddContent.match(RE_GLIBC_VERSION); - if (versionMatch) { - cachedVersionFilesystem = versionMatch[1]; - } - } catch (e3) {} - return cachedVersionFilesystem; - }; - var versionFromFilesystemSync = () => { - if (cachedVersionFilesystem !== undefined) { - return cachedVersionFilesystem; - } - cachedVersionFilesystem = null; - try { - const lddContent = readFileSync2(LDD_PATH); - const versionMatch = lddContent.match(RE_GLIBC_VERSION); - if (versionMatch) { - cachedVersionFilesystem = versionMatch[1]; - } - } catch (e3) {} - return cachedVersionFilesystem; - }; - var versionFromReport = () => { - const report = getReport(); - if (report.header && report.header.glibcVersionRuntime) { - return report.header.glibcVersionRuntime; - } - return null; - }; - var versionSuffix = (s2) => s2.trim().split(/\s+/)[1]; - var versionFromCommand = (out) => { - const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); - if (getconf && getconf.includes(GLIBC)) { - return versionSuffix(getconf); - } - if (ldd1 && ldd2 && ldd1.includes(MUSL)) { - return versionSuffix(ldd2); - } - return null; - }; - var version2 = async () => { - let version3 = null; - if (isLinux()) { - version3 = await versionFromFilesystem(); - if (!version3) { - version3 = versionFromReport(); - } - if (!version3) { - const out = await safeCommand(); - version3 = versionFromCommand(out); - } - } - return version3; - }; - var versionSync = () => { - let version3 = null; - if (isLinux()) { - version3 = versionFromFilesystemSync(); - if (!version3) { - version3 = versionFromReport(); - } - if (!version3) { - const out = safeCommandSync(); - version3 = versionFromCommand(out); - } - } - return version3; - }; - module.exports = { - GLIBC, - MUSL, - family, - familySync, - isNonGlibcLinux, - isNonGlibcLinuxSync, - version: version2, - versionSync - }; -}); - -// node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/node-gyp-build.js -var require_node_gyp_build = __commonJS((exports, module) => { - var fs3 = __require("fs"); - var path2 = __require("path"); - var url = __require("url"); - var os = __require("os"); - var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; - var vars = process.config && process.config.variables || {}; - var prebuildsOnly = !!process.env.PREBUILDS_ONLY; - var versions = process.versions; - var abi = versions.modules; - if (versions.deno || process.isBun) { - abi = "unsupported"; + const js = d2.getUTCDay(); + return js === 0 ? 7 : js; } - var runtime = isElectron() ? "electron" : isNwjs() ? "node-webkit" : "node"; - var arch = process.env.npm_config_arch || os.arch(); - var platform = process.env.npm_config_platform || os.platform(); - var libc = process.env.LIBC || (isMusl(platform) ? "musl" : "glibc"); - var armv = process.env.ARM_VERSION || (arch === "arm64" ? "8" : vars.arm_version) || ""; - var uv = (versions.uv || "").split(".")[0]; - module.exports = load; - function load(dir) { - return runtimeRequire(load.resolve(dir)); + function computeOrdinal(year, month, day) { + return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; } - load.resolve = load.path = function(dir) { - dir = path2.resolve(dir || "."); - var packageName = ""; - var packageNameError; - try { - packageName = runtimeRequire(path2.join(dir, "package.json")).name; - var varName = packageName.toUpperCase().replace(/-/g, "_"); - if (process.env[varName + "_PREBUILD"]) - dir = process.env[varName + "_PREBUILD"]; - } catch (err) { - packageNameError = err; - } - if (!prebuildsOnly) { - var release = getFirst(path2.join(dir, "build/Release"), matchBuild); - if (release) - return release; - var debug = getFirst(path2.join(dir, "build/Debug"), matchBuild); - if (debug) - return debug; - } - var prebuild = resolve(dir); - if (prebuild) - return prebuild; - var nearby = resolve(path2.dirname(process.execPath)); - if (nearby) - return nearby; - var platformPackage = (packageName[0] == "@" ? "" : "@" + packageName + "/") + packageName + "-" + platform + "-" + arch; - var packageResolutionError; - try { - var prebuildPackage = path2.dirname(__require("module").createRequire(url.pathToFileURL(path2.join(dir, "package.json"))).resolve(platformPackage)); - return resolveFile(prebuildPackage); - } catch (error) { - packageResolutionError = error; - } - var target = [ - "platform=" + platform, - "arch=" + arch, - "runtime=" + runtime, - "abi=" + abi, - "uv=" + uv, - armv ? "armv=" + armv : "", - "libc=" + libc, - "node=" + process.versions.node, - process.versions.electron ? "electron=" + process.versions.electron : "", - typeof __webpack_require__ === "function" ? "webpack=true" : "" - ].filter(Boolean).join(" "); - let errMessage = "No native build was found for " + target + ` - attempted loading from: ` + dir + " and package:" + " " + platformPackage + ` -`; - if (packageNameError) { - errMessage += "Error finding package.json: " + packageNameError.message + ` -`; - } - if (packageResolutionError) { - errMessage += "Error resolving package: " + packageResolutionError.message + ` -`; - } - throw new Error(errMessage); - function resolve(dir2) { - var tuples = readdirSync(path2.join(dir2, "prebuilds")).map(parseTuple); - var tuple2 = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]; - if (!tuple2) - return; - return resolveFile(path2.join(dir2, "prebuilds", tuple2.name)); - } - function resolveFile(prebuilds) { - var parsed = readdirSync(prebuilds).map(parseTags); - var candidates = parsed.filter(matchTags(runtime, abi)); - var winner = candidates.sort(compareTags(runtime))[0]; - if (winner) - return path2.join(prebuilds, winner.file); - } - }; - function readdirSync(dir) { - try { - return fs3.readdirSync(dir); - } catch (err) { - return []; - } + function uncomputeOrdinal(year, ordinal) { + const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i2) => i2 < ordinal), day = ordinal - table[month0]; + return { + month: month0 + 1, + day + }; } - function getFirst(dir, filter) { - var files = readdirSync(dir).filter(filter); - return files[0] && path2.join(dir, files[0]); + function isoWeekdayToLocal(isoWeekday, startOfWeek) { + return (isoWeekday - startOfWeek + 7) % 7 + 1; } - function matchBuild(name) { - return /\.node$/.test(name); + function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) { + const { + year, + month, + day + } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); + let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear; + if (weekNumber < 1) { + weekYear = year - 1; + weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); + } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) { + weekYear = year + 1; + weekNumber = 1; + } else { + weekYear = year; + } + return { + weekYear, + weekNumber, + weekday, + ...timeObject(gregObj) + }; } - function parseTuple(name) { - var arr = name.split("-"); - if (arr.length !== 2) - return; - var platform2 = arr[0]; - var architectures = arr[1].split("+"); - if (!platform2) - return; - if (!architectures.length) - return; - if (!architectures.every(Boolean)) - return; - return { name, platform: platform2, architectures }; + function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) { + const { + weekYear, + weekNumber, + weekday + } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear); + let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year; + if (ordinal < 1) { + year = weekYear - 1; + ordinal += daysInYear(year); + } else if (ordinal > yearInDays) { + year = weekYear + 1; + ordinal -= daysInYear(weekYear); + } else { + year = weekYear; + } + const { + month, + day + } = uncomputeOrdinal(year, ordinal); + return { + year, + month, + day, + ...timeObject(weekData) + }; } - function matchTuple(platform2, arch2) { - return function(tuple2) { - if (tuple2 == null) - return false; - if (tuple2.platform !== platform2) - return false; - return tuple2.architectures.includes(arch2); + function gregorianToOrdinal(gregData) { + const { + year, + month, + day + } = gregData; + const ordinal = computeOrdinal(year, month, day); + return { + year, + ordinal, + ...timeObject(gregData) }; } - function compareTuples(a2, b2) { - return a2.architectures.length - b2.architectures.length; + function ordinalToGregorian(ordinalData) { + const { + year, + ordinal + } = ordinalData; + const { + month, + day + } = uncomputeOrdinal(year, ordinal); + return { + year, + month, + day, + ...timeObject(ordinalData) + }; } - function parseTags(file) { - var arr = file.split("."); - var extension = arr.pop(); - var tags = { file, specificity: 0 }; - if (extension !== "node") - return; - for (var i2 = 0;i2 < arr.length; i2++) { - var tag2 = arr[i2]; - if (tag2 === "node" || tag2 === "electron" || tag2 === "node-webkit") { - tags.runtime = tag2; - } else if (tag2 === "napi") { - tags.napi = true; - } else if (tag2.slice(0, 3) === "abi") { - tags.abi = tag2.slice(3); - } else if (tag2.slice(0, 2) === "uv") { - tags.uv = tag2.slice(2); - } else if (tag2.slice(0, 4) === "armv") { - tags.armv = tag2.slice(4); - } else if (tag2 === "glibc" || tag2 === "musl") { - tags.libc = tag2; - } else { - continue; + function usesLocalWeekValues(obj, loc) { + const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); + if (hasLocaleWeekData) { + const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); + if (hasIsoWeekData) { + throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields"); } - tags.specificity++; + if (!isUndefined(obj.localWeekday)) + obj.weekday = obj.localWeekday; + if (!isUndefined(obj.localWeekNumber)) + obj.weekNumber = obj.localWeekNumber; + if (!isUndefined(obj.localWeekYear)) + obj.weekYear = obj.localWeekYear; + delete obj.localWeekday; + delete obj.localWeekNumber; + delete obj.localWeekYear; + return { + minDaysInFirstWeek: loc.getMinDaysInFirstWeek(), + startOfWeek: loc.getStartOfWeek() + }; + } else { + return { + minDaysInFirstWeek: 4, + startOfWeek: 1 + }; } - return tags; } - function matchTags(runtime2, abi2) { - return function(tags) { - if (tags == null) - return false; - if (tags.runtime !== runtime2 && !runtimeAgnostic(tags)) - return false; - if (tags.abi !== abi2 && !tags.napi) - return false; - if (tags.uv && tags.uv !== uv) - return false; - if (tags.armv && tags.armv !== armv) - return false; - if (tags.libc && tags.libc !== libc) - return false; - return true; - }; + function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) { + const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)), validWeekday = integerBetween(obj.weekday, 1, 7); + if (!validYear) { + return unitOutOfRange("weekYear", obj.weekYear); + } else if (!validWeek) { + return unitOutOfRange("week", obj.weekNumber); + } else if (!validWeekday) { + return unitOutOfRange("weekday", obj.weekday); + } else + return false; } - function runtimeAgnostic(tags) { - return tags.runtime === "node" && tags.napi; + function hasInvalidOrdinalData(obj) { + const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); + if (!validYear) { + return unitOutOfRange("year", obj.year); + } else if (!validOrdinal) { + return unitOutOfRange("ordinal", obj.ordinal); + } else + return false; } - function compareTags(runtime2) { - return function(a2, b2) { - if (a2.runtime !== b2.runtime) { - return a2.runtime === runtime2 ? -1 : 1; - } else if (a2.abi !== b2.abi) { - return a2.abi ? -1 : 1; - } else if (a2.specificity !== b2.specificity) { - return a2.specificity > b2.specificity ? -1 : 1; - } else { - return 0; - } - }; + function hasInvalidGregorianData(obj) { + const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); + if (!validYear) { + return unitOutOfRange("year", obj.year); + } else if (!validMonth) { + return unitOutOfRange("month", obj.month); + } else if (!validDay) { + return unitOutOfRange("day", obj.day); + } else + return false; } - function isNwjs() { - return !!(process.versions && process.versions.nw); + function hasInvalidTimeData(obj) { + const { + hour, + minute, + second, + millisecond + } = obj; + const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); + if (!validHour) { + return unitOutOfRange("hour", hour); + } else if (!validMinute) { + return unitOutOfRange("minute", minute); + } else if (!validSecond) { + return unitOutOfRange("second", second); + } else if (!validMillisecond) { + return unitOutOfRange("millisecond", millisecond); + } else + return false; } - function isElectron() { - if (process.versions && process.versions.electron) - return true; - if (process.env.ELECTRON_RUN_AS_NODE) - return true; - return typeof window !== "undefined" && window.process && window.process.type === "renderer"; + function isUndefined(o2) { + return typeof o2 === "undefined"; } - function isMusl(platform2) { - if (platform2 !== "linux") + function isNumber(o2) { + return typeof o2 === "number"; + } + function isInteger(o2) { + return typeof o2 === "number" && o2 % 1 === 0; + } + function isString(o2) { + return typeof o2 === "string"; + } + function isDate2(o2) { + return Object.prototype.toString.call(o2) === "[object Date]"; + } + function hasRelative() { + try { + return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; + } catch (e3) { return false; - const { familySync, MUSL } = require_detect_libc(); - return familySync() === MUSL; + } } - load.parseTags = parseTags; - load.matchTags = matchTags; - load.compareTags = compareTags; - load.parseTuple = parseTuple; - load.matchTuple = matchTuple; - load.compareTuples = compareTuples; -}); - -// node_modules/.pnpm/node-gyp-build-optional-packages@5.2.2/node_modules/node-gyp-build-optional-packages/index.js -var require_node_gyp_build_optional_packages = __commonJS((exports, module) => { - var runtimeRequire = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require; - if (typeof runtimeRequire.addon === "function") { - module.exports = runtimeRequire.addon.bind(runtimeRequire); - } else { - module.exports = require_node_gyp_build(); + function hasLocaleWeekInfo() { + try { + return typeof Intl !== "undefined" && !!Intl.Locale && (("weekInfo" in Intl.Locale.prototype) || ("getWeekInfo" in Intl.Locale.prototype)); + } catch (e3) { + return false; + } } -}); - -// node_modules/.pnpm/msgpackr-extract@3.0.3/node_modules/msgpackr-extract/index.js -var require_msgpackr_extract = __commonJS((exports, module) => { - var __dirname = "/Users/shivamverma/Desktop/CodeSM/backend/node_modules/.pnpm/msgpackr-extract@3.0.3/node_modules/msgpackr-extract"; - module.exports = require_node_gyp_build_optional_packages()(__dirname); -}); - -// node_modules/.pnpm/msgpackr@1.11.10/node_modules/msgpackr/dist/node.cjs -var require_node4 = __commonJS((exports) => { - var stream = __require("stream"); - var module$1 = __require("module"); - var decoder; - try { - decoder = new TextDecoder; - } catch (error) {} - var src; - var srcEnd; - var position$1 = 0; - var EMPTY_ARRAY = []; - var strings = EMPTY_ARRAY; - var stringPosition = 0; - var currentUnpackr = {}; - var currentStructures; - var srcString; - var srcStringStart = 0; - var srcStringEnd = 0; - var bundledStrings$1; - var referenceMap; - var currentExtensions = []; - var dataView; - var defaultOptions = { - useRecords: false, - mapsAsObjects: true - }; - - class C1Type { - } - var C1 = new C1Type; - C1.name = "MessagePack 0xC1"; - var sequentialMode = false; - var inlineObjectReadThreshold = 2; - var readStruct$1; - var onLoadedStructures$1; - var onSaveState; - - class Unpackr { - constructor(options) { - if (options) { - if (options.useRecords === false && options.mapsAsObjects === undefined) - options.mapsAsObjects = true; - if (options.sequential && options.trusted !== false) { - options.trusted = true; - if (!options.structures && options.useRecords != false) { - options.structures = []; - if (!options.maxSharedStructures) - options.maxSharedStructures = 0; - } - } - if (options.structures) - options.structures.sharedLength = options.structures.length; - else if (options.getStructures) { - (options.structures = []).uninitialized = true; - options.structures.sharedLength = 0; - } - if (options.int64AsNumber) { - options.int64AsType = "number"; - } - } - Object.assign(this, options); + function maybeArray(thing) { + return Array.isArray(thing) ? thing : [thing]; + } + function bestBy(arr, by2, compare4) { + if (arr.length === 0) { + return; } - unpack(source, options) { - if (src) { - return saveState$1(() => { - clearSource(); - return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options); - }); - } - if (!source.buffer && source.constructor === ArrayBuffer) - source = typeof Buffer !== "undefined" ? Buffer.from(source) : new Uint8Array(source); - if (typeof options === "object") { - srcEnd = options.end || source.length; - position$1 = options.start || 0; + return arr.reduce((best, next) => { + const pair = [by2(next), next]; + if (!best) { + return pair; + } else if (compare4(best[0], pair[0]) === best[0]) { + return best; } else { - position$1 = 0; - srcEnd = options > -1 ? options : source.length; - } - stringPosition = 0; - srcStringEnd = 0; - srcString = null; - strings = EMPTY_ARRAY; - bundledStrings$1 = null; - src = source; - try { - dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength)); - } catch (error) { - src = null; - if (source instanceof Uint8Array) - throw error; - throw new Error("Source must be a Uint8Array or Buffer but was a " + (source && typeof source == "object" ? source.constructor.name : typeof source)); + return pair; } - if (this instanceof Unpackr) { - currentUnpackr = this; - if (this.structures) { - currentStructures = this.structures; - return checkedRead(options); - } else if (!currentStructures || currentStructures.length > 0) { - currentStructures = []; - } - } else { - currentUnpackr = defaultOptions; - if (!currentStructures || currentStructures.length > 0) - currentStructures = []; + }, null)[1]; + } + function pick(obj, keys) { + return keys.reduce((a2, k2) => { + a2[k2] = obj[k2]; + return a2; + }, {}); + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + function validateWeekSettings(settings) { + if (settings == null) { + return null; + } else if (typeof settings !== "object") { + throw new InvalidArgumentError("Week settings must be an object"); + } else { + if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v2) => !integerBetween(v2, 1, 7))) { + throw new InvalidArgumentError("Invalid week settings"); } - return checkedRead(options); + return { + firstDay: settings.firstDay, + minimalDays: settings.minimalDays, + weekend: Array.from(settings.weekend) + }; } - unpackMultiple(source, forEach2) { - let values, lastPosition = 0; - try { - sequentialMode = true; - let size = source.length; - let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size); - if (forEach2) { - if (forEach2(value, lastPosition, position$1) === false) - return; - while (position$1 < size) { - lastPosition = position$1; - if (forEach2(checkedRead(), lastPosition, position$1) === false) { - return; - } - } - } else { - values = [value]; - while (position$1 < size) { - lastPosition = position$1; - values.push(checkedRead()); - } - return values; - } - } catch (error) { - error.lastPosition = lastPosition; - error.values = values; - throw error; - } finally { - sequentialMode = false; - clearSource(); - } + } + function integerBetween(thing, bottom, top) { + return isInteger(thing) && thing >= bottom && thing <= top; + } + function floorMod(x2, n3) { + return x2 - n3 * Math.floor(x2 / n3); + } + function padStart(input, n3 = 2) { + const isNeg = input < 0; + let padded; + if (isNeg) { + padded = "-" + ("" + -input).padStart(n3, "0"); + } else { + padded = ("" + input).padStart(n3, "0"); } - _mergeStructures(loadedStructures, existingStructures) { - if (onLoadedStructures$1) - loadedStructures = onLoadedStructures$1.call(this, loadedStructures); - loadedStructures = loadedStructures || []; - if (Object.isFrozen(loadedStructures)) - loadedStructures = loadedStructures.map((structure) => structure.slice(0)); - for (let i2 = 0, l2 = loadedStructures.length;i2 < l2; i2++) { - let structure = loadedStructures[i2]; - if (structure) { - structure.isShared = true; - if (i2 >= 32) - structure.highByte = i2 - 32 >> 5; - } - } - loadedStructures.sharedLength = loadedStructures.length; - for (let id in existingStructures || []) { - if (id >= 0) { - let structure = loadedStructures[id]; - let existing = existingStructures[id]; - if (existing) { - if (structure) - (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure; - loadedStructures[id] = existing; - } - } - } - return this.structures = loadedStructures; + return padded; + } + function parseInteger(string2) { + if (isUndefined(string2) || string2 === null || string2 === "") { + return; + } else { + return parseInt(string2, 10); } - decode(source, options) { - return this.unpack(source, options); + } + function parseFloating(string2) { + if (isUndefined(string2) || string2 === null || string2 === "") { + return; + } else { + return parseFloat(string2); } } - function checkedRead(options) { - try { - if (!currentUnpackr.trusted && !sequentialMode) { - let sharedLength = currentStructures.sharedLength || 0; - if (sharedLength < currentStructures.length) - currentStructures.length = sharedLength; - } - let result; - if (currentUnpackr.randomAccessStructure && src[position$1] < 64 && src[position$1] >= 32 && readStruct$1) { - result = readStruct$1(src, position$1, srcEnd, currentUnpackr); - src = null; - if (!(options && options.lazy) && result) - result = result.toJSON(); - position$1 = srcEnd; - } else - result = read(); - if (bundledStrings$1) { - position$1 = bundledStrings$1.postBundlePosition; - bundledStrings$1 = null; - } - if (sequentialMode) - currentStructures.restoreStructures = null; - if (position$1 == srcEnd) { - if (currentStructures && currentStructures.restoreStructures) - restoreStructures(); - currentStructures = null; - src = null; - if (referenceMap) - referenceMap = null; - } else if (position$1 > srcEnd) { - throw new Error("Unexpected end of MessagePack data"); - } else if (!sequentialMode) { - let jsonView; - try { - jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100); - } catch (error) { - jsonView = "(JSON view not available " + error + ")"; - } - throw new Error("Data read, but end of buffer not reached " + jsonView); - } - return result; - } catch (error) { - if (currentStructures && currentStructures.restoreStructures) - restoreStructures(); - clearSource(); - if (error instanceof RangeError || error.message.startsWith("Unexpected end of buffer") || position$1 > srcEnd) { - error.incomplete = true; - } - throw error; + function parseMillis(fraction) { + if (isUndefined(fraction) || fraction === null || fraction === "") { + return; + } else { + const f2 = parseFloat("0." + fraction) * 1000; + return Math.floor(f2); } } - function restoreStructures() { - for (let id in currentStructures.restoreStructures) { - currentStructures[id] = currentStructures.restoreStructures[id]; + function roundTo(number2, digits, rounding = "round") { + const factor = 10 ** digits; + switch (rounding) { + case "expand": + return number2 > 0 ? Math.ceil(number2 * factor) / factor : Math.floor(number2 * factor) / factor; + case "trunc": + return Math.trunc(number2 * factor) / factor; + case "round": + return Math.round(number2 * factor) / factor; + case "floor": + return Math.floor(number2 * factor) / factor; + case "ceil": + return Math.ceil(number2 * factor) / factor; + default: + throw new RangeError(`Value rounding ${rounding} is out of range`); } - currentStructures.restoreStructures = null; } - function read() { - let token = src[position$1++]; - if (token < 160) { - if (token < 128) { - if (token < 64) - return token; - else { - let structure = currentStructures[token & 63] || currentUnpackr.getStructures && loadStructures()[token & 63]; - if (structure) { - if (!structure.read) { - structure.read = createStructureReader(structure, token & 63); - } - return structure.read(); - } else - return token; - } - } else if (token < 144) { - token -= 128; - if (currentUnpackr.mapsAsObjects) { - let object2 = {}; - for (let i2 = 0;i2 < token; i2++) { - let key = readKey(); - if (key === "__proto__") - key = "__proto_"; - object2[key] = read(); - } - return object2; - } else { - let map = new Map; - for (let i2 = 0;i2 < token; i2++) { - map.set(read(), read()); - } - return map; - } - } else { - token -= 144; - let array2 = new Array(token); - for (let i2 = 0;i2 < token; i2++) { - array2[i2] = read(); - } - if (currentUnpackr.freezeData) - return Object.freeze(array2); - return array2; - } - } else if (token < 192) { - let length = token - 160; - if (srcStringEnd >= position$1) { - return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart); - } - if (srcStringEnd == 0 && srcEnd < 140) { - let string2 = length < 16 ? shortStringInJS(length) : longStringInJS(length); - if (string2 != null) - return string2; - } - return readFixedString(length); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + function daysInYear(year) { + return isLeapYear(year) ? 366 : 365; + } + function daysInMonth(year, month) { + const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; + if (modMonth === 2) { + return isLeapYear(modYear) ? 29 : 28; } else { - let value; - switch (token) { - case 192: - return null; - case 193: - if (bundledStrings$1) { - value = read(); - if (value > 0) - return bundledStrings$1[1].slice(bundledStrings$1.position1, bundledStrings$1.position1 += value); - else - return bundledStrings$1[0].slice(bundledStrings$1.position0, bundledStrings$1.position0 -= value); - } - return C1; - case 194: - return false; - case 195: - return true; - case 196: - value = src[position$1++]; - if (value === undefined) - throw new Error("Unexpected end of buffer"); - return readBin(value); - case 197: - value = dataView.getUint16(position$1); - position$1 += 2; - return readBin(value); - case 198: - value = dataView.getUint32(position$1); - position$1 += 4; - return readBin(value); - case 199: - return readExt(src[position$1++]); - case 200: - value = dataView.getUint16(position$1); - position$1 += 2; - return readExt(value); - case 201: - value = dataView.getUint32(position$1); - position$1 += 4; - return readExt(value); - case 202: - value = dataView.getFloat32(position$1); - if (currentUnpackr.useFloat32 > 2) { - let multiplier = mult10[(src[position$1] & 127) << 1 | src[position$1 + 1] >> 7]; - position$1 += 4; - return (multiplier * value + (value > 0 ? 0.5 : -0.5) >> 0) / multiplier; - } - position$1 += 4; - return value; - case 203: - value = dataView.getFloat64(position$1); - position$1 += 8; - return value; - case 204: - return src[position$1++]; - case 205: - value = dataView.getUint16(position$1); - position$1 += 2; - return value; - case 206: - value = dataView.getUint32(position$1); - position$1 += 4; - return value; - case 207: - if (currentUnpackr.int64AsType === "number") { - value = dataView.getUint32(position$1) * 4294967296; - value += dataView.getUint32(position$1 + 4); - } else if (currentUnpackr.int64AsType === "string") { - value = dataView.getBigUint64(position$1).toString(); - } else if (currentUnpackr.int64AsType === "auto") { - value = dataView.getBigUint64(position$1); - if (value <= BigInt(2) << BigInt(52)) - value = Number(value); - } else - value = dataView.getBigUint64(position$1); - position$1 += 8; - return value; - case 208: - return dataView.getInt8(position$1++); - case 209: - value = dataView.getInt16(position$1); - position$1 += 2; - return value; - case 210: - value = dataView.getInt32(position$1); - position$1 += 4; - return value; - case 211: - if (currentUnpackr.int64AsType === "number") { - value = dataView.getInt32(position$1) * 4294967296; - value += dataView.getUint32(position$1 + 4); - } else if (currentUnpackr.int64AsType === "string") { - value = dataView.getBigInt64(position$1).toString(); - } else if (currentUnpackr.int64AsType === "auto") { - value = dataView.getBigInt64(position$1); - if (value >= BigInt(-2) << BigInt(52) && value <= BigInt(2) << BigInt(52)) - value = Number(value); - } else - value = dataView.getBigInt64(position$1); - position$1 += 8; - return value; - case 212: - value = src[position$1++]; - if (value == 114) { - return recordDefinition(src[position$1++] & 63); - } else { - let extension = currentExtensions[value]; - if (extension) { - if (extension.read) { - position$1++; - return extension.read(read()); - } else if (extension.noBuffer) { - position$1++; - return extension(); - } else - return extension(src.subarray(position$1, ++position$1)); - } else - throw new Error("Unknown extension " + value); - } - case 213: - value = src[position$1]; - if (value == 114) { - position$1++; - return recordDefinition(src[position$1++] & 63, src[position$1++]); - } else - return readExt(2); - case 214: - return readExt(4); - case 215: - return readExt(8); - case 216: - return readExt(16); - case 217: - value = src[position$1++]; - if (srcStringEnd >= position$1) { - return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart); - } - return readString8(value); - case 218: - value = dataView.getUint16(position$1); - position$1 += 2; - if (srcStringEnd >= position$1) { - return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart); - } - return readString16(value); - case 219: - value = dataView.getUint32(position$1); - position$1 += 4; - if (srcStringEnd >= position$1) { - return srcString.slice(position$1 - srcStringStart, (position$1 += value) - srcStringStart); - } - return readString32(value); - case 220: - value = dataView.getUint16(position$1); - position$1 += 2; - return readArray(value); - case 221: - value = dataView.getUint32(position$1); - position$1 += 4; - return readArray(value); - case 222: - value = dataView.getUint16(position$1); - position$1 += 2; - return readMap(value); - case 223: - value = dataView.getUint32(position$1); - position$1 += 4; - return readMap(value); - default: - if (token >= 224) - return token - 256; - if (token === undefined) { - let error = new Error("Unexpected end of MessagePack data"); - error.incomplete = true; - throw error; - } - throw new Error("Unknown MessagePack token " + token); - } + return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; } } - var validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; - function createStructureReader(structure, firstId) { - function readObject() { - if (readObject.count++ > inlineObjectReadThreshold) { - let optimizedReadObject; - try { - optimizedReadObject = structure.read = new Function("r", "return function(){return " + (currentUnpackr.freezeData ? "Object.freeze" : "") + "({" + structure.map((key) => key === "__proto__" ? "__proto_:r()" : validName.test(key) ? key + ":r()" : "[" + JSON.stringify(key) + "]:r()").join(",") + "})}")(read); - } catch (error) { - inlineObjectReadThreshold = Infinity; - return readObject(); - } - if (structure.highByte === 0) - structure.read = createSecondByteReader(firstId, structure.read); - return optimizedReadObject(); - } - let object2 = {}; - for (let i2 = 0, l2 = structure.length;i2 < l2; i2++) { - let key = structure[i2]; - if (key === "__proto__") - key = "__proto_"; - object2[key] = read(); - } - if (currentUnpackr.freezeData) - return Object.freeze(object2); - return object2; - } - readObject.count = 0; - if (structure.highByte === 0) { - return createSecondByteReader(firstId, readObject); + function objToLocalTS(obj) { + let d2 = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); + if (obj.year < 100 && obj.year >= 0) { + d2 = new Date(d2); + d2.setUTCFullYear(obj.year, obj.month - 1, obj.day); } - return readObject; + return +d2; } - var createSecondByteReader = (firstId, read0) => { - return function() { - let highByte = src[position$1++]; - if (highByte === 0) - return read0(); - let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5); - let structure = currentStructures[id] || loadStructures()[id]; - if (!structure) { - throw new Error("Record id is not defined for " + id); - } - if (!structure.read) - structure.read = createStructureReader(structure, firstId); - return structure.read(); + function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) { + const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); + return -fwdlw + minDaysInFirstWeek - 1; + } + function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { + const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); + const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); + return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7; + } + function untruncateYear(year) { + if (year > 99) { + return year; + } else + return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year; + } + function parseZoneInfo(ts, offsetFormat, locale2, timeZone = null) { + const date4 = new Date(ts), intlOpts = { + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit" }; - }; - function loadStructures() { - let loadedStructures = saveState$1(() => { - src = null; - return currentUnpackr.getStructures(); - }); - return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures); - } - var readFixedString = readStringJS; - var readString8 = readStringJS; - var readString16 = readStringJS; - var readString32 = readStringJS; - exports.isNativeAccelerationEnabled = false; - function setExtractor(extractStrings) { - exports.isNativeAccelerationEnabled = true; - readFixedString = readString2(1); - readString8 = readString2(2); - readString16 = readString2(3); - readString32 = readString2(5); - function readString2(headerLength) { - return function readString3(length) { - let string2 = strings[stringPosition++]; - if (string2 == null) { - if (bundledStrings$1) - return readStringJS(length); - let byteOffset = src.byteOffset; - let extraction = extractStrings(position$1 - headerLength + byteOffset, srcEnd + byteOffset, src.buffer); - if (typeof extraction == "string") { - string2 = extraction; - strings = EMPTY_ARRAY; - } else { - strings = extraction; - stringPosition = 1; - srcStringEnd = 1; - string2 = strings[0]; - if (string2 === undefined) - throw new Error("Unexpected end of buffer"); - } - } - let srcStringLength = string2.length; - if (srcStringLength <= length) { - position$1 += length; - return string2; - } - srcString = string2; - srcStringStart = position$1; - srcStringEnd = position$1 + srcStringLength; - position$1 += length; - return string2.slice(0, length); - }; + if (timeZone) { + intlOpts.timeZone = timeZone; } + const modified = { + timeZoneName: offsetFormat, + ...intlOpts + }; + const parsed = new Intl.DateTimeFormat(locale2, modified).formatToParts(date4).find((m2) => m2.type.toLowerCase() === "timezonename"); + return parsed ? parsed.value : null; } - function readStringJS(length) { - let result; - if (length < 16) { - if (result = shortStringInJS(length)) - return result; + function signedOffset(offHourStr, offMinuteStr) { + let offHour = parseInt(offHourStr, 10); + if (Number.isNaN(offHour)) { + offHour = 0; } - if (length > 64 && decoder) - return decoder.decode(src.subarray(position$1, position$1 += length)); - const end = position$1 + length; - const units = []; - result = ""; - while (position$1 < end) { - const byte1 = src[position$1++]; - if ((byte1 & 128) === 0) { - units.push(byte1); - } else if ((byte1 & 224) === 192) { - const byte2 = src[position$1++] & 63; - const codePoint = (byte1 & 31) << 6 | byte2; - if (codePoint < 128) { - units.push(65533); - } else { - units.push(codePoint); - } - } else if ((byte1 & 240) === 224) { - const byte2 = src[position$1++] & 63; - const byte3 = src[position$1++] & 63; - const codePoint = (byte1 & 31) << 12 | byte2 << 6 | byte3; - if (codePoint < 2048 || codePoint >= 55296 && codePoint <= 57343) { - units.push(65533); - } else { - units.push(codePoint); - } - } else if ((byte1 & 248) === 240) { - const byte2 = src[position$1++] & 63; - const byte3 = src[position$1++] & 63; - const byte4 = src[position$1++] & 63; - let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4; - if (unit < 65536 || unit > 1114111) { - units.push(65533); - } else if (unit > 65535) { - unit -= 65536; - units.push(unit >>> 10 & 1023 | 55296); - unit = 56320 | unit & 1023; - units.push(unit); - } else { - units.push(unit); - } - } else { - units.push(65533); - } - if (units.length >= 4096) { - result += fromCharCode.apply(String, units); - units.length = 0; + const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; + return offHour * 60 + offMinSigned; + } + function asNumber(value) { + const numericValue = Number(value); + if (typeof value === "boolean" || value === "" || !Number.isFinite(numericValue)) + throw new InvalidArgumentError(`Invalid unit value ${value}`); + return numericValue; + } + function normalizeObject(obj, normalizer) { + const normalized = {}; + for (const u2 in obj) { + if (hasOwnProperty(obj, u2)) { + const v2 = obj[u2]; + if (v2 === undefined || v2 === null) + continue; + normalized[normalizer(u2)] = asNumber(v2); } } - if (units.length > 0) { - result += fromCharCode.apply(String, units); + return normalized; + } + function formatOffset(offset2, format) { + const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign2 = offset2 >= 0 ? "+" : "-"; + switch (format) { + case "short": + return `${sign2}${padStart(hours, 2)}:${padStart(minutes, 2)}`; + case "narrow": + return `${sign2}${hours}${minutes > 0 ? `:${minutes}` : ""}`; + case "techie": + return `${sign2}${padStart(hours, 2)}${padStart(minutes, 2)}`; + default: + throw new RangeError(`Value format ${format} is out of range for property format`); } - return result; } - function readString(source, start, length) { - let existingSrc = src; - src = source; - position$1 = start; - try { - return readStringJS(length); - } finally { - src = existingSrc; + function timeObject(obj) { + return pick(obj, ["hour", "minute", "second", "millisecond"]); + } + var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; + var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; + function months(length) { + switch (length) { + case "narrow": + return [...monthsNarrow]; + case "short": + return [...monthsShort]; + case "long": + return [...monthsLong]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; + case "2-digit": + return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; + default: + return null; } } - function readArray(length) { - let array2 = new Array(length); - for (let i2 = 0;i2 < length; i2++) { - array2[i2] = read(); + var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; + var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; + var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; + function weekdays(length) { + switch (length) { + case "narrow": + return [...weekdaysNarrow]; + case "short": + return [...weekdaysShort]; + case "long": + return [...weekdaysLong]; + case "numeric": + return ["1", "2", "3", "4", "5", "6", "7"]; + default: + return null; } - if (currentUnpackr.freezeData) - return Object.freeze(array2); - return array2; } - function readMap(length) { - if (currentUnpackr.mapsAsObjects) { - let object2 = {}; - for (let i2 = 0;i2 < length; i2++) { - let key = readKey(); - if (key === "__proto__") - key = "__proto_"; - object2[key] = read(); - } - return object2; - } else { - let map = new Map; - for (let i2 = 0;i2 < length; i2++) { - map.set(read(), read()); - } - return map; + var meridiems = ["AM", "PM"]; + var erasLong = ["Before Christ", "Anno Domini"]; + var erasShort = ["BC", "AD"]; + var erasNarrow = ["B", "A"]; + function eras(length) { + switch (length) { + case "narrow": + return [...erasNarrow]; + case "short": + return [...erasShort]; + case "long": + return [...erasLong]; + default: + return null; } } - var fromCharCode = String.fromCharCode; - function longStringInJS(length) { - let start = position$1; - let bytes = new Array(length); - for (let i2 = 0;i2 < length; i2++) { - const byte = src[position$1++]; - if ((byte & 128) > 0) { - position$1 = start; - return; + function meridiemForDateTime(dt) { + return meridiems[dt.hour < 12 ? 0 : 1]; + } + function weekdayForDateTime(dt, length) { + return weekdays(length)[dt.weekday - 1]; + } + function monthForDateTime(dt, length) { + return months(length)[dt.month - 1]; + } + function eraForDateTime(dt, length) { + return eras(length)[dt.year < 0 ? 0 : 1]; + } + function formatRelativeTime(unit, count2, numeric3 = "always", narrow = false) { + const units = { + years: ["year", "yr."], + quarters: ["quarter", "qtr."], + months: ["month", "mo."], + weeks: ["week", "wk."], + days: ["day", "day", "days"], + hours: ["hour", "hr."], + minutes: ["minute", "min."], + seconds: ["second", "sec."] + }; + const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; + if (numeric3 === "auto" && lastable) { + const isDay = unit === "days"; + switch (count2) { + case 1: + return isDay ? "tomorrow" : `next ${units[unit][0]}`; + case -1: + return isDay ? "yesterday" : `last ${units[unit][0]}`; + case 0: + return isDay ? "today" : `this ${units[unit][0]}`; } - bytes[i2] = byte; } - return fromCharCode.apply(String, bytes); + const isInPast = Object.is(count2, -0) || count2 < 0, fmtValue = Math.abs(count2), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; + return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; } - function shortStringInJS(length) { - if (length < 4) { - if (length < 2) { - if (length === 0) - return ""; - else { - let a2 = src[position$1++]; - if ((a2 & 128) > 1) { - position$1 -= 1; - return; - } - return fromCharCode(a2); - } + function stringifyTokens(splits, tokenToString) { + let s3 = ""; + for (const token of splits) { + if (token.literal) { + s3 += token.val; } else { - let a2 = src[position$1++]; - let b2 = src[position$1++]; - if ((a2 & 128) > 0 || (b2 & 128) > 0) { - position$1 -= 2; - return; - } - if (length < 3) - return fromCharCode(a2, b2); - let c2 = src[position$1++]; - if ((c2 & 128) > 0) { - position$1 -= 3; - return; - } - return fromCharCode(a2, b2, c2); - } - } else { - let a2 = src[position$1++]; - let b2 = src[position$1++]; - let c2 = src[position$1++]; - let d2 = src[position$1++]; - if ((a2 & 128) > 0 || (b2 & 128) > 0 || (c2 & 128) > 0 || (d2 & 128) > 0) { - position$1 -= 4; - return; + s3 += tokenToString(token.val); } - if (length < 6) { - if (length === 4) - return fromCharCode(a2, b2, c2, d2); - else { - let e3 = src[position$1++]; - if ((e3 & 128) > 0) { - position$1 -= 5; - return; - } - return fromCharCode(a2, b2, c2, d2, e3); - } - } else if (length < 8) { - let e3 = src[position$1++]; - let f2 = src[position$1++]; - if ((e3 & 128) > 0 || (f2 & 128) > 0) { - position$1 -= 6; - return; - } - if (length < 7) - return fromCharCode(a2, b2, c2, d2, e3, f2); - let g2 = src[position$1++]; - if ((g2 & 128) > 0) { - position$1 -= 7; - return; - } - return fromCharCode(a2, b2, c2, d2, e3, f2, g2); - } else { - let e3 = src[position$1++]; - let f2 = src[position$1++]; - let g2 = src[position$1++]; - let h2 = src[position$1++]; - if ((e3 & 128) > 0 || (f2 & 128) > 0 || (g2 & 128) > 0 || (h2 & 128) > 0) { - position$1 -= 8; - return; - } - if (length < 10) { - if (length === 8) - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2); - else { - let i2 = src[position$1++]; - if ((i2 & 128) > 0) { - position$1 -= 9; - return; - } - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2); - } - } else if (length < 12) { - let i2 = src[position$1++]; - let j2 = src[position$1++]; - if ((i2 & 128) > 0 || (j2 & 128) > 0) { - position$1 -= 10; - return; - } - if (length < 11) - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2); - let k2 = src[position$1++]; - if ((k2 & 128) > 0) { - position$1 -= 11; - return; + } + return s3; + } + var macroTokenToFormatOpts = { + D: DATE_SHORT, + DD: DATE_MED, + DDD: DATE_FULL, + DDDD: DATE_HUGE, + t: TIME_SIMPLE, + tt: TIME_WITH_SECONDS, + ttt: TIME_WITH_SHORT_OFFSET, + tttt: TIME_WITH_LONG_OFFSET, + T: TIME_24_SIMPLE, + TT: TIME_24_WITH_SECONDS, + TTT: TIME_24_WITH_SHORT_OFFSET, + TTTT: TIME_24_WITH_LONG_OFFSET, + f: DATETIME_SHORT, + ff: DATETIME_MED, + fff: DATETIME_FULL, + ffff: DATETIME_HUGE, + F: DATETIME_SHORT_WITH_SECONDS, + FF: DATETIME_MED_WITH_SECONDS, + FFF: DATETIME_FULL_WITH_SECONDS, + FFFF: DATETIME_HUGE_WITH_SECONDS + }; + + class Formatter { + static create(locale2, opts = {}) { + return new Formatter(locale2, opts); + } + static parseFormat(fmt) { + let current = null, currentFull = "", bracketed = false; + const splits = []; + for (let i2 = 0;i2 < fmt.length; i2++) { + const c2 = fmt.charAt(i2); + if (c2 === "'") { + if (currentFull.length > 0 || bracketed) { + splits.push({ + literal: bracketed || /^\s+$/.test(currentFull), + val: currentFull === "" ? "'" : currentFull + }); } - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2); + current = null; + currentFull = ""; + bracketed = !bracketed; + } else if (bracketed) { + currentFull += c2; + } else if (c2 === current) { + currentFull += c2; } else { - let i2 = src[position$1++]; - let j2 = src[position$1++]; - let k2 = src[position$1++]; - let l2 = src[position$1++]; - if ((i2 & 128) > 0 || (j2 & 128) > 0 || (k2 & 128) > 0 || (l2 & 128) > 0) { - position$1 -= 12; - return; - } - if (length < 14) { - if (length === 12) - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2); - else { - let m2 = src[position$1++]; - if ((m2 & 128) > 0) { - position$1 -= 13; - return; - } - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2, m2); - } - } else { - let m2 = src[position$1++]; - let n2 = src[position$1++]; - if ((m2 & 128) > 0 || (n2 & 128) > 0) { - position$1 -= 14; - return; - } - if (length < 15) - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2, m2, n2); - let o2 = src[position$1++]; - if ((o2 & 128) > 0) { - position$1 -= 15; - return; - } - return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2); + if (currentFull.length > 0) { + splits.push({ + literal: /^\s+$/.test(currentFull), + val: currentFull + }); } + currentFull = c2; + current = c2; } } + if (currentFull.length > 0) { + splits.push({ + literal: bracketed || /^\s+$/.test(currentFull), + val: currentFull + }); + } + return splits; } - } - function readOnlyJSString() { - let token = src[position$1++]; - let length; - if (token < 192) { - length = token - 160; - } else { - switch (token) { - case 217: - length = src[position$1++]; - break; - case 218: - length = dataView.getUint16(position$1); - position$1 += 2; - break; - case 219: - length = dataView.getUint32(position$1); - position$1 += 4; - break; - default: - throw new Error("Expected string"); + static macroTokenToFormatOpts(token) { + return macroTokenToFormatOpts[token]; + } + constructor(locale2, formatOpts) { + this.opts = formatOpts; + this.loc = locale2; + this.systemLoc = null; + } + formatWithSystemDefault(dt, opts) { + if (this.systemLoc === null) { + this.systemLoc = this.loc.redefaultToSystem(); } + const df = this.systemLoc.dtFormatter(dt, { + ...this.opts, + ...opts + }); + return df.format(); } - return readStringJS(length); - } - function readBin(length) { - return currentUnpackr.copyBuffers ? Uint8Array.prototype.slice.call(src, position$1, position$1 += length) : src.subarray(position$1, position$1 += length); - } - function readExt(length) { - let type = src[position$1++]; - if (currentExtensions[type]) { - let end; - return currentExtensions[type](src.subarray(position$1, end = position$1 += length), (readPosition) => { - position$1 = readPosition; - try { - return read(); - } finally { - position$1 = end; - } + dtFormatter(dt, opts = {}) { + return this.loc.dtFormatter(dt, { + ...this.opts, + ...opts }); - } else - throw new Error("Unknown extension type " + type); - } - var keyCache = new Array(4096); - function readKey() { - let length = src[position$1++]; - if (length >= 160 && length < 192) { - length = length - 160; - if (srcStringEnd >= position$1) - return srcString.slice(position$1 - srcStringStart, (position$1 += length) - srcStringStart); - else if (!(srcStringEnd == 0 && srcEnd < 180)) - return readFixedString(length); - } else { - position$1--; - return asSafeString(read()); - } - let key = (length << 5 ^ (length > 1 ? dataView.getUint16(position$1) : length > 0 ? src[position$1] : 0)) & 4095; - let entry = keyCache[key]; - let checkPosition = position$1; - let end = position$1 + length - 3; - let chunk; - let i2 = 0; - if (entry && entry.bytes == length) { - while (checkPosition < end) { - chunk = dataView.getUint32(checkPosition); - if (chunk != entry[i2++]) { - checkPosition = 1879048192; - break; - } - checkPosition += 4; + } + formatDateTime(dt, opts) { + return this.dtFormatter(dt, opts).format(); + } + formatDateTimeParts(dt, opts) { + return this.dtFormatter(dt, opts).formatToParts(); + } + formatInterval(interval3, opts) { + const df = this.dtFormatter(interval3.start, opts); + return df.dtf.formatRange(interval3.start.toJSDate(), interval3.end.toJSDate()); + } + resolvedOptions(dt, opts) { + return this.dtFormatter(dt, opts).resolvedOptions(); + } + num(n3, p2 = 0, signDisplay = undefined) { + if (this.opts.forceSimple) { + return padStart(n3, p2); } - end += 3; - while (checkPosition < end) { - chunk = src[checkPosition++]; - if (chunk != entry[i2++]) { - checkPosition = 1879048192; - break; - } + const opts = { + ...this.opts + }; + if (p2 > 0) { + opts.padTo = p2; } - if (checkPosition === end) { - position$1 = checkPosition; - return entry.string; + if (signDisplay) { + opts.signDisplay = signDisplay; } - end -= 3; - checkPosition = position$1; - } - entry = []; - keyCache[key] = entry; - entry.bytes = length; - while (checkPosition < end) { - chunk = dataView.getUint32(checkPosition); - entry.push(chunk); - checkPosition += 4; + return this.loc.numberFormatter(opts).format(n3); } - end += 3; - while (checkPosition < end) { - chunk = src[checkPosition++]; - entry.push(chunk); - } - let string2 = length < 16 ? shortStringInJS(length) : longStringInJS(length); - if (string2 != null) - return entry.string = string2; - return entry.string = readFixedString(length); - } - function asSafeString(property) { - if (typeof property === "string") - return property; - if (typeof property === "number" || typeof property === "boolean" || typeof property === "bigint") - return property.toString(); - if (property == null) - return property + ""; - if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every((item) => ["string", "number", "boolean", "bigint"].includes(typeof item))) { - return property.flat().toString(); - } - throw new Error(`Invalid property type for record: ${typeof property}`); - } - var recordDefinition = (id, highByte) => { - let structure = read().map(asSafeString); - let firstByte = id; - if (highByte !== undefined) { - id = id < 32 ? -((highByte << 5) + id) : (highByte << 5) + id; - structure.highByte = highByte; - } - let existingStructure = currentStructures[id]; - if (existingStructure && (existingStructure.isShared || sequentialMode)) { - (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure; - } - currentStructures[id] = structure; - structure.read = createStructureReader(structure, firstByte); - return structure.read(); - }; - currentExtensions[0] = () => {}; - currentExtensions[0].noBuffer = true; - currentExtensions[66] = (data) => { - let headLength = data.byteLength % 8 || 8; - let head = BigInt(data[0] & 128 ? data[0] - 256 : data[0]); - for (let i2 = 1;i2 < headLength; i2++) { - head <<= BigInt(8); - head += BigInt(data[i2]); - } - if (data.byteLength !== headLength) { - let view = new DataView(data.buffer, data.byteOffset, data.byteLength); - let decode2 = (start, end) => { - let length = end - start; - if (length <= 40) { - let out = view.getBigUint64(start); - for (let i2 = start + 8;i2 < end; i2 += 8) { - out <<= BigInt(64n); - out |= view.getBigUint64(i2); - } - return out; + formatDateTimeFromString(dt, fmt) { + const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string2 = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => { + if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { + return "Z"; } - let middle = start + (length >> 4 << 3); - let left = decode2(start, middle); - let right = decode2(middle, end); - return left << BigInt((end - middle) * 8) | right; - }; - head = head << BigInt((view.byteLength - headLength) * 8) | decode2(headLength, view.byteLength); - } - return head; - }; - var errors = { - Error, - EvalError, - RangeError, - ReferenceError, - SyntaxError, - TypeError, - URIError, - AggregateError: typeof AggregateError === "function" ? AggregateError : null - }; - currentExtensions[101] = () => { - let data = read(); - if (!errors[data[0]]) { - let error = Error(data[1], { cause: data[2] }); - error.name = data[0]; - return error; - } - return errors[data[0]](data[1], { cause: data[2] }); - }; - currentExtensions[105] = (data) => { - if (currentUnpackr.structuredClone === false) - throw new Error("Structured clone extension is disabled"); - let id = dataView.getUint32(position$1 - 4); - if (!referenceMap) - referenceMap = new Map; - let token = src[position$1]; - let target2; - if (token >= 144 && token < 160 || token == 220 || token == 221) - target2 = []; - else if (token >= 128 && token < 144 || token == 222 || token == 223) - target2 = new Map; - else if ((token >= 199 && token <= 201 || token >= 212 && token <= 216) && src[position$1 + 1] === 115) - target2 = new Set; - else - target2 = {}; - let refEntry = { target: target2 }; - referenceMap.set(id, refEntry); - let targetProperties = read(); - if (!refEntry.used) { - return refEntry.target = targetProperties; - } else { - Object.assign(target2, targetProperties); - } - if (target2 instanceof Map) - for (let [k2, v2] of targetProperties.entries()) - target2.set(k2, v2); - if (target2 instanceof Set) - for (let i2 of Array.from(targetProperties)) - target2.add(i2); - return target2; - }; - currentExtensions[112] = (data) => { - if (currentUnpackr.structuredClone === false) - throw new Error("Structured clone extension is disabled"); - let id = dataView.getUint32(position$1 - 4); - let refEntry = referenceMap.get(id); - refEntry.used = true; - return refEntry.target; - }; - currentExtensions[115] = () => new Set(read()); - var typedArrays = ["Int8", "Uint8", "Uint8Clamped", "Int16", "Uint16", "Int32", "Uint32", "Float32", "Float64", "BigInt64", "BigUint64"].map((type) => type + "Array"); - var glbl = typeof globalThis === "object" ? globalThis : window; - currentExtensions[116] = (data) => { - let typeCode = data[0]; - let buffer = Uint8Array.prototype.slice.call(data, 1).buffer; - let typedArrayName = typedArrays[typeCode]; - if (!typedArrayName) { - if (typeCode === 16) - return buffer; - if (typeCode === 17) - return new DataView(buffer); - throw new Error("Could not find typed array for code " + typeCode); - } - return new glbl[typedArrayName](buffer); - }; - currentExtensions[120] = () => { - let data = read(); - return new RegExp(data[0], data[1]); - }; - var TEMP_BUNDLE = []; - currentExtensions[98] = (data) => { - let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; - let dataPosition = position$1; - position$1 += dataSize - data.length; - bundledStrings$1 = TEMP_BUNDLE; - bundledStrings$1 = [readOnlyJSString(), readOnlyJSString()]; - bundledStrings$1.position0 = 0; - bundledStrings$1.position1 = 0; - bundledStrings$1.postBundlePosition = position$1; - position$1 = dataPosition; - return read(); - }; - currentExtensions[255] = (data) => { - if (data.length == 4) - return new Date((data[0] * 16777216 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000); - else if (data.length == 8) - return new Date(((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1e6 + ((data[3] & 3) * 4294967296 + data[4] * 16777216 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000); - else if (data.length == 12) - return new Date(((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1e6 + ((data[4] & 128 ? -281474976710656 : 0) + data[6] * 1099511627776 + data[7] * 4294967296 + data[8] * 16777216 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000); - else - return new Date("invalid"); - }; - function saveState$1(callback) { - if (onSaveState) - onSaveState(); - let savedSrcEnd = srcEnd; - let savedPosition = position$1; - let savedStringPosition = stringPosition; - let savedSrcStringStart = srcStringStart; - let savedSrcStringEnd = srcStringEnd; - let savedSrcString = srcString; - let savedStrings = strings; - let savedReferenceMap = referenceMap; - let savedBundledStrings = bundledStrings$1; - let savedSrc = new Uint8Array(src.slice(0, srcEnd)); - let savedStructures = currentStructures; - let savedStructuresContents = currentStructures.slice(0, currentStructures.length); - let savedPackr = currentUnpackr; - let savedSequentialMode = sequentialMode; - let value = callback(); - srcEnd = savedSrcEnd; - position$1 = savedPosition; - stringPosition = savedStringPosition; - srcStringStart = savedSrcStringStart; - srcStringEnd = savedSrcStringEnd; - srcString = savedSrcString; - strings = savedStrings; - referenceMap = savedReferenceMap; - bundledStrings$1 = savedBundledStrings; - src = savedSrc; - sequentialMode = savedSequentialMode; - currentStructures = savedStructures; - currentStructures.splice(0, currentStructures.length, ...savedStructuresContents); - currentUnpackr = savedPackr; - dataView = new DataView(src.buffer, src.byteOffset, src.byteLength); - return value; - } - function clearSource() { - src = null; - referenceMap = null; - currentStructures = null; - } - function addExtension$1(extension) { - if (extension.unpack) - currentExtensions[extension.type] = extension.unpack; - else - currentExtensions[extension.type] = extension; - } - var mult10 = new Array(147); - for (let i2 = 0;i2 < 256; i2++) { - mult10[i2] = +("1e" + Math.floor(45.15 - i2 * 0.30103)); - } - var Decoder = Unpackr; - var defaultUnpackr = new Unpackr({ useRecords: false }); - var unpack = defaultUnpackr.unpack; - var unpackMultiple = defaultUnpackr.unpackMultiple; - var decode = defaultUnpackr.unpack; - var FLOAT32_OPTIONS = { - NEVER: 0, - ALWAYS: 1, - DECIMAL_ROUND: 3, - DECIMAL_FIT: 4 - }; - var f32Array = new Float32Array(1); - var u8Array = new Uint8Array(f32Array.buffer, 0, 4); - function roundFloat32(float32Number) { - f32Array[0] = float32Number; - let multiplier = mult10[(u8Array[3] & 127) << 1 | u8Array[2] >> 7]; - return (multiplier * float32Number + (float32Number > 0 ? 0.5 : -0.5) >> 0) / multiplier; - } - function setReadStruct(updatedReadStruct, loadedStructs, saveState2) { - readStruct$1 = updatedReadStruct; - onLoadedStructures$1 = loadedStructs; - onSaveState = saveState2; - } - var textEncoder$1; - try { - textEncoder$1 = new TextEncoder; - } catch (error) {} - var extensions; - var extensionClasses; - var hasNodeBuffer$1 = typeof Buffer !== "undefined"; - var ByteArrayAllocate = hasNodeBuffer$1 ? function(length) { - return Buffer.allocUnsafeSlow(length); - } : Uint8Array; - var ByteArray = hasNodeBuffer$1 ? Buffer : Uint8Array; - var MAX_BUFFER_SIZE = hasNodeBuffer$1 ? 4294967296 : 2144337920; - var target; - var keysTarget; - var targetView; - var position = 0; - var safeEnd; - var bundledStrings = null; - var writeStructSlots; - var MAX_BUNDLE_SIZE = 21760; - var hasNonLatin = /[\u0080-\uFFFF]/; - var RECORD_SYMBOL = Symbol("record-id"); - - class Packr extends Unpackr { - constructor(options) { - super(options); - this.offset = 0; - let start; - let hasSharedUpdate; - let structures; - let referenceMap2; - let encodeUtf82 = ByteArray.prototype.utf8Write ? function(string2, position2) { - return target.utf8Write(string2, position2, target.byteLength - position2); - } : textEncoder$1 && textEncoder$1.encodeInto ? function(string2, position2) { - return textEncoder$1.encodeInto(string2, target.subarray(position2)).written; - } : false; - let packr = this; - if (!options) - options = {}; - let isSequential = options && options.sequential; - let hasSharedStructures = options.structures || options.saveStructures; - let maxSharedStructures = options.maxSharedStructures; - if (maxSharedStructures == null) - maxSharedStructures = hasSharedStructures ? 32 : 0; - if (maxSharedStructures > 8160) - throw new Error("Maximum maxSharedStructure is 8160"); - if (options.structuredClone && options.moreTypes == undefined) { - this.moreTypes = true; - } - let maxOwnStructures = options.maxOwnStructures; - if (maxOwnStructures == null) - maxOwnStructures = hasSharedStructures ? 32 : 64; - if (!this.structures && options.useRecords != false) - this.structures = []; - let useTwoByteRecords = maxSharedStructures > 32 || maxOwnStructures + maxSharedStructures > 64; - let sharedLimitId = maxSharedStructures + 64; - let maxStructureId = maxSharedStructures + maxOwnStructures + 64; - if (maxStructureId > 8256) { - throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192"); - } - let recordIdsToRemove = []; - let transitionsCount = 0; - let serializationsSinceTransitionRebuild = 0; - this.pack = this.encode = function(value, encodeOptions) { - if (!target) { - target = new ByteArrayAllocate(8192); - targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192)); - position = 0; - } - safeEnd = target.length - 10; - if (safeEnd - position < 2048) { - target = new ByteArrayAllocate(target.length); - targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length)); - safeEnd = target.length - 10; - position = 0; - } else - position = position + 7 & 2147483640; - start = position; - if (encodeOptions & RESERVE_START_SPACE) - position += encodeOptions & 255; - referenceMap2 = packr.structuredClone ? new Map : null; - if (packr.bundleStrings && typeof value !== "string") { - bundledStrings = []; - bundledStrings.size = Infinity; - } else - bundledStrings = null; - structures = packr.structures; - if (structures) { - if (structures.uninitialized) - structures = packr._mergeStructures(packr.getStructures()); - let sharedLength = structures.sharedLength || 0; - if (sharedLength > maxSharedStructures) { - throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to " + structures.sharedLength); - } - if (!structures.transitions) { - structures.transitions = Object.create(null); - for (let i2 = 0;i2 < sharedLength; i2++) { - let keys = structures[i2]; - if (!keys) - continue; - let nextTransition, transition = structures.transitions; - for (let j2 = 0, l2 = keys.length;j2 < l2; j2++) { - let key = keys[j2]; - nextTransition = transition[key]; - if (!nextTransition) { - nextTransition = transition[key] = Object.create(null); - } - transition = nextTransition; - } - transition[RECORD_SYMBOL] = i2 + 64; - } - this.lastNamedStructuresLength = sharedLength; - } - if (!isSequential) { - structures.nextId = sharedLength + 64; - } - } - if (hasSharedUpdate) - hasSharedUpdate = false; - let encodingError; - try { - if (packr.randomAccessStructure && value && typeof value === "object") { - if (value.constructor === Object) - writeStruct2(value); - else if (value.constructor !== Map && !Array.isArray(value) && !extensionClasses.some((extClass) => value instanceof extClass)) { - writeStruct2(value.toJSON ? value.toJSON() : value); - } else - pack2(value); - } else - pack2(value); - let lastBundle = bundledStrings; - if (bundledStrings) - writeBundles(start, pack2, 0); - if (referenceMap2 && referenceMap2.idsToInsert) { - let idsToInsert = referenceMap2.idsToInsert.sort((a2, b2) => a2.offset > b2.offset ? 1 : -1); - let i2 = idsToInsert.length; - let incrementPosition = -1; - while (lastBundle && i2 > 0) { - let insertionPoint = idsToInsert[--i2].offset + start; - if (insertionPoint < lastBundle.stringsPosition + start && incrementPosition === -1) - incrementPosition = 0; - if (insertionPoint > lastBundle.position + start) { - if (incrementPosition >= 0) - incrementPosition += 6; - } else { - if (incrementPosition >= 0) { - targetView.setUint32(lastBundle.position + start, targetView.getUint32(lastBundle.position + start) + incrementPosition); - incrementPosition = -1; - } - lastBundle = lastBundle.previous; - i2++; - } - } - if (incrementPosition >= 0 && lastBundle) { - targetView.setUint32(lastBundle.position + start, targetView.getUint32(lastBundle.position + start) + incrementPosition); - } - position += idsToInsert.length * 6; - if (position > safeEnd) - makeRoom(position); - packr.offset = position; - let serialized = insertIds(target.subarray(start, position), idsToInsert); - referenceMap2 = null; - return serialized; - } - packr.offset = position; - if (encodeOptions & REUSE_BUFFER_MODE) { - target.start = start; - target.end = position; - return target; - } - return target.subarray(start, position); - } catch (error) { - encodingError = error; - throw error; - } finally { - if (structures) { - resetStructures(); - if (hasSharedUpdate && packr.saveStructures) { - let sharedLength = structures.sharedLength || 0; - let returnBuffer = target.subarray(start, position); - let newSharedData = prepareStructures$1(structures, packr); - if (!encodingError) { - if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) { - return packr.pack(value, encodeOptions); - } - packr.lastNamedStructuresLength = sharedLength; - if (target.length > 1073741824) - target = null; - return returnBuffer; - } - } - } - if (target.length > 1073741824) - target = null; - if (encodeOptions & RESET_BUFFER_MODE) - position = start; - } - }; - const resetStructures = () => { - if (serializationsSinceTransitionRebuild < 10) - serializationsSinceTransitionRebuild++; - let sharedLength = structures.sharedLength || 0; - if (structures.length > sharedLength && !isSequential) - structures.length = sharedLength; - if (transitionsCount > 1e4) { - structures.transitions = null; - serializationsSinceTransitionRebuild = 0; - transitionsCount = 0; - if (recordIdsToRemove.length > 0) - recordIdsToRemove = []; - } else if (recordIdsToRemove.length > 0 && !isSequential) { - for (let i2 = 0, l2 = recordIdsToRemove.length;i2 < l2; i2++) { - recordIdsToRemove[i2][RECORD_SYMBOL] = 0; - } - recordIdsToRemove = []; - } - }; - const packArray = (value) => { - var length = value.length; - if (length < 16) { - target[position++] = 144 | length; - } else if (length < 65536) { - target[position++] = 220; - target[position++] = length >> 8; - target[position++] = length & 255; - } else { - target[position++] = 221; - targetView.setUint32(position, length); - position += 4; - } - for (let i2 = 0;i2 < length; i2++) { - pack2(value[i2]); - } - }; - const pack2 = (value) => { - if (position > safeEnd) - target = makeRoom(position); - var type = typeof value; - var length; - if (type === "string") { - let strLength = value.length; - if (bundledStrings && strLength >= 4 && strLength < 4096) { - if ((bundledStrings.size += strLength) > MAX_BUNDLE_SIZE) { - let extStart; - let maxBytes2 = (bundledStrings[0] ? bundledStrings[0].length * 3 + bundledStrings[1].length : 0) + 10; - if (position + maxBytes2 > safeEnd) - target = makeRoom(position + maxBytes2); - let lastBundle; - if (bundledStrings.position) { - lastBundle = bundledStrings; - target[position] = 200; - position += 3; - target[position++] = 98; - extStart = position - start; - position += 4; - writeBundles(start, pack2, 0); - targetView.setUint16(extStart + start - 3, position - start - extStart); - } else { - target[position++] = 214; - target[position++] = 98; - extStart = position - start; - position += 4; - } - bundledStrings = ["", ""]; - bundledStrings.previous = lastBundle; - bundledStrings.size = 0; - bundledStrings.position = extStart; - } - let twoByte = hasNonLatin.test(value); - bundledStrings[twoByte ? 0 : 1] += value; - target[position++] = 193; - pack2(twoByte ? -strLength : strLength); - return; - } - let headerSize; - if (strLength < 32) { - headerSize = 1; - } else if (strLength < 256) { - headerSize = 2; - } else if (strLength < 65536) { - headerSize = 3; - } else { - headerSize = 5; - } - let maxBytes = strLength * 3; - if (position + maxBytes > safeEnd) - target = makeRoom(position + maxBytes); - if (strLength < 64 || !encodeUtf82) { - let i2, c1, c2, strPosition = position + headerSize; - for (i2 = 0;i2 < strLength; i2++) { - c1 = value.charCodeAt(i2); - if (c1 < 128) { - target[strPosition++] = c1; - } else if (c1 < 2048) { - target[strPosition++] = c1 >> 6 | 192; - target[strPosition++] = c1 & 63 | 128; - } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i2 + 1)) & 64512) === 56320) { - c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); - i2++; - target[strPosition++] = c1 >> 18 | 240; - target[strPosition++] = c1 >> 12 & 63 | 128; - target[strPosition++] = c1 >> 6 & 63 | 128; - target[strPosition++] = c1 & 63 | 128; - } else { - target[strPosition++] = c1 >> 12 | 224; - target[strPosition++] = c1 >> 6 & 63 | 128; - target[strPosition++] = c1 & 63 | 128; - } - } - length = strPosition - position - headerSize; - } else { - length = encodeUtf82(value, position + headerSize); - } - if (length < 32) { - target[position++] = 160 | length; - } else if (length < 256) { - if (headerSize < 2) { - target.copyWithin(position + 2, position + 1, position + 1 + length); - } - target[position++] = 217; - target[position++] = length; - } else if (length < 65536) { - if (headerSize < 3) { - target.copyWithin(position + 3, position + 2, position + 2 + length); - } - target[position++] = 218; - target[position++] = length >> 8; - target[position++] = length & 255; - } else { - if (headerSize < 5) { - target.copyWithin(position + 5, position + 3, position + 3 + length); - } - target[position++] = 219; - targetView.setUint32(position, length); - position += 4; - } - position += length; - } else if (type === "number") { - if (value >>> 0 === value) { - if (value < 32 || value < 128 && this.useRecords === false || value < 64 && !this.randomAccessStructure) { - target[position++] = value; - } else if (value < 256) { - target[position++] = 204; - target[position++] = value; - } else if (value < 65536) { - target[position++] = 205; - target[position++] = value >> 8; - target[position++] = value & 255; - } else { - target[position++] = 206; - targetView.setUint32(position, value); - position += 4; - } - } else if (value >> 0 === value) { - if (value >= -32) { - target[position++] = 256 + value; - } else if (value >= -128) { - target[position++] = 208; - target[position++] = value + 256; - } else if (value >= -32768) { - target[position++] = 209; - targetView.setInt16(position, value); - position += 2; - } else { - target[position++] = 210; - targetView.setInt32(position, value); - position += 4; - } - } else { - let useFloat32; - if ((useFloat32 = this.useFloat32) > 0 && value < 4294967296 && value >= -2147483648) { - target[position++] = 202; - targetView.setFloat32(position, value); - let xShifted; - if (useFloat32 < 4 || (xShifted = value * mult10[(target[position] & 127) << 1 | target[position + 1] >> 7]) >> 0 === xShifted) { - position += 4; - return; - } else - position--; - } - target[position++] = 203; - targetView.setFloat64(position, value); - position += 8; - } - } else if (type === "object" || type === "function") { - if (!value) - target[position++] = 192; - else { - if (referenceMap2) { - let referee = referenceMap2.get(value); - if (referee) { - if (!referee.id) { - let idsToInsert = referenceMap2.idsToInsert || (referenceMap2.idsToInsert = []); - referee.id = idsToInsert.push(referee); - } - target[position++] = 214; - target[position++] = 112; - targetView.setUint32(position, referee.id); - position += 4; - return; - } else - referenceMap2.set(value, { offset: position - start }); - } - let constructor = value.constructor; - if (constructor === Object) { - writeObject(value); - } else if (constructor === Array) { - packArray(value); - } else if (constructor === Map) { - if (this.mapAsEmptyObject) - target[position++] = 128; - else { - length = value.size; - if (length < 16) { - target[position++] = 128 | length; - } else if (length < 65536) { - target[position++] = 222; - target[position++] = length >> 8; - target[position++] = length & 255; - } else { - target[position++] = 223; - targetView.setUint32(position, length); - position += 4; - } - for (let [key, entryValue] of value) { - pack2(key); - pack2(entryValue); - } - } - } else { - for (let i2 = 0, l2 = extensions.length;i2 < l2; i2++) { - let extensionClass = extensionClasses[i2]; - if (value instanceof extensionClass) { - let extension = extensions[i2]; - if (extension.write) { - if (extension.type) { - target[position++] = 212; - target[position++] = extension.type; - target[position++] = 0; - } - let writeResult = extension.write.call(this, value); - if (writeResult === value) { - if (Array.isArray(value)) { - packArray(value); - } else { - writeObject(value); - } - } else { - pack2(writeResult); - } - return; - } - let currentTarget = target; - let currentTargetView = targetView; - let currentPosition = position; - target = null; - let result; - try { - result = extension.pack.call(this, value, (size) => { - target = currentTarget; - currentTarget = null; - position += size; - if (position > safeEnd) - makeRoom(position); - return { - target, - targetView, - position: position - size - }; - }, pack2); - } finally { - if (currentTarget) { - target = currentTarget; - targetView = currentTargetView; - position = currentPosition; - safeEnd = target.length - 10; - } - } - if (result) { - if (result.length + position > safeEnd) - makeRoom(result.length + position); - position = writeExtensionData(result, target, position, extension.type); - } - return; - } - } - if (Array.isArray(value)) { - packArray(value); - } else { - if (value.toJSON) { - const json2 = value.toJSON(); - if (json2 !== value) - return pack2(json2); - } - if (type === "function") - return pack2(this.writeFunction && this.writeFunction(value)); - writeObject(value); - } - } - } - } else if (type === "boolean") { - target[position++] = value ? 195 : 194; - } else if (type === "bigint") { - if (value < 9223372036854776000 && value >= -9223372036854776000) { - target[position++] = 211; - targetView.setBigInt64(position, value); - } else if (value < 18446744073709552000 && value > 0) { - target[position++] = 207; - targetView.setBigUint64(position, value); - } else { - if (this.largeBigIntToFloat) { - target[position++] = 203; - targetView.setFloat64(position, Number(value)); - } else if (this.largeBigIntToString) { - return pack2(value.toString()); - } else if (this.useBigIntExtension || this.moreTypes) { - let empty = value < 0 ? BigInt(-1) : BigInt(0); - let array2; - if (value >> BigInt(65536) === empty) { - let mask = BigInt(18446744073709552000) - BigInt(1); - let chunks = []; - while (true) { - chunks.push(value & mask); - if (value >> BigInt(63) === empty) - break; - value >>= BigInt(64); - } - array2 = new Uint8Array(new BigUint64Array(chunks).buffer); - array2.reverse(); - } else { - let invert = value < 0; - let string2 = (invert ? ~value : value).toString(16); - if (string2.length % 2) { - string2 = "0" + string2; - } else if (parseInt(string2.charAt(0), 16) >= 8) { - string2 = "00" + string2; - } - if (hasNodeBuffer$1) { - array2 = Buffer.from(string2, "hex"); - } else { - array2 = new Uint8Array(string2.length / 2); - for (let i2 = 0;i2 < array2.length; i2++) { - array2[i2] = parseInt(string2.slice(i2 * 2, i2 * 2 + 2), 16); - } - } - if (invert) { - for (let i2 = 0;i2 < array2.length; i2++) - array2[i2] = ~array2[i2]; - } - } - if (array2.length + position > safeEnd) - makeRoom(array2.length + position); - position = writeExtensionData(array2, target, position, 66); - return; - } else { - throw new RangeError(value + " was too large to fit in MessagePack 64-bit integer format, use" + " useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set" + " largeBigIntToString to convert to string"); - } - } - position += 8; - } else if (type === "undefined") { - if (this.encodeUndefinedAsNil) - target[position++] = 192; - else { - target[position++] = 212; - target[position++] = 0; - target[position++] = 0; - } - } else { - throw new Error("Unknown type: " + type); - } - }; - const writePlainObject = this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues ? (object2) => { - let keys; - if (this.skipValues) { - keys = []; - for (let key2 in object2) { - if ((typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key2)) && !this.skipValues.includes(object2[key2])) - keys.push(key2); - } - } else { - keys = Object.keys(object2); - } - let length = keys.length; - if (length < 16) { - target[position++] = 128 | length; - } else if (length < 65536) { - target[position++] = 222; - target[position++] = length >> 8; - target[position++] = length & 255; - } else { - target[position++] = 223; - targetView.setUint32(position, length); - position += 4; - } - let key; - if (this.coercibleKeyAsNumber) { - for (let i2 = 0;i2 < length; i2++) { - key = keys[i2]; - let num = Number(key); - pack2(isNaN(num) ? key : num); - pack2(object2[key]); - } + return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; + }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string2({ + hour: "numeric", + hourCycle: "h12" + }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string2(standalone ? { + month: length + } : { + month: length, + day: "numeric" + }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string2(standalone ? { + weekday: length + } : { + weekday: length, + month: "long", + day: "numeric" + }, "weekday"), maybeMacro = (token) => { + const formatOpts = Formatter.macroTokenToFormatOpts(token); + if (formatOpts) { + return this.formatWithSystemDefault(dt, formatOpts); } else { - for (let i2 = 0;i2 < length; i2++) { - pack2(key = keys[i2]); - pack2(object2[key]); - } - } - } : (object2) => { - target[position++] = 222; - let objectOffset = position - start; - position += 2; - let size = 0; - for (let key in object2) { - if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { - pack2(key); - pack2(object2[key]); - size++; - } + return token; } - if (size > 65535) { - throw new Error("Object is too large to serialize with fast 16-bit map size," + ' use the "variableMapSize" option to serialize this object'); + }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string2({ + era: length + }, "era"), tokenToString = (token) => { + switch (token) { + case "S": + return this.num(dt.millisecond); + case "u": + case "SSS": + return this.num(dt.millisecond, 3); + case "s": + return this.num(dt.second); + case "ss": + return this.num(dt.second, 2); + case "uu": + return this.num(Math.floor(dt.millisecond / 10), 2); + case "uuu": + return this.num(Math.floor(dt.millisecond / 100)); + case "m": + return this.num(dt.minute); + case "mm": + return this.num(dt.minute, 2); + case "h": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); + case "hh": + return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); + case "H": + return this.num(dt.hour); + case "HH": + return this.num(dt.hour, 2); + case "Z": + return formatOffset2({ + format: "narrow", + allowZ: this.opts.allowZ + }); + case "ZZ": + return formatOffset2({ + format: "short", + allowZ: this.opts.allowZ + }); + case "ZZZ": + return formatOffset2({ + format: "techie", + allowZ: this.opts.allowZ + }); + case "ZZZZ": + return dt.zone.offsetName(dt.ts, { + format: "short", + locale: this.loc.locale + }); + case "ZZZZZ": + return dt.zone.offsetName(dt.ts, { + format: "long", + locale: this.loc.locale + }); + case "z": + return dt.zoneName; + case "a": + return meridiem(); + case "d": + return useDateTimeFormatter ? string2({ + day: "numeric" + }, "day") : this.num(dt.day); + case "dd": + return useDateTimeFormatter ? string2({ + day: "2-digit" + }, "day") : this.num(dt.day, 2); + case "c": + return this.num(dt.weekday); + case "ccc": + return weekday("short", true); + case "cccc": + return weekday("long", true); + case "ccccc": + return weekday("narrow", true); + case "E": + return this.num(dt.weekday); + case "EEE": + return weekday("short", false); + case "EEEE": + return weekday("long", false); + case "EEEEE": + return weekday("narrow", false); + case "L": + return useDateTimeFormatter ? string2({ + month: "numeric", + day: "numeric" + }, "month") : this.num(dt.month); + case "LL": + return useDateTimeFormatter ? string2({ + month: "2-digit", + day: "numeric" + }, "month") : this.num(dt.month, 2); + case "LLL": + return month("short", true); + case "LLLL": + return month("long", true); + case "LLLLL": + return month("narrow", true); + case "M": + return useDateTimeFormatter ? string2({ + month: "numeric" + }, "month") : this.num(dt.month); + case "MM": + return useDateTimeFormatter ? string2({ + month: "2-digit" + }, "month") : this.num(dt.month, 2); + case "MMM": + return month("short", false); + case "MMMM": + return month("long", false); + case "MMMMM": + return month("narrow", false); + case "y": + return useDateTimeFormatter ? string2({ + year: "numeric" + }, "year") : this.num(dt.year); + case "yy": + return useDateTimeFormatter ? string2({ + year: "2-digit" + }, "year") : this.num(dt.year.toString().slice(-2), 2); + case "yyyy": + return useDateTimeFormatter ? string2({ + year: "numeric" + }, "year") : this.num(dt.year, 4); + case "yyyyyy": + return useDateTimeFormatter ? string2({ + year: "numeric" + }, "year") : this.num(dt.year, 6); + case "G": + return era("short"); + case "GG": + return era("long"); + case "GGGGG": + return era("narrow"); + case "kk": + return this.num(dt.weekYear.toString().slice(-2), 2); + case "kkkk": + return this.num(dt.weekYear, 4); + case "W": + return this.num(dt.weekNumber); + case "WW": + return this.num(dt.weekNumber, 2); + case "n": + return this.num(dt.localWeekNumber); + case "nn": + return this.num(dt.localWeekNumber, 2); + case "ii": + return this.num(dt.localWeekYear.toString().slice(-2), 2); + case "iiii": + return this.num(dt.localWeekYear, 4); + case "o": + return this.num(dt.ordinal); + case "ooo": + return this.num(dt.ordinal, 3); + case "q": + return this.num(dt.quarter); + case "qq": + return this.num(dt.quarter, 2); + case "X": + return this.num(Math.floor(dt.ts / 1000)); + case "x": + return this.num(dt.ts); + default: + return maybeMacro(token); } - target[objectOffset++ + start] = size >> 8; - target[objectOffset + start] = size & 255; }; - const writeRecord = this.useRecords === false ? writePlainObject : options.progressiveRecords && !useTwoByteRecords ? (object2) => { - let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); - let objectOffset = position++ - start; - let wroteKeys; - for (let key in object2) { - if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { - nextTransition = transition[key]; - if (nextTransition) - transition = nextTransition; - else { - let keys = Object.keys(object2); - let lastTransition = transition; - transition = structures.transitions; - let newTransitions = 0; - for (let i2 = 0, l2 = keys.length;i2 < l2; i2++) { - let key2 = keys[i2]; - nextTransition = transition[key2]; - if (!nextTransition) { - nextTransition = transition[key2] = Object.create(null); - newTransitions++; - } - transition = nextTransition; - } - if (objectOffset + start + 1 == position) { - position--; - newRecord(transition, keys, newTransitions); - } else - insertNewRecord(transition, keys, objectOffset, newTransitions); - wroteKeys = true; - transition = lastTransition[key]; - } - pack2(object2[key]); - } - } - if (!wroteKeys) { - let recordId = transition[RECORD_SYMBOL]; - if (recordId) - target[objectOffset + start] = recordId; - else - insertNewRecord(transition, Object.keys(object2), objectOffset, 0); - } - } : (object2) => { - let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); - let newTransitions = 0; - for (let key in object2) - if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { - nextTransition = transition[key]; - if (!nextTransition) { - nextTransition = transition[key] = Object.create(null); - newTransitions++; - } - transition = nextTransition; - } - let recordId = transition[RECORD_SYMBOL]; - if (recordId) { - if (recordId >= 96 && useTwoByteRecords) { - target[position++] = ((recordId -= 96) & 31) + 96; - target[position++] = recordId >> 5; - } else - target[position++] = recordId; - } else { - newRecord(transition, transition.__keys__ || Object.keys(object2), newTransitions); + return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); + } + formatDurationFromString(dur, fmt) { + const invertLargest = this.opts.signMode === "negativeLargestOnly" ? -1 : 1; + const tokenToField = (token) => { + switch (token[0]) { + case "S": + return "milliseconds"; + case "s": + return "seconds"; + case "m": + return "minutes"; + case "h": + return "hours"; + case "d": + return "days"; + case "w": + return "weeks"; + case "M": + return "months"; + case "y": + return "years"; + default: + return null; } - for (let key in object2) - if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { - pack2(object2[key]); - } - }; - const checkUseRecords = typeof this.useRecords == "function" && this.useRecords; - const writeObject = checkUseRecords ? (object2) => { - checkUseRecords(object2) ? writeRecord(object2) : writePlainObject(object2); - } : writeRecord; - const makeRoom = (end) => { - let newSize; - if (end > 16777216) { - if (end - start > MAX_BUFFER_SIZE) - throw new Error("Packed buffer would be larger than maximum buffer size"); - newSize = Math.min(MAX_BUFFER_SIZE, Math.round(Math.max((end - start) * (end > 67108864 ? 1.25 : 2), 4194304) / 4096) * 4096); - } else - newSize = (Math.max(end - start << 2, target.length - 1) >> 12) + 1 << 12; - let newBuffer = new ByteArrayAllocate(newSize); - targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize)); - end = Math.min(end, target.length); - if (target.copy) - target.copy(newBuffer, 0, start, end); - else - newBuffer.set(target.slice(start, end)); - position -= start; - start = 0; - safeEnd = newBuffer.length - 10; - return target = newBuffer; - }; - const newRecord = (transition, keys, newTransitions) => { - let recordId = structures.nextId; - if (!recordId) - recordId = 64; - if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) { - recordId = structures.nextOwnId; - if (!(recordId < maxStructureId)) - recordId = sharedLimitId; - structures.nextOwnId = recordId + 1; - } else { - if (recordId >= maxStructureId) - recordId = sharedLimitId; - structures.nextId = recordId + 1; - } - let highByte = keys.highByte = recordId >= 96 && useTwoByteRecords ? recordId - 96 >> 5 : -1; - transition[RECORD_SYMBOL] = recordId; - transition.__keys__ = keys; - structures[recordId - 64] = keys; - if (recordId < sharedLimitId) { - keys.isShared = true; - structures.sharedLength = recordId - 63; - hasSharedUpdate = true; - if (highByte >= 0) { - target[position++] = (recordId & 31) + 96; - target[position++] = highByte; - } else { - target[position++] = recordId; - } - } else { - if (highByte >= 0) { - target[position++] = 213; - target[position++] = 114; - target[position++] = (recordId & 31) + 96; - target[position++] = highByte; + }, tokenToString = (lildur, info) => (token) => { + const mapped = tokenToField(token); + if (mapped) { + const inversionFactor = info.isNegativeDuration && mapped !== info.largestUnit ? invertLargest : 1; + let signDisplay; + if (this.opts.signMode === "negativeLargestOnly" && mapped !== info.largestUnit) { + signDisplay = "never"; + } else if (this.opts.signMode === "all") { + signDisplay = "always"; } else { - target[position++] = 212; - target[position++] = 114; - target[position++] = recordId; + signDisplay = "auto"; } - if (newTransitions) - transitionsCount += serializationsSinceTransitionRebuild * newTransitions; - if (recordIdsToRemove.length >= maxOwnStructures) - recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; - recordIdsToRemove.push(transition); - pack2(keys); - } - }; - const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => { - let mainTarget = target; - let mainPosition = position; - let mainSafeEnd = safeEnd; - let mainStart = start; - target = keysTarget; - position = 0; - start = 0; - if (!target) - keysTarget = target = new ByteArrayAllocate(8192); - safeEnd = target.length - 10; - newRecord(transition, keys, newTransitions); - keysTarget = target; - let keysPosition = position; - target = mainTarget; - position = mainPosition; - safeEnd = mainSafeEnd; - start = mainStart; - if (keysPosition > 1) { - let newEnd = position + keysPosition - 1; - if (newEnd > safeEnd) - makeRoom(newEnd); - let insertionPosition = insertionOffset + start; - target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position); - target.set(keysTarget.slice(0, keysPosition), insertionPosition); - position = newEnd; + return this.num(lildur.get(mapped) * inversionFactor, token.length, signDisplay); } else { - target[insertionOffset + start] = keysTarget[0]; + return token; } + }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, { + literal, + val + }) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t9) => t9)), durationInfo = { + isNegativeDuration: collapsed < 0, + largestUnit: Object.keys(collapsed.values)[0] }; - const writeStruct2 = (object2) => { - let newPosition = writeStructSlots(object2, target, start, position, structures, makeRoom, (value, newPosition2, notifySharedUpdate) => { - if (notifySharedUpdate) - return hasSharedUpdate = true; - position = newPosition2; - let startTarget = target; - pack2(value); - resetStructures(); - if (startTarget !== target) { - return { position, targetView, target }; - } - return position; - }, this); - if (newPosition === 0) - return writeObject(object2); - position = newPosition; - }; - } - useBuffer(buffer) { - target = buffer; - target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength)); - targetView = target.dataView; - position = 0; - } - set position(value) { - position = value; - } - get position() { - return position; - } - clearSharedData() { - if (this.structures) - this.structures = []; - if (this.typedStructs) - this.typedStructs = []; - } - } - extensionClasses = [Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor, DataView, C1Type]; - extensions = [{ - pack(date3, allocateForWrite, pack2) { - let seconds = date3.getTime() / 1000; - if ((this.useTimestamp32 || date3.getMilliseconds() === 0) && seconds >= 0 && seconds < 4294967296) { - let { target: target2, targetView: targetView2, position: position2 } = allocateForWrite(6); - target2[position2++] = 214; - target2[position2++] = 255; - targetView2.setUint32(position2, seconds); - } else if (seconds > 0 && seconds < 4294967296) { - let { target: target2, targetView: targetView2, position: position2 } = allocateForWrite(10); - target2[position2++] = 215; - target2[position2++] = 255; - targetView2.setUint32(position2, date3.getMilliseconds() * 4000000 + (seconds / 1000 / 4294967296 >> 0)); - targetView2.setUint32(position2 + 4, seconds); - } else if (isNaN(seconds)) { - if (this.onInvalidDate) { - allocateForWrite(0); - return pack2(this.onInvalidDate()); - } - let { target: target2, targetView: targetView2, position: position2 } = allocateForWrite(3); - target2[position2++] = 212; - target2[position2++] = 255; - target2[position2++] = 255; - } else { - let { target: target2, targetView: targetView2, position: position2 } = allocateForWrite(15); - target2[position2++] = 199; - target2[position2++] = 12; - target2[position2++] = 255; - targetView2.setUint32(position2, date3.getMilliseconds() * 1e6); - targetView2.setBigInt64(position2 + 4, BigInt(Math.floor(seconds))); - } - } - }, { - pack(set, allocateForWrite, pack2) { - if (this.setAsEmptyObject) { - allocateForWrite(0); - return pack2({}); - } - let array2 = Array.from(set); - let { target: target2, position: position2 } = allocateForWrite(this.moreTypes ? 3 : 0); - if (this.moreTypes) { - target2[position2++] = 212; - target2[position2++] = 115; - target2[position2++] = 0; - } - pack2(array2); - } - }, { - pack(error, allocateForWrite, pack2) { - let { target: target2, position: position2 } = allocateForWrite(this.moreTypes ? 3 : 0); - if (this.moreTypes) { - target2[position2++] = 212; - target2[position2++] = 101; - target2[position2++] = 0; - } - pack2([error.name, error.message, error.cause]); - } - }, { - pack(regex, allocateForWrite, pack2) { - let { target: target2, position: position2 } = allocateForWrite(this.moreTypes ? 3 : 0); - if (this.moreTypes) { - target2[position2++] = 212; - target2[position2++] = 120; - target2[position2++] = 0; - } - pack2([regex.source, regex.flags]); - } - }, { - pack(arrayBuffer, allocateForWrite) { - if (this.moreTypes) - writeExtBuffer(arrayBuffer, 16, allocateForWrite); - else - writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite); - } - }, { - pack(typedArray, allocateForWrite) { - let constructor = typedArray.constructor; - if (constructor !== ByteArray && this.moreTypes) - writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite); - else - writeBuffer(typedArray, allocateForWrite); - } - }, { - pack(arrayBuffer, allocateForWrite) { - if (this.moreTypes) - writeExtBuffer(arrayBuffer, 17, allocateForWrite); - else - writeBuffer(hasNodeBuffer$1 ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite); - } - }, { - pack(c1, allocateForWrite) { - let { target: target2, position: position2 } = allocateForWrite(1); - target2[position2] = 193; - } - }]; - function writeExtBuffer(typedArray, type, allocateForWrite, encode2) { - let length = typedArray.byteLength; - if (length + 1 < 256) { - var { target: target2, position: position2 } = allocateForWrite(4 + length); - target2[position2++] = 199; - target2[position2++] = length + 1; - } else if (length + 1 < 65536) { - var { target: target2, position: position2 } = allocateForWrite(5 + length); - target2[position2++] = 200; - target2[position2++] = length + 1 >> 8; - target2[position2++] = length + 1 & 255; - } else { - var { target: target2, position: position2, targetView: targetView2 } = allocateForWrite(7 + length); - target2[position2++] = 201; - targetView2.setUint32(position2, length + 1); - position2 += 4; - } - target2[position2++] = 116; - target2[position2++] = type; - if (!typedArray.buffer) - typedArray = new Uint8Array(typedArray); - target2.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position2); - } - function writeBuffer(buffer, allocateForWrite) { - let length = buffer.byteLength; - var target2, position2; - if (length < 256) { - var { target: target2, position: position2 } = allocateForWrite(length + 2); - target2[position2++] = 196; - target2[position2++] = length; - } else if (length < 65536) { - var { target: target2, position: position2 } = allocateForWrite(length + 3); - target2[position2++] = 197; - target2[position2++] = length >> 8; - target2[position2++] = length & 255; - } else { - var { target: target2, position: position2, targetView: targetView2 } = allocateForWrite(length + 5); - target2[position2++] = 198; - targetView2.setUint32(position2, length); - position2 += 4; + return stringifyTokens(tokens, tokenToString(collapsed, durationInfo)); } - target2.set(buffer, position2); } - function writeExtensionData(result, target2, position2, type) { - let length = result.length; - switch (length) { - case 1: - target2[position2++] = 212; - break; - case 2: - target2[position2++] = 213; - break; - case 4: - target2[position2++] = 214; - break; - case 8: - target2[position2++] = 215; - break; - case 16: - target2[position2++] = 216; - break; - default: - if (length < 256) { - target2[position2++] = 199; - target2[position2++] = length; - } else if (length < 65536) { - target2[position2++] = 200; - target2[position2++] = length >> 8; - target2[position2++] = length & 255; - } else { - target2[position2++] = 201; - target2[position2++] = length >> 24; - target2[position2++] = length >> 16 & 255; - target2[position2++] = length >> 8 & 255; - target2[position2++] = length & 255; - } - } - target2[position2++] = type; - target2.set(result, position2); - position2 += length; - return position2; + var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; + function combineRegexes(...regexes) { + const full = regexes.reduce((f2, r2) => f2 + r2.source, ""); + return RegExp(`^${full}$`); } - function insertIds(serialized, idsToInsert) { - let nextId; - let distanceToMove = idsToInsert.length * 6; - let lastEnd = serialized.length - distanceToMove; - while (nextId = idsToInsert.pop()) { - let offset = nextId.offset; - let id = nextId.id; - serialized.copyWithin(offset + distanceToMove, offset, lastEnd); - distanceToMove -= 6; - let position2 = offset + distanceToMove; - serialized[position2++] = 214; - serialized[position2++] = 105; - serialized[position2++] = id >> 24; - serialized[position2++] = id >> 16 & 255; - serialized[position2++] = id >> 8 & 255; - serialized[position2++] = id & 255; - lastEnd = offset; - } - return serialized; - } - function writeBundles(start, pack2, incrementPosition) { - if (bundledStrings.length > 0) { - targetView.setUint32(bundledStrings.position + start, position + incrementPosition - bundledStrings.position - start); - bundledStrings.stringsPosition = position - start; - let writeStrings = bundledStrings; - bundledStrings = null; - pack2(writeStrings[0]); - pack2(writeStrings[1]); - } - } - function addExtension(extension) { - if (extension.Class) { - if (!extension.pack && !extension.write) - throw new Error("Extension has no pack or write function"); - if (extension.pack && !extension.type) - throw new Error("Extension has no type (numeric code to identify the extension)"); - extensionClasses.unshift(extension.Class); - extensions.unshift(extension); - } - addExtension$1(extension); - } - function prepareStructures$1(structures, packr) { - structures.isCompatible = (existingStructures) => { - let compatible = !existingStructures || (packr.lastNamedStructuresLength || 0) === existingStructures.length; - if (!compatible) - packr._mergeStructures(existingStructures); - return compatible; - }; - return structures; - } - function setWriteStructSlots(writeSlots, makeStructures) { - writeStructSlots = writeSlots; - prepareStructures$1 = makeStructures; - } - var defaultPackr = new Packr({ useRecords: false }); - var pack = defaultPackr.pack; - var encode = defaultPackr.pack; - var Encoder = Packr; - var { NEVER, ALWAYS, DECIMAL_ROUND, DECIMAL_FIT } = FLOAT32_OPTIONS; - var REUSE_BUFFER_MODE = 512; - var RESET_BUFFER_MODE = 1024; - var RESERVE_START_SPACE = 2048; - var ASCII = 3; - var NUMBER = 0; - var UTF8 = 2; - var OBJECT_DATA = 1; - var DATE = 16; - var TYPE_NAMES = ["num", "object", "string", "ascii"]; - TYPE_NAMES[DATE] = "date"; - var float32Headers = [false, true, true, false, false, true, true, false]; - var evalSupported; - try { - new Function(""); - evalSupported = true; - } catch (error) {} - var updatedPosition; - var hasNodeBuffer = typeof Buffer !== "undefined"; - var textEncoder; - var currentSource; - try { - textEncoder = new TextEncoder; - } catch (error) {} - var encodeUtf8 = hasNodeBuffer ? function(target2, string2, position2) { - return target2.utf8Write(string2, position2, target2.byteLength - position2); - } : textEncoder && textEncoder.encodeInto ? function(target2, string2, position2) { - return textEncoder.encodeInto(string2, target2.subarray(position2)).written; - } : false; - setWriteStructSlots(writeStruct, prepareStructures); - function writeStruct(object2, target2, encodingStart, position2, structures, makeRoom, pack2, packr) { - let typedStructs = packr.typedStructs || (packr.typedStructs = []); - let targetView2 = target2.dataView; - let refsStartPosition = (typedStructs.lastStringStart || 100) + position2; - let safeEnd2 = target2.length - 10; - let start = position2; - if (position2 > safeEnd2) { - target2 = makeRoom(position2); - targetView2 = target2.dataView; - position2 -= encodingStart; - start -= encodingStart; - refsStartPosition -= encodingStart; - encodingStart = 0; - safeEnd2 = target2.length - 10; - } - let refOffset, refPosition = refsStartPosition; - let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null)); - let nextId = typedStructs.nextId || typedStructs.length; - let headerSize = nextId < 15 ? 1 : nextId < 240 ? 2 : nextId < 61440 ? 3 : nextId < 15728640 ? 4 : 0; - if (headerSize === 0) - return 0; - position2 += headerSize; - let queuedReferences = []; - let usedAscii0; - let keyIndex = 0; - for (let key in object2) { - let value = object2[key]; - let nextTransition = transition[key]; - if (!nextTransition) { - transition[key] = nextTransition = { - key, - parent: transition, - enumerationOffset: 0, - ascii0: null, - ascii8: null, - num8: null, - string16: null, - object16: null, - num32: null, - float64: null, - date64: null - }; - } - if (position2 > safeEnd2) { - target2 = makeRoom(position2); - targetView2 = target2.dataView; - position2 -= encodingStart; - start -= encodingStart; - refsStartPosition -= encodingStart; - refPosition -= encodingStart; - encodingStart = 0; - safeEnd2 = target2.length - 10; - } - switch (typeof value) { - case "number": - let number2 = value; - if (nextId < 200 || !nextTransition.num64) { - if (number2 >> 0 === number2 && number2 < 536870912 && number2 > -520093696) { - if (number2 < 246 && number2 >= 0 && (nextTransition.num8 && !(nextId > 200 && nextTransition.num32) || number2 < 32 && !nextTransition.num32)) { - transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1); - target2[position2++] = number2; - } else { - transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4); - targetView2.setUint32(position2, number2, true); - position2 += 4; - } - break; - } else if (number2 < 4294967296 && number2 >= -2147483648) { - targetView2.setFloat32(position2, number2, true); - if (float32Headers[target2[position2 + 3] >>> 5]) { - let xShifted; - if ((xShifted = number2 * mult10[(target2[position2 + 3] & 127) << 1 | target2[position2 + 2] >> 7]) >> 0 === xShifted) { - transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4); - position2 += 4; - break; - } - } - } - } - transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8); - targetView2.setFloat64(position2, number2, true); - position2 += 8; - break; - case "string": - let strLength = value.length; - refOffset = refPosition - refsStartPosition; - if ((strLength << 2) + refPosition > safeEnd2) { - target2 = makeRoom((strLength << 2) + refPosition); - targetView2 = target2.dataView; - position2 -= encodingStart; - start -= encodingStart; - refsStartPosition -= encodingStart; - refPosition -= encodingStart; - encodingStart = 0; - safeEnd2 = target2.length - 10; - } - if (strLength > 65280 + refOffset >> 2) { - queuedReferences.push(key, value, position2 - start); - break; - } - let isNotAscii; - let strStart = refPosition; - if (strLength < 64) { - let i2, c1, c2; - for (i2 = 0;i2 < strLength; i2++) { - c1 = value.charCodeAt(i2); - if (c1 < 128) { - target2[refPosition++] = c1; - } else if (c1 < 2048) { - isNotAscii = true; - target2[refPosition++] = c1 >> 6 | 192; - target2[refPosition++] = c1 & 63 | 128; - } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i2 + 1)) & 64512) === 56320) { - isNotAscii = true; - c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); - i2++; - target2[refPosition++] = c1 >> 18 | 240; - target2[refPosition++] = c1 >> 12 & 63 | 128; - target2[refPosition++] = c1 >> 6 & 63 | 128; - target2[refPosition++] = c1 & 63 | 128; - } else { - isNotAscii = true; - target2[refPosition++] = c1 >> 12 | 224; - target2[refPosition++] = c1 >> 6 & 63 | 128; - target2[refPosition++] = c1 & 63 | 128; - } - } - } else { - refPosition += encodeUtf8(target2, value, refPosition); - isNotAscii = refPosition - strStart > strLength; - } - if (refOffset < 160 || refOffset < 246 && (nextTransition.ascii8 || nextTransition.string8)) { - if (isNotAscii) { - if (!(transition = nextTransition.string8)) { - if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) { - transition.__type = UTF8; - nextTransition.ascii8 = null; - nextTransition.string8 = transition; - pack2(null, 0, true); - } else { - transition = createTypeTransition(nextTransition, UTF8, 1); - } - } - } else if (refOffset === 0 && !usedAscii0) { - usedAscii0 = true; - transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0); - break; - } else if (!(transition = nextTransition.ascii8) && !(typedStructs.length > 10 && (transition = nextTransition.string8))) - transition = createTypeTransition(nextTransition, ASCII, 1); - target2[position2++] = refOffset; - } else { - transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2); - targetView2.setUint16(position2, refOffset, true); - position2 += 2; - } - break; - case "object": - if (value) { - if (value.constructor === Date) { - transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8); - targetView2.setFloat64(position2, value.getTime(), true); - position2 += 8; - } else { - queuedReferences.push(key, value, keyIndex); - } - break; - } else { - nextTransition = anyType(nextTransition, position2, targetView2, -10); - if (nextTransition) { - transition = nextTransition; - position2 = updatedPosition; - } else - queuedReferences.push(key, value, keyIndex); - } - break; - case "boolean": - transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1); - target2[position2++] = value ? 249 : 248; - break; - case "undefined": - nextTransition = anyType(nextTransition, position2, targetView2, -9); - if (nextTransition) { - transition = nextTransition; - position2 = updatedPosition; - } else - queuedReferences.push(key, value, keyIndex); - break; - default: - queuedReferences.push(key, value, keyIndex); - } - keyIndex++; + function combineExtractors(...extractors) { + return (m2) => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => { + const [val, zone, next] = ex(m2, cursor); + return [{ + ...mergedVals, + ...val + }, zone || mergedZone, next]; + }, [{}, null, 1]).slice(0, 2); + } + function parse2(s3, ...patterns) { + if (s3 == null) { + return [null, null]; } - for (let i2 = 0, l2 = queuedReferences.length;i2 < l2; ) { - let key = queuedReferences[i2++]; - let value = queuedReferences[i2++]; - let propertyIndex = queuedReferences[i2++]; - let nextTransition = transition[key]; - if (!nextTransition) { - transition[key] = nextTransition = { - key, - parent: transition, - enumerationOffset: propertyIndex - keyIndex, - ascii0: null, - ascii8: null, - num8: null, - string16: null, - object16: null, - num32: null, - float64: null - }; + for (const [regex, extractor] of patterns) { + const m2 = regex.exec(s3); + if (m2) { + return extractor(m2); } - let newPosition; - if (value) { - let size; - refOffset = refPosition - refsStartPosition; - if (refOffset < 65280) { - transition = nextTransition.object16; - if (transition) - size = 2; - else if (transition = nextTransition.object32) - size = 4; - else { - transition = createTypeTransition(nextTransition, OBJECT_DATA, 2); - size = 2; - } - } else { - transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4); - size = 4; - } - newPosition = pack2(value, refPosition); - if (typeof newPosition === "object") { - refPosition = newPosition.position; - targetView2 = newPosition.targetView; - target2 = newPosition.target; - refsStartPosition -= encodingStart; - position2 -= encodingStart; - start -= encodingStart; - encodingStart = 0; - } else - refPosition = newPosition; - if (size === 2) { - targetView2.setUint16(position2, refOffset, true); - position2 += 2; - } else { - targetView2.setUint32(position2, refOffset, true); - position2 += 4; - } - } else { - transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2); - targetView2.setInt16(position2, value === null ? -10 : -9, true); - position2 += 2; - } - keyIndex++; - } - let recordId = transition[RECORD_SYMBOL]; - if (recordId == null) { - recordId = packr.typedStructs.length; - let structure = []; - let nextTransition = transition; - let key, type; - while ((type = nextTransition.__type) !== undefined) { - let size = nextTransition.__size; - nextTransition = nextTransition.__parent; - key = nextTransition.key; - let property = [type, size, key]; - if (nextTransition.enumerationOffset) - property.push(nextTransition.enumerationOffset); - structure.push(property); - nextTransition = nextTransition.parent; - } - structure.reverse(); - transition[RECORD_SYMBOL] = recordId; - packr.typedStructs[recordId] = structure; - pack2(null, 0, true); - } - switch (headerSize) { - case 1: - if (recordId >= 16) - return 0; - target2[start] = recordId + 32; - break; - case 2: - if (recordId >= 256) - return 0; - target2[start] = 56; - target2[start + 1] = recordId; - break; - case 3: - if (recordId >= 65536) - return 0; - target2[start] = 57; - targetView2.setUint16(start + 1, recordId, true); - break; - case 4: - if (recordId >= 16777216) - return 0; - targetView2.setUint32(start, (recordId << 8) + 58, true); - break; } - if (position2 < refsStartPosition) { - if (refsStartPosition === refPosition) - return position2; - target2.copyWithin(position2, refsStartPosition, refPosition); - refPosition += position2 - refsStartPosition; - typedStructs.lastStringStart = position2 - start; - } else if (position2 > refsStartPosition) { - if (refsStartPosition === refPosition) - return position2; - typedStructs.lastStringStart = position2 - start; - return writeStruct(object2, target2, encodingStart, start, structures, makeRoom, pack2, packr); - } - return refPosition; - } - function anyType(transition, position2, targetView2, value) { - let nextTransition; - if (nextTransition = transition.ascii8 || transition.num8) { - targetView2.setInt8(position2, value, true); - updatedPosition = position2 + 1; - return nextTransition; - } - if (nextTransition = transition.string16 || transition.object16) { - targetView2.setInt16(position2, value, true); - updatedPosition = position2 + 2; - return nextTransition; - } - if (nextTransition = transition.num32) { - targetView2.setUint32(position2, 3758096640 + value, true); - updatedPosition = position2 + 4; - return nextTransition; - } - if (nextTransition = transition.num64) { - targetView2.setFloat64(position2, NaN, true); - targetView2.setInt8(position2, value); - updatedPosition = position2 + 8; - return nextTransition; - } - updatedPosition = position2; - return; + return [null, null]; } - function createTypeTransition(transition, type, size) { - let typeName = TYPE_NAMES[type] + (size << 3); - let newTransition = transition[typeName] || (transition[typeName] = Object.create(null)); - newTransition.__type = type; - newTransition.__size = size; - newTransition.__parent = transition; - return newTransition; - } - function onLoadedStructures(sharedData) { - if (!(sharedData instanceof Map)) - return sharedData; - let typed = sharedData.get("typed") || []; - if (Object.isFrozen(typed)) - typed = typed.map((structure) => structure.slice(0)); - let named = sharedData.get("named"); - let transitions = Object.create(null); - for (let i2 = 0, l2 = typed.length;i2 < l2; i2++) { - let structure = typed[i2]; - let transition = transitions; - for (let [type, size, key] of structure) { - let nextTransition = transition[key]; - if (!nextTransition) { - transition[key] = nextTransition = { - key, - parent: transition, - enumerationOffset: 0, - ascii0: null, - ascii8: null, - num8: null, - string16: null, - object16: null, - num32: null, - float64: null, - date64: null - }; - } - transition = createTypeTransition(nextTransition, type, size); + function simpleParse(...keys) { + return (match2, cursor) => { + const ret = {}; + let i2; + for (i2 = 0;i2 < keys.length; i2++) { + ret[keys[i2]] = parseInteger(match2[cursor + i2]); } - transition[RECORD_SYMBOL] = i2; - } - typed.transitions = transitions; - this.typedStructs = typed; - this.lastTypedStructuresLength = typed.length; - return named; + return [ret, null, cursor + i2]; + }; } - var sourceSymbol = Symbol.for("source"); - function readStruct(src2, position2, srcEnd2, unpackr) { - let recordId = src2[position2++] - 32; - if (recordId >= 24) { - switch (recordId) { - case 24: - recordId = src2[position2++]; - break; - case 25: - recordId = src2[position2++] + (src2[position2++] << 8); - break; - case 26: - recordId = src2[position2++] + (src2[position2++] << 8) + (src2[position2++] << 16); - break; - case 27: - recordId = src2[position2++] + (src2[position2++] << 8) + (src2[position2++] << 16) + (src2[position2++] << 24); - break; - } - } - let structure = unpackr.typedStructs && unpackr.typedStructs[recordId]; - if (!structure) { - src2 = Uint8Array.prototype.slice.call(src2, position2, srcEnd2); - srcEnd2 -= position2; - position2 = 0; - if (!unpackr.getStructures) - throw new Error(`Reference to shared structure ${recordId} without getStructures method`); - unpackr._mergeStructures(unpackr.getStructures()); - if (!unpackr.typedStructs) - throw new Error("Could not find any shared typed structures"); - unpackr.lastTypedStructuresLength = unpackr.typedStructs.length; - structure = unpackr.typedStructs[recordId]; - if (!structure) - throw new Error("Could not find typed structure " + recordId); - } - var construct2 = structure.construct; - var fullConstruct = structure.fullConstruct; - if (!construct2) { - construct2 = structure.construct = function LazyObject() {}; - fullConstruct = structure.fullConstruct = function LoadedObject() {}; - fullConstruct.prototype = unpackr.structPrototype || {}; - var prototype = construct2.prototype = unpackr.structPrototype ? Object.create(unpackr.structPrototype) : {}; - let properties = []; - let currentOffset = 0; - let lastRefProperty; - for (let i2 = 0, l2 = structure.length;i2 < l2; i2++) { - let definition = structure[i2]; - let [type, size, key, enumerationOffset] = definition; - if (key === "__proto__") - key = "__proto_"; - let property = { - key, - offset: currentOffset - }; - if (enumerationOffset) - properties.splice(i2 + enumerationOffset, 0, property); - else - properties.push(property); - let getRef; - switch (size) { - case 0: - getRef = () => 0; - break; - case 1: - getRef = (source, position3) => { - let ref = source.bytes[position3 + property.offset]; - return ref >= 246 ? toConstant(ref) : ref; - }; - break; - case 2: - getRef = (source, position3) => { - let src3 = source.bytes; - let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); - let ref = dataView2.getUint16(position3 + property.offset, true); - return ref >= 65280 ? toConstant(ref & 255) : ref; - }; - break; - case 4: - getRef = (source, position3) => { - let src3 = source.bytes; - let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); - let ref = dataView2.getUint32(position3 + property.offset, true); - return ref >= 4294967040 ? toConstant(ref & 255) : ref; - }; - break; - } - property.getRef = getRef; - currentOffset += size; - let get; - switch (type) { - case ASCII: - if (lastRefProperty && !lastRefProperty.next) - lastRefProperty.next = property; - lastRefProperty = property; - property.multiGetCount = 0; - get = function(source) { - let src3 = source.bytes; - let position3 = source.position; - let refStart = currentOffset + position3; - let ref = getRef(source, position3); - if (typeof ref !== "number") - return ref; - let end, next = property.next; - while (next) { - end = next.getRef(source, position3); - if (typeof end === "number") - break; - else - end = null; - next = next.next; - } - if (end == null) - end = source.bytesEnd - refStart; - if (source.srcString) { - return source.srcString.slice(ref, end); - } - return readString(src3, ref + refStart, end - ref); - }; - break; - case UTF8: - case OBJECT_DATA: - if (lastRefProperty && !lastRefProperty.next) - lastRefProperty.next = property; - lastRefProperty = property; - get = function(source) { - let position3 = source.position; - let refStart = currentOffset + position3; - let ref = getRef(source, position3); - if (typeof ref !== "number") - return ref; - let src3 = source.bytes; - let end, next = property.next; - while (next) { - end = next.getRef(source, position3); - if (typeof end === "number") - break; - else - end = null; - next = next.next; - } - if (end == null) - end = source.bytesEnd - refStart; - if (type === UTF8) { - return src3.toString("utf8", ref + refStart, end + refStart); - } else { - currentSource = source; - try { - return unpackr.unpack(src3, { start: ref + refStart, end: end + refStart }); - } finally { - currentSource = null; - } - } - }; - break; - case NUMBER: - switch (size) { - case 4: - get = function(source) { - let src3 = source.bytes; - let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); - let position3 = source.position + property.offset; - let value = dataView2.getInt32(position3, true); - if (value < 536870912) { - if (value > -520093696) - return value; - if (value > -536870912) - return toConstant(value & 255); - } - let fValue = dataView2.getFloat32(position3, true); - let multiplier = mult10[(src3[position3 + 3] & 127) << 1 | src3[position3 + 2] >> 7]; - return (multiplier * fValue + (fValue > 0 ? 0.5 : -0.5) >> 0) / multiplier; - }; - break; - case 8: - get = function(source) { - let src3 = source.bytes; - let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); - let value = dataView2.getFloat64(source.position + property.offset, true); - if (isNaN(value)) { - let byte = src3[source.position + property.offset]; - if (byte >= 246) - return toConstant(byte); - } - return value; - }; - break; - case 1: - get = function(source) { - let src3 = source.bytes; - let value = src3[source.position + property.offset]; - return value < 246 ? value : toConstant(value); - }; - break; - } - break; - case DATE: - get = function(source) { - let src3 = source.bytes; - let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); - return new Date(dataView2.getFloat64(source.position + property.offset, true)); - }; - break; - } - property.get = get; - } - if (evalSupported) { - let objectLiteralProperties = []; - let args = []; - let i2 = 0; - let hasInheritedProperties; - for (let property of properties) { - if (unpackr.alwaysLazyProperty && unpackr.alwaysLazyProperty(property.key)) { - hasInheritedProperties = true; - continue; - } - Object.defineProperty(prototype, property.key, { get: withSource(property.get), enumerable: true }); - let valueFunction = "v" + i2++; - args.push(valueFunction); - objectLiteralProperties.push("o[" + JSON.stringify(property.key) + "]=" + valueFunction + "(s)"); - } - if (hasInheritedProperties) { - objectLiteralProperties.push("__proto__:this"); - } - let toObject = new Function(...args, "var c=this;return function(s){var o=new c();" + objectLiteralProperties.join(";") + ";return o;}").apply(fullConstruct, properties.map((prop) => prop.get)); - Object.defineProperty(prototype, "toJSON", { - value(omitUnderscoredProperties) { - return toObject.call(this, this[sourceSymbol]); - } - }); - } else { - Object.defineProperty(prototype, "toJSON", { - value(omitUnderscoredProperties) { - let resolved = {}; - for (let i2 = 0, l2 = properties.length;i2 < l2; i2++) { - let key = properties[i2].key; - resolved[key] = this[key]; - } - return resolved; - } - }); - } - } - var instance = new construct2; - instance[sourceSymbol] = { - bytes: src2, - position: position2, - srcString: "", - bytesEnd: srcEnd2 + var offsetRegex = /(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/; + var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; + var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; + var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); + var isoTimeExtensionRegex = RegExp(`(?:[Tt]${isoTimeRegex.source})?`); + var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; + var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; + var isoOrdinalRegex = /(\d{4})-?(\d{3})/; + var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); + var extractISOOrdinalData = simpleParse("year", "ordinal"); + var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; + var sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`); + var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); + function int(match2, pos, fallback) { + const m2 = match2[pos]; + return isUndefined(m2) ? fallback : parseInteger(m2); + } + function extractISOYmd(match2, cursor) { + const item = { + year: int(match2, cursor), + month: int(match2, cursor + 1, 1), + day: int(match2, cursor + 2, 1) }; - return instance; + return [item, null, cursor + 3]; } - function toConstant(code) { - switch (code) { - case 246: - return null; - case 247: - return; - case 248: - return false; - case 249: - return true; - } - throw new Error("Unknown constant"); + function extractISOTime(match2, cursor) { + const item = { + hours: int(match2, cursor, 0), + minutes: int(match2, cursor + 1, 0), + seconds: int(match2, cursor + 2, 0), + milliseconds: parseMillis(match2[cursor + 3]) + }; + return [item, null, cursor + 4]; } - function withSource(get) { - return function() { - return get(this[sourceSymbol]); - }; - } - function saveState() { - if (currentSource) { - currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd); - currentSource.position = 0; - currentSource.bytesEnd = currentSource.bytes.length; - } - } - function prepareStructures(structures, packr) { - if (packr.typedStructs) { - let structMap = new Map; - structMap.set("named", structures); - structMap.set("typed", packr.typedStructs); - structures = structMap; - } - let lastTypedStructuresLength = packr.lastTypedStructuresLength || 0; - structures.isCompatible = (existing) => { - let compatible = true; - if (existing instanceof Map) { - let named = existing.get("named") || []; - if (named.length !== (packr.lastNamedStructuresLength || 0)) - compatible = false; - let typed = existing.get("typed") || []; - if (typed.length !== lastTypedStructuresLength) - compatible = false; - } else if (existing instanceof Array || Array.isArray(existing)) { - if (existing.length !== (packr.lastNamedStructuresLength || 0)) - compatible = false; - } - if (!compatible) - packr._mergeStructures(existing); - return compatible; - }; - packr.lastTypedStructuresLength = packr.typedStructs && packr.typedStructs.length; - return structures; - } - setReadStruct(readStruct, onLoadedStructures, saveState); - - class PackrStream extends stream.Transform { - constructor(options) { - if (!options) - options = {}; - options.writableObjectMode = true; - super(options); - options.sequential = true; - this.packr = options.packr || new Packr(options); - } - _transform(value, encoding, callback) { - this.push(this.packr.pack(value)); - callback(); - } + function extractISOOffset(match2, cursor) { + const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); + return [{}, zone, cursor + 3]; } - - class UnpackrStream extends stream.Transform { - constructor(options) { - if (!options) - options = {}; - options.objectMode = true; - super(options); - options.structures = []; - this.unpackr = options.unpackr || new Unpackr(options); - } - _transform(chunk, encoding, callback) { - if (this.incompleteBuffer) { - chunk = Buffer.concat([this.incompleteBuffer, chunk]); - this.incompleteBuffer = null; - } - let values; - try { - values = this.unpackr.unpackMultiple(chunk); - } catch (error) { - if (error.incomplete) { - this.incompleteBuffer = chunk.slice(error.lastPosition); - values = error.values; - } else - throw error; - } finally { - for (let value of values || []) { - if (value === null) - value = this.getNullValue(); - this.push(value); - } - } - if (callback) - callback(); - } - getNullValue() { - return Symbol.for(null); + function extractIANAZone(match2, cursor) { + const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null; + return [{}, zone, cursor + 1]; + } + var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); + var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; + function extractISODuration(match2) { + const [s3, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2; + const hasNegativePrefix = s3[0] === "-"; + const negativeSeconds = secondStr && secondStr[0] === "-"; + const maybeNegate = (num, force = false) => num !== undefined && (force || num && hasNegativePrefix) ? -num : num; + return [{ + years: maybeNegate(parseFloating(yearStr)), + months: maybeNegate(parseFloating(monthStr)), + weeks: maybeNegate(parseFloating(weekStr)), + days: maybeNegate(parseFloating(dayStr)), + hours: maybeNegate(parseFloating(hourStr)), + minutes: maybeNegate(parseFloating(minuteStr)), + seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), + milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) + }]; + } + var obsOffsets = { + GMT: 0, + EDT: -4 * 60, + EST: -5 * 60, + CDT: -5 * 60, + CST: -6 * 60, + MDT: -6 * 60, + MST: -7 * 60, + PDT: -7 * 60, + PST: -8 * 60 + }; + function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { + const result = { + year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), + month: monthsShort.indexOf(monthStr) + 1, + day: parseInteger(dayStr), + hour: parseInteger(hourStr), + minute: parseInteger(minuteStr) + }; + if (secondStr) + result.second = parseInteger(secondStr); + if (weekdayStr) { + result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; } + return result; } - function packIter(objectIterator, options = {}) { - if (!objectIterator || typeof objectIterator !== "object") { - throw new Error("first argument must be an Iterable, Async Iterable, or a Promise for an Async Iterable"); - } else if (typeof objectIterator[Symbol.iterator] === "function") { - return packIterSync(objectIterator, options); - } else if (typeof objectIterator.then === "function" || typeof objectIterator[Symbol.asyncIterator] === "function") { - return packIterAsync(objectIterator, options); + var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; + function extractRFC2822(match2) { + const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + let offset2; + if (obsOffset) { + offset2 = obsOffsets[obsOffset]; + } else if (milOffset) { + offset2 = 0; } else { - throw new Error("first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a Promise"); + offset2 = signedOffset(offHourStr, offMinuteStr); } + return [result, new FixedOffsetZone(offset2)]; } - function* packIterSync(objectIterator, options) { - const packr = new Packr(options); - for (const value of objectIterator) { - yield packr.pack(value); - } + function preprocessRFC2822(s3) { + return s3.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); } - async function* packIterAsync(objectIterator, options) { - const packr = new Packr(options); - for await (const value of objectIterator) { - yield packr.pack(value); - } + var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; + var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; + var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; + function extractRFC1123Or850(match2) { + const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; } - function unpackIter(bufferIterator, options = {}) { - if (!bufferIterator || typeof bufferIterator !== "object") { - throw new Error("first argument must be an Iterable, Async Iterable, Iterator, Async Iterator, or a promise"); - } - const unpackr = new Unpackr(options); - let incomplete; - const parser = (chunk) => { - let yields; - if (incomplete) { - chunk = Buffer.concat([incomplete, chunk]); - incomplete = undefined; - } - try { - yields = unpackr.unpackMultiple(chunk); - } catch (err) { - if (err.incomplete) { - incomplete = chunk.slice(err.lastPosition); - yields = err.values; - } else { - throw err; - } - } - return yields; - }; - if (typeof bufferIterator[Symbol.iterator] === "function") { - return function* iter() { - for (const value of bufferIterator) { - yield* parser(value); - } - }(); - } else if (typeof bufferIterator[Symbol.asyncIterator] === "function") { - return async function* iter() { - for await (const value of bufferIterator) { - yield* parser(value); - } - }(); - } + function extractASCII(match2) { + const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); + return [result, FixedOffsetZone.utcInstance]; } - var decodeIter = unpackIter; - var encodeIter = packIter; - var useRecords = false; - var mapsAsObjects = true; - var nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === "true"; - if (!nativeAccelerationDisabled) { - let extractor; - try { - if (true) - extractor = require_msgpackr_extract(); - else - ; - if (extractor) - setExtractor(extractor.extractStrings); - } catch (error) {} + var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); + var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); + var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); + var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); + var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); + var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone); + var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone); + var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); + function parseISODate(s3) { + return parse2(s3, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); } - exports.ALWAYS = ALWAYS; - exports.C1 = C1; - exports.DECIMAL_FIT = DECIMAL_FIT; - exports.DECIMAL_ROUND = DECIMAL_ROUND; - exports.Decoder = Decoder; - exports.DecoderStream = UnpackrStream; - exports.Encoder = Encoder; - exports.EncoderStream = PackrStream; - exports.FLOAT32_OPTIONS = FLOAT32_OPTIONS; - exports.NEVER = NEVER; - exports.Packr = Packr; - exports.PackrStream = PackrStream; - exports.RESERVE_START_SPACE = RESERVE_START_SPACE; - exports.RESET_BUFFER_MODE = RESET_BUFFER_MODE; - exports.REUSE_BUFFER_MODE = REUSE_BUFFER_MODE; - exports.Unpackr = Unpackr; - exports.UnpackrStream = UnpackrStream; - exports.addExtension = addExtension; - exports.clearSource = clearSource; - exports.decode = decode; - exports.decodeIter = decodeIter; - exports.encode = encode; - exports.encodeIter = encodeIter; - exports.mapsAsObjects = mapsAsObjects; - exports.pack = pack; - exports.roundFloat32 = roundFloat32; - exports.unpack = unpack; - exports.unpackMultiple = unpackMultiple; - exports.useRecords = useRecords; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts.js -var require_scripts = __commonJS((exports, module) => { - var _ = require_lodash11(); - var msgpackr = require_node4(); - var packer = new msgpackr.Packr({ - useRecords: false, - encodeUndefinedAsNil: true - }); - var pack = packer.pack; - var scripts = { - isJobInList(client, listKey, jobId) { - return client.isJobInList([listKey, jobId]).then((result) => { - return result === 1; - }); - }, - addJob(client, queue, job, opts) { - const queueKeys = queue.keys; - let keys = [ - queueKeys.wait, - queueKeys.paused, - queueKeys["meta-paused"], - queueKeys.id, - queueKeys.delayed, - queueKeys.priority - ]; - const args = [ - queueKeys[""], - _.isUndefined(opts.customJobId) ? "" : opts.customJobId, - job.name, - job.data, - pack(job.opts), - job.timestamp, - job.delay, - job.delay ? job.timestamp + job.delay : 0, - opts.priority || 0, - opts.lifo ? "RPUSH" : "LPUSH", - queue.token, - job.debounceId ? `${queueKeys.de}:${job.debounceId}` : null, - opts.debounce ? opts.debounce.id : null, - opts.debounce ? opts.debounce.ttl : null - ]; - keys = keys.concat(args); - return client.addJob(keys); - }, - pause(queue, pause) { - let src = "wait", dst = "paused"; - if (!pause) { - src = "paused"; - dst = "wait"; - } - const keys = _.map([src, dst, "meta-paused", pause ? "paused" : "resumed", "meta"], (name) => { - return queue.toKey(name); - }); - return queue.client.pause(keys.concat([pause ? "paused" : "resumed"])); - }, - async addLog(queue, jobId, logRow, keepLogs) { - const client = await queue.client; - const keys = [queue.toKey(jobId), queue.toKey(jobId) + ":logs"]; - const result = await client.addLog(keys.concat([jobId, logRow, keepLogs ? keepLogs : ""])); - if (result < 0) { - throw scripts.finishedErrors(result, jobId, "addLog"); - } - return result; + function parseRFC2822Date(s3) { + return parse2(preprocessRFC2822(s3), [rfc2822, extractRFC2822]); + } + function parseHTTPDate(s3) { + return parse2(s3, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); + } + function parseISODuration(s3) { + return parse2(s3, [isoDuration, extractISODuration]); + } + var extractISOTimeOnly = combineExtractors(extractISOTime); + function parseISOTimeOnly(s3) { + return parse2(s3, [isoTimeOnly, extractISOTimeOnly]); + } + var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); + var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); + var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); + function parseSQL(s3) { + return parse2(s3, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); + } + var INVALID$2 = "Invalid Duration"; + var lowOrderMatrix = { + weeks: { + days: 7, + hours: 7 * 24, + minutes: 7 * 24 * 60, + seconds: 7 * 24 * 60 * 60, + milliseconds: 7 * 24 * 60 * 60 * 1000 }, - getCountsPerPriorityArgs(queue, priorities) { - const keys = [ - queue.keys.wait, - queue.keys.paused, - queue.keys["meta-paused"], - queue.keys.priority - ]; - const args = priorities; - return keys.concat(args); + days: { + hours: 24, + minutes: 24 * 60, + seconds: 24 * 60 * 60, + milliseconds: 24 * 60 * 60 * 1000 }, - async getCountsPerPriority(queue, priorities) { - const client = await queue.client; - const args = this.getCountsPerPriorityArgs(queue, priorities); - return client.getCountsPerPriority(args); - }, - moveToActive(queue, jobId) { - const queueKeys = queue.keys; - const keys = [queueKeys.wait, queueKeys.active, queueKeys.priority]; - keys[3] = keys[1] + "@" + queue.token; - keys[4] = queueKeys.stalled; - keys[5] = queueKeys.limiter; - keys[6] = queueKeys.delayed; - keys[7] = queueKeys.drained; - const args = [ - queueKeys[""], - queue.token, - queue.settings.lockDuration, - Date.now(), - jobId - ]; - if (queue.limiter) { - args.push(queue.limiter.max, queue.limiter.duration, !!queue.limiter.bounceBack); - queue.limiter.groupKey && args.push(true); - } - return queue.client.moveToActive(keys.concat(args)).then(raw2jobData); + hours: { + minutes: 60, + seconds: 60 * 60, + milliseconds: 60 * 60 * 1000 }, - updateProgress(job, progress) { - const queue = job.queue; - const keys = [job.id, "progress"].map((name) => { - return queue.toKey(name); - }); - const progressJson = JSON.stringify(progress); - return queue.client.updateProgress(keys, [ - progressJson, - JSON.stringify({ jobId: job.id, progress }) - ]).then((code) => { - if (code < 0) { - throw scripts.finishedErrors(code, job.id, "updateProgress"); - } - queue.emit("progress", job, progress); - }); + minutes: { + seconds: 60, + milliseconds: 60 * 1000 }, - updateData(job, data) { - const queue = job.queue; - const keys = [job.id].map((name) => { - return queue.toKey(name); - }); - const dataJson = JSON.stringify(data); - return queue.client.updateData(keys, [dataJson]); + seconds: { + milliseconds: 1000 + } + }; + var casualMatrix = { + years: { + quarters: 4, + months: 12, + weeks: 52, + days: 365, + hours: 365 * 24, + minutes: 365 * 24 * 60, + seconds: 365 * 24 * 60 * 60, + milliseconds: 365 * 24 * 60 * 60 * 1000 }, - saveStacktraceArgs(job, stacktrace, failedReason) { - const queue = job.queue; - const keys = [queue.toKey(job.id)]; - return keys.concat([stacktrace, failedReason, job.attemptsMade]); + quarters: { + months: 3, + weeks: 13, + days: 91, + hours: 91 * 24, + minutes: 91 * 24 * 60, + seconds: 91 * 24 * 60 * 60, + milliseconds: 91 * 24 * 60 * 60 * 1000 }, - retryJobsArgs(queue, count) { - const keys = [ - queue.toKey(""), - queue.toKey("failed"), - queue.toKey("wait"), - queue.toKey("meta-paused"), - queue.toKey("paused") - ]; - const args = [count]; - return keys.concat(args); + months: { + weeks: 4, + days: 30, + hours: 30 * 24, + minutes: 30 * 24 * 60, + seconds: 30 * 24 * 60 * 60, + milliseconds: 30 * 24 * 60 * 60 * 1000 }, - async retryJobs(queue, count = 1000) { - const client = await queue.client; - const args = this.retryJobsArgs(queue, count); - return client.retryJobs(args); + ...lowOrderMatrix + }; + var daysInYearAccurate = 146097 / 400; + var daysInMonthAccurate = 146097 / 4800; + var accurateMatrix = { + years: { + quarters: 4, + months: 12, + weeks: daysInYearAccurate / 7, + days: daysInYearAccurate, + hours: daysInYearAccurate * 24, + minutes: daysInYearAccurate * 24 * 60, + seconds: daysInYearAccurate * 24 * 60 * 60, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 }, - moveToFinishedArgs(job, val, propVal, shouldRemove, target, ignoreLock, notFetch) { - const queue = job.queue; - const queueKeys = queue.keys; - const metricsKey = queue.toKey(`metrics:${target}`); - const keys = [ - queueKeys.active, - queueKeys[target], - queue.toKey(job.id), - queueKeys.wait, - queueKeys.priority, - queueKeys.active + "@" + queue.token, - queueKeys.delayed, - queueKeys.stalled, - metricsKey - ]; - const keepJobs = pack(typeof shouldRemove === "object" ? shouldRemove : typeof shouldRemove === "number" ? { count: shouldRemove } : { count: shouldRemove ? 0 : -1 }); - const args = [ - job.id, - job.finishedOn, - propVal, - _.isUndefined(val) ? "null" : val, - ignoreLock ? "0" : queue.token, - keepJobs, - JSON.stringify({ jobId: job.id, val }), - notFetch || queue.paused || queue.closing || queue.limiter ? 0 : 1, - queueKeys[""], - queue.settings.lockDuration, - queue.token, - queue.metrics && queue.metrics.maxDataPoints - ]; - return keys.concat(args); + quarters: { + months: 3, + weeks: daysInYearAccurate / 28, + days: daysInYearAccurate / 4, + hours: daysInYearAccurate * 24 / 4, + minutes: daysInYearAccurate * 24 * 60 / 4, + seconds: daysInYearAccurate * 24 * 60 * 60 / 4, + milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4 }, - moveToFinished(job, val, propVal, shouldRemove, target, ignoreLock, notFetch = false) { - const args = scripts.moveToFinishedArgs(job, val, propVal, shouldRemove, target, ignoreLock, notFetch, job.queue.toKey("")); - return job.queue.client.moveToFinished(args).then((result) => { - if (result < 0) { - throw scripts.finishedErrors(result, job.id, "finished", "active"); - } else if (result) { - return raw2jobData(result); - } - return 0; - }); + months: { + weeks: daysInMonthAccurate / 7, + days: daysInMonthAccurate, + hours: daysInMonthAccurate * 24, + minutes: daysInMonthAccurate * 24 * 60, + seconds: daysInMonthAccurate * 24 * 60 * 60, + milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 }, - finishedErrors(code, jobId, command, state) { - switch (code) { - case -1: - return new Error("Missing key for job " + jobId + " " + command); - case -2: - return new Error("Missing lock for job " + jobId + " " + command); - case -3: - return new Error(`Job ${jobId} is not in the ${state} state. ${command}`); - case -6: - return new Error(`Lock mismatch for job ${jobId}. Cmd ${command} from ${state}`); + ...lowOrderMatrix + }; + var orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"]; + var reverseUnits = orderedUnits$1.slice(0).reverse(); + function clone$1(dur, alts, clear = false) { + const conf = { + values: clear ? alts.values : { + ...dur.values, + ...alts.values || {} + }, + loc: dur.loc.clone(alts.loc), + conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, + matrix: alts.matrix || dur.matrix + }; + return new Duration(conf); + } + function durationToMillis(matrix, vals) { + var _vals$milliseconds; + let sum = (_vals$milliseconds = vals.milliseconds) != null ? _vals$milliseconds : 0; + for (const unit of reverseUnits.slice(1)) { + if (vals[unit]) { + sum += vals[unit] * matrix[unit]["milliseconds"]; } - }, - moveToCompleted(job, returnvalue, removeOnComplete, ignoreLock, notFetch = false) { - return scripts.moveToFinished(job, returnvalue, "returnvalue", removeOnComplete, "completed", ignoreLock, notFetch); - }, - moveToFailedArgs(job, failedReason, removeOnFailed, ignoreLock) { - return scripts.moveToFinishedArgs(job, failedReason, "failedReason", removeOnFailed, "failed", ignoreLock, true); - }, - moveToFailed(job, failedReason, removeOnFailed, ignoreLock) { - const args = scripts.moveToFailedArgs(job, failedReason, removeOnFailed, ignoreLock); - return scripts.moveToFinished(args); - }, - isFinished(job) { - const keys = _.map(["completed", "failed"], (key) => { - return job.queue.toKey(key); - }); - return job.queue.client.isFinished(keys.concat([job.id])); - }, - moveToDelayedArgs(queue, jobId, timestamp2, ignoreLock) { - timestamp2 = _.isUndefined(timestamp2) ? 0 : timestamp2; - timestamp2 = +timestamp2 || 0; - timestamp2 = timestamp2 < 0 ? 0 : timestamp2; - if (timestamp2 > 0) { - timestamp2 = timestamp2 * 4096 + (jobId & 4095); + } + return sum; + } + function normalizeValues(matrix, vals) { + const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; + orderedUnits$1.reduceRight((previous, current) => { + if (!isUndefined(vals[current])) { + if (previous) { + const previousVal = vals[previous] * factor; + const conv = matrix[current][previous]; + const rollUp = Math.floor(previousVal / conv); + vals[current] += rollUp * factor; + vals[previous] -= rollUp * conv * factor; + } + return current; + } else { + return previous; } - const keys = _.map(["active", "delayed", jobId, "stalled"], (name) => { - return queue.toKey(name); - }); - return keys.concat([ - JSON.stringify(timestamp2), - jobId, - ignoreLock ? "0" : queue.token - ]); - }, - moveToDelayed(queue, jobId, timestamp2, ignoreLock) { - const args = scripts.moveToDelayedArgs(queue, jobId, timestamp2, ignoreLock); - return queue.client.moveToDelayed(args).then((result) => { - switch (result) { - case -1: - throw new Error("Missing Job " + jobId + " when trying to move from active to delayed"); - case -2: - throw new Error("Job " + jobId + " was locked when trying to move from active to delayed"); + }, null); + orderedUnits$1.reduce((previous, current) => { + if (!isUndefined(vals[current])) { + if (previous) { + const fraction = vals[previous] % 1; + vals[previous] -= fraction; + vals[current] += fraction * matrix[previous][current]; } - }); - }, - remove(queue, jobId) { - const keys = [ - queue.keys.active, - queue.keys.wait, - queue.keys.delayed, - queue.keys.paused, - queue.keys.completed, - queue.keys.failed, - queue.keys.priority, - queue.toKey(jobId), - queue.toKey(`${jobId}:logs`), - queue.keys.limiter, - queue.toKey("") - ]; - return queue.client.removeJob(keys.concat([jobId, queue.token])); - }, - async removeWithPattern(queue, pattern) { - const keys = [ - queue.keys.active, - queue.keys.wait, - queue.keys.delayed, - queue.keys.paused, - queue.keys.completed, - queue.keys.failed, - queue.keys.priority, - queue.keys.limiter - ]; - const allRemoved = []; - let cursor = "0", removed; - do { - [cursor, removed] = await queue.client.removeJobs(keys.concat([queue.toKey(""), pattern, cursor])); - allRemoved.push.apply(allRemoved, removed); - } while (cursor !== "0"); - return allRemoved; - }, - extendLock(queue, jobId, duration) { - return queue.client.extendLock([ - queue.toKey(jobId) + ":lock", - queue.keys.stalled, - queue.token, - duration, - jobId - ]); - }, - releaseLock(queue, jobId) { - return queue.client.releaseLock([ - queue.toKey(jobId) + ":lock", - queue.token - ]); - }, - takeLock(queue, job) { - return queue.client.takeLock([ - job.lockKey(), - queue.token, - queue.settings.lockDuration - ]); - }, - updateDelaySet(queue, delayedTimestamp) { - const keys = [ - queue.keys.delayed, - queue.keys.active, - queue.keys.wait, - queue.keys.priority, - queue.keys.paused, - queue.keys["meta-paused"] - ]; - const args = [queue.toKey(""), delayedTimestamp, queue.token]; - return queue.client.updateDelaySet(keys.concat(args)); - }, - promote(queue, jobId) { - const keys = [ - queue.keys.delayed, - queue.keys.wait, - queue.keys.paused, - queue.keys["meta-paused"], - queue.keys.priority - ]; - const args = [queue.toKey(""), jobId, queue.token]; - return queue.client.promote(keys.concat(args)); - }, - moveUnlockedJobsToWait(queue) { - const keys = [ - queue.keys.stalled, - queue.keys.wait, - queue.keys.active, - queue.keys.failed, - queue.keys["stalled-check"], - queue.keys["meta-paused"], - queue.keys.paused - ]; - const args = [ - queue.settings.maxStalledCount, - queue.toKey(""), - Date.now(), - queue.settings.stalledInterval - ]; - return queue.client.moveStalledJobsToWait(keys.concat(args)); - }, - cleanJobsInSet(queue, set, ts, limit) { - return queue.client.cleanJobsInSet([ - queue.toKey(set), - queue.toKey("priority"), - queue.keys.limiter, - queue.toKey(""), - ts, - limit || 0, - set - ]); - }, - retryJobArgs(job, ignoreLock) { - const queue = job.queue; - const jobId = job.id; - const keys = _.map(["active", "wait", jobId, "meta-paused", "paused", "stalled", "priority"], (name) => { - return queue.toKey(name); - }); - const pushCmd = (job.opts.lifo ? "R" : "L") + "PUSH"; - return keys.concat([pushCmd, jobId, ignoreLock ? "0" : job.queue.token]); - }, - reprocessJob(job, options) { - const queue = job.queue; - const keys = [ - queue.toKey(job.id), - queue.toKey(job.id) + ":lock", - queue.toKey(options.state), - queue.toKey("wait"), - queue.toKey("meta-paused"), - queue.toKey("paused") - ]; - const args = [ - job.id, - (job.opts.lifo ? "R" : "L") + "PUSH", - queue.token, - Date.now() - ]; - return queue.client.reprocessJob(keys.concat(args)); - }, - obliterate(queue, opts) { - const client = queue.client; - const keys = [queue.keys["meta-paused"], queue.toKey("")]; - const args = [opts.count, opts.force ? "force" : null]; - return client.obliterate(keys.concat(args)).then((result) => { - if (result < 0) { - switch (result) { - case -1: - throw new Error("Cannot obliterate non-paused queue"); - case -2: - throw new Error("Cannot obliterate queue with active jobs"); - } - } - return result; - }); - } - }; - module.exports = scripts; - function array2obj(arr) { - const obj = {}; - for (let i2 = 0;i2 < arr.length; i2 += 2) { - obj[arr[i2]] = arr[i2 + 1]; - } - return obj; + return current; + } else { + return previous; + } + }, null); } - function raw2jobData(raw) { - if (raw) { - const jobData = raw[0]; - if (jobData.length) { - const job = array2obj(jobData); - return [job, raw[1]]; + function removeZeroes(vals) { + const newVals = {}; + for (const [key, value] of Object.entries(vals)) { + if (value !== 0) { + newVals[key] = value; } } - return []; + return newVals; } -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/errors.js -var require_errors11 = __commonJS((exports, module) => { - exports.Messages = { - RETRY_JOB_NOT_EXIST: "Couldn't retry job: The job doesn't exist", - RETRY_JOB_IS_LOCKED: "Couldn't retry job: The job is locked", - RETRY_JOB_NOT_FAILED: "Couldn't retry job: The job has been already retried or has not failed", - MISSING_REDIS_OPTS: `Using a redis instance with enableReadyCheck or maxRetriesPerRequest for bclient/subscriber is not permitted. - see https://github.com/OptimalBits/bull/issues/1873 - ` - }; -}); -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/backoffs.js -var require_backoffs = __commonJS((exports, module) => { - var _ = require_lodash11(); - var builtinStrategies = { - fixed(delay) { - return function() { - return delay; - }; - }, - exponential(delay) { - return function(attemptsMade) { - return Math.round((Math.pow(2, attemptsMade) - 1) * delay); - }; - } - }; - function lookupStrategy(backoff, customStrategies) { - if (backoff.type in customStrategies) { - return customStrategies[backoff.type]; - } else if (backoff.type in builtinStrategies) { - return builtinStrategies[backoff.type](backoff.delay); - } else { - throw new Error("Unknown backoff strategy " + backoff.type + ". If a custom backoff strategy is used, specify it when the queue is created."); - } - } - module.exports = { - normalize(backoff) { - if (_.isFinite(backoff)) { - return { - type: "fixed", - delay: backoff - }; - } else if (backoff) { - return backoff; - } - }, - calculate(backoff, attemptsMade, customStrategies, err, strategyOptions) { - if (backoff) { - const strategy = lookupStrategy(backoff, customStrategies, strategyOptions); - return strategy(attemptsMade, err, strategyOptions); + class Duration { + constructor(config) { + const accurate = config.conversionAccuracy === "longterm" || false; + let matrix = accurate ? accurateMatrix : casualMatrix; + if (config.matrix) { + matrix = config.matrix; } + this.values = config.values; + this.loc = config.loc || Locale.create(); + this.conversionAccuracy = accurate ? "longterm" : "casual"; + this.invalid = config.invalid || null; + this.matrix = matrix; + this.isLuxonDuration = true; } - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/job.js -var require_job = __commonJS((exports, module) => { - var _ = require_lodash11(); - var utils = require_utils12(); - var scripts = require_scripts(); - var debuglog = __require("util").debuglog("bull"); - var errors = require_errors11(); - var backoffs = require_backoffs(); - var FINISHED_WATCHDOG = 5000; - var DEFAULT_JOB_NAME = "__default__"; - var jobFields = [ - "opts", - "name", - "id", - "progress", - "delay", - "timestamp", - "finishedOn", - "processedOn", - "retriedOn", - "failedReason", - "attemptsMade", - "stacktrace", - "returnvalue" - ]; - var Job = function(queue, name, data, opts) { - if (typeof name !== "string") { - opts = data; - data = name; - name = DEFAULT_JOB_NAME; + static fromMillis(count2, opts) { + return Duration.fromObject({ + milliseconds: count2 + }, opts); } - this.opts = setDefaultOpts(opts); - this.name = name; - this.queue = queue; - this.data = data; - this._progress = 0; - this.delay = this.opts.delay < 0 ? 0 : this.opts.delay; - this.timestamp = this.opts.timestamp; - this.stacktrace = []; - this.returnvalue = null; - this.attemptsMade = 0; - this.toKey = _.bind(queue.toKey, queue); - this.debounceId = this.opts.debounce ? this.opts.debounce.id : undefined; - }; - function setDefaultOpts(opts) { - const _opts = Object.assign({}, opts); - _opts.attempts = typeof _opts.attempts == "undefined" ? 1 : _opts.attempts; - _opts.delay = typeof _opts.delay == "undefined" ? 0 : Number(_opts.delay); - _opts.timestamp = typeof _opts.timestamp == "undefined" ? Date.now() : _opts.timestamp; - _opts.attempts = parseInt(_opts.attempts); - _opts.backoff = backoffs.normalize(_opts.backoff); - return _opts; - } - Job.DEFAULT_JOB_NAME = DEFAULT_JOB_NAME; - function addJob(queue, client, job) { - const opts = job.opts; - const jobData = job.toData(); - return scripts.addJob(client, queue, jobData, { - lifo: opts.lifo, - customJobId: opts.jobId, - priority: opts.priority, - debounce: opts.debounce - }); - } - Job.create = function(queue, name, data, opts) { - const job = new Job(queue, name, data, opts); - return queue.isReady().then(() => { - return addJob(queue, queue.client, job); - }).then((jobId) => { - job.id = jobId; - debuglog("Job added", jobId); - return job; - }); - }; - Job.createBulk = function(queue, jobs) { - jobs = jobs.map((job) => new Job(queue, job.name, job.data, job.opts)); - return queue.isReady().then(() => { - const multi = queue.client.multi(); - for (const job of jobs) { - addJob(queue, multi, job); + static fromObject(obj, opts = {}) { + if (obj == null || typeof obj !== "object") { + throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`); } - return multi.exec(); - }).then((res) => { - res.forEach((res2, index2) => { - jobs[index2].id = res2[1]; - debuglog("Job added", res2[1]); + return new Duration({ + values: normalizeObject(obj, Duration.normalizeUnit), + loc: Locale.fromObject(opts), + conversionAccuracy: opts.conversionAccuracy, + matrix: opts.matrix }); - return jobs; - }); - }; - Job.fromId = async function(queue, jobId, opts) { - if (!jobId) { - return Promise.resolve(); } - const jobKey = queue.toKey(jobId); - let rawJob; - if (opts && opts.excludeData) { - rawJob = _.zipObject(jobFields, await queue.client.hmget(jobKey, jobFields)); - } else { - rawJob = await queue.client.hgetall(jobKey); + static fromDurationLike(durationLike) { + if (isNumber(durationLike)) { + return Duration.fromMillis(durationLike); + } else if (Duration.isDuration(durationLike)) { + return durationLike; + } else if (typeof durationLike === "object") { + return Duration.fromObject(durationLike); + } else { + throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`); + } } - return _.isEmpty(rawJob) ? null : Job.fromJSON(queue, rawJob, jobId); - }; - Job.remove = async function(queue, pattern) { - await queue.isReady(); - const removed = await scripts.removeWithPattern(queue, pattern); - removed.forEach((jobId) => queue.emit("removed", jobId)); - }; - Job.prototype.progress = function(progress) { - if (_.isUndefined(progress)) { - return this._progress; + static fromISO(text3, opts) { + const [parsed] = parseISODuration(text3); + if (parsed) { + return Duration.fromObject(parsed, opts); + } else { + return Duration.invalid("unparsable", `the input "${text3}" can't be parsed as ISO 8601`); + } } - this._progress = progress; - return scripts.updateProgress(this, progress); - }; - Job.prototype.update = async function(data) { - this.data = data; - const code = await scripts.updateData(this, data); - if (code < 0) { - throw scripts.finishedErrors(code, this.id, "updateData"); + static fromISOTime(text3, opts) { + const [parsed] = parseISOTimeOnly(text3); + if (parsed) { + return Duration.fromObject(parsed, opts); + } else { + return Duration.invalid("unparsable", `the input "${text3}" can't be parsed as ISO 8601`); + } } - }; - Job.prototype.toJSON = function() { - const opts = Object.assign({}, this.opts); - return { - id: this.id, - name: this.name, - data: this.data || {}, - opts, - progress: this._progress, - delay: this.delay, - timestamp: this.timestamp, - attemptsMade: this.attemptsMade, - failedReason: this.failedReason, - stacktrace: this.stacktrace || null, - returnvalue: this.returnvalue || null, - debounceId: this.debounceId || null, - finishedOn: this.finishedOn || null, - processedOn: this.processedOn || null - }; - }; - Job.prototype.toData = function() { - const json2 = this.toJSON(); - json2.data = JSON.stringify(json2.data); - json2.opts = JSON.stringify(json2.opts); - json2.stacktrace = JSON.stringify(json2.stacktrace); - json2.failedReason = JSON.stringify(json2.failedReason); - json2.returnvalue = JSON.stringify(json2.returnvalue); - return json2; - }; - Job.prototype.lockKey = function() { - return this.toKey(this.id) + ":lock"; - }; - Job.prototype.takeLock = function() { - return scripts.takeLock(this.queue, this).then((lock) => { - return lock || false; - }); - }; - Job.prototype.releaseLock = function() { - return scripts.releaseLock(this.queue, this.id).then((unlocked) => { - if (unlocked != 1) { - throw new Error("Could not release lock for job " + this.id); - } - }); - }; - Job.prototype.extendLock = function(duration) { - return scripts.extendLock(this.queue, this.id, duration); - }; - Job.prototype.moveToCompleted = function(returnValue, ignoreLock, notFetch = false) { - return this.queue.isReady().then(() => { - this.returnvalue = returnValue || 0; - returnValue = utils.tryCatch(JSON.stringify, JSON, [returnValue]); - if (returnValue === utils.errorObject) { - const err = utils.errorObject.value; - return Promise.reject(err); - } - this.finishedOn = Date.now(); - return scripts.moveToCompleted(this, returnValue, this.opts.removeOnComplete, ignoreLock, notFetch); - }); - }; - Job.prototype.discard = function() { - this._discarded = true; - }; - Job.prototype.moveToFailed = async function(err, ignoreLock) { - err = err || { message: "Unknown reason" }; - this.failedReason = err.message; - await this.queue.isReady(); - let command; - const multi = this.queue.client.multi(); - this._saveAttempt(multi, err); - let moveToFailed = false; - if (this.attemptsMade < this.opts.attempts && !this._discarded) { - const delay = await backoffs.calculate(this.opts.backoff, this.attemptsMade, this.queue.settings.backoffStrategies, err, _.get(this, "opts.backoff.options", null)); - if (delay === -1) { - moveToFailed = true; - } else if (delay) { - const args = scripts.moveToDelayedArgs(this.queue, this.id, Date.now() + delay, ignoreLock); - multi.moveToDelayed(args); - command = "delayed"; + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); + } + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { + throw new InvalidDurationError(invalid); } else { - multi.retryJob(scripts.retryJobArgs(this, ignoreLock)); - command = "retry"; + return new Duration({ + invalid + }); } - } else { - moveToFailed = true; } - if (moveToFailed) { - this.finishedOn = Date.now(); - const args = scripts.moveToFailedArgs(this, err.message, this.opts.removeOnFail, ignoreLock); - multi.moveToFinished(args); - command = "failed"; + static normalizeUnit(unit) { + const normalized = { + year: "years", + years: "years", + quarter: "quarters", + quarters: "quarters", + month: "months", + months: "months", + week: "weeks", + weeks: "weeks", + day: "days", + days: "days", + hour: "hours", + hours: "hours", + minute: "minutes", + minutes: "minutes", + second: "seconds", + seconds: "seconds", + millisecond: "milliseconds", + milliseconds: "milliseconds" + }[unit ? unit.toLowerCase() : unit]; + if (!normalized) + throw new InvalidUnitError(unit); + return normalized; + } + static isDuration(o2) { + return o2 && o2.isLuxonDuration || false; } - const results = await multi.exec(); - const code = _.last(results)[1]; - if (code < 0) { - throw scripts.finishedErrors(code, this.id, command, "active"); + get locale() { + return this.isValid ? this.loc.locale : null; } - }; - Job.prototype.moveToDelayed = function(timestamp2, ignoreLock) { - return scripts.moveToDelayed(this.queue, this.id, timestamp2, ignoreLock); - }; - Job.prototype.promote = function() { - const queue = this.queue; - const jobId = this.id; - return queue.isReady().then(() => scripts.promote(queue, jobId).then((result) => { - if (result === -1) { - throw new Error("Job " + jobId + " is not in a delayed state"); - } - })); - }; - Job.prototype.retry = function() { - return this.queue.isReady().then(() => { - this.failedReason = null; - this.finishedOn = null; - this.processedOn = null; - this.retriedOn = Date.now(); - return scripts.reprocessJob(this, { state: "failed" }).then((result) => { - if (result === 1) { - return; - } else if (result === 0) { - throw new Error(errors.Messages.RETRY_JOB_NOT_EXIST); - } else if (result === -1) { - throw new Error(errors.Messages.RETRY_JOB_IS_LOCKED); - } else if (result === -2) { - throw new Error(errors.Messages.RETRY_JOB_NOT_FAILED); + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; + } + toFormat(fmt, opts = {}) { + const fmtOpts = { + ...opts, + floor: opts.round !== false && opts.floor !== false + }; + return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; + } + toHuman(opts = {}) { + if (!this.isValid) + return INVALID$2; + const showZeros = opts.showZeros !== false; + const l3 = orderedUnits$1.map((unit) => { + const val = this.values[unit]; + if (isUndefined(val) || val === 0 && !showZeros) { + return null; } + return this.loc.numberFormatter({ + style: "unit", + unitDisplay: "long", + ...opts, + unit: unit.slice(0, -1) + }).format(val); + }).filter((n3) => n3); + return this.loc.listFormatter({ + type: "conjunction", + style: opts.listStyle || "narrow", + ...opts + }).format(l3); + } + toObject() { + if (!this.isValid) + return {}; + return { + ...this.values + }; + } + toISO() { + if (!this.isValid) + return null; + let s3 = "P"; + if (this.years !== 0) + s3 += this.years + "Y"; + if (this.months !== 0 || this.quarters !== 0) + s3 += this.months + this.quarters * 3 + "M"; + if (this.weeks !== 0) + s3 += this.weeks + "W"; + if (this.days !== 0) + s3 += this.days + "D"; + if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) + s3 += "T"; + if (this.hours !== 0) + s3 += this.hours + "H"; + if (this.minutes !== 0) + s3 += this.minutes + "M"; + if (this.seconds !== 0 || this.milliseconds !== 0) + s3 += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; + if (s3 === "P") + s3 += "T0S"; + return s3; + } + toISOTime(opts = {}) { + if (!this.isValid) + return null; + const millis = this.toMillis(); + if (millis < 0 || millis >= 86400000) + return null; + opts = { + suppressMilliseconds: false, + suppressSeconds: false, + includePrefix: false, + format: "extended", + ...opts, + includeOffset: false + }; + const dateTime = DateTime.fromMillis(millis, { + zone: "UTC" }); - }); - }; - Job.prototype.log = function(logRow) { - return scripts.addLog(this.queue, this.id, logRow); - }; - Job.prototype.isCompleted = function() { - return this._isDone("completed"); - }; - Job.prototype.isFailed = function() { - return this._isDone("failed"); - }; - Job.prototype.isDelayed = function() { - return this._isDone("delayed"); - }; - Job.prototype.isActive = function() { - return this._isInList("active"); - }; - Job.prototype.isWaiting = function() { - return this._isInList("wait"); - }; - Job.prototype.isPaused = function() { - return this._isInList("paused"); - }; - Job.prototype.isStuck = function() { - return this.getState().then((state) => { - return state === "stuck"; - }); - }; - Job.prototype.isDiscarded = function() { - return this._discarded; - }; - Job.prototype.getState = function() { - const fns = [ - { fn: "isCompleted", state: "completed" }, - { fn: "isFailed", state: "failed" }, - { fn: "isDelayed", state: "delayed" }, - { fn: "isActive", state: "active" }, - { fn: "isWaiting", state: "waiting" }, - { fn: "isPaused", state: "paused" } - ]; - return fns.reduce((result, fn) => { - return result.then((state) => { - if (state) { - return state; + return dateTime.toISOTime(opts); + } + toJSON() { + return this.toISO(); + } + toString() { + return this.toISO(); + } + [Symbol.for("nodejs.util.inspect.custom")]() { + if (this.isValid) { + return `Duration { values: ${JSON.stringify(this.values)} }`; + } else { + return `Duration { Invalid, reason: ${this.invalidReason} }`; + } + } + toMillis() { + if (!this.isValid) + return NaN; + return durationToMillis(this.matrix, this.values); + } + valueOf() { + return this.toMillis(); + } + plus(duration) { + if (!this.isValid) + return this; + const dur = Duration.fromDurationLike(duration), result = {}; + for (const k2 of orderedUnits$1) { + if (hasOwnProperty(dur.values, k2) || hasOwnProperty(this.values, k2)) { + result[k2] = dur.get(k2) + this.get(k2); } - return this[fn.fn]().then((result2) => { - return result2 ? fn.state : null; - }); + } + return clone$1(this, { + values: result + }, true); + } + minus(duration) { + if (!this.isValid) + return this; + const dur = Duration.fromDurationLike(duration); + return this.plus(dur.negate()); + } + mapUnits(fn) { + if (!this.isValid) + return this; + const result = {}; + for (const k2 of Object.keys(this.values)) { + result[k2] = asNumber(fn(this.values[k2], k2)); + } + return clone$1(this, { + values: result + }, true); + } + get(unit) { + return this[Duration.normalizeUnit(unit)]; + } + set(values) { + if (!this.isValid) + return this; + const mixed2 = { + ...this.values, + ...normalizeObject(values, Duration.normalizeUnit) + }; + return clone$1(this, { + values: mixed2 }); - }, Promise.resolve()).then((result) => { - return result ? result : "stuck"; - }); - }; - Job.prototype.remove = function() { - const queue = this.queue; - const job = this; - return queue.isReady().then(() => { - return scripts.remove(queue, job.id).then((removed) => { - if (removed) { - queue.emit("removed", job); - } else { - throw new Error("Could not remove job " + job.id); - } + } + reconfigure({ + locale: locale2, + numberingSystem, + conversionAccuracy, + matrix + } = {}) { + const loc = this.loc.clone({ + locale: locale2, + numberingSystem }); - }); - }; - Job.prototype.finished = async function() { - await Promise.all([ - this.queue._registerEvent("global:completed"), - this.queue._registerEvent("global:failed") - ]); - await this.queue.isReady(); - const status = await scripts.isFinished(this); - const finished = status > 0; - if (finished) { - const job = await Job.fromId(this.queue, this.id); - if (status == 2) { - throw new Error(job.failedReason); - } else { - return job.returnvalue; + const opts = { + loc, + matrix, + conversionAccuracy + }; + return clone$1(this, opts); + } + as(unit) { + return this.isValid ? this.shiftTo(unit).get(unit) : NaN; + } + normalize() { + if (!this.isValid) + return this; + const vals = this.toObject(); + normalizeValues(this.matrix, vals); + return clone$1(this, { + values: vals + }, true); + } + rescale() { + if (!this.isValid) + return this; + const vals = removeZeroes(this.normalize().shiftToAll().toObject()); + return clone$1(this, { + values: vals + }, true); + } + shiftTo(...units) { + if (!this.isValid) + return this; + if (units.length === 0) { + return this; } - } else { - return new Promise((resolve, reject) => { - const onCompleted = (jobId, resultValue) => { - if (String(jobId) === String(this.id)) { - let result = undefined; - try { - if (typeof resultValue === "string") { - result = JSON.parse(resultValue); - } - } catch (err) { - debuglog("corrupted resultValue: " + resultValue, err); - } - resolve(result); - removeListeners(); - } - }; - const onFailed = (jobId, failedReason) => { - if (String(jobId) === String(this.id)) { - reject(new Error(failedReason)); - removeListeners(); + units = units.map((u2) => Duration.normalizeUnit(u2)); + const built = {}, accumulated = {}, vals = this.toObject(); + let lastUnit; + for (const k2 of orderedUnits$1) { + if (units.indexOf(k2) >= 0) { + lastUnit = k2; + let own = 0; + for (const ak2 in accumulated) { + own += this.matrix[ak2][k2] * accumulated[ak2]; + accumulated[ak2] = 0; } - }; - this.queue.on("global:completed", onCompleted); - this.queue.on("global:failed", onFailed); - const removeListeners = () => { - clearInterval(interval2); - this.queue.removeListener("global:completed", onCompleted); - this.queue.removeListener("global:failed", onFailed); - }; - const interval2 = setInterval(() => { - if (this._isQueueClosing()) { - removeListeners(); - reject(new Error("cannot check if job is finished in a closing queue.")); - } else { - scripts.isFinished(this).then((status2) => { - const finished2 = status2 > 0; - if (finished2) { - Job.fromId(this.queue, this.id).then((job) => { - removeListeners(); - if (status2 == 2) { - reject(new Error(job.failedReason)); - } else { - resolve(job.returnvalue); - } - }); - } - }); + if (isNumber(vals[k2])) { + own += vals[k2]; } - }, FINISHED_WATCHDOG); - }); + const i2 = Math.trunc(own); + built[k2] = i2; + accumulated[k2] = (own * 1000 - i2 * 1000) / 1000; + } else if (isNumber(vals[k2])) { + accumulated[k2] = vals[k2]; + } + } + for (const key in accumulated) { + if (accumulated[key] !== 0) { + built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; + } + } + normalizeValues(this.matrix, built); + return clone$1(this, { + values: built + }, true); } - }; - Job.prototype._isQueueClosing = function() { - return this.queue.closing; - }; - Job.prototype._isDone = function(list) { - return this.queue.client.zscore(this.queue.toKey(list), this.id).then((score) => { - return score !== null; - }); - }; - Job.prototype._isInList = function(list) { - return scripts.isJobInList(this.queue.client, this.queue.toKey(list), this.id); - }; - Job.prototype._saveAttempt = function(multi, err) { - this.attemptsMade++; - this.stacktrace = this.stacktrace || []; - if (err && err.stack) { - this.stacktrace.push(err.stack); - if (this.opts.stackTraceLimit) { - this.stacktrace = this.stacktrace.slice(-this.opts.stackTraceLimit); + shiftToAll() { + if (!this.isValid) + return this; + return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"); + } + negate() { + if (!this.isValid) + return this; + const negated = {}; + for (const k2 of Object.keys(this.values)) { + negated[k2] = this.values[k2] === 0 ? 0 : -this.values[k2]; } + return clone$1(this, { + values: negated + }, true); } - const args = scripts.saveStacktraceArgs(this, JSON.stringify(this.stacktrace), err && err.message); - multi.saveStacktrace(args); - }; - Job.fromJSON = function(queue, json2, jobId) { - const opts = JSON.parse(json2.opts || "{}"); - const data = opts.preventParsingData ? json2.data : JSON.parse(json2.data || "{}"); - const job = new Job(queue, json2.name || Job.DEFAULT_JOB_NAME, data, opts); - job.id = json2.id || jobId; - try { - job._progress = JSON.parse(json2.progress || 0); - } catch (err) { - console.error(`Error parsing progress ${json2.progress} with ${err.message}`); + removeZeros() { + if (!this.isValid) + return this; + const vals = removeZeroes(this.values); + return clone$1(this, { + values: vals + }, true); } - job.delay = parseInt(json2.delay); - job.timestamp = parseInt(json2.timestamp); - if (json2.finishedOn) { - job.finishedOn = parseInt(json2.finishedOn); + get years() { + return this.isValid ? this.values.years || 0 : NaN; } - if (json2.processedOn) { - job.processedOn = parseInt(json2.processedOn); + get quarters() { + return this.isValid ? this.values.quarters || 0 : NaN; } - if (json2.retriedOn) { - job.retriedOn = parseInt(json2.retriedOn); + get months() { + return this.isValid ? this.values.months || 0 : NaN; } - job.failedReason = json2.failedReason; - job.attemptsMade = parseInt(json2.attemptsMade || 0); - job.stacktrace = getTraces(json2.stacktrace); - if (typeof json2.returnvalue === "string") { - job.returnvalue = getReturnValue(json2.returnvalue); + get weeks() { + return this.isValid ? this.values.weeks || 0 : NaN; } - if (json2.deid) { - job.debounceId = json2.deid; + get days() { + return this.isValid ? this.values.days || 0 : NaN; } - return job; - }; - function getTraces(stacktrace) { - const _traces = utils.tryCatch(JSON.parse, JSON, [stacktrace]); - if (_traces === utils.errorObject || !(_traces instanceof Array)) { - return []; - } else { - return _traces; + get hours() { + return this.isValid ? this.values.hours || 0 : NaN; } - } - function getReturnValue(_value) { - const value = utils.tryCatch(JSON.parse, JSON, [_value]); - if (value !== utils.errorObject) { - return value; - } else { - debuglog("corrupted returnvalue: " + _value, value); + get minutes() { + return this.isValid ? this.values.minutes || 0 : NaN; } - } - module.exports = Job; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/rng.js -var require_rng = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = rng2; - var _crypto = _interopRequireDefault(__require("crypto")); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - var rnds8Pool2 = new Uint8Array(256); - var poolPtr2 = rnds8Pool2.length; - function rng2() { - if (poolPtr2 > rnds8Pool2.length - 16) { - _crypto.default.randomFillSync(rnds8Pool2); - poolPtr2 = 0; + get seconds() { + return this.isValid ? this.values.seconds || 0 : NaN; } - return rnds8Pool2.slice(poolPtr2, poolPtr2 += 16); - } -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/regex.js -var require_regex = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/validate.js -var require_validate = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _regex = _interopRequireDefault(require_regex()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function validate3(uuid2) { - return typeof uuid2 === "string" && _regex.default.test(uuid2); - } - var _default = validate3; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/stringify.js -var require_stringify3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _validate = _interopRequireDefault(require_validate()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - var byteToHex2 = []; - for (let i2 = 0;i2 < 256; ++i2) { - byteToHex2.push((i2 + 256).toString(16).substr(1)); - } - function stringify(arr, offset = 0) { - const uuid2 = (byteToHex2[arr[offset + 0]] + byteToHex2[arr[offset + 1]] + byteToHex2[arr[offset + 2]] + byteToHex2[arr[offset + 3]] + "-" + byteToHex2[arr[offset + 4]] + byteToHex2[arr[offset + 5]] + "-" + byteToHex2[arr[offset + 6]] + byteToHex2[arr[offset + 7]] + "-" + byteToHex2[arr[offset + 8]] + byteToHex2[arr[offset + 9]] + "-" + byteToHex2[arr[offset + 10]] + byteToHex2[arr[offset + 11]] + byteToHex2[arr[offset + 12]] + byteToHex2[arr[offset + 13]] + byteToHex2[arr[offset + 14]] + byteToHex2[arr[offset + 15]]).toLowerCase(); - if (!(0, _validate.default)(uuid2)) { - throw TypeError("Stringified UUID is invalid"); + get milliseconds() { + return this.isValid ? this.values.milliseconds || 0 : NaN; } - return uuid2; - } - var _default = stringify; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/v1.js -var require_v1 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _rng = _interopRequireDefault(require_rng()); - var _stringify = _interopRequireDefault(require_stringify3()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - var _nodeId; - var _clockseq; - var _lastMSecs = 0; - var _lastNSecs = 0; - function v1(options, buf, offset) { - let i2 = buf && offset || 0; - const b2 = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - if (node == null) { - node = _nodeId = [seedBytes[0] | 1, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - if (clockseq == null) { - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 16383; - } - } - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 1e4; - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 16383; - } - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - if (nsecs >= 1e4) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - msecs += 12219292800000; - const tl = ((msecs & 268435455) * 1e4 + nsecs) % 4294967296; - b2[i2++] = tl >>> 24 & 255; - b2[i2++] = tl >>> 16 & 255; - b2[i2++] = tl >>> 8 & 255; - b2[i2++] = tl & 255; - const tmh = msecs / 4294967296 * 1e4 & 268435455; - b2[i2++] = tmh >>> 8 & 255; - b2[i2++] = tmh & 255; - b2[i2++] = tmh >>> 24 & 15 | 16; - b2[i2++] = tmh >>> 16 & 255; - b2[i2++] = clockseq >>> 8 | 128; - b2[i2++] = clockseq & 255; - for (let n2 = 0;n2 < 6; ++n2) { - b2[i2 + n2] = node[n2]; - } - return buf || (0, _stringify.default)(b2); - } - var _default = v1; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/parse.js -var require_parse4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _validate = _interopRequireDefault(require_validate()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function parse2(uuid2) { - if (!(0, _validate.default)(uuid2)) { - throw TypeError("Invalid UUID"); - } - let v2; - const arr = new Uint8Array(16); - arr[0] = (v2 = parseInt(uuid2.slice(0, 8), 16)) >>> 24; - arr[1] = v2 >>> 16 & 255; - arr[2] = v2 >>> 8 & 255; - arr[3] = v2 & 255; - arr[4] = (v2 = parseInt(uuid2.slice(9, 13), 16)) >>> 8; - arr[5] = v2 & 255; - arr[6] = (v2 = parseInt(uuid2.slice(14, 18), 16)) >>> 8; - arr[7] = v2 & 255; - arr[8] = (v2 = parseInt(uuid2.slice(19, 23), 16)) >>> 8; - arr[9] = v2 & 255; - arr[10] = (v2 = parseInt(uuid2.slice(24, 36), 16)) / 1099511627776 & 255; - arr[11] = v2 / 4294967296 & 255; - arr[12] = v2 >>> 24 & 255; - arr[13] = v2 >>> 16 & 255; - arr[14] = v2 >>> 8 & 255; - arr[15] = v2 & 255; - return arr; - } - var _default = parse2; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/v35.js -var require_v35 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = _default; - exports.URL = exports.DNS = undefined; - var _stringify = _interopRequireDefault(require_stringify3()); - var _parse = _interopRequireDefault(require_parse4()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); - const bytes = []; - for (let i2 = 0;i2 < str.length; ++i2) { - bytes.push(str.charCodeAt(i2)); + get isValid() { + return this.invalid === null; } - return bytes; - } - var DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; - exports.DNS = DNS; - var URL2 = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; - exports.URL = URL2; - function _default(name, version2, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === "string") { - value = stringToBytes(value); + get invalidReason() { + return this.invalid ? this.invalid.reason : null; + } + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; + } + equals(other) { + if (!this.isValid || !other.isValid) { + return false; } - if (typeof namespace === "string") { - namespace = (0, _parse.default)(namespace); + if (!this.loc.equals(other.loc)) { + return false; } - if (namespace.length !== 16) { - throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)"); + function eq2(v1, v2) { + if (v1 === undefined || v1 === 0) + return v2 === undefined || v2 === 0; + return v1 === v2; } - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 15 | version2; - bytes[8] = bytes[8] & 63 | 128; - if (buf) { - offset = offset || 0; - for (let i2 = 0;i2 < 16; ++i2) { - buf[offset + i2] = bytes[i2]; + for (const u2 of orderedUnits$1) { + if (!eq2(this.values[u2], other.values[u2])) { + return false; } - return buf; } - return (0, _stringify.default)(bytes); + return true; } - try { - generateUUID.name = name; - } catch (err) {} - generateUUID.DNS = DNS; - generateUUID.URL = URL2; - return generateUUID; - } -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/md5.js -var require_md5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _crypto = _interopRequireDefault(__require("crypto")); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; } - function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === "string") { - bytes = Buffer.from(bytes, "utf8"); + var INVALID$1 = "Invalid Interval"; + function validateStartEnd(start, end) { + if (!start || !start.isValid) { + return Interval.invalid("missing or invalid start"); + } else if (!end || !end.isValid) { + return Interval.invalid("missing or invalid end"); + } else if (end < start) { + return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`); + } else { + return null; } - return _crypto.default.createHash("md5").update(bytes).digest(); - } - var _default = md5; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/v3.js -var require_v3 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _v = _interopRequireDefault(require_v35()); - var _md = _interopRequireDefault(require_md5()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; } - var v3 = (0, _v.default)("v3", 48, _md.default); - var _default = v3; - exports.default = _default; -}); -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/v4.js -var require_v4 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _rng = _interopRequireDefault(require_rng()); - var _stringify = _interopRequireDefault(require_stringify3()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function v42(options, buf, offset) { - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - rnds[6] = rnds[6] & 15 | 64; - rnds[8] = rnds[8] & 63 | 128; - if (buf) { - offset = offset || 0; - for (let i2 = 0;i2 < 16; ++i2) { - buf[offset + i2] = rnds[i2]; + class Interval { + constructor(config) { + this.s = config.start; + this.e = config.end; + this.invalid = config.invalid || null; + this.isLuxonInterval = true; + } + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); + } + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { + throw new InvalidIntervalError(invalid); + } else { + return new Interval({ + invalid + }); } - return buf; } - return (0, _stringify.default)(rnds); - } - var _default = v42; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/sha1.js -var require_sha1 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _crypto = _interopRequireDefault(__require("crypto")); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === "string") { - bytes = Buffer.from(bytes, "utf8"); + static fromDateTimes(start, end) { + const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); + const validateError = validateStartEnd(builtStart, builtEnd); + if (validateError == null) { + return new Interval({ + start: builtStart, + end: builtEnd + }); + } else { + return validateError; + } } - return _crypto.default.createHash("sha1").update(bytes).digest(); - } - var _default = sha1; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/v5.js -var require_v5 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _v = _interopRequireDefault(require_v35()); - var _sha = _interopRequireDefault(require_sha1()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - var v5 = (0, _v.default)("v5", 80, _sha.default); - var _default = v5; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/nil.js -var require_nil = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _default = "00000000-0000-0000-0000-000000000000"; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/version.js -var require_version2 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.default = undefined; - var _validate = _interopRequireDefault(require_validate()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } - function version2(uuid2) { - if (!(0, _validate.default)(uuid2)) { - throw TypeError("Invalid UUID"); + static after(start, duration) { + const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start); + return Interval.fromDateTimes(dt, dt.plus(dur)); } - return parseInt(uuid2.substr(14, 1), 16); - } - var _default = version2; - exports.default = _default; -}); - -// node_modules/.pnpm/uuid@8.3.2/node_modules/uuid/dist/index.js -var require_dist7 = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { - value: true - }); - Object.defineProperty(exports, "v1", { - enumerable: true, - get: function() { - return _v.default; + static before(end, duration) { + const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end); + return Interval.fromDateTimes(dt.minus(dur), dt); } - }); - Object.defineProperty(exports, "v3", { - enumerable: true, - get: function() { - return _v2.default; + static fromISO(text3, opts) { + const [s3, e3] = (text3 || "").split("/", 2); + if (s3 && e3) { + let start, startIsValid; + try { + start = DateTime.fromISO(s3, opts); + startIsValid = start.isValid; + } catch (e4) { + startIsValid = false; + } + let end, endIsValid; + try { + end = DateTime.fromISO(e3, opts); + endIsValid = end.isValid; + } catch (e4) { + endIsValid = false; + } + if (startIsValid && endIsValid) { + return Interval.fromDateTimes(start, end); + } + if (startIsValid) { + const dur = Duration.fromISO(e3, opts); + if (dur.isValid) { + return Interval.after(start, dur); + } + } else if (endIsValid) { + const dur = Duration.fromISO(s3, opts); + if (dur.isValid) { + return Interval.before(end, dur); + } + } + } + return Interval.invalid("unparsable", `the input "${text3}" can't be parsed as ISO 8601`); } - }); - Object.defineProperty(exports, "v4", { - enumerable: true, - get: function() { - return _v3.default; + static isInterval(o2) { + return o2 && o2.isLuxonInterval || false; } - }); - Object.defineProperty(exports, "v5", { - enumerable: true, - get: function() { - return _v4.default; + get start() { + return this.isValid ? this.s : null; } - }); - Object.defineProperty(exports, "NIL", { - enumerable: true, - get: function() { - return _nil.default; + get end() { + return this.isValid ? this.e : null; } - }); - Object.defineProperty(exports, "version", { - enumerable: true, - get: function() { - return _version.default; + get lastDateTime() { + return this.isValid ? this.e ? this.e.minus(1) : null : null; } - }); - Object.defineProperty(exports, "validate", { - enumerable: true, - get: function() { - return _validate.default; + get isValid() { + return this.invalidReason === null; } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return _stringify.default; + get invalidReason() { + return this.invalid ? this.invalid.reason : null; } - }); - Object.defineProperty(exports, "parse", { - enumerable: true, - get: function() { - return _parse.default; + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; } - }); - var _v = _interopRequireDefault(require_v1()); - var _v2 = _interopRequireDefault(require_v3()); - var _v3 = _interopRequireDefault(require_v4()); - var _v4 = _interopRequireDefault(require_v5()); - var _nil = _interopRequireDefault(require_nil()); - var _version = _interopRequireDefault(require_version2()); - var _validate = _interopRequireDefault(require_validate()); - var _stringify = _interopRequireDefault(require_stringify3()); - var _parse = _interopRequireDefault(require_parse4()); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { default: obj }; - } -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/timer-manager.js -var require_timer_manager = __commonJS((exports, module) => { - var _ = require_lodash11(); - var uuid2 = require_dist7(); - function TimerManager() { - this.idle = true; - this.listeners = []; - this.timers = {}; - } - TimerManager.prototype.set = function(name, delay, fn) { - const id = uuid2.v4(); - const timer = setTimeout((timerInstance, timeoutId) => { - timerInstance.clear(timeoutId); - try { - fn(); - } catch (err) { - console.error(err); + length(unit = "milliseconds") { + return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; + } + count(unit = "milliseconds", opts) { + if (!this.isValid) + return NaN; + const start = this.start.startOf(unit, opts); + let end; + if (opts != null && opts.useLocaleWeeks) { + end = this.end.reconfigure({ + locale: start.locale + }); + } else { + end = this.end; } - }, delay, this, id); - this.timers[id] = { - name, - timer - }; - this.idle = false; - return id; - }; - TimerManager.prototype.clear = function(id) { - const timers = this.timers; - const timer = timers[id]; - if (!timer) { - return; + end = end.startOf(unit, opts); + return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf()); + } + hasSame(unit) { + return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; + } + isEmpty() { + return this.s.valueOf() === this.e.valueOf(); + } + isAfter(dateTime) { + if (!this.isValid) + return false; + return this.s > dateTime; + } + isBefore(dateTime) { + if (!this.isValid) + return false; + return this.e <= dateTime; + } + contains(dateTime) { + if (!this.isValid) + return false; + return this.s <= dateTime && this.e > dateTime; + } + set({ + start, + end + } = {}) { + if (!this.isValid) + return this; + return Interval.fromDateTimes(start || this.s, end || this.e); } - clearTimeout(timer.timer); - delete timers[id]; - if (!this.idle && _.size(timers) === 0) { - while (this.listeners.length) { - this.listeners.pop()(); + splitAt(...dateTimes) { + if (!this.isValid) + return []; + const sorted = dateTimes.map(friendlyDateTime).filter((d2) => this.contains(d2)).sort((a2, b2) => a2.toMillis() - b2.toMillis()), results = []; + let { + s: s3 + } = this, i2 = 0; + while (s3 < this.e) { + const added = sorted[i2] || this.e, next = +added > +this.e ? this.e : added; + results.push(Interval.fromDateTimes(s3, next)); + s3 = next; + i2 += 1; } - this.idle = true; + return results; } - }; - TimerManager.prototype.clearAll = function() { - _.each(this.timers, (timer, id) => { - this.clear(id); - }); - }; - TimerManager.prototype.whenIdle = function() { - return new Promise((resolve) => { - if (this.idle) { - resolve(); - } else { - this.listeners.unshift(resolve); + splitBy(duration) { + const dur = Duration.fromDurationLike(duration); + if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { + return []; } - }); - }; - module.exports = TimerManager; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/p-timeout.js -var require_p_timeout = __commonJS((exports, module) => { - class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = "TimeoutError"; + let { + s: s3 + } = this, idx = 1, next; + const results = []; + while (s3 < this.e) { + const added = this.start.plus(dur.mapUnits((x2) => x2 * idx)); + next = +added > +this.e ? this.e : added; + results.push(Interval.fromDateTimes(s3, next)); + s3 = next; + idx += 1; + } + return results; } - } - exports.TimeoutError = TimeoutError; - exports.pTimeout = function pTimeout(promise, milliseconds, fallback, options) { - let timer; - const cancelablePromise = new Promise((resolve, reject) => { - if (typeof milliseconds !== "number" || Math.sign(milliseconds) !== 1) { - throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${milliseconds}\``); + divideEqually(numberOfParts) { + if (!this.isValid) + return []; + return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); + } + overlaps(other) { + return this.e > other.s && this.s < other.e; + } + abutsStart(other) { + if (!this.isValid) + return false; + return +this.e === +other.s; + } + abutsEnd(other) { + if (!this.isValid) + return false; + return +other.e === +this.s; + } + engulfs(other) { + if (!this.isValid) + return false; + return this.s <= other.s && this.e >= other.e; + } + equals(other) { + if (!this.isValid || !other.isValid) { + return false; } - if (milliseconds === Number.POSITIVE_INFINITY) { - resolve(promise); - return; + return this.s.equals(other.s) && this.e.equals(other.e); + } + intersection(other) { + if (!this.isValid) + return this; + const s3 = this.s > other.s ? this.s : other.s, e3 = this.e < other.e ? this.e : other.e; + if (s3 >= e3) { + return null; + } else { + return Interval.fromDateTimes(s3, e3); } - options = { - customTimers: { setTimeout, clearTimeout }, - ...options - }; - timer = options.customTimers.setTimeout.call(undefined, () => { - if (typeof fallback === "function") { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } - return; - } - const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); - if (typeof promise.cancel === "function") { - promise.cancel(); + } + union(other) { + if (!this.isValid) + return this; + const s3 = this.s < other.s ? this.s : other.s, e3 = this.e > other.e ? this.e : other.e; + return Interval.fromDateTimes(s3, e3); + } + static merge(intervals) { + const [found, final] = intervals.sort((a2, b2) => a2.s - b2.s).reduce(([sofar, current], item) => { + if (!current) { + return [sofar, item]; + } else if (current.overlaps(item) || current.abutsStart(item)) { + return [sofar, current.union(item)]; + } else { + return [sofar.concat([current]), item]; } - reject(timeoutError); - }, milliseconds); - (async () => { - try { - resolve(await promise); - } catch (error) { - reject(error); - } finally { - options.customTimers.clearTimeout.call(undefined, timer); + }, [[], null]); + if (final) { + found.push(final); + } + return found; + } + static xor(intervals) { + let start = null, currentCount = 0; + const results = [], ends = intervals.map((i2) => [{ + time: i2.s, + type: "s" + }, { + time: i2.e, + type: "e" + }]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a2, b2) => a2.time - b2.time); + for (const i2 of arr) { + currentCount += i2.type === "s" ? 1 : -1; + if (currentCount === 1) { + start = i2.time; + } else { + if (start && +start !== +i2.time) { + results.push(Interval.fromDateTimes(start, i2.time)); + } + start = null; } - })(); - }); - cancelablePromise["clear"] = () => { - clearTimeout(timer); - timer = undefined; - }; - return cancelablePromise; - }; -}); + } + return Interval.merge(results); + } + difference(...intervals) { + return Interval.xor([this].concat(intervals)).map((i2) => this.intersection(i2)).filter((i2) => i2 && !i2.isEmpty()); + } + toString() { + if (!this.isValid) + return INVALID$1; + return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + if (this.isValid) { + return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`; + } else { + return `Interval { Invalid, reason: ${this.invalidReason} }`; + } + } + toLocaleString(formatOpts = DATE_SHORT, opts = {}) { + return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1; + } + toISO(opts) { + if (!this.isValid) + return INVALID$1; + return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; + } + toISODate() { + if (!this.isValid) + return INVALID$1; + return `${this.s.toISODate()}/${this.e.toISODate()}`; + } + toISOTime(opts) { + if (!this.isValid) + return INVALID$1; + return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; + } + toFormat(dateFormat, { + separator = " \u2013 " + } = {}) { + if (!this.isValid) + return INVALID$1; + return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; + } + toDuration(unit, opts) { + if (!this.isValid) { + return Duration.invalid(this.invalidReason); + } + return this.e.diff(this.s, unit, opts); + } + mapEndpoints(mapFn) { + return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); + } + } -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/addJob-6.js -var require_addJob_6 = __commonJS((exports, module) => { - var content = `--[[ - Adds a job to the queue by doing the following: - - Increases the job counter if needed. - - Creates a new job key with the job data. - - if delayed: - - computes timestamp. - - adds to delayed zset. - - Emits a global event 'delayed' if the job is delayed. - - if not delayed - - Adds the jobId to the wait/paused list in one of three ways: - - LIFO - - FIFO - - prioritized. - - Adds the job to the "added" list so that workers gets notified. - Input: - KEYS[1] 'wait', - KEYS[2] 'paused' - KEYS[3] 'meta-paused' - KEYS[4] 'id' - KEYS[5] 'delayed' - KEYS[6] 'priority' - ARGV[1] key prefix, - ARGV[2] custom id (will not generate one automatically) - ARGV[3] name - ARGV[4] data (json stringified job data) - ARGV[5] opts (json stringified job opts) - ARGV[6] timestamp - ARGV[7] delay - ARGV[8] delayedTimestamp - ARGV[9] priority - ARGV[10] LIFO - ARGV[11] token - ARGV[12] debounce key - ARGV[13] debounceId - ARGV[14] debounceTtl -]] -local jobId -local jobIdKey -local rcall = redis.call --- Includes ---[[ - Function to add job considering priority. -]] -local function addJobWithPriority(priorityKey, priority, jobId, targetKey) - rcall("ZADD", priorityKey, priority, jobId) - local count = rcall("ZCOUNT", priorityKey, 0, priority) - local len = rcall("LLEN", targetKey) - local id = rcall("LINDEX", targetKey, len - (count - 1)) - if id then - rcall("LINSERT", targetKey, "BEFORE", id, jobId) - else - rcall("RPUSH", targetKey, jobId) - end -end ---[[ - Function to debounce a job. -]] -local function debounceJob(prefixKey, debounceId, ttl, jobId, debounceKey, token) - if debounceId ~= "" then - local debounceKeyExists - if ttl ~= "" then - debounceKeyExists = not rcall('SET', debounceKey, jobId, 'PX', ttl, 'NX') - else - debounceKeyExists = not rcall('SET', debounceKey, jobId, 'NX') - end - if debounceKeyExists then - local currentDebounceJobId = rcall('GET', debounceKey) - rcall("PUBLISH", prefixKey .. "debounced@" .. token, currentDebounceJobId) - return currentDebounceJobId - end - end -end ---[[ - Function to check for the meta.paused key to decide if we are paused or not - (since an empty list and !EXISTS are not really the same). -]] -local function getTargetQueueList(queueMetaKey, waitKey, pausedKey) - if rcall("EXISTS", queueMetaKey) ~= 1 then - return waitKey, false - else - return pausedKey, true - end -end -local jobCounter = rcall("INCR", KEYS[4]) -if ARGV[2] == "" then - jobId = jobCounter - jobIdKey = ARGV[1] .. jobId -else - jobId = ARGV[2] - jobIdKey = ARGV[1] .. jobId - if rcall("EXISTS", jobIdKey) == 1 then - rcall("PUBLISH", ARGV[1] .. "duplicated@" .. ARGV[11], jobId) - return jobId .. "" -- convert to string - end -end -local debounceKey = ARGV[12] -local opts = cmsgpack.unpack(ARGV[5]) -local debouncedJobId = debounceJob(ARGV[1], ARGV[13], ARGV[14], - jobId, debounceKey, ARGV[11]) -if debouncedJobId then - return debouncedJobId -end -local debounceId = ARGV[13] -local optionalValues = {} -if debounceId ~= "" then - table.insert(optionalValues, "deid") - table.insert(optionalValues, debounceId) -end - -- Store the job. -rcall("HMSET", jobIdKey, "name", ARGV[3], "data", ARGV[4], "opts", opts, "timestamp", - ARGV[6], "delay", ARGV[7], "priority", ARGV[9], unpack(optionalValues)) --- Check if job is delayed -local delayedTimestamp = tonumber(ARGV[8]) -if(delayedTimestamp ~= 0) then - local timestamp = delayedTimestamp * 0x1000 + bit.band(jobCounter, 0xfff) - rcall("ZADD", KEYS[5], timestamp, jobId) - rcall("PUBLISH", KEYS[5], delayedTimestamp) -else - local target - -- Whe check for the meta-paused key to decide if we are paused or not - -- (since an empty list and !EXISTS are not really the same) - local target, paused = getTargetQueueList(KEYS[3], KEYS[1], KEYS[2]) - -- Standard or priority add - local priority = tonumber(ARGV[9]) - if priority == 0 then - -- LIFO or FIFO - rcall(ARGV[10], target, jobId) - else - addJobWithPriority(KEYS[6], priority, jobId, target) - end - -- Emit waiting event (wait..ing@token) - rcall("PUBLISH", KEYS[1] .. "ing@" .. ARGV[11], jobId) -end -return jobId .. "" -- convert to string -`; - module.exports = { - name: "addJob", - content, - keys: 6 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/addLog-2.js -var require_addLog_2 = __commonJS((exports, module) => { - var content = `--[[ - Add job log - Input: - KEYS[1] job id key - KEYS[2] job logs key - ARGV[1] id - ARGV[2] log - ARGV[3] keepLogs - Output: - -1 - Missing job. -]] -local rcall = redis.call -if rcall("EXISTS", KEYS[1]) == 1 then -- // Make sure job exists - local logCount = rcall("RPUSH", KEYS[2], ARGV[2]) - if ARGV[3] ~= '' then - local keepLogs = tonumber(ARGV[3]) - rcall("LTRIM", KEYS[2], -keepLogs, -1) - return math.min(keepLogs, logCount) - end - return logCount -else - return -1 -end -`; - module.exports = { - name: "addLog", - content, - keys: 2 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/cleanJobsInSet-3.js -var require_cleanJobsInSet_3 = __commonJS((exports, module) => { - var content = `--[[ - Remove jobs from the specific set. - Input: - KEYS[1] set key, - KEYS[2] priority key - KEYS[3] rate limiter key - ARGV[1] prefix key - ARGV[2] maxTimestamp - ARGV[3] limit the number of jobs to be removed. 0 is unlimited - ARGV[4] set name, can be any of 'wait', 'active', 'paused', 'delayed', 'completed', or 'failed' -]] -local setKey = KEYS[1] -local priorityKey = KEYS[2] -local rateLimiterKey = KEYS[3] -local prefixKey = ARGV[1] -local maxTimestamp = ARGV[2] -local limitStr = ARGV[3] -local setName = ARGV[4] -local isList = false -local rcall = redis.call --- Includes ---[[ - Function to remove debounce key. -]] -local function removeDebounceKey(prefixKey, jobKey) - local debounceId = rcall("HGET", jobKey, "deid") - if debounceId then - local debounceKey = prefixKey .. "de:" .. debounceId - rcall("DEL", debounceKey) - end -end -if setName == "wait" or setName == "active" or setName == "paused" then - isList = true -end --- We use ZRANGEBYSCORE to make the case where we're deleting a limited number --- of items in a sorted set only run a single iteration. If we simply used --- ZRANGE, we may take a long time traversing through jobs that are within the --- grace period. -local function shouldUseZRangeByScore(isList, limit) - return not isList and limit > 0 -end -local function getJobs(setKey, isList, rangeStart, rangeEnd, maxTimestamp, limit) - if isList then - return rcall("LRANGE", setKey, rangeStart, rangeEnd) - elseif shouldUseZRangeByScore(isList, limit) then - return rcall("ZRANGEBYSCORE", setKey, 0, maxTimestamp, "LIMIT", 0, limit) - else - return rcall("ZRANGE", setKey, rangeStart, rangeEnd) - end -end -local limit = tonumber(limitStr) -local rangeStart = 0 -local rangeEnd = -1 --- If we're only deleting _n_ items, avoid retrieving all items --- for faster performance --- --- Start from the tail of the list, since that's where oldest elements --- are generally added for FIFO lists -if limit > 0 then - rangeStart = -1 - limit + 1 - rangeEnd = -1 -end -local jobIds = getJobs(setKey, isList, rangeStart, rangeEnd, maxTimestamp, limit) -local deleted = {} -local deletedCount = 0 -local jobTS --- Run this loop: --- - Once, if limit is -1 or 0 --- - As many times as needed if limit is positive -while ((limit <= 0 or deletedCount < limit) and next(jobIds, nil) ~= nil) do - local jobIdsLen = #jobIds - for i, jobId in ipairs(jobIds) do - if limit > 0 and deletedCount >= limit then - break - end - local jobKey = prefixKey .. jobId - if (rcall("EXISTS", jobKey .. ":lock") == 0) then - -- Find the right timestamp of the job to compare to maxTimestamp: - -- * finishedOn says when the job was completed, but it isn't set unless the job has actually completed - -- * processedOn represents when the job was last attempted, but it doesn't get populated until the job is first tried - -- * timestamp is the original job submission time - -- Fetch all three of these (in that order) and use the first one that is set so that we'll leave jobs that have been active within the grace period: - for _, ts in ipairs(rcall("HMGET", jobKey, "finishedOn", "processedOn", "timestamp")) do - if (ts) then - jobTS = ts - break - end - end - if (not jobTS or jobTS < maxTimestamp) then - if isList then - -- Job ids can't be the empty string. Use the empty string as a - -- deletion marker. The actual deletion will occur at the end of the - -- script. - rcall("LSET", setKey, rangeEnd - jobIdsLen + i, "") - else - rcall("ZREM", setKey, jobId) - end - rcall("ZREM", priorityKey, jobId) - if setName ~= "completed" and setName ~= "failed" then - removeDebounceKey(prefixKey, jobKey) - end - rcall("DEL", jobKey) - rcall("DEL", jobKey .. ":logs") - -- delete keys related to rate limiter - -- NOTE: this code is unncessary for other sets than wait, paused and delayed. - local limiterIndexTable = rateLimiterKey .. ":index" - local limitedSetKey = rcall("HGET", limiterIndexTable, jobId) - if limitedSetKey then - rcall("SREM", limitedSetKey, jobId) - rcall("HDEL", limiterIndexTable, jobId) - end - deletedCount = deletedCount + 1 - table.insert(deleted, jobId) - end - end - end - -- If we didn't have a limit or used the single-iteration ZRANGEBYSCORE - -- function, return immediately. We should have deleted all the jobs we can - if limit <= 0 or shouldUseZRangeByScore(isList, limit) then - break - end - if deletedCount < limit then - -- We didn't delete enough. Look for more to delete - rangeStart = rangeStart - limit - rangeEnd = rangeEnd - limit - jobIds = getJobs(setKey, isList, rangeStart, rangeEnd, maxTimestamp, limit) - end -end -if isList then - rcall("LREM", setKey, 0, "") -end -return deleted -`; - module.exports = { - name: "cleanJobsInSet", - content, - keys: 3 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/extendLock-2.js -var require_extendLock_2 = __commonJS((exports, module) => { - var content = `--[[ - Extend lock and removes the job from the stalled set. - Input: - KEYS[1] 'lock', - KEYS[2] 'stalled' - ARGV[1] token - ARGV[2] lock duration in milliseconds - ARGV[3] jobid - Output: - "1" if lock extended succesfully. -]] -local rcall = redis.call -if rcall("GET", KEYS[1]) == ARGV[1] then - if rcall("SET", KEYS[1], ARGV[1], "PX", ARGV[2]) then - rcall("SREM", KEYS[2], ARGV[3]) - return 1 - end -end -return 0 -`; - module.exports = { - name: "extendLock", - content, - keys: 2 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/getCountsPerPriority-4.js -var require_getCountsPerPriority_4 = __commonJS((exports, module) => { - var content = `--[[ - Get counts per provided states - Input: - KEYS[1] wait key - KEYS[2] paused key - KEYS[3] meta-paused key - KEYS[4] priority key - ARGV[1...] priorities -]] -local rcall = redis.call -local results = {} -local prioritizedKey = KEYS[4] --- Includes ---[[ - Function to check for the meta.paused key to decide if we are paused or not - (since an empty list and !EXISTS are not really the same). -]] -local function getTargetQueueList(queueMetaKey, waitKey, pausedKey) - if rcall("EXISTS", queueMetaKey) ~= 1 then - return waitKey, false - else - return pausedKey, true - end -end -for i = 1, #ARGV do - local priority = tonumber(ARGV[i]) - if priority == 0 then - local target = getTargetQueueList(KEYS[3], KEYS[1], KEYS[2]) - local count = rcall("LLEN", target) - rcall("ZCARD", prioritizedKey) - if count < 0 then - -- considering when last waiting job is moved to active before - -- removing priority reference - results[#results+1] = 0 - else - results[#results+1] = count - end - else - results[#results+1] = rcall("ZCOUNT", prioritizedKey, - priority, priority) - end -end -return results -`; - module.exports = { - name: "getCountsPerPriority", - content, - keys: 4 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/isFinished-2.js -var require_isFinished_2 = __commonJS((exports, module) => { - var content = `--[[ - Checks if a job is finished (.i.e. is in the completed or failed set) - Input: - KEYS[1] completed key - KEYS[2] failed key - ARGV[1] job id - Output: - 0 - not finished. - 1 - completed. - 2 - failed. -]] -if redis.call("ZSCORE", KEYS[1], ARGV[1]) ~= false then - return 1 -end -if redis.call("ZSCORE", KEYS[2], ARGV[1]) ~= false then - return 2 -end -return redis.call("ZSCORE", KEYS[2], ARGV[1]) -`; - module.exports = { - name: "isFinished", - content, - keys: 2 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/isJobInList-1.js -var require_isJobInList_1 = __commonJS((exports, module) => { - var content = `--[[ - Checks if job is in a given list. - Input: - KEYS[1] - ARGV[1] - Output: - 1 if element found in the list. -]] -local function item_in_list (list, item) - for _, v in pairs(list) do - if v == item then - return 1 - end - end - return nil -end -local items = redis.call("LRANGE", KEYS[1] , 0, -1) -return item_in_list(items, ARGV[1]) -`; - module.exports = { - name: "isJobInList", - content, - keys: 1 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/moveStalledJobsToWait-7.js -var require_moveStalledJobsToWait_7 = __commonJS((exports, module) => { - var content = `--[[ - Move stalled jobs to wait. - Input: - KEYS[1] 'stalled' (SET) - KEYS[2] 'wait', (LIST) - KEYS[3] 'active', (LIST) - KEYS[4] 'failed', (ZSET) - KEYS[5] 'stalled-check', (KEY) - KEYS[6] 'meta-paused', (KEY) - KEYS[7] 'paused', (LIST) - ARGV[1] Max stalled job count - ARGV[2] queue.toKey('') - ARGV[3] timestamp - ARGV[4] max check time - Events: - 'stalled' with stalled job id. -]] -local rcall = redis.call --- Includes ---[[ - Function to loop in batches. - Just a bit of warning, some commands as ZREM - could receive a maximum of 7000 parameters per call. -]] -local function batches(n, batchSize) - local i = 0 - return function() - local from = i * batchSize + 1 - i = i + 1 - if (from <= n) then - local to = math.min(from + batchSize - 1, n) - return from, to - end - end -end ---[[ - Function to check for the meta.paused key to decide if we are paused or not - (since an empty list and !EXISTS are not really the same). -]] -local function getTargetQueueList(queueMetaKey, waitKey, pausedKey) - if rcall("EXISTS", queueMetaKey) ~= 1 then - return waitKey, false - else - return pausedKey, true - end -end ---[[ - Function to remove debounce key if needed. -]] -local function removeDebounceKeyIfNeeded(prefixKey, debounceId) - if debounceId then - local debounceKey = prefixKey .. "de:" .. debounceId - local pttl = rcall("PTTL", debounceKey) - if pttl == 0 or pttl == -1 then - rcall("DEL", debounceKey) - end - end -end -local function removeJob(jobId, baseKey) - local jobKey = baseKey .. jobId - rcall("DEL", jobKey, jobKey .. ':logs') -end -local function removeJobsByMaxAge(timestamp, maxAge, targetSet, prefix) - local start = timestamp - maxAge * 1000 - local jobIds = rcall("ZREVRANGEBYSCORE", targetSet, start, "-inf") - for i, jobId in ipairs(jobIds) do - removeJob(jobId, prefix) - end - rcall("ZREMRANGEBYSCORE", targetSet, "-inf", start) -end -local function removeJobsByMaxCount(maxCount, targetSet, prefix) - local start = maxCount - local jobIds = rcall("ZREVRANGE", targetSet, start, -1) - for i, jobId in ipairs(jobIds) do - removeJob(jobId, prefix) - end - rcall("ZREMRANGEBYRANK", targetSet, 0, -(maxCount + 1)) -end --- Check if we need to check for stalled jobs now. -if rcall("EXISTS", KEYS[5]) == 1 then - return {{}, {}} -end -rcall("SET", KEYS[5], ARGV[3], "PX", ARGV[4]) --- Move all stalled jobs to wait -local stalling = rcall('SMEMBERS', KEYS[1]) -local stalled = {} -local failed = {} -if(#stalling > 0) then - rcall('DEL', KEYS[1]) - local MAX_STALLED_JOB_COUNT = tonumber(ARGV[1]) - -- Remove from active list - for i, jobId in ipairs(stalling) do - local jobKey = ARGV[2] .. jobId - -- Check that the lock is also missing, then we can handle this job as really stalled. - if(rcall("EXISTS", jobKey .. ":lock") == 0) then - -- Remove from the active queue. - local removed = rcall("LREM", KEYS[3], 1, jobId) - if(removed > 0) then - -- If this job has been stalled too many times, such as if it crashes the worker, then fail it. - local stalledCount = rcall("HINCRBY", jobKey, "stalledCounter", 1) - if(stalledCount > MAX_STALLED_JOB_COUNT) then - local jobAttributes = rcall("HMGET", jobKey, "opts", "deid") - local opts = cjson.decode(jobAttributes[1]) - local removeOnFailType = type(opts["removeOnFail"]) - rcall("ZADD", KEYS[4], ARGV[3], jobId) - rcall("HMSET", jobKey, "failedReason", "job stalled more than allowable limit", - "finishedOn", ARGV[3]) - removeDebounceKeyIfNeeded(ARGV[2], jobAttributes[2]) - rcall("PUBLISH", KEYS[4], '{"jobId":"' .. jobId .. '", "val": "job stalled more than maxStalledCount"}') - if removeOnFailType == "number" then - removeJobsByMaxCount(opts["removeOnFail"], - KEYS[4], ARGV[2]) - elseif removeOnFailType == "boolean" then - if opts["removeOnFail"] then - removeJob(jobId, ARGV[2]) - rcall("ZREM", KEYS[4], jobId) - end - elseif removeOnFailType ~= "nil" then - local maxAge = opts["removeOnFail"]["age"] - local maxCount = opts["removeOnFail"]["count"] - if maxAge ~= nil then - removeJobsByMaxAge(ARGV[3], maxAge, - KEYS[4], ARGV[2]) - end - if maxCount ~= nil and maxCount > 0 then - removeJobsByMaxCount(maxCount, KEYS[4], - ARGV[2]) - end - end - table.insert(failed, jobId) - else - local target = getTargetQueueList(KEYS[6], KEYS[2], KEYS[7]) - -- Move the job back to the wait queue, to immediately be picked up by a waiting worker. - rcall("RPUSH", target, jobId) - rcall('PUBLISH', KEYS[1] .. '@', jobId) - table.insert(stalled, jobId) - end - end - end - end -end --- Mark potentially stalled jobs -local active = rcall('LRANGE', KEYS[3], 0, -1) -if (#active > 0) then - for from, to in batches(#active, 7000) do - rcall('SADD', KEYS[1], unpack(active, from, to)) - end -end -return {failed, stalled} -`; - module.exports = { - name: "moveStalledJobsToWait", - content, - keys: 7 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/moveToActive-8.js -var require_moveToActive_8 = __commonJS((exports, module) => { - var content = `--[[ - Move next job to be processed to active, lock it and fetch its data. The job - may be delayed, in that case we need to move it to the delayed set instead. - This operation guarantees that the worker owns the job during the locks - expiration time. The worker is responsible of keeping the lock fresh - so that no other worker picks this job again. - Input: - KEYS[1] wait key - KEYS[2] active key - KEYS[3] priority key - KEYS[4] active event key - KEYS[5] stalled key - -- Rate limiting - KEYS[6] rate limiter key - KEYS[7] delayed key - -- - KEYS[8] drained key - ARGV[1] key prefix - ARGV[2] lock token - ARGV[3] lock duration in milliseconds - ARGV[4] timestamp - ARGV[5] optional jobid - ARGV[6] optional jobs per time unit (rate limiter) - ARGV[7] optional time unit (rate limiter) - ARGV[8] optional do not do anything with job if rate limit hit - ARGV[9] optional rate limit by key -]] -local rcall = redis.call -local rateLimit = function(jobId, maxJobs) - local rateLimiterKey = KEYS[6]; - local limiterIndexTable = rateLimiterKey .. ":index" - -- Rate limit by group? - if(ARGV[9]) then - local group = string.match(jobId, "[^:]+$") - if group ~= nil then - rateLimiterKey = rateLimiterKey .. ":" .. group - end - end - -- -- key for storing rate limited jobs - -- When a job has been previously rate limited it should be part of this set - -- if the job is back here means that the delay time for this job has passed and now we should - -- be able to process it again. - local limitedSetKey = rateLimiterKey .. ":limited" - local delay = 0 - -- -- Check if job was already limited - local isLimited = rcall("SISMEMBER", limitedSetKey, jobId); - if isLimited == 1 then - -- Remove from limited zset since we are going to try to process it - rcall("SREM", limitedSetKey, jobId) - rcall("HDEL", limiterIndexTable, jobId) - else - -- If not, check if there are any limited jobs - -- If the job has not been rate limited, we should check if there are any other rate limited jobs, because if that - -- is the case we do not want to process this job, just calculate a delay for it and put it to "sleep". - local numLimitedJobs = rcall("SCARD", limitedSetKey) - if numLimitedJobs > 0 then - -- Note, add some slack to compensate for drift. - delay = ((numLimitedJobs * ARGV[7] * 1.1) / maxJobs) + tonumber(rcall("PTTL", rateLimiterKey)) - end - end - local jobCounter = tonumber(rcall("GET", rateLimiterKey)) - if(jobCounter == nil) then - jobCounter = 0 - end - -- check if rate limit hit - if (delay == 0) and (jobCounter >= maxJobs) then - -- Seems like there are no current rated limited jobs, but the jobCounter has exceeded the number of jobs for this unit of time so we need to rate limit this job. - local exceedingJobs = jobCounter - maxJobs - delay = tonumber(rcall("PTTL", rateLimiterKey)) + ((exceedingJobs) * ARGV[7]) / maxJobs - end - if delay > 0 then - local bounceBack = ARGV[8] - if bounceBack == 'false' then - local timestamp = delay + tonumber(ARGV[4]) - -- put job into delayed queue - rcall("ZADD", KEYS[7], timestamp * 0x1000 + bit.band(jobCounter, 0xfff), jobId) - rcall("PUBLISH", KEYS[7], timestamp) - rcall("SADD", limitedSetKey, jobId) - -- store index so that we can delete rate limited data - rcall("HSET", limiterIndexTable, jobId, limitedSetKey) - end - -- remove from active queue - rcall("LREM", KEYS[2], 1, jobId) - return true - else - -- false indicates not rate limited - -- increment jobCounter only when a job is not rate limited - if (jobCounter == 0) then - rcall("PSETEX", rateLimiterKey, ARGV[7], 1) - else - rcall("INCR", rateLimiterKey) - end - return false - end -end -local jobId = ARGV[5] -if jobId ~= '' then - -- clean stalled key - rcall("SREM", KEYS[5], jobId) -else - -- move from wait to active - jobId = rcall("RPOPLPUSH", KEYS[1], KEYS[2]) -end -if jobId then - -- Check if we need to perform rate limiting. - local maxJobs = tonumber(ARGV[6]) - if maxJobs then - if rateLimit(jobId, maxJobs) then - return - end - end - -- get a lock - local jobKey = ARGV[1] .. jobId - local lockKey = jobKey .. ':lock' - rcall("SET", lockKey, ARGV[2], "PX", ARGV[3]) - -- remove from priority - rcall("ZREM", KEYS[3], jobId) - rcall("PUBLISH", KEYS[4], jobId) - rcall("HSET", jobKey, "processedOn", ARGV[4]) - return {rcall("HGETALL", jobKey), jobId} -- get job data -else - rcall("PUBLISH", KEYS[8], "") -end -`; - module.exports = { - name: "moveToActive", - content, - keys: 8 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/moveToDelayed-4.js -var require_moveToDelayed_4 = __commonJS((exports, module) => { - var content = `--[[ - Moves job from active to delayed set. - Input: - KEYS[1] active key - KEYS[2] delayed key - KEYS[3] job key - KEYS[4] stalled key - ARGV[1] delayedTimestamp - ARGV[2] the id of the job - ARGV[3] queue token - Output: - 0 - OK - -1 - Missing job. - -2 - Job is locked. - Events: - - delayed key. -]] -local rcall = redis.call --- Includes -local function removeLock(jobKey, stalledKey, token, jobId) - if token ~= "0" then - local lockKey = jobKey .. ':lock' - local lockToken = rcall("GET", lockKey) - if lockToken == token then - rcall("DEL", lockKey) - rcall("SREM", stalledKey, jobId) - else - if lockToken then - -- Lock exists but token does not match - return -6 - else - -- Lock is missing completely - return -2 - end - end - end - return 0 -end -if rcall("EXISTS", KEYS[3]) == 1 then - local errorCode = removeLock(KEYS[3], KEYS[4], ARGV[3], ARGV[2]) - if errorCode < 0 then - return errorCode - end - local numRemovedElements = rcall("LREM", KEYS[1], -1, ARGV[2]) - if numRemovedElements < 1 then return -3 end - local score = tonumber(ARGV[1]) - rcall("ZADD", KEYS[2], score, ARGV[2]) - rcall("PUBLISH", KEYS[2], (score / 0x1000)) - return 0 -else - return -1 -end -`; - module.exports = { - name: "moveToDelayed", - content, - keys: 4 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/moveToFinished-9.js -var require_moveToFinished_9 = __commonJS((exports, module) => { - var content = `--[[ - Move job from active to a finished status (completed or failed) - A job can only be moved to completed if it was active. - The job must be locked before it can be moved to a finished status, - and the lock must be released in this script. - Input: - KEYS[1] active key - KEYS[2] completed/failed key - KEYS[3] jobId key - KEYS[4] wait key - KEYS[5] priority key - KEYS[6] active event key - KEYS[7] delayed key - KEYS[8] stalled key - KEYS[9] metrics key - ARGV[1] jobId - ARGV[2] timestamp - ARGV[3] msg property - ARGV[4] return value / failed reason - ARGV[5] token - ARGV[6] shouldRemove - ARGV[7] event data (? maybe just send jobid). - ARGV[8] should fetch next job - ARGV[9] base key - ARGV[10] lock token - ARGV[11] lock duration in milliseconds - ARGV[12] maxMetricsSize - Output: - 0 OK - -1 Missing key. - -2 Missing lock. - -3 - Job not in active set. - Events: - 'completed/failed' -]] -local rcall = redis.call --- Includes ---[[ - Functions to collect metrics based on a current and previous count of jobs. - Granualarity is fixed at 1 minute. -]] --- Includes ---[[ - Function to loop in batches. - Just a bit of warning, some commands as ZREM - could receive a maximum of 7000 parameters per call. -]] -local function batches(n, batchSize) - local i = 0 - return function() - local from = i * batchSize + 1 - i = i + 1 - if (from <= n) then - local to = math.min(from + batchSize - 1, n) - return from, to - end - end -end -local function collectMetrics(metaKey, dataPointsList, maxDataPoints, timestamp) - -- Increment current count - local count = rcall("HINCRBY", metaKey, "count", 1) - 1 - -- Compute how many data points we need to add to the list, N. - local prevTS = rcall("HGET", metaKey, "prevTS") - if not prevTS then - -- If prevTS is nil, set it to the current timestamp - rcall("HSET", metaKey, "prevTS", timestamp, "prevCount", 0) - return - end - local N = math.min(math.floor(timestamp / 60000) - math.floor(prevTS / 60000), tonumber(maxDataPoints)) - if N > 0 then - local delta = count - rcall("HGET", metaKey, "prevCount") - -- If N > 1, add N-1 zeros to the list - if N > 1 then - local points = {} - points[1] = delta - for i = 2, N do points[i] = 0 end - for from, to in batches(#points, 7000) do - rcall("LPUSH", dataPointsList, unpack(points, from, to)) - end - else - -- LPUSH delta to the list - rcall("LPUSH", dataPointsList, delta) - end - -- LTRIM to keep list to its max size - rcall("LTRIM", dataPointsList, 0, maxDataPoints - 1) - -- update prev count with current count - rcall("HSET", metaKey, "prevCount", count, "prevTS", timestamp) - end -end -local function removeLock(jobKey, stalledKey, token, jobId) - if token ~= "0" then - local lockKey = jobKey .. ':lock' - local lockToken = rcall("GET", lockKey) - if lockToken == token then - rcall("DEL", lockKey) - rcall("SREM", stalledKey, jobId) - else - if lockToken then - -- Lock exists but token does not match - return -6 - else - -- Lock is missing completely - return -2 - end - end - end - return 0 -end ---[[ - Function to remove debounce key if needed. -]] -local function removeDebounceKeyIfNeeded(prefixKey, debounceId) - if debounceId then - local debounceKey = prefixKey .. "de:" .. debounceId - local pttl = rcall("PTTL", debounceKey) - if pttl == 0 or pttl == -1 then - rcall("DEL", debounceKey) - end - end -end -if rcall("EXISTS", KEYS[3]) == 1 then -- // Make sure job exists - local errorCode = removeLock(KEYS[3], KEYS[8], ARGV[5], ARGV[1]) - if errorCode < 0 then - return errorCode - end - -- Remove from active list (if not active we shall return error) - local numRemovedElements = rcall("LREM", KEYS[1], -1, ARGV[1]) - if numRemovedElements < 1 then return -3 end - local debounceId = rcall("HGET", KEYS[3], "deid") - removeDebounceKeyIfNeeded(ARGV[9], debounceId) - -- Remove job? - local keepJobs = cmsgpack.unpack(ARGV[6]) - local maxCount = keepJobs['count'] - local maxAge = keepJobs['age'] - local targetSet = KEYS[2] - local timestamp = ARGV[2] - if maxCount ~= 0 then - -- Add to complete/failed set - rcall("ZADD", targetSet, timestamp, ARGV[1]) - rcall("HMSET", KEYS[3], ARGV[3], ARGV[4], "finishedOn", timestamp) -- "returnvalue" / "failedReason" and "finishedOn" - local function removeJobs(jobIds) - for i, jobId in ipairs(jobIds) do - local jobKey = ARGV[9] .. jobId - local jobLogKey = jobKey .. ':logs' - rcall("DEL", jobKey, jobLogKey) - end - end - -- Remove old jobs? - if maxAge ~= nil then - local start = timestamp - maxAge * 1000 - local jobIds = rcall("ZREVRANGEBYSCORE", targetSet, start, "-inf") - removeJobs(jobIds) - rcall("ZREMRANGEBYSCORE", targetSet, "-inf", start) - end - if maxCount ~= nil and maxCount > 0 then - local start = maxCount - local jobIds = rcall("ZREVRANGE", targetSet, start, -1) - removeJobs(jobIds) - rcall("ZREMRANGEBYRANK", targetSet, 0, -(maxCount + 1)); - end - else - local jobLogKey = KEYS[3] .. ':logs' - rcall("DEL", KEYS[3], jobLogKey) - end - -- Collect metrics - if ARGV[12] ~= "" then - collectMetrics(KEYS[9], KEYS[9]..':data', ARGV[12], timestamp) - end - rcall("PUBLISH", targetSet, ARGV[7]) - -- Try to get next job to avoid an extra roundtrip if the queue is not closing, - -- and not rate limited. - if (ARGV[8] == "1") then - -- move from wait to active - local jobId = rcall("RPOPLPUSH", KEYS[4], KEYS[1]) - if jobId then - local jobKey = ARGV[9] .. jobId - local lockKey = jobKey .. ':lock' - -- get a lock - rcall("SET", lockKey, ARGV[11], "PX", ARGV[10]) - rcall("ZREM", KEYS[5], jobId) -- remove from priority - rcall("PUBLISH", KEYS[6], jobId) - rcall("HSET", jobKey, "processedOn", ARGV[2]) - return {rcall("HGETALL", jobKey), jobId} -- get job data - end - end - return 0 -else - return -1 -end -`; - module.exports = { - name: "moveToFinished", - content, - keys: 9 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/obliterate-2.js -var require_obliterate_2 = __commonJS((exports, module) => { - var content = `--[[ - Completely obliterates a queue and all of its contents - Input: - KEYS[1] meta-paused - KEYS[2] base - ARGV[1] count - ARGV[2] force -]] --- This command completely destroys a queue including all of its jobs, current or past --- leaving no trace of its existence. Since this script needs to iterate to find all the job --- keys, consider that this call may be slow for very large queues. --- The queue needs to be "paused" or it will return an error --- If the queue has currently active jobs then the script by default will return error, --- however this behaviour can be overrided using the 'force' option. -local maxCount = tonumber(ARGV[1]) -local baseKey = KEYS[2] -local rcall = redis.call --- Includes ---[[ - Function to remove debounce key. -]] -local function removeDebounceKey(prefixKey, jobKey) - local debounceId = rcall("HGET", jobKey, "deid") - if debounceId then - local debounceKey = prefixKey .. "de:" .. debounceId - rcall("DEL", debounceKey) - end -end -local function getListItems(keyName, max) - return rcall('LRANGE', keyName, 0, max - 1) -end -local function getZSetItems(keyName, max) - return rcall('ZRANGE', keyName, 0, max - 1) -end -local function removeJobs(baseKey, keys) - for i, key in ipairs(keys) do - local jobKey = baseKey .. key - rcall("DEL", jobKey, jobKey .. ':logs') - removeDebounceKey(baseKey, jobKey) - end - maxCount = maxCount - #keys -end -local function removeListJobs(keyName, max) - local jobs = getListItems(keyName, max) - removeJobs(baseKey, jobs) - rcall("LTRIM", keyName, #jobs, -1) -end -local function removeZSetJobs(keyName, max) - local jobs = getZSetItems(keyName, max) - removeJobs(baseKey, jobs) - if (#jobs > 0) then rcall("ZREM", keyName, unpack(jobs)) end -end -local function removeLockKeys(keys) - for i, key in ipairs(keys) do rcall("DEL", baseKey .. key .. ':lock') end -end --- 1) Check if paused, if not return with error. -if rcall("EXISTS", KEYS[1]) ~= 1 then - return -1 -- Error, NotPaused -end --- 2) Check if there are active jobs, if there are and not "force" return error. -local activeKey = baseKey .. 'active' -local activeJobs = getListItems(activeKey, maxCount) -if (#activeJobs > 0) then - if (ARGV[2] == "") then - return -2 -- Error, ExistsActiveJobs - end -end -removeLockKeys(activeJobs) -removeJobs(baseKey, activeJobs) -rcall("LTRIM", activeKey, #activeJobs, -1) -if (maxCount <= 0) then return 1 end -local waitKey = baseKey .. 'paused' -removeListJobs(waitKey, maxCount) -if (maxCount <= 0) then return 1 end -local delayedKey = baseKey .. 'delayed' -removeZSetJobs(delayedKey, maxCount) -if (maxCount <= 0) then return 1 end -local completedKey = baseKey .. 'completed' -removeZSetJobs(completedKey, maxCount) -if (maxCount <= 0) then return 1 end -local failedKey = baseKey .. 'failed' -removeZSetJobs(failedKey, maxCount) -if (maxCount <= 0) then return 1 end -if (maxCount > 0) then - rcall("DEL", baseKey .. 'priority') - rcall("DEL", baseKey .. 'stalled-check') - rcall("DEL", baseKey .. 'stalled') - rcall("DEL", baseKey .. 'meta-paused') - rcall("DEL", baseKey .. 'meta') - rcall("DEL", baseKey .. 'id') - rcall("DEL", baseKey .. 'repeat') - rcall("DEL", baseKey .. 'metrics:completed') - rcall("DEL", baseKey .. 'metrics:completed:data') - rcall("DEL", baseKey .. 'metrics:failed') - rcall("DEL", baseKey .. 'metrics:failed:data') - return 0 -else - return 1 -end -`; - module.exports = { - name: "obliterate", - content, - keys: 2 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/pause-5.js -var require_pause_5 = __commonJS((exports, module) => { - var content = `--[[ - Pauses or resumes a queue globably. - Input: - KEYS[1] 'wait' or 'paused'' - KEYS[2] 'paused' or 'wait' - KEYS[3] 'meta-paused' - KEYS[4] 'paused' o 'resumed' event. - KEYS[5] 'meta' this key is only used in BullMQ and above. - ARGV[1] 'paused' or 'resumed' - Event: - publish paused or resumed event. -]] -local rcall = redis.call -if rcall("EXISTS", KEYS[1]) == 1 then - rcall("RENAME", KEYS[1], KEYS[2]) -end -if ARGV[1] == "paused" then - rcall("SET", KEYS[3], 1) - -- for forwards compatibility - rcall("HSET", KEYS[5], "paused", 1) -else - rcall("DEL", KEYS[3]) - -- for forwards compatibility - rcall("HDEL", KEYS[5], "paused") -end -rcall("PUBLISH", KEYS[4], ARGV[1]) -`; - module.exports = { - name: "pause", - content, - keys: 5 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/promote-5.js -var require_promote_5 = __commonJS((exports, module) => { - var content = `--[[ - Promotes a job that is currently "delayed" to the "waiting" state - Input: - KEYS[1] 'delayed' - KEYS[2] 'wait' - KEYS[3] 'paused' - KEYS[4] 'meta-paused' - KEYS[5] 'priority' - ARGV[1] queue.toKey('') - ARGV[2] jobId - ARGV[3] queue token - Events: - 'waiting' -]] -local rcall = redis.call; -local jobId = ARGV[2] --- Includes ---[[ - Function to add job considering priority. -]] -local function addJobWithPriority(priorityKey, priority, jobId, targetKey) - rcall("ZADD", priorityKey, priority, jobId) - local count = rcall("ZCOUNT", priorityKey, 0, priority) - local len = rcall("LLEN", targetKey) - local id = rcall("LINDEX", targetKey, len - (count - 1)) - if id then - rcall("LINSERT", targetKey, "BEFORE", id, jobId) - else - rcall("RPUSH", targetKey, jobId) - end -end ---[[ - Function to check for the meta.paused key to decide if we are paused or not - (since an empty list and !EXISTS are not really the same). -]] -local function getTargetQueueList(queueMetaKey, waitKey, pausedKey) - if rcall("EXISTS", queueMetaKey) ~= 1 then - return waitKey, false - else - return pausedKey, true - end -end -if rcall("ZREM", KEYS[1], jobId) == 1 then - local priority = tonumber(rcall("HGET", ARGV[1] .. jobId, "priority")) or 0 - local target = getTargetQueueList(KEYS[4], KEYS[2], KEYS[3]) - if priority == 0 then - -- LIFO or FIFO - rcall("LPUSH", target, jobId) - else - addJobWithPriority(KEYS[5], priority, jobId, target) - end - -- Emit waiting event (wait..ing@token) - rcall("PUBLISH", KEYS[2] .. "ing@" .. ARGV[3], jobId) - rcall("HSET", ARGV[1] .. jobId, "delay", 0) - return 0 -else - return -1 -end -`; - module.exports = { - name: "promote", - content, - keys: 5 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/releaseLock-1.js -var require_releaseLock_1 = __commonJS((exports, module) => { - var content = `--[[ - Release lock - Input: - KEYS[1] 'lock', - ARGV[1] token - ARGV[2] lock duration in milliseconds - Output: - "OK" if lock extented succesfully. -]] -local rcall = redis.call -if rcall("GET", KEYS[1]) == ARGV[1] then - return rcall("DEL", KEYS[1]) -else - return 0 -end -`; - module.exports = { - name: "releaseLock", - content, - keys: 1 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/removeJob-11.js -var require_removeJob_11 = __commonJS((exports, module) => { - var content = `--[[ - Remove a job from all the queues it may be in as well as all its data. - In order to be able to remove a job, it must be unlocked. - Input: - KEYS[1] 'active', - KEYS[2] 'wait', - KEYS[3] 'delayed', - KEYS[4] 'paused', - KEYS[5] 'completed', - KEYS[6] 'failed', - KEYS[7] 'priority', - KEYS[8] jobId key - KEYS[9] job logs - KEYS[10] rate limiter index table - KEYS[11] prefix key - ARGV[1] jobId - ARGV[2] lock token - Events: - 'removed' -]] --- TODO PUBLISH global event 'removed' -local rcall = redis.call --- Includes ---[[ - Function to remove debounce key. -]] -local function removeDebounceKey(prefixKey, jobKey) - local debounceId = rcall("HGET", jobKey, "deid") - if debounceId then - local debounceKey = prefixKey .. "de:" .. debounceId - rcall("DEL", debounceKey) - end -end -local lockKey = KEYS[8] .. ':lock' -local lock = rcall("GET", lockKey) -if not lock then -- or (lock == ARGV[2])) then - local jobId = ARGV[1] - rcall("LREM", KEYS[1], 0, jobId) - rcall("LREM", KEYS[2], 0, jobId) - rcall("ZREM", KEYS[3], jobId) - rcall("LREM", KEYS[4], 0, jobId) - rcall("ZREM", KEYS[5], jobId) - rcall("ZREM", KEYS[6], jobId) - rcall("ZREM", KEYS[7], jobId) - removeDebounceKey(KEYS[11], KEYS[8]) - rcall("DEL", KEYS[8]) - rcall("DEL", KEYS[9]) - -- delete keys related to rate limiter - local limiterIndexTable = KEYS[10] .. ":index" - local limitedSetKey = rcall("HGET", limiterIndexTable, jobId) - if limitedSetKey then - rcall("SREM", limitedSetKey, jobId) - rcall("HDEL", limiterIndexTable, jobId) - end - return 1 -else - return 0 -end -`; - module.exports = { - name: "removeJob", - content, - keys: 11 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/removeJobs-8.js -var require_removeJobs_8 = __commonJS((exports, module) => { - var content = `--[[ - Remove all jobs matching a given pattern from all the queues they may be in as well as all its data. - In order to be able to remove any job, they must be unlocked. - Input: - KEYS[1] 'active', - KEYS[2] 'wait', - KEYS[3] 'delayed', - KEYS[4] 'paused', - KEYS[5] 'completed', - KEYS[6] 'failed', - KEYS[7] 'priority', - KEYS[8] 'rate-limiter' - ARGV[1] prefix - ARGV[2] pattern - ARGV[3] cursor - Events: - 'removed' -]] --- TODO PUBLISH global events 'removed' -local rcall = redis.call -local result = rcall("SCAN", ARGV[3], "MATCH", ARGV[1] .. ARGV[2]) -local cursor = result[1]; -local jobKeys = result[2]; -local removed = {} -local prefixLen = string.len(ARGV[1]) + 1 -for i, jobKey in ipairs(jobKeys) do - local keyTypeResp = rcall("TYPE", jobKey) - if keyTypeResp["ok"] == "hash" then - local jobId = string.sub(jobKey, prefixLen) - local lockKey = jobKey .. ':lock' - local lock = redis.call("GET", lockKey) - if not lock then - rcall("LREM", KEYS[1], 0, jobId) - rcall("LREM", KEYS[2], 0, jobId) - rcall("ZREM", KEYS[3], jobId) - rcall("LREM", KEYS[4], 0, jobId) - rcall("ZREM", KEYS[5], jobId) - rcall("ZREM", KEYS[6], jobId) - rcall("ZREM", KEYS[7], jobId) - rcall("DEL", jobKey) - rcall("DEL", jobKey .. ':logs') - -- delete keys related to rate limiter - local limiterIndexTable = KEYS[8] .. ":index" - local limitedSetKey = rcall("HGET", limiterIndexTable, jobId) - if limitedSetKey then - rcall("SREM", limitedSetKey, jobId) - rcall("HDEL", limiterIndexTable, jobId) - end - table.insert(removed, jobId) - end - end -end -return {cursor, removed} -`; - module.exports = { - name: "removeJobs", - content, - keys: 8 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/removeRepeatable-2.js -var require_removeRepeatable_2 = __commonJS((exports, module) => { - var content = `--[[ - Removes a repeatable job - Input: - KEYS[1] repeat jobs key - KEYS[2] delayed jobs key - ARGV[1] repeat job id - ARGV[2] repeat job key - ARGV[3] queue key -]] -local millis = redis.call("ZSCORE", KEYS[1], ARGV[2]) -if(millis) then - -- Delete next programmed job. - local repeatJobId = ARGV[1] .. millis - if(redis.call("ZREM", KEYS[2], repeatJobId) == 1) then - redis.call("DEL", ARGV[3] .. repeatJobId) - end -end -redis.call("ZREM", KEYS[1], ARGV[2]); -`; - module.exports = { - name: "removeRepeatable", - content, - keys: 2 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/reprocessJob-6.js -var require_reprocessJob_6 = __commonJS((exports, module) => { - var content = `--[[ - Attempts to reprocess a job - Input: - KEYS[1] job key - KEYS[2] job lock key - KEYS[3] job state - KEYS[4] wait key - KEYS[5] meta-pause - KEYS[6] paused key - ARGV[1] job.id, - ARGV[2] (job.opts.lifo ? 'R' : 'L') + 'PUSH' - ARGV[3] token - ARGV[4] timestamp - Output: - 1 means the operation was a success - 0 means the job does not exist - -1 means the job is currently locked and can't be retried. - -2 means the job was not found in the expected set. -]] -local rcall = redis.call; -if (rcall("EXISTS", KEYS[1]) == 1) then - if (rcall("EXISTS", KEYS[2]) == 0) then - rcall("HDEL", KEYS[1], "finishedOn", "processedOn", "failedReason") - rcall("HSET", KEYS[1], "retriedOn", ARGV[4]) - if (rcall("ZREM", KEYS[3], ARGV[1]) == 1) then - local target - if rcall("EXISTS", KEYS[5]) ~= 1 then - target = KEYS[4] - else - target = KEYS[6] - end - rcall(ARGV[2], target, ARGV[1]) - -- Emit waiting event (wait..ing@token) - rcall("PUBLISH", KEYS[4] .. "ing@" .. ARGV[3], ARGV[1]) - return 1 - else - return -2 - end - else - return -1 - end -else - return 0 -end -`; - module.exports = { - name: "reprocessJob", - content, - keys: 6 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/retryJob-7.js -var require_retryJob_7 = __commonJS((exports, module) => { - var content = `--[[ - Retries a failed job by moving it back to the wait queue. - Input: - KEYS[1] 'active', - KEYS[2] 'wait' - KEYS[3] jobId key - KEYS[4] 'meta-paused' - KEYS[5] 'paused' - KEYS[6] stalled key - KEYS[7] 'priority' - ARGV[1] pushCmd - ARGV[2] jobId - ARGV[3] token - Events: - 'prefix:added' - Output: - 0 - OK - -1 - Missing key - -2 - Job Not locked - -3 - Job not in active set -]] -local rcall = redis.call --- Includes ---[[ - Function to add job considering priority. -]] -local function addJobWithPriority(priorityKey, priority, jobId, targetKey) - rcall("ZADD", priorityKey, priority, jobId) - local count = rcall("ZCOUNT", priorityKey, 0, priority) - local len = rcall("LLEN", targetKey) - local id = rcall("LINDEX", targetKey, len - (count - 1)) - if id then - rcall("LINSERT", targetKey, "BEFORE", id, jobId) - else - rcall("RPUSH", targetKey, jobId) - end -end ---[[ - Function to check for the meta.paused key to decide if we are paused or not - (since an empty list and !EXISTS are not really the same). -]] -local function getTargetQueueList(queueMetaKey, waitKey, pausedKey) - if rcall("EXISTS", queueMetaKey) ~= 1 then - return waitKey, false - else - return pausedKey, true - end -end -local function removeLock(jobKey, stalledKey, token, jobId) - if token ~= "0" then - local lockKey = jobKey .. ':lock' - local lockToken = rcall("GET", lockKey) - if lockToken == token then - rcall("DEL", lockKey) - rcall("SREM", stalledKey, jobId) - else - if lockToken then - -- Lock exists but token does not match - return -6 - else - -- Lock is missing completely - return -2 - end - end - end - return 0 -end -if rcall("EXISTS", KEYS[3]) == 1 then - local errorCode = removeLock(KEYS[3], KEYS[6], ARGV[3], ARGV[2]) - if errorCode < 0 then - return errorCode - end - local numRemovedElements = rcall("LREM", KEYS[1], -1, ARGV[2]) - if numRemovedElements < 1 then return -3 end - local target = getTargetQueueList(KEYS[4], KEYS[2], KEYS[5]) - local priority = tonumber(rcall("HGET", KEYS[3], "priority")) or 0 - if priority == 0 then - -- LIFO or FIFO - rcall(ARGV[1], target, ARGV[2]) - else - addJobWithPriority(KEYS[7], priority, ARGV[2], target) - end - return 0 -else - return -1 -end -`; - module.exports = { - name: "retryJob", - content, - keys: 7 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/retryJobs-5.js -var require_retryJobs_5 = __commonJS((exports, module) => { - var content = `--[[ - Attempts to retry all failed jobs - Input: - KEYS[1] base key - KEYS[2] failed state key - KEYS[3] wait state key - KEYS[4] 'meta-paused' - KEYS[5] 'paused' - ARGV[1] count - Output: - 1 means the operation is not completed - 0 means the operation is completed -]] -local baseKey = KEYS[1] -local maxCount = tonumber(ARGV[1]) -local rcall = redis.call; --- Includes ---[[ - Function to loop in batches. - Just a bit of warning, some commands as ZREM - could receive a maximum of 7000 parameters per call. -]] -local function batches(n, batchSize) - local i = 0 - return function() - local from = i * batchSize + 1 - i = i + 1 - if (from <= n) then - local to = math.min(from + batchSize - 1, n) - return from, to - end - end -end -local function getZSetItems(keyName, max) - return rcall('ZRANGE', keyName, 0, max - 1) -end -local jobs = getZSetItems(KEYS[2], maxCount) -if (#jobs > 0) then - for i, key in ipairs(jobs) do - local jobKey = baseKey .. key - rcall("HDEL", jobKey, "finishedOn", "processedOn", "failedReason") - end - local target - if rcall("EXISTS", KEYS[4]) ~= 1 then - target = KEYS[3] - else - target = KEYS[5] - end - for from, to in batches(#jobs, 7000) do - rcall("ZREM", KEYS[2], unpack(jobs, from, to)) - rcall("LPUSH", target, unpack(jobs, from, to)) - end -end -maxCount = maxCount - #jobs -if (maxCount <= 0) then return 1 end -return 0 -`; - module.exports = { - name: "retryJobs", - content, - keys: 5 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/saveStacktrace-1.js -var require_saveStacktrace_1 = __commonJS((exports, module) => { - var content = `--[[ - Save stacktrace and failedReason. - Input: - KEYS[1] job key - ARGV[1] stacktrace - ARGV[2] failedReason - ARGV[3] attemptsMade - Output: - 0 - OK - -1 - Missing key -]] -local rcall = redis.call -if rcall("EXISTS", KEYS[1]) == 1 then - rcall("HMSET", KEYS[1], "stacktrace", ARGV[1], "failedReason", ARGV[2], - "attemptsMade", ARGV[3]) - return 0 -else - return -1 -end -`; - module.exports = { - name: "saveStacktrace", - content, - keys: 1 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/takeLock-1.js -var require_takeLock_1 = __commonJS((exports, module) => { - var content = `--[[ - Takes a lock - Input: - KEYS[1] 'lock', - ARGV[1] token - ARGV[2] lock duration in milliseconds - Output: - "OK" if lock taken successfully. -]] -if redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) then - return 1 -else - return 0 -end -`; - module.exports = { - name: "takeLock", - content, - keys: 1 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/updateData-1.js -var require_updateData_1 = __commonJS((exports, module) => { - var content = `--[[ - Update job data - Input: - KEYS[1] Job id key - ARGV[1] data - Output: - 0 - OK - -1 - Missing job. -]] -local rcall = redis.call -if rcall("EXISTS",KEYS[1]) == 1 then -- // Make sure job exists - rcall("HSET", KEYS[1], "data", ARGV[1]) - return 0 -else - return -1 -end -`; - module.exports = { - name: "updateData", - content, - keys: 1 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/updateDelaySet-6.js -var require_updateDelaySet_6 = __commonJS((exports, module) => { - var content = `--[[ - Updates the delay set, by picking a delayed job that should - be processed now. - Input: - KEYS[1] 'delayed' - KEYS[2] 'active' - KEYS[3] 'wait' - KEYS[4] 'priority' - KEYS[5] 'paused' - KEYS[6] 'meta-paused' - ARGV[1] queue.toKey('') - ARGV[2] delayed timestamp - ARGV[3] queue token - Events: - 'removed' -]] -local rcall = redis.call; --- Includes ---[[ - Function to add job considering priority. -]] -local function addJobWithPriority(priorityKey, priority, jobId, targetKey) - rcall("ZADD", priorityKey, priority, jobId) - local count = rcall("ZCOUNT", priorityKey, 0, priority) - local len = rcall("LLEN", targetKey) - local id = rcall("LINDEX", targetKey, len - (count - 1)) - if id then - rcall("LINSERT", targetKey, "BEFORE", id, jobId) - else - rcall("RPUSH", targetKey, jobId) - end -end ---[[ - Function to check for the meta.paused key to decide if we are paused or not - (since an empty list and !EXISTS are not really the same). -]] -local function getTargetQueueList(queueMetaKey, waitKey, pausedKey) - if rcall("EXISTS", queueMetaKey) ~= 1 then - return waitKey, false - else - return pausedKey, true - end -end --- Try to get as much as 1000 jobs at once -local jobs = rcall("ZRANGEBYSCORE", KEYS[1], 0, tonumber(ARGV[2]) * 0x1000, "LIMIT", 0, 1000) -if(#jobs > 0) then - rcall("ZREM", KEYS[1], unpack(jobs)) - -- check if we need to use push in paused instead of waiting - local target = getTargetQueueList(KEYS[6], KEYS[3], KEYS[5]) - for _, jobId in ipairs(jobs) do - -- Is this really needed? - rcall("LREM", KEYS[2], 0, jobId) - local priority = tonumber(rcall("HGET", ARGV[1] .. jobId, "priority")) or 0 - if priority == 0 then - -- LIFO or FIFO - rcall("LPUSH", target, jobId) - else - addJobWithPriority(KEYS[4], priority, jobId, target) - end - -- Emit waiting event (wait..ing@token) - rcall("PUBLISH", KEYS[3] .. "ing@" .. ARGV[3], jobId) - rcall("HSET", ARGV[1] .. jobId, "delay", 0) - end -end -local nextTimestamp = rcall("ZRANGE", KEYS[1], 0, 0, "WITHSCORES")[2] -if(nextTimestamp ~= nil) then - rcall("PUBLISH", KEYS[1], nextTimestamp / 0x1000) -end -return nextTimestamp -`; - module.exports = { - name: "updateDelaySet", - content, - keys: 6 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/updateProgress-2.js -var require_updateProgress_2 = __commonJS((exports, module) => { - var content = `--[[ - Update job progress - Input: - KEYS[1] Job id key - KEYS[2] progress event key - ARGV[1] progress - ARGV[2] event data - Event: - progress(jobId, progress) -]] -local rcall = redis.call -if rcall("EXISTS", KEYS[1]) == 1 then -- // Make sure job exists - rcall("HSET", KEYS[1], "progress", ARGV[1]) - rcall("PUBLISH", KEYS[2], ARGV[2]) - return 0 -else - return -1 -end -`; - module.exports = { - name: "updateProgress", - content, - keys: 2 - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/scripts/index.js -var require_scripts2 = __commonJS((exports, module) => { - module.exports = { - ["addJob-6"]: require_addJob_6(), - ["addLog-2"]: require_addLog_2(), - ["cleanJobsInSet-3"]: require_cleanJobsInSet_3(), - ["extendLock-2"]: require_extendLock_2(), - ["getCountsPerPriority-4"]: require_getCountsPerPriority_4(), - ["isFinished-2"]: require_isFinished_2(), - ["isJobInList-1"]: require_isJobInList_1(), - ["moveStalledJobsToWait-7"]: require_moveStalledJobsToWait_7(), - ["moveToActive-8"]: require_moveToActive_8(), - ["moveToDelayed-4"]: require_moveToDelayed_4(), - ["moveToFinished-9"]: require_moveToFinished_9(), - ["obliterate-2"]: require_obliterate_2(), - ["pause-5"]: require_pause_5(), - ["promote-5"]: require_promote_5(), - ["releaseLock-1"]: require_releaseLock_1(), - ["removeJob-11"]: require_removeJob_11(), - ["removeJobs-8"]: require_removeJobs_8(), - ["removeRepeatable-2"]: require_removeRepeatable_2(), - ["reprocessJob-6"]: require_reprocessJob_6(), - ["retryJob-7"]: require_retryJob_7(), - ["retryJobs-5"]: require_retryJobs_5(), - ["saveStacktrace-1"]: require_saveStacktrace_1(), - ["takeLock-1"]: require_takeLock_1(), - ["updateData-1"]: require_updateData_1(), - ["updateDelaySet-6"]: require_updateDelaySet_6(), - ["updateProgress-2"]: require_updateProgress_2() - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/getters.js -var require_getters = __commonJS((exports, module) => { - var _ = require_lodash11(); - var Job = require_job(); - var scripts = require_scripts(); - module.exports = function(Queue) { - Queue.prototype.getJob = async function(jobId) { - await this.isReady(); - return Job.fromId(this, jobId); - }; - Queue.prototype.getCountsPerPriority = async function(priorities) { - const uniquePriorities = [...new Set(priorities)]; - const responses = await scripts.getCountsPerPriority(this, uniquePriorities); - const counts = {}; - responses.forEach((res, index2) => { - counts[`${uniquePriorities[index2]}`] = res || 0; - }); - return counts; - }; - Queue.prototype._commandByType = function(types6, count, callback) { - return _.map(types6, (type) => { - type = type === "waiting" ? "wait" : type; - const key = this.toKey(type); - switch (type) { - case "completed": - case "failed": - case "delayed": - case "repeat": - return callback(key, count ? "zcard" : "zrange"); - case "active": - case "wait": - case "paused": - return callback(key, count ? "llen" : "lrange"); - } - }); - }; - Queue.prototype.count = function() { - return this.getJobCountByTypes("wait", "paused", "delayed"); - }; - Queue.prototype.getJobCountByTypes = function() { - return this.getJobCounts.apply(this, arguments).then((result) => { - return _.chain(result).values().sum().value(); - }); - }; - Queue.prototype.getJobCounts = function() { - const types6 = parseTypeArg(arguments); - const multi = this.multi(); - this._commandByType(types6, true, (key, command) => { - multi[command](key); - }); - return multi.exec().then((res) => { - const counts = {}; - res.forEach((res2, index2) => { - counts[types6[index2]] = res2[1] || 0; - }); - return counts; - }); - }; - Queue.prototype.getCompletedCount = function() { - return this.getJobCountByTypes("completed"); - }; - Queue.prototype.getFailedCount = function() { - return this.getJobCountByTypes("failed"); - }; - Queue.prototype.getDelayedCount = function() { - return this.getJobCountByTypes("delayed"); - }; - Queue.prototype.getActiveCount = function() { - return this.getJobCountByTypes("active"); - }; - Queue.prototype.getWaitingCount = function() { - return this.getJobCountByTypes("wait", "paused"); - }; - Queue.prototype.getStalledCount = function() { - const key = this.toKey("stalled"); - return this.client.scard(key); - }; - Queue.prototype.getPausedCount = function() { - return this.getJobCountByTypes("paused"); - }; - Queue.prototype.getWaiting = function(start, end, opts) { - return this.getJobs(["wait", "paused"], start, end, true, opts); - }; - Queue.prototype.getActive = function(start, end, opts) { - return this.getJobs("active", start, end, true, opts); - }; - Queue.prototype.getDelayed = function(start, end, opts) { - return this.getJobs("delayed", start, end, true, opts); - }; - Queue.prototype.getCompleted = function(start, end, opts) { - return this.getJobs("completed", start, end, false, opts); - }; - Queue.prototype.getFailed = function(start, end, opts) { - return this.getJobs("failed", start, end, false, opts); - }; - Queue.prototype.getRanges = function(types6, start, end, asc2) { - start = _.isUndefined(start) ? 0 : start; - end = _.isUndefined(end) ? -1 : end; - const multi = this.multi(); - const multiCommands = []; - this._commandByType(parseTypeArg(types6), false, (key, command) => { - switch (command) { - case "lrange": - if (asc2) { - multiCommands.push("lrange"); - multi.lrange(key, -(end + 1), -(start + 1)); - } else { - multi.lrange(key, start, end); - } - break; - case "zrange": - multiCommands.push("zrange"); - if (asc2) { - multi.zrange(key, start, end); - } else { - multi.zrevrange(key, start, end); - } - break; - } - }); - return multi.exec().then((responses) => { - let results = []; - responses.forEach((response, index2) => { - const result = response[1] || []; - if (asc2 && multiCommands[index2] === "lrange") { - results = results.concat(result.reverse()); - } else { - results = results.concat(result); - } - }); - return results; - }); - }; - Queue.prototype.getJobs = function(types6, start, end, asc2, opts) { - return this.getRanges(types6, start, end, asc2).then((jobIds) => { - return Promise.all(jobIds.map((jobId) => this.getJobFromId(jobId, opts))); - }); - }; - Queue.prototype.getJobLogs = function(jobId, start, end, asc2 = true) { - start = _.isUndefined(start) ? 0 : start; - end = _.isUndefined(end) ? -1 : end; - const multi = this.multi(); - const logsKey = this.toKey(jobId + ":logs"); - if (asc2) { - multi.lrange(logsKey, start, end); - } else { - multi.lrange(logsKey, -(end + 1), -(start + 1)); - } - multi.llen(logsKey); - return multi.exec().then((result) => { - if (!asc2) { - result[0][1].reverse(); - } - return { - logs: result[0][1], - count: result[1][1] - }; - }); - }; - Queue.prototype.getMetrics = async function(type, start = 0, end = -1) { - const metricsKey = this.toKey(`metrics:${type}`); - const dataKey = `${metricsKey}:data`; - const multi = this.multi(); - multi.hmget(metricsKey, "count", "prevTS", "prevCount"); - multi.lrange(dataKey, start, end); - multi.llen(dataKey); - const [hmget, range, len] = await multi.exec(); - const [err, [count, prevTS, prevCount]] = hmget; - const [err2, data] = range; - const [err3, numPoints] = len; - if (err || err2) { - throw err || err2 || err3; - } - return { - meta: { - count: parseInt(count || "0", 10), - prevTS: parseInt(prevTS || "0", 10), - prevCount: parseInt(prevCount || "0", 10) - }, - data, - count: numPoints - }; - }; - }; - function parseTypeArg(args) { - const types6 = _.chain([]).concat(args).join(",").split(/\s*,\s*/g).compact().value(); - return types6.length ? types6 : ["waiting", "active", "completed", "failed", "delayed", "paused"]; - } -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/worker.js -var require_worker = __commonJS((exports, module) => { - var utils = require_utils12(); - var clientCommandMessageReg = /ERR unknown command ['`]\s*client\s*['`]/; - module.exports = function(Queue) { - Queue.prototype.setWorkerName = function() { - return utils.isRedisReady(this.client).then(() => { - const connectionName = this.clientName(); - this.bclient.options.connectionName = connectionName; - return this.bclient.client("setname", connectionName); - }).catch((err) => { - if (!clientCommandMessageReg.test(err.message)) - throw err; - }); - }; - Queue.prototype.getWorkers = function() { - return utils.isRedisReady(this.client).then(() => { - return this.client.client("list"); - }).then((clients) => { - return this.parseClientList(clients); - }).catch((err) => { - if (!clientCommandMessageReg.test(err.message)) - throw err; - }); - }; - Queue.prototype.base64Name = function() { - return Buffer.from(this.name).toString("base64"); - }; - Queue.prototype.clientName = function() { - return this.keyPrefix + ":" + this.base64Name(); - }; - Queue.prototype.parseClientList = function(list) { - const lines = list.split(` -`); - const clients = []; - lines.forEach((line2) => { - const client = {}; - const keyValues = line2.split(" "); - keyValues.forEach((keyValue) => { - const index2 = keyValue.indexOf("="); - const key = keyValue.substring(0, index2); - const value = keyValue.substring(index2 + 1); - client[key] = value; - }); - const name = client["name"]; - if (name && name.startsWith(this.clientName())) { - client["name"] = this.name; - clients.push(client); - } + class Info { + static hasDST(zone = Settings.defaultZone) { + const proto = DateTime.now().setZone(zone).set({ + month: 12 }); - return clients; - }; - }; -}); - -// node_modules/.pnpm/luxon@3.7.2/node_modules/luxon/build/node/luxon.js -var require_luxon = __commonJS((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - - class LuxonError extends Error { - } - - class InvalidDateTimeError extends LuxonError { - constructor(reason) { - super(`Invalid DateTime: ${reason.toMessage()}`); + return !zone.isUniversal && proto.offset !== proto.set({ + month: 6 + }).offset; } - } - - class InvalidIntervalError extends LuxonError { - constructor(reason) { - super(`Invalid Interval: ${reason.toMessage()}`); + static isValidIANAZone(zone) { + return IANAZone.isValidZone(zone); } - } - - class InvalidDurationError extends LuxonError { - constructor(reason) { - super(`Invalid Duration: ${reason.toMessage()}`); + static normalizeZone(input) { + return normalizeZone(input, Settings.defaultZone); } - } - - class ConflictingSpecificationError extends LuxonError { - } - - class InvalidUnitError extends LuxonError { - constructor(unit) { - super(`Invalid unit ${unit}`); + static getStartOfWeek({ + locale: locale2 = null, + locObj = null + } = {}) { + return (locObj || Locale.create(locale2)).getStartOfWeek(); } - } - - class InvalidArgumentError extends LuxonError { - } - - class ZoneIsAbstractError extends LuxonError { - constructor() { - super("Zone is an abstract class"); + static getMinimumDaysInFirstWeek({ + locale: locale2 = null, + locObj = null + } = {}) { + return (locObj || Locale.create(locale2)).getMinDaysInFirstWeek(); } - } - var n2 = "numeric"; - var s2 = "short"; - var l2 = "long"; - var DATE_SHORT = { - year: n2, - month: n2, - day: n2 - }; - var DATE_MED = { - year: n2, - month: s2, - day: n2 - }; - var DATE_MED_WITH_WEEKDAY = { - year: n2, - month: s2, - day: n2, - weekday: s2 - }; - var DATE_FULL = { - year: n2, - month: l2, - day: n2 - }; - var DATE_HUGE = { - year: n2, - month: l2, - day: n2, - weekday: l2 - }; - var TIME_SIMPLE = { - hour: n2, - minute: n2 - }; - var TIME_WITH_SECONDS = { - hour: n2, - minute: n2, - second: n2 - }; - var TIME_WITH_SHORT_OFFSET = { - hour: n2, - minute: n2, - second: n2, - timeZoneName: s2 - }; - var TIME_WITH_LONG_OFFSET = { - hour: n2, - minute: n2, - second: n2, - timeZoneName: l2 - }; - var TIME_24_SIMPLE = { - hour: n2, - minute: n2, - hourCycle: "h23" - }; - var TIME_24_WITH_SECONDS = { - hour: n2, - minute: n2, - second: n2, - hourCycle: "h23" - }; - var TIME_24_WITH_SHORT_OFFSET = { - hour: n2, - minute: n2, - second: n2, - hourCycle: "h23", - timeZoneName: s2 - }; - var TIME_24_WITH_LONG_OFFSET = { - hour: n2, - minute: n2, - second: n2, - hourCycle: "h23", - timeZoneName: l2 - }; - var DATETIME_SHORT = { - year: n2, - month: n2, - day: n2, - hour: n2, - minute: n2 - }; - var DATETIME_SHORT_WITH_SECONDS = { - year: n2, - month: n2, - day: n2, - hour: n2, - minute: n2, - second: n2 - }; - var DATETIME_MED = { - year: n2, - month: s2, - day: n2, - hour: n2, - minute: n2 - }; - var DATETIME_MED_WITH_SECONDS = { - year: n2, - month: s2, - day: n2, - hour: n2, - minute: n2, - second: n2 - }; - var DATETIME_MED_WITH_WEEKDAY = { - year: n2, - month: s2, - day: n2, - weekday: s2, - hour: n2, - minute: n2 - }; - var DATETIME_FULL = { - year: n2, - month: l2, - day: n2, - hour: n2, - minute: n2, - timeZoneName: s2 - }; - var DATETIME_FULL_WITH_SECONDS = { - year: n2, - month: l2, - day: n2, - hour: n2, - minute: n2, - second: n2, - timeZoneName: s2 - }; - var DATETIME_HUGE = { - year: n2, - month: l2, - day: n2, - weekday: l2, - hour: n2, - minute: n2, - timeZoneName: l2 - }; - var DATETIME_HUGE_WITH_SECONDS = { - year: n2, - month: l2, - day: n2, - weekday: l2, - hour: n2, - minute: n2, - second: n2, - timeZoneName: l2 - }; - - class Zone { - get type() { - throw new ZoneIsAbstractError; - } - get name() { - throw new ZoneIsAbstractError; + static getWeekendWeekdays({ + locale: locale2 = null, + locObj = null + } = {}) { + return (locObj || Locale.create(locale2)).getWeekendDays().slice(); } - get ianaName() { - return this.name; + static months(length = "long", { + locale: locale2 = null, + numberingSystem = null, + locObj = null, + outputCalendar = "gregory" + } = {}) { + return (locObj || Locale.create(locale2, numberingSystem, outputCalendar)).months(length); } - get isUniversal() { - throw new ZoneIsAbstractError; + static monthsFormat(length = "long", { + locale: locale2 = null, + numberingSystem = null, + locObj = null, + outputCalendar = "gregory" + } = {}) { + return (locObj || Locale.create(locale2, numberingSystem, outputCalendar)).months(length, true); } - offsetName(ts, opts) { - throw new ZoneIsAbstractError; + static weekdays(length = "long", { + locale: locale2 = null, + numberingSystem = null, + locObj = null + } = {}) { + return (locObj || Locale.create(locale2, numberingSystem, null)).weekdays(length); } - formatOffset(ts, format) { - throw new ZoneIsAbstractError; + static weekdaysFormat(length = "long", { + locale: locale2 = null, + numberingSystem = null, + locObj = null + } = {}) { + return (locObj || Locale.create(locale2, numberingSystem, null)).weekdays(length, true); } - offset(ts) { - throw new ZoneIsAbstractError; + static meridiems({ + locale: locale2 = null + } = {}) { + return Locale.create(locale2).meridiems(); } - equals(otherZone) { - throw new ZoneIsAbstractError; + static eras(length = "short", { + locale: locale2 = null + } = {}) { + return Locale.create(locale2, null, "gregory").eras(length); } - get isValid() { - throw new ZoneIsAbstractError; + static features() { + return { + relative: hasRelative(), + localeWeek: hasLocaleWeekInfo() + }; } } - var singleton$1 = null; - - class SystemZone extends Zone { - static get instance() { - if (singleton$1 === null) { - singleton$1 = new SystemZone; + function dayDiff(earlier, later) { + const utcDayStart = (dt) => dt.toUTC(0, { + keepLocalTime: true + }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier); + return Math.floor(Duration.fromMillis(ms).as("days")); + } + function highOrderDiffs(cursor, later, units) { + const differs = [["years", (a2, b2) => b2.year - a2.year], ["quarters", (a2, b2) => b2.quarter - a2.quarter + (b2.year - a2.year) * 4], ["months", (a2, b2) => b2.month - a2.month + (b2.year - a2.year) * 12], ["weeks", (a2, b2) => { + const days = dayDiff(a2, b2); + return (days - days % 7) / 7; + }], ["days", dayDiff]]; + const results = {}; + const earlier = cursor; + let lowestOrder, highWater; + for (const [unit, differ] of differs) { + if (units.indexOf(unit) >= 0) { + lowestOrder = unit; + results[unit] = differ(cursor, later); + highWater = earlier.plus(results); + if (highWater > later) { + results[unit]--; + cursor = earlier.plus(results); + if (cursor > later) { + highWater = cursor; + results[unit]--; + cursor = earlier.plus(results); + } + } else { + cursor = highWater; + } } - return singleton$1; - } - get type() { - return "system"; } - get name() { - return new Intl.DateTimeFormat().resolvedOptions().timeZone; + return [cursor, results, highWater, lowestOrder]; + } + function diff(earlier, later, units, opts) { + let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); + const remainingMillis = later - cursor; + const lowerOrderUnits = units.filter((u2) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u2) >= 0); + if (lowerOrderUnits.length === 0) { + if (highWater < later) { + highWater = cursor.plus({ + [lowestOrder]: 1 + }); + } + if (highWater !== cursor) { + results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); + } } - get isUniversal() { - return false; + const duration = Duration.fromObject(results, opts); + if (lowerOrderUnits.length > 0) { + return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); + } else { + return duration; } - offsetName(ts, { - format, - locale: locale2 - }) { - return parseZoneInfo(ts, format, locale2); + } + var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; + function intUnit(regex, post = (i2) => i2) { + return { + regex, + deser: ([s3]) => post(parseDigits(s3)) + }; + } + var NBSP = String.fromCharCode(160); + var spaceOrNBSP = `[ ${NBSP}]`; + var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); + function fixListRegex(s3) { + return s3.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); + } + function stripInsensitivities(s3) { + return s3.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); + } + function oneOf(strings2, startIndex) { + if (strings2 === null) { + return null; + } else { + return { + regex: RegExp(strings2.map(fixListRegex).join("|")), + deser: ([s3]) => strings2.findIndex((i2) => stripInsensitivities(s3) === stripInsensitivities(i2)) + startIndex + }; } - formatOffset(ts, format) { - return formatOffset(this.offset(ts), format); + } + function offset(regex, groups) { + return { + regex, + deser: ([, h2, m2]) => signedOffset(h2, m2), + groups + }; + } + function simple(regex) { + return { + regex, + deser: ([s3]) => s3 + }; + } + function escapeToken(value) { + return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); + } + function unitForToken(token, loc) { + const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t9) => ({ + regex: RegExp(escapeToken(t9.val)), + deser: ([s3]) => s3, + literal: true + }), unitate = (t9) => { + if (token.literal) { + return literal(t9); + } + switch (t9.val) { + case "G": + return oneOf(loc.eras("short"), 0); + case "GG": + return oneOf(loc.eras("long"), 0); + case "y": + return intUnit(oneToSix); + case "yy": + return intUnit(twoToFour, untruncateYear); + case "yyyy": + return intUnit(four); + case "yyyyy": + return intUnit(fourToSix); + case "yyyyyy": + return intUnit(six); + case "M": + return intUnit(oneOrTwo); + case "MM": + return intUnit(two); + case "MMM": + return oneOf(loc.months("short", true), 1); + case "MMMM": + return oneOf(loc.months("long", true), 1); + case "L": + return intUnit(oneOrTwo); + case "LL": + return intUnit(two); + case "LLL": + return oneOf(loc.months("short", false), 1); + case "LLLL": + return oneOf(loc.months("long", false), 1); + case "d": + return intUnit(oneOrTwo); + case "dd": + return intUnit(two); + case "o": + return intUnit(oneToThree); + case "ooo": + return intUnit(three); + case "HH": + return intUnit(two); + case "H": + return intUnit(oneOrTwo); + case "hh": + return intUnit(two); + case "h": + return intUnit(oneOrTwo); + case "mm": + return intUnit(two); + case "m": + return intUnit(oneOrTwo); + case "q": + return intUnit(oneOrTwo); + case "qq": + return intUnit(two); + case "s": + return intUnit(oneOrTwo); + case "ss": + return intUnit(two); + case "S": + return intUnit(oneToThree); + case "SSS": + return intUnit(three); + case "u": + return simple(oneToNine); + case "uu": + return simple(oneOrTwo); + case "uuu": + return intUnit(one); + case "a": + return oneOf(loc.meridiems(), 0); + case "kkkk": + return intUnit(four); + case "kk": + return intUnit(twoToFour, untruncateYear); + case "W": + return intUnit(oneOrTwo); + case "WW": + return intUnit(two); + case "E": + case "c": + return intUnit(one); + case "EEE": + return oneOf(loc.weekdays("short", false), 1); + case "EEEE": + return oneOf(loc.weekdays("long", false), 1); + case "ccc": + return oneOf(loc.weekdays("short", true), 1); + case "cccc": + return oneOf(loc.weekdays("long", true), 1); + case "Z": + case "ZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); + case "ZZZ": + return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); + case "z": + return simple(/[a-z_+-/]{1,256}?/i); + case " ": + return simple(/[^\S\n\r]/); + default: + return literal(t9); + } + }; + const unit = unitate(token) || { + invalidReason: MISSING_FTP + }; + unit.token = token; + return unit; + } + var partTypeStyleToTokenVal = { + year: { + "2-digit": "yy", + numeric: "yyyyy" + }, + month: { + numeric: "M", + "2-digit": "MM", + short: "MMM", + long: "MMMM" + }, + day: { + numeric: "d", + "2-digit": "dd" + }, + weekday: { + short: "EEE", + long: "EEEE" + }, + dayperiod: "a", + dayPeriod: "a", + hour12: { + numeric: "h", + "2-digit": "hh" + }, + hour24: { + numeric: "H", + "2-digit": "HH" + }, + minute: { + numeric: "m", + "2-digit": "mm" + }, + second: { + numeric: "s", + "2-digit": "ss" + }, + timeZoneName: { + long: "ZZZZZ", + short: "ZZZ" } - offset(ts) { - return -new Date(ts).getTimezoneOffset(); + }; + function tokenForPart(part, formatOpts, resolvedOpts) { + const { + type, + value + } = part; + if (type === "literal") { + const isSpace = /^\s+$/.test(value); + return { + literal: !isSpace, + val: isSpace ? " " : value + }; } - equals(otherZone) { - return otherZone.type === "system"; + const style = formatOpts[type]; + let actualType = type; + if (type === "hour") { + if (formatOpts.hour12 != null) { + actualType = formatOpts.hour12 ? "hour12" : "hour24"; + } else if (formatOpts.hourCycle != null) { + if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { + actualType = "hour12"; + } else { + actualType = "hour24"; + } + } else { + actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; + } } - get isValid() { - return true; + let val = partTypeStyleToTokenVal[actualType]; + if (typeof val === "object") { + val = val[style]; } - } - var dtfCache = new Map; - function makeDTF(zoneName) { - let dtf = dtfCache.get(zoneName); - if (dtf === undefined) { - dtf = new Intl.DateTimeFormat("en-US", { - hour12: false, - timeZone: zoneName, - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - era: "short" - }); - dtfCache.set(zoneName, dtf); + if (val) { + return { + literal: false, + val + }; } - return dtf; + return; } - var typeToPos = { - year: 0, - month: 1, - day: 2, - era: 3, - hour: 4, - minute: 5, - second: 6 - }; - function hackyOffset(dtf, date3) { - const formatted = dtf.format(date3).replace(/\u200E/g, ""), parsed = /(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(formatted), [, fMonth, fDay, fYear, fadOrBc, fHour, fMinute, fSecond] = parsed; - return [fYear, fMonth, fDay, fadOrBc, fHour, fMinute, fSecond]; + function buildRegex(units) { + const re = units.map((u2) => u2.regex).reduce((f2, r2) => `${f2}(${r2.source})`, ""); + return [`^${re}$`, units]; } - function partsOffset(dtf, date3) { - const formatted = dtf.formatToParts(date3); - const filled = []; - for (let i2 = 0;i2 < formatted.length; i2++) { - const { - type, - value - } = formatted[i2]; - const pos = typeToPos[type]; - if (type === "era") { - filled[pos] = value; - } else if (!isUndefined(pos)) { - filled[pos] = parseInt(value, 10); + function match(input, regex, handlers) { + const matches = input.match(regex); + if (matches) { + const all = {}; + let matchIndex = 1; + for (const i2 in handlers) { + if (hasOwnProperty(handlers, i2)) { + const h2 = handlers[i2], groups = h2.groups ? h2.groups + 1 : 1; + if (!h2.literal && h2.token) { + all[h2.token.val[0]] = h2.deser(matches.slice(matchIndex, matchIndex + groups)); + } + matchIndex += groups; + } } + return [matches, all]; + } else { + return [matches, {}]; } - return filled; } - var ianaZoneCache = new Map; - - class IANAZone extends Zone { - static create(name) { - let zone = ianaZoneCache.get(name); - if (zone === undefined) { - ianaZoneCache.set(name, zone = new IANAZone(name)); + function dateTimeFromMatches(matches) { + const toField = (token) => { + switch (token) { + case "S": + return "millisecond"; + case "s": + return "second"; + case "m": + return "minute"; + case "h": + case "H": + return "hour"; + case "d": + return "day"; + case "o": + return "ordinal"; + case "L": + case "M": + return "month"; + case "y": + return "year"; + case "E": + case "c": + return "weekday"; + case "W": + return "weekNumber"; + case "k": + return "weekYear"; + case "q": + return "quarter"; + default: + return null; } - return zone; - } - static resetCache() { - ianaZoneCache.clear(); - dtfCache.clear(); - } - static isValidSpecifier(s3) { - return this.isValidZone(s3); + }; + let zone = null; + let specificOffset; + if (!isUndefined(matches.z)) { + zone = IANAZone.create(matches.z); } - static isValidZone(zone) { + if (!isUndefined(matches.Z)) { if (!zone) { - return false; - } - try { - new Intl.DateTimeFormat("en-US", { - timeZone: zone - }).format(); - return true; - } catch (e3) { - return false; + zone = new FixedOffsetZone(matches.Z); } + specificOffset = matches.Z; } - constructor(name) { - super(); - this.zoneName = name; - this.valid = IANAZone.isValidZone(name); + if (!isUndefined(matches.q)) { + matches.M = (matches.q - 1) * 3 + 1; } - get type() { - return "iana"; + if (!isUndefined(matches.h)) { + if (matches.h < 12 && matches.a === 1) { + matches.h += 12; + } else if (matches.h === 12 && matches.a === 0) { + matches.h = 0; + } } - get name() { - return this.zoneName; + if (matches.G === 0 && matches.y) { + matches.y = -matches.y; } - get isUniversal() { - return false; + if (!isUndefined(matches.u)) { + matches.S = parseMillis(matches.u); } - offsetName(ts, { - format, - locale: locale2 - }) { - return parseZoneInfo(ts, format, locale2, this.name); + const vals = Object.keys(matches).reduce((r2, k2) => { + const f2 = toField(k2); + if (f2) { + r2[f2] = matches[k2]; + } + return r2; + }, {}); + return [vals, zone, specificOffset]; + } + var dummyDateTimeCache = null; + function getDummyDateTime() { + if (!dummyDateTimeCache) { + dummyDateTimeCache = DateTime.fromMillis(1555555555555); } - formatOffset(ts, format) { - return formatOffset(this.offset(ts), format); + return dummyDateTimeCache; + } + function maybeExpandMacroToken(token, locale2) { + if (token.literal) { + return token; } - offset(ts) { - if (!this.valid) - return NaN; - const date3 = new Date(ts); - if (isNaN(date3)) - return NaN; - const dtf = makeDTF(this.name); - let [year, month, day, adOrBc, hour, minute, second] = dtf.formatToParts ? partsOffset(dtf, date3) : hackyOffset(dtf, date3); - if (adOrBc === "BC") { - year = -Math.abs(year) + 1; + const formatOpts = Formatter.macroTokenToFormatOpts(token.val); + const tokens = formatOptsToTokens(formatOpts, locale2); + if (tokens == null || tokens.includes(undefined)) { + return token; + } + return tokens; + } + function expandMacroTokens(tokens, locale2) { + return Array.prototype.concat(...tokens.map((t9) => maybeExpandMacroToken(t9, locale2))); + } + + class TokenParser { + constructor(locale2, format) { + this.locale = locale2; + this.format = format; + this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale2); + this.units = this.tokens.map((t9) => unitForToken(t9, locale2)); + this.disqualifyingUnit = this.units.find((t9) => t9.invalidReason); + if (!this.disqualifyingUnit) { + const [regexString, handlers] = buildRegex(this.units); + this.regex = RegExp(regexString, "i"); + this.handlers = handlers; } - const adjustedHour = hour === 24 ? 0 : hour; - const asUTC = objToLocalTS({ - year, - month, - day, - hour: adjustedHour, - minute, - second, - millisecond: 0 - }); - let asTS = +date3; - const over = asTS % 1000; - asTS -= over >= 0 ? over : 1000 + over; - return (asUTC - asTS) / (60 * 1000); } - equals(otherZone) { - return otherZone.type === "iana" && otherZone.name === this.name; + explainFromTokens(input) { + if (!this.isValid) { + return { + input, + tokens: this.tokens, + invalidReason: this.invalidReason + }; + } else { + const [rawMatches, matches] = match(input, this.regex, this.handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, undefined]; + if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { + throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); + } + return { + input, + tokens: this.tokens, + regex: this.regex, + rawMatches, + matches, + result, + zone, + specificOffset + }; + } } get isValid() { - return this.valid; - } - } - var intlLFCache = {}; - function getCachedLF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let dtf = intlLFCache[key]; - if (!dtf) { - dtf = new Intl.ListFormat(locString, opts); - intlLFCache[key] = dtf; + return !this.disqualifyingUnit; } - return dtf; - } - var intlDTCache = new Map; - function getCachedDTF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let dtf = intlDTCache.get(key); - if (dtf === undefined) { - dtf = new Intl.DateTimeFormat(locString, opts); - intlDTCache.set(key, dtf); + get invalidReason() { + return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; } - return dtf; } - var intlNumCache = new Map; - function getCachedINF(locString, opts = {}) { - const key = JSON.stringify([locString, opts]); - let inf = intlNumCache.get(key); - if (inf === undefined) { - inf = new Intl.NumberFormat(locString, opts); - intlNumCache.set(key, inf); - } - return inf; + function explainFromTokens(locale2, input, format) { + const parser = new TokenParser(locale2, format); + return parser.explainFromTokens(input); } - var intlRelCache = new Map; - function getCachedRTF(locString, opts = {}) { + function parseFromTokens(locale2, input, format) { const { - base, - ...cacheKeyOpts - } = opts; - const key = JSON.stringify([locString, cacheKeyOpts]); - let inf = intlRelCache.get(key); - if (inf === undefined) { - inf = new Intl.RelativeTimeFormat(locString, opts); - intlRelCache.set(key, inf); - } - return inf; + result, + zone, + specificOffset, + invalidReason + } = explainFromTokens(locale2, input, format); + return [result, zone, specificOffset, invalidReason]; } - var sysLocaleCache = null; - function systemLocale() { - if (sysLocaleCache) { - return sysLocaleCache; - } else { - sysLocaleCache = new Intl.DateTimeFormat().resolvedOptions().locale; - return sysLocaleCache; + function formatOptsToTokens(formatOpts, locale2) { + if (!formatOpts) { + return null; } + const formatter = Formatter.create(locale2, formatOpts); + const df = formatter.dtFormatter(getDummyDateTime()); + const parts = df.formatToParts(); + const resolvedOpts = df.resolvedOptions(); + return parts.map((p2) => tokenForPart(p2, formatOpts, resolvedOpts)); } - var intlResolvedOptionsCache = new Map; - function getCachedIntResolvedOptions(locString) { - let opts = intlResolvedOptionsCache.get(locString); - if (opts === undefined) { - opts = new Intl.DateTimeFormat(locString).resolvedOptions(); - intlResolvedOptionsCache.set(locString, opts); + var INVALID = "Invalid DateTime"; + var MAX_DATE = 8640000000000000; + function unsupportedZone(zone) { + return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); + } + function possiblyCachedWeekData(dt) { + if (dt.weekData === null) { + dt.weekData = gregorianToWeek(dt.c); } - return opts; + return dt.weekData; } - var weekInfoCache = new Map; - function getCachedWeekInfo(locString) { - let data = weekInfoCache.get(locString); - if (!data) { - const locale2 = new Intl.Locale(locString); - data = "getWeekInfo" in locale2 ? locale2.getWeekInfo() : locale2.weekInfo; - if (!("minimalDays" in data)) { - data = { - ...fallbackWeekSettings, - ...data - }; - } - weekInfoCache.set(locString, data); + function possiblyCachedLocalWeekData(dt) { + if (dt.localWeekData === null) { + dt.localWeekData = gregorianToWeek(dt.c, dt.loc.getMinDaysInFirstWeek(), dt.loc.getStartOfWeek()); } - return data; + return dt.localWeekData; } - function parseLocaleString(localeStr) { - const xIndex = localeStr.indexOf("-x-"); - if (xIndex !== -1) { - localeStr = localeStr.substring(0, xIndex); + function clone4(inst, alts) { + const current = { + ts: inst.ts, + zone: inst.zone, + c: inst.c, + o: inst.o, + loc: inst.loc, + invalid: inst.invalid + }; + return new DateTime({ + ...current, + ...alts, + old: current + }); + } + function fixOffset(localTS, o2, tz) { + let utcGuess = localTS - o2 * 60 * 1000; + const o22 = tz.offset(utcGuess); + if (o2 === o22) { + return [utcGuess, o2]; } - const uIndex = localeStr.indexOf("-u-"); - if (uIndex === -1) { - return [localeStr]; - } else { - let options; - let selectedStr; - try { - options = getCachedDTF(localeStr).resolvedOptions(); - selectedStr = localeStr; - } catch (e3) { - const smaller = localeStr.substring(0, uIndex); - options = getCachedDTF(smaller).resolvedOptions(); - selectedStr = smaller; - } - const { - numberingSystem, - calendar - } = options; - return [selectedStr, numberingSystem, calendar]; + utcGuess -= (o22 - o2) * 60 * 1000; + const o3 = tz.offset(utcGuess); + if (o22 === o3) { + return [utcGuess, o22]; } + return [localTS - Math.min(o22, o3) * 60 * 1000, Math.max(o22, o3)]; } - function intlConfigString(localeStr, numberingSystem, outputCalendar) { - if (outputCalendar || numberingSystem) { - if (!localeStr.includes("-u-")) { - localeStr += "-u"; - } - if (outputCalendar) { - localeStr += `-ca-${outputCalendar}`; - } - if (numberingSystem) { - localeStr += `-nu-${numberingSystem}`; - } - return localeStr; - } else { - return localeStr; - } + function tsToObj(ts, offset2) { + ts += offset2 * 60 * 1000; + const d2 = new Date(ts); + return { + year: d2.getUTCFullYear(), + month: d2.getUTCMonth() + 1, + day: d2.getUTCDate(), + hour: d2.getUTCHours(), + minute: d2.getUTCMinutes(), + second: d2.getUTCSeconds(), + millisecond: d2.getUTCMilliseconds() + }; } - function mapMonths(f2) { - const ms = []; - for (let i2 = 1;i2 <= 12; i2++) { - const dt = DateTime.utc(2009, i2, 1); - ms.push(f2(dt)); - } - return ms; + function objToTS(obj, offset2, zone) { + return fixOffset(objToLocalTS(obj), offset2, zone); } - function mapWeekdays(f2) { - const ms = []; - for (let i2 = 1;i2 <= 7; i2++) { - const dt = DateTime.utc(2016, 11, 13 + i2); - ms.push(f2(dt)); + function adjustTime(inst, dur) { + const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c2 = { + ...inst.c, + year, + month, + day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 + }, millisToAdd = Duration.fromObject({ + years: dur.years - Math.trunc(dur.years), + quarters: dur.quarters - Math.trunc(dur.quarters), + months: dur.months - Math.trunc(dur.months), + weeks: dur.weeks - Math.trunc(dur.weeks), + days: dur.days - Math.trunc(dur.days), + hours: dur.hours, + minutes: dur.minutes, + seconds: dur.seconds, + milliseconds: dur.milliseconds + }).as("milliseconds"), localTS = objToLocalTS(c2); + let [ts, o2] = fixOffset(localTS, oPre, inst.zone); + if (millisToAdd !== 0) { + ts += millisToAdd; + o2 = inst.zone.offset(ts); } - return ms; + return { + ts, + o: o2 + }; } - function listStuff(loc, length, englishFn, intlFn) { - const mode = loc.listingMode(); - if (mode === "error") { - return null; - } else if (mode === "en") { - return englishFn(length); + function parseDataToDateTime(parsed, parsedZone, opts, format, text3, specificOffset) { + const { + setZone, + zone + } = opts; + if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { + const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { + ...opts, + zone: interpretationZone, + specificOffset + }); + return setZone ? inst : inst.setZone(zone); } else { - return intlFn(length); + return DateTime.invalid(new Invalid("unparsable", `the input "${text3}" can't be parsed as ${format}`)); } } - function supportsFastNumbers(loc) { - if (loc.numberingSystem && loc.numberingSystem !== "latn") { - return false; - } else { - return loc.numberingSystem === "latn" || !loc.locale || loc.locale.startsWith("en") || getCachedIntResolvedOptions(loc.locale).numberingSystem === "latn"; - } + function toTechFormat(dt, format, allowZ = true) { + return dt.isValid ? Formatter.create(Locale.create("en-US"), { + allowZ, + forceSimple: true + }).formatDateTimeFromString(dt, format) : null; } - - class PolyNumberFormatter { - constructor(intl, forceSimple, opts) { - this.padTo = opts.padTo || 0; - this.floor = opts.floor || false; - const { - padTo, - floor, - ...otherOpts - } = opts; - if (!forceSimple || Object.keys(otherOpts).length > 0) { - const intlOpts = { - useGrouping: false, - ...opts - }; - if (opts.padTo > 0) - intlOpts.minimumIntegerDigits = opts.padTo; - this.inf = getCachedINF(intl, intlOpts); - } - } - format(i2) { - if (this.inf) { - const fixed = this.floor ? Math.floor(i2) : i2; - return this.inf.format(fixed); - } else { - const fixed = this.floor ? Math.floor(i2) : roundTo(i2, 3); - return padStart(fixed, this.padTo); - } + function toISODate(o2, extended, precision) { + const longFormat = o2.c.year > 9999 || o2.c.year < 0; + let c2 = ""; + if (longFormat && o2.c.year >= 0) + c2 += "+"; + c2 += padStart(o2.c.year, longFormat ? 6 : 4); + if (precision === "year") + return c2; + if (extended) { + c2 += "-"; + c2 += padStart(o2.c.month); + if (precision === "month") + return c2; + c2 += "-"; + } else { + c2 += padStart(o2.c.month); + if (precision === "month") + return c2; } + c2 += padStart(o2.c.day); + return c2; } - - class PolyDateFormatter { - constructor(dt, intl, opts) { - this.opts = opts; - this.originalZone = undefined; - let z2 = undefined; - if (this.opts.timeZone) { - this.dt = dt; - } else if (dt.zone.type === "fixed") { - const gmtOffset = -1 * (dt.offset / 60); - const offsetZ = gmtOffset >= 0 ? `Etc/GMT+${gmtOffset}` : `Etc/GMT${gmtOffset}`; - if (dt.offset !== 0 && IANAZone.create(offsetZ).valid) { - z2 = offsetZ; - this.dt = dt; + function toISOTime(o2, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision) { + let showSeconds = !suppressSeconds || o2.c.millisecond !== 0 || o2.c.second !== 0, c2 = ""; + switch (precision) { + case "day": + case "month": + case "year": + break; + default: + c2 += padStart(o2.c.hour); + if (precision === "hour") + break; + if (extended) { + c2 += ":"; + c2 += padStart(o2.c.minute); + if (precision === "minute") + break; + if (showSeconds) { + c2 += ":"; + c2 += padStart(o2.c.second); + } } else { - z2 = "UTC"; - this.dt = dt.offset === 0 ? dt : dt.setZone("UTC").plus({ - minutes: dt.offset - }); - this.originalZone = dt.zone; + c2 += padStart(o2.c.minute); + if (precision === "minute") + break; + if (showSeconds) { + c2 += padStart(o2.c.second); + } } - } else if (dt.zone.type === "system") { - this.dt = dt; - } else if (dt.zone.type === "iana") { - this.dt = dt; - z2 = dt.zone.name; + if (precision === "second") + break; + if (showSeconds && (!suppressMilliseconds || o2.c.millisecond !== 0)) { + c2 += "."; + c2 += padStart(o2.c.millisecond, 3); + } + } + if (includeOffset) { + if (o2.isOffsetFixed && o2.offset === 0 && !extendedZone) { + c2 += "Z"; + } else if (o2.o < 0) { + c2 += "-"; + c2 += padStart(Math.trunc(-o2.o / 60)); + c2 += ":"; + c2 += padStart(Math.trunc(-o2.o % 60)); } else { - z2 = "UTC"; - this.dt = dt.setZone("UTC").plus({ - minutes: dt.offset - }); - this.originalZone = dt.zone; + c2 += "+"; + c2 += padStart(Math.trunc(o2.o / 60)); + c2 += ":"; + c2 += padStart(Math.trunc(o2.o % 60)); } - const intlOpts = { - ...this.opts - }; - intlOpts.timeZone = intlOpts.timeZone || z2; - this.dtf = getCachedDTF(intl, intlOpts); } - format() { - if (this.originalZone) { - return this.formatToParts().map(({ - value - }) => value).join(""); - } - return this.dtf.format(this.dt.toJSDate()); + if (extendedZone) { + c2 += "[" + o2.zone.ianaName + "]"; } - formatToParts() { - const parts = this.dtf.formatToParts(this.dt.toJSDate()); - if (this.originalZone) { - return parts.map((part) => { - if (part.type === "timeZoneName") { - const offsetName = this.originalZone.offsetName(this.dt.ts, { - locale: this.dt.locale, - format: this.opts.timeZoneName - }); - return { - ...part, - value: offsetName - }; - } else { - return part; - } - }); - } - return parts; + return c2; + } + var defaultUnitValues = { + month: 1, + day: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var defaultWeekUnitValues = { + weekNumber: 1, + weekday: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var defaultOrdinalUnitValues = { + ordinal: 1, + hour: 0, + minute: 0, + second: 0, + millisecond: 0 + }; + var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; + var orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"]; + var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; + function normalizeUnit(unit) { + const normalized = { + year: "year", + years: "year", + month: "month", + months: "month", + day: "day", + days: "day", + hour: "hour", + hours: "hour", + minute: "minute", + minutes: "minute", + quarter: "quarter", + quarters: "quarter", + second: "second", + seconds: "second", + millisecond: "millisecond", + milliseconds: "millisecond", + weekday: "weekday", + weekdays: "weekday", + weeknumber: "weekNumber", + weeksnumber: "weekNumber", + weeknumbers: "weekNumber", + weekyear: "weekYear", + weekyears: "weekYear", + ordinal: "ordinal" + }[unit.toLowerCase()]; + if (!normalized) + throw new InvalidUnitError(unit); + return normalized; + } + function normalizeUnitWithLocalWeeks(unit) { + switch (unit.toLowerCase()) { + case "localweekday": + case "localweekdays": + return "localWeekday"; + case "localweeknumber": + case "localweeknumbers": + return "localWeekNumber"; + case "localweekyear": + case "localweekyears": + return "localWeekYear"; + default: + return normalizeUnit(unit); } - resolvedOptions() { - return this.dtf.resolvedOptions(); + } + function guessOffsetForZone(zone) { + if (zoneOffsetTs === undefined) { + zoneOffsetTs = Settings.now(); + } + if (zone.type !== "iana") { + return zone.offset(zoneOffsetTs); + } + const zoneName = zone.name; + let offsetGuess = zoneOffsetGuessCache.get(zoneName); + if (offsetGuess === undefined) { + offsetGuess = zone.offset(zoneOffsetTs); + zoneOffsetGuessCache.set(zoneName, offsetGuess); } + return offsetGuess; } - - class PolyRelFormatter { - constructor(intl, isEnglish, opts) { - this.opts = { - style: "long", - ...opts - }; - if (!isEnglish && hasRelative()) { - this.rtf = getCachedRTF(intl, opts); + function quickDT(obj, opts) { + const zone = normalizeZone(opts.zone, Settings.defaultZone); + if (!zone.isValid) { + return DateTime.invalid(unsupportedZone(zone)); + } + const loc = Locale.fromObject(opts); + let ts, o2; + if (!isUndefined(obj.year)) { + for (const u2 of orderedUnits) { + if (isUndefined(obj[u2])) { + obj[u2] = defaultUnitValues[u2]; + } + } + const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); + if (invalid) { + return DateTime.invalid(invalid); } + const offsetProvis = guessOffsetForZone(zone); + [ts, o2] = objToTS(obj, offsetProvis, zone); + } else { + ts = Settings.now(); } - format(count, unit) { - if (this.rtf) { - return this.rtf.format(count, unit); + return new DateTime({ + ts, + zone, + loc, + o: o2 + }); + } + function diffRelative(start, end, opts) { + const round = isUndefined(opts.round) ? true : opts.round, rounding = isUndefined(opts.rounding) ? "trunc" : opts.rounding, format = (c2, unit) => { + c2 = roundTo(c2, round || opts.calendary ? 0 : 2, opts.calendary ? "round" : rounding); + const formatter = end.loc.clone(opts).relFormatter(opts); + return formatter.format(c2, unit); + }, differ = (unit) => { + if (opts.calendary) { + if (!end.hasSame(start, unit)) { + return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); + } else + return 0; } else { - return formatRelativeTime(unit, count, this.opts.numeric, this.opts.style !== "long"); + return end.diff(start, unit).get(unit); } + }; + if (opts.unit) { + return format(differ(opts.unit), opts.unit); } - formatToParts(count, unit) { - if (this.rtf) { - return this.rtf.formatToParts(count, unit); - } else { - return []; + for (const unit of opts.units) { + const count2 = differ(unit); + if (Math.abs(count2) >= 1) { + return format(count2, unit); } } + return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); } - var fallbackWeekSettings = { - firstDay: 1, - minimalDays: 4, - weekend: [6, 7] - }; - - class Locale { - static fromOpts(opts) { - return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.weekSettings, opts.defaultToEN); + function lastOpts(argList) { + let opts = {}, args; + if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { + opts = argList[argList.length - 1]; + args = Array.from(argList).slice(0, argList.length - 1); + } else { + args = Array.from(argList); } - static create(locale2, numberingSystem, outputCalendar, weekSettings, defaultToEN = false) { - const specifiedLocale = locale2 || Settings.defaultLocale; - const localeR = specifiedLocale || (defaultToEN ? "en-US" : systemLocale()); - const numberingSystemR = numberingSystem || Settings.defaultNumberingSystem; - const outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; - const weekSettingsR = validateWeekSettings(weekSettings) || Settings.defaultWeekSettings; - return new Locale(localeR, numberingSystemR, outputCalendarR, weekSettingsR, specifiedLocale); + return [opts, args]; + } + var zoneOffsetTs; + var zoneOffsetGuessCache = new Map; + + class DateTime { + constructor(config) { + const zone = config.zone || Settings.defaultZone; + let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); + this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; + let c2 = null, o2 = null; + if (!invalid) { + const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); + if (unchanged) { + [c2, o2] = [config.old.c, config.old.o]; + } else { + const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts); + c2 = tsToObj(this.ts, ot); + invalid = Number.isNaN(c2.year) ? new Invalid("invalid input") : null; + c2 = invalid ? null : c2; + o2 = invalid ? null : ot; + } + } + this._zone = zone; + this.loc = config.loc || Locale.create(); + this.invalid = invalid; + this.weekData = null; + this.localWeekData = null; + this.c = c2; + this.o = o2; + this.isLuxonDateTime = true; } - static resetCache() { - sysLocaleCache = null; - intlDTCache.clear(); - intlNumCache.clear(); - intlRelCache.clear(); - intlResolvedOptionsCache.clear(); - weekInfoCache.clear(); + static now() { + return new DateTime({}); } - static fromObject({ - locale: locale2, - numberingSystem, - outputCalendar, - weekSettings - } = {}) { - return Locale.create(locale2, numberingSystem, outputCalendar, weekSettings); + static local() { + const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; + return quickDT({ + year, + month, + day, + hour, + minute, + second, + millisecond + }, opts); } - constructor(locale2, numbering, outputCalendar, weekSettings, specifiedLocale) { - const [parsedLocale, parsedNumberingSystem, parsedOutputCalendar] = parseLocaleString(locale2); - this.locale = parsedLocale; - this.numberingSystem = numbering || parsedNumberingSystem || null; - this.outputCalendar = outputCalendar || parsedOutputCalendar || null; - this.weekSettings = weekSettings; - this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); - this.weekdaysCache = { - format: {}, - standalone: {} - }; - this.monthsCache = { - format: {}, - standalone: {} - }; - this.meridiemCache = null; - this.eraCache = {}; - this.specifiedLocale = specifiedLocale; - this.fastNumbersCached = null; + static utc() { + const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; + opts.zone = FixedOffsetZone.utcInstance; + return quickDT({ + year, + month, + day, + hour, + minute, + second, + millisecond + }, opts); } - get fastNumbers() { - if (this.fastNumbersCached == null) { - this.fastNumbersCached = supportsFastNumbers(this); + static fromJSDate(date4, options = {}) { + const ts = isDate2(date4) ? date4.valueOf() : NaN; + if (Number.isNaN(ts)) { + return DateTime.invalid("invalid input"); } - return this.fastNumbersCached; - } - listingMode() { - const isActuallyEn = this.isEnglish(); - const hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === "latn") && (this.outputCalendar === null || this.outputCalendar === "gregory"); - return isActuallyEn && hasNoWeirdness ? "en" : "intl"; - } - clone(alts) { - if (!alts || Object.getOwnPropertyNames(alts).length === 0) { - return this; - } else { - return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, validateWeekSettings(alts.weekSettings) || this.weekSettings, alts.defaultToEN || false); + const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); + if (!zoneToUse.isValid) { + return DateTime.invalid(unsupportedZone(zoneToUse)); } - } - redefaultToEN(alts = {}) { - return this.clone({ - ...alts, - defaultToEN: true - }); - } - redefaultToSystem(alts = {}) { - return this.clone({ - ...alts, - defaultToEN: false - }); - } - months(length, format = false) { - return listStuff(this, length, months, () => { - const monthSpecialCase = this.intl === "ja" || this.intl.startsWith("ja-"); - format &= !monthSpecialCase; - const intl = format ? { - month: length, - day: "numeric" - } : { - month: length - }, formatStr = format ? "format" : "standalone"; - if (!this.monthsCache[formatStr][length]) { - const mapper = !monthSpecialCase ? (dt) => this.extract(dt, intl, "month") : (dt) => this.dtFormatter(dt, intl).format(); - this.monthsCache[formatStr][length] = mapMonths(mapper); - } - return this.monthsCache[formatStr][length]; + return new DateTime({ + ts, + zone: zoneToUse, + loc: Locale.fromObject(options) }); } - weekdays(length, format = false) { - return listStuff(this, length, weekdays, () => { - const intl = format ? { - weekday: length, - year: "numeric", - month: "long", - day: "numeric" - } : { - weekday: length - }, formatStr = format ? "format" : "standalone"; - if (!this.weekdaysCache[formatStr][length]) { - this.weekdaysCache[formatStr][length] = mapWeekdays((dt) => this.extract(dt, intl, "weekday")); - } - return this.weekdaysCache[formatStr][length]; - }); + static fromMillis(milliseconds, options = {}) { + if (!isNumber(milliseconds)) { + throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`); + } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { + return DateTime.invalid("Timestamp out of range"); + } else { + return new DateTime({ + ts: milliseconds, + zone: normalizeZone(options.zone, Settings.defaultZone), + loc: Locale.fromObject(options) + }); + } } - meridiems() { - return listStuff(this, undefined, () => meridiems, () => { - if (!this.meridiemCache) { - const intl = { - hour: "numeric", - hourCycle: "h12" - }; - this.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map((dt) => this.extract(dt, intl, "dayperiod")); - } - return this.meridiemCache; - }); + static fromSeconds(seconds, options = {}) { + if (!isNumber(seconds)) { + throw new InvalidArgumentError("fromSeconds requires a numerical input"); + } else { + return new DateTime({ + ts: seconds * 1000, + zone: normalizeZone(options.zone, Settings.defaultZone), + loc: Locale.fromObject(options) + }); + } } - eras(length) { - return listStuff(this, length, eras, () => { - const intl = { - era: length - }; - if (!this.eraCache[length]) { - this.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map((dt) => this.extract(dt, intl, "era")); + static fromObject(obj, opts = {}) { + obj = obj || {}; + const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); + if (!zoneToUse.isValid) { + return DateTime.invalid(unsupportedZone(zoneToUse)); + } + const loc = Locale.fromObject(opts); + const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); + const { + minDaysInFirstWeek, + startOfWeek + } = usesLocalWeekValues(normalized, loc); + const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); + } + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); + } + const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; + let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); + if (useWeekData) { + units = orderedWeekUnits; + defaultValues = defaultWeekUnitValues; + objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek); + } else if (containsOrdinal) { + units = orderedOrdinalUnits; + defaultValues = defaultOrdinalUnitValues; + objNow = gregorianToOrdinal(objNow); + } else { + units = orderedUnits; + defaultValues = defaultUnitValues; + } + let foundFirst = false; + for (const u2 of units) { + const v2 = normalized[u2]; + if (!isUndefined(v2)) { + foundFirst = true; + } else if (foundFirst) { + normalized[u2] = defaultValues[u2]; + } else { + normalized[u2] = objNow[u2]; } - return this.eraCache[length]; + } + const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); + if (invalid) { + return DateTime.invalid(invalid); + } + const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({ + ts: tsFinal, + zone: zoneToUse, + o: offsetFinal, + loc }); + if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { + return DateTime.invalid("mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`); + } + if (!inst.isValid) { + return DateTime.invalid(inst.invalid); + } + return inst; } - extract(dt, intlOpts, field) { - const df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find((m2) => m2.type.toLowerCase() === field); - return matching ? matching.value : null; + static fromISO(text3, opts = {}) { + const [vals, parsedZone] = parseISODate(text3); + return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text3); } - numberFormatter(opts = {}) { - return new PolyNumberFormatter(this.intl, opts.forceSimple || this.fastNumbers, opts); + static fromRFC2822(text3, opts = {}) { + const [vals, parsedZone] = parseRFC2822Date(text3); + return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text3); } - dtFormatter(dt, intlOpts = {}) { - return new PolyDateFormatter(dt, this.intl, intlOpts); + static fromHTTP(text3, opts = {}) { + const [vals, parsedZone] = parseHTTPDate(text3); + return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); } - relFormatter(opts = {}) { - return new PolyRelFormatter(this.intl, this.isEnglish(), opts); + static fromFormat(text3, fmt, opts = {}) { + if (isUndefined(text3) || isUndefined(fmt)) { + throw new InvalidArgumentError("fromFormat requires an input string and a format"); + } + const { + locale: locale2 = null, + numberingSystem = null + } = opts, localeToUse = Locale.fromOpts({ + locale: locale2, + numberingSystem, + defaultToEN: true + }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text3, fmt); + if (invalid) { + return DateTime.invalid(invalid); + } else { + return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text3, specificOffset); + } } - listFormatter(opts = {}) { - return getCachedLF(this.intl, opts); + static fromString(text3, fmt, opts = {}) { + return DateTime.fromFormat(text3, fmt, opts); } - isEnglish() { - return this.locale === "en" || this.locale.toLowerCase() === "en-us" || getCachedIntResolvedOptions(this.intl).locale.startsWith("en-us"); + static fromSQL(text3, opts = {}) { + const [vals, parsedZone] = parseSQL(text3); + return parseDataToDateTime(vals, parsedZone, opts, "SQL", text3); } - getWeekSettings() { - if (this.weekSettings) { - return this.weekSettings; - } else if (!hasLocaleWeekInfo()) { - return fallbackWeekSettings; + static invalid(reason, explanation = null) { + if (!reason) { + throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); + } + const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); + if (Settings.throwOnInvalid) { + throw new InvalidDateTimeError(invalid); } else { - return getCachedWeekInfo(this.locale); + return new DateTime({ + invalid + }); } } - getStartOfWeek() { - return this.getWeekSettings().firstDay; - } - getMinDaysInFirstWeek() { - return this.getWeekSettings().minimalDays; - } - getWeekendDays() { - return this.getWeekSettings().weekend; + static isDateTime(o2) { + return o2 && o2.isLuxonDateTime || false; } - equals(other) { - return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; + static parseFormatForOpts(formatOpts, localeOpts = {}) { + const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); + return !tokenList ? null : tokenList.map((t9) => t9 ? t9.val : null).join(""); } - toString() { - return `Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`; + static expandFormat(fmt, localeOpts = {}) { + const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); + return expanded.map((t9) => t9.val).join(""); } - } - var singleton = null; - - class FixedOffsetZone extends Zone { - static get utcInstance() { - if (singleton === null) { - singleton = new FixedOffsetZone(0); - } - return singleton; + static resetCache() { + zoneOffsetTs = undefined; + zoneOffsetGuessCache.clear(); } - static instance(offset2) { - return offset2 === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset2); + get(unit) { + return this[unit]; } - static parseSpecifier(s3) { - if (s3) { - const r2 = s3.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); - if (r2) { - return new FixedOffsetZone(signedOffset(r2[1], r2[2])); - } - } - return null; + get isValid() { + return this.invalid === null; } - constructor(offset2) { - super(); - this.fixed = offset2; + get invalidReason() { + return this.invalid ? this.invalid.reason : null; } - get type() { - return "fixed"; + get invalidExplanation() { + return this.invalid ? this.invalid.explanation : null; } - get name() { - return this.fixed === 0 ? "UTC" : `UTC${formatOffset(this.fixed, "narrow")}`; + get locale() { + return this.isValid ? this.loc.locale : null; } - get ianaName() { - if (this.fixed === 0) { - return "Etc/UTC"; - } else { - return `Etc/GMT${formatOffset(-this.fixed, "narrow")}`; - } + get numberingSystem() { + return this.isValid ? this.loc.numberingSystem : null; } - offsetName() { - return this.name; + get outputCalendar() { + return this.isValid ? this.loc.outputCalendar : null; } - formatOffset(ts, format) { - return formatOffset(this.fixed, format); + get zone() { + return this._zone; } - get isUniversal() { - return true; + get zoneName() { + return this.isValid ? this.zone.name : null; } - offset() { - return this.fixed; + get year() { + return this.isValid ? this.c.year : NaN; } - equals(otherZone) { - return otherZone.type === "fixed" && otherZone.fixed === this.fixed; + get quarter() { + return this.isValid ? Math.ceil(this.c.month / 3) : NaN; } - get isValid() { - return true; + get month() { + return this.isValid ? this.c.month : NaN; } - } - - class InvalidZone extends Zone { - constructor(zoneName) { - super(); - this.zoneName = zoneName; + get day() { + return this.isValid ? this.c.day : NaN; } - get type() { - return "invalid"; + get hour() { + return this.isValid ? this.c.hour : NaN; } - get name() { - return this.zoneName; + get minute() { + return this.isValid ? this.c.minute : NaN; } - get isUniversal() { - return false; + get second() { + return this.isValid ? this.c.second : NaN; } - offsetName() { - return null; + get millisecond() { + return this.isValid ? this.c.millisecond : NaN; } - formatOffset() { - return ""; + get weekYear() { + return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; } - offset() { - return NaN; + get weekNumber() { + return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; } - equals() { - return false; + get weekday() { + return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; } - get isValid() { - return false; + get isWeekend() { + return this.isValid && this.loc.getWeekendDays().includes(this.weekday); } - } - function normalizeZone(input, defaultZone2) { - if (isUndefined(input) || input === null) { - return defaultZone2; - } else if (input instanceof Zone) { - return input; - } else if (isString(input)) { - const lowered = input.toLowerCase(); - if (lowered === "default") - return defaultZone2; - else if (lowered === "local" || lowered === "system") - return SystemZone.instance; - else if (lowered === "utc" || lowered === "gmt") - return FixedOffsetZone.utcInstance; - else - return FixedOffsetZone.parseSpecifier(lowered) || IANAZone.create(input); - } else if (isNumber(input)) { - return FixedOffsetZone.instance(input); - } else if (typeof input === "object" && "offset" in input && typeof input.offset === "function") { - return input; - } else { - return new InvalidZone(input); + get localWeekday() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; } - } - var numberingSystems = { - arab: "[\u0660-\u0669]", - arabext: "[\u06F0-\u06F9]", - bali: "[\u1B50-\u1B59]", - beng: "[\u09E6-\u09EF]", - deva: "[\u0966-\u096F]", - fullwide: "[\uFF10-\uFF19]", - gujr: "[\u0AE6-\u0AEF]", - hanidec: "[\u3007|\u4E00|\u4E8C|\u4E09|\u56DB|\u4E94|\u516D|\u4E03|\u516B|\u4E5D]", - khmr: "[\u17E0-\u17E9]", - knda: "[\u0CE6-\u0CEF]", - laoo: "[\u0ED0-\u0ED9]", - limb: "[\u1946-\u194F]", - mlym: "[\u0D66-\u0D6F]", - mong: "[\u1810-\u1819]", - mymr: "[\u1040-\u1049]", - orya: "[\u0B66-\u0B6F]", - tamldec: "[\u0BE6-\u0BEF]", - telu: "[\u0C66-\u0C6F]", - thai: "[\u0E50-\u0E59]", - tibt: "[\u0F20-\u0F29]", - latn: "\\d" - }; - var numberingSystemsUTF16 = { - arab: [1632, 1641], - arabext: [1776, 1785], - bali: [6992, 7001], - beng: [2534, 2543], - deva: [2406, 2415], - fullwide: [65296, 65303], - gujr: [2790, 2799], - khmr: [6112, 6121], - knda: [3302, 3311], - laoo: [3792, 3801], - limb: [6470, 6479], - mlym: [3430, 3439], - mong: [6160, 6169], - mymr: [4160, 4169], - orya: [2918, 2927], - tamldec: [3046, 3055], - telu: [3174, 3183], - thai: [3664, 3673], - tibt: [3872, 3881] - }; - var hanidecChars = numberingSystems.hanidec.replace(/[\[|\]]/g, "").split(""); - function parseDigits(str) { - let value = parseInt(str, 10); - if (isNaN(value)) { - value = ""; - for (let i2 = 0;i2 < str.length; i2++) { - const code = str.charCodeAt(i2); - if (str[i2].search(numberingSystems.hanidec) !== -1) { - value += hanidecChars.indexOf(str[i2]); - } else { - for (const key in numberingSystemsUTF16) { - const [min, max] = numberingSystemsUTF16[key]; - if (code >= min && code <= max) { - value += code - min; - } - } - } - } - return parseInt(value, 10); - } else { - return value; + get localWeekNumber() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; } - } - var digitRegexCache = new Map; - function resetDigitRegexCache() { - digitRegexCache.clear(); - } - function digitRegex({ - numberingSystem - }, append = "") { - const ns = numberingSystem || "latn"; - let appendCache = digitRegexCache.get(ns); - if (appendCache === undefined) { - appendCache = new Map; - digitRegexCache.set(ns, appendCache); + get localWeekYear() { + return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN; } - let regex = appendCache.get(append); - if (regex === undefined) { - regex = new RegExp(`${numberingSystems[ns]}${append}`); - appendCache.set(append, regex); + get ordinal() { + return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; } - return regex; - } - var now = () => Date.now(); - var defaultZone = "system"; - var defaultLocale = null; - var defaultNumberingSystem = null; - var defaultOutputCalendar = null; - var twoDigitCutoffYear = 60; - var throwOnInvalid; - var defaultWeekSettings = null; - - class Settings { - static get now() { - return now; + get monthShort() { + return this.isValid ? Info.months("short", { + locObj: this.loc + })[this.month - 1] : null; } - static set now(n3) { - now = n3; + get monthLong() { + return this.isValid ? Info.months("long", { + locObj: this.loc + })[this.month - 1] : null; } - static set defaultZone(zone) { - defaultZone = zone; + get weekdayShort() { + return this.isValid ? Info.weekdays("short", { + locObj: this.loc + })[this.weekday - 1] : null; } - static get defaultZone() { - return normalizeZone(defaultZone, SystemZone.instance); + get weekdayLong() { + return this.isValid ? Info.weekdays("long", { + locObj: this.loc + })[this.weekday - 1] : null; } - static get defaultLocale() { - return defaultLocale; + get offset() { + return this.isValid ? +this.o : NaN; } - static set defaultLocale(locale2) { - defaultLocale = locale2; + get offsetNameShort() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "short", + locale: this.locale + }); + } else { + return null; + } } - static get defaultNumberingSystem() { - return defaultNumberingSystem; + get offsetNameLong() { + if (this.isValid) { + return this.zone.offsetName(this.ts, { + format: "long", + locale: this.locale + }); + } else { + return null; + } } - static set defaultNumberingSystem(numberingSystem) { - defaultNumberingSystem = numberingSystem; + get isOffsetFixed() { + return this.isValid ? this.zone.isUniversal : null; } - static get defaultOutputCalendar() { - return defaultOutputCalendar; + get isInDST() { + if (this.isOffsetFixed) { + return false; + } else { + return this.offset > this.set({ + month: 1, + day: 1 + }).offset || this.offset > this.set({ + month: 5 + }).offset; + } } - static set defaultOutputCalendar(outputCalendar) { - defaultOutputCalendar = outputCalendar; + getPossibleOffsets() { + if (!this.isValid || this.isOffsetFixed) { + return [this]; + } + const dayMs = 86400000; + const minuteMs = 60000; + const localTS = objToLocalTS(this.c); + const oEarlier = this.zone.offset(localTS - dayMs); + const oLater = this.zone.offset(localTS + dayMs); + const o1 = this.zone.offset(localTS - oEarlier * minuteMs); + const o2 = this.zone.offset(localTS - oLater * minuteMs); + if (o1 === o2) { + return [this]; + } + const ts1 = localTS - o1 * minuteMs; + const ts2 = localTS - o2 * minuteMs; + const c1 = tsToObj(ts1, o1); + const c2 = tsToObj(ts2, o2); + if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { + return [clone4(this, { + ts: ts1 + }), clone4(this, { + ts: ts2 + })]; + } + return [this]; } - static get defaultWeekSettings() { - return defaultWeekSettings; + get isInLeapYear() { + return isLeapYear(this.year); } - static set defaultWeekSettings(weekSettings) { - defaultWeekSettings = validateWeekSettings(weekSettings); + get daysInMonth() { + return daysInMonth(this.year, this.month); } - static get twoDigitCutoffYear() { - return twoDigitCutoffYear; + get daysInYear() { + return this.isValid ? daysInYear(this.year) : NaN; } - static set twoDigitCutoffYear(cutoffYear) { - twoDigitCutoffYear = cutoffYear % 100; + get weeksInWeekYear() { + return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; } - static get throwOnInvalid() { - return throwOnInvalid; + get weeksInLocalWeekYear() { + return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN; } - static set throwOnInvalid(t9) { - throwOnInvalid = t9; + resolvedLocaleOptions(opts = {}) { + const { + locale: locale2, + numberingSystem, + calendar + } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this); + return { + locale: locale2, + numberingSystem, + outputCalendar: calendar + }; } - static resetCaches() { - Locale.resetCache(); - IANAZone.resetCache(); - DateTime.resetCache(); - resetDigitRegexCache(); + toUTC(offset2 = 0, opts = {}) { + return this.setZone(FixedOffsetZone.instance(offset2), opts); } - } - - class Invalid { - constructor(reason, explanation) { - this.reason = reason; - this.explanation = explanation; + toLocal() { + return this.setZone(Settings.defaultZone); } - toMessage() { - if (this.explanation) { - return `${this.reason}: ${this.explanation}`; + setZone(zone, { + keepLocalTime = false, + keepCalendarTime = false + } = {}) { + zone = normalizeZone(zone, Settings.defaultZone); + if (zone.equals(this.zone)) { + return this; + } else if (!zone.isValid) { + return DateTime.invalid(unsupportedZone(zone)); } else { - return this.reason; + let newTS = this.ts; + if (keepLocalTime || keepCalendarTime) { + const offsetGuess = zone.offset(this.ts); + const asObj = this.toObject(); + [newTS] = objToTS(asObj, offsetGuess, zone); + } + return clone4(this, { + ts: newTS, + zone + }); } } - } - var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; - var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; - function unitOutOfRange(unit, value) { - return new Invalid("unit out of range", `you specified ${value} (of type ${typeof value}) as a ${unit}, which is invalid`); - } - function dayOfWeek(year, month, day) { - const d2 = new Date(Date.UTC(year, month - 1, day)); - if (year < 100 && year >= 0) { - d2.setUTCFullYear(d2.getUTCFullYear() - 1900); + reconfigure({ + locale: locale2, + numberingSystem, + outputCalendar + } = {}) { + const loc = this.loc.clone({ + locale: locale2, + numberingSystem, + outputCalendar + }); + return clone4(this, { + loc + }); } - const js = d2.getUTCDay(); - return js === 0 ? 7 : js; - } - function computeOrdinal(year, month, day) { - return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; - } - function uncomputeOrdinal(year, ordinal) { - const table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex((i2) => i2 < ordinal), day = ordinal - table[month0]; - return { - month: month0 + 1, - day - }; - } - function isoWeekdayToLocal(isoWeekday, startOfWeek) { - return (isoWeekday - startOfWeek + 7) % 7 + 1; - } - function gregorianToWeek(gregObj, minDaysInFirstWeek = 4, startOfWeek = 1) { - const { - year, - month, - day - } = gregObj, ordinal = computeOrdinal(year, month, day), weekday = isoWeekdayToLocal(dayOfWeek(year, month, day), startOfWeek); - let weekNumber = Math.floor((ordinal - weekday + 14 - minDaysInFirstWeek) / 7), weekYear; - if (weekNumber < 1) { - weekYear = year - 1; - weekNumber = weeksInWeekYear(weekYear, minDaysInFirstWeek, startOfWeek); - } else if (weekNumber > weeksInWeekYear(year, minDaysInFirstWeek, startOfWeek)) { - weekYear = year + 1; - weekNumber = 1; - } else { - weekYear = year; - } - return { - weekYear, - weekNumber, - weekday, - ...timeObject(gregObj) - }; - } - function weekToGregorian(weekData, minDaysInFirstWeek = 4, startOfWeek = 1) { - const { - weekYear, - weekNumber, - weekday - } = weekData, weekdayOfJan4 = isoWeekdayToLocal(dayOfWeek(weekYear, 1, minDaysInFirstWeek), startOfWeek), yearInDays = daysInYear(weekYear); - let ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 7 + minDaysInFirstWeek, year; - if (ordinal < 1) { - year = weekYear - 1; - ordinal += daysInYear(year); - } else if (ordinal > yearInDays) { - year = weekYear + 1; - ordinal -= daysInYear(weekYear); - } else { - year = weekYear; + setLocale(locale2) { + return this.reconfigure({ + locale: locale2 + }); } - const { - month, - day - } = uncomputeOrdinal(year, ordinal); - return { - year, - month, - day, - ...timeObject(weekData) - }; - } - function gregorianToOrdinal(gregData) { - const { - year, - month, - day - } = gregData; - const ordinal = computeOrdinal(year, month, day); - return { - year, - ordinal, - ...timeObject(gregData) - }; - } - function ordinalToGregorian(ordinalData) { - const { - year, - ordinal - } = ordinalData; - const { - month, - day - } = uncomputeOrdinal(year, ordinal); - return { - year, - month, - day, - ...timeObject(ordinalData) - }; - } - function usesLocalWeekValues(obj, loc) { - const hasLocaleWeekData = !isUndefined(obj.localWeekday) || !isUndefined(obj.localWeekNumber) || !isUndefined(obj.localWeekYear); - if (hasLocaleWeekData) { - const hasIsoWeekData = !isUndefined(obj.weekday) || !isUndefined(obj.weekNumber) || !isUndefined(obj.weekYear); - if (hasIsoWeekData) { - throw new ConflictingSpecificationError("Cannot mix locale-based week fields with ISO-based week fields"); + set(values) { + if (!this.isValid) + return this; + const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks); + const { + minDaysInFirstWeek, + startOfWeek + } = usesLocalWeekValues(normalized, this.loc); + const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; + if ((containsGregor || containsOrdinal) && definiteWeekDef) { + throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } - if (!isUndefined(obj.localWeekday)) - obj.weekday = obj.localWeekday; - if (!isUndefined(obj.localWeekNumber)) - obj.weekNumber = obj.localWeekNumber; - if (!isUndefined(obj.localWeekYear)) - obj.weekYear = obj.localWeekYear; - delete obj.localWeekday; - delete obj.localWeekNumber; - delete obj.localWeekYear; - return { - minDaysInFirstWeek: loc.getMinDaysInFirstWeek(), - startOfWeek: loc.getStartOfWeek() - }; - } else { - return { - minDaysInFirstWeek: 4, - startOfWeek: 1 - }; - } - } - function hasInvalidWeekData(obj, minDaysInFirstWeek = 4, startOfWeek = 1) { - const validYear = isInteger(obj.weekYear), validWeek = integerBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear, minDaysInFirstWeek, startOfWeek)), validWeekday = integerBetween(obj.weekday, 1, 7); - if (!validYear) { - return unitOutOfRange("weekYear", obj.weekYear); - } else if (!validWeek) { - return unitOutOfRange("week", obj.weekNumber); - } else if (!validWeekday) { - return unitOutOfRange("weekday", obj.weekday); - } else - return false; - } - function hasInvalidOrdinalData(obj) { - const validYear = isInteger(obj.year), validOrdinal = integerBetween(obj.ordinal, 1, daysInYear(obj.year)); - if (!validYear) { - return unitOutOfRange("year", obj.year); - } else if (!validOrdinal) { - return unitOutOfRange("ordinal", obj.ordinal); - } else - return false; - } - function hasInvalidGregorianData(obj) { - const validYear = isInteger(obj.year), validMonth = integerBetween(obj.month, 1, 12), validDay = integerBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); - if (!validYear) { - return unitOutOfRange("year", obj.year); - } else if (!validMonth) { - return unitOutOfRange("month", obj.month); - } else if (!validDay) { - return unitOutOfRange("day", obj.day); - } else - return false; - } - function hasInvalidTimeData(obj) { - const { - hour, - minute, - second, - millisecond - } = obj; - const validHour = integerBetween(hour, 0, 23) || hour === 24 && minute === 0 && second === 0 && millisecond === 0, validMinute = integerBetween(minute, 0, 59), validSecond = integerBetween(second, 0, 59), validMillisecond = integerBetween(millisecond, 0, 999); - if (!validHour) { - return unitOutOfRange("hour", hour); - } else if (!validMinute) { - return unitOutOfRange("minute", minute); - } else if (!validSecond) { - return unitOutOfRange("second", second); - } else if (!validMillisecond) { - return unitOutOfRange("millisecond", millisecond); - } else - return false; - } - function isUndefined(o2) { - return typeof o2 === "undefined"; - } - function isNumber(o2) { - return typeof o2 === "number"; - } - function isInteger(o2) { - return typeof o2 === "number" && o2 % 1 === 0; - } - function isString(o2) { - return typeof o2 === "string"; - } - function isDate2(o2) { - return Object.prototype.toString.call(o2) === "[object Date]"; - } - function hasRelative() { - try { - return typeof Intl !== "undefined" && !!Intl.RelativeTimeFormat; - } catch (e3) { - return false; + if (containsGregorMD && containsOrdinal) { + throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); + } + let mixed2; + if (settingWeekStuff) { + mixed2 = weekToGregorian({ + ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), + ...normalized + }, minDaysInFirstWeek, startOfWeek); + } else if (!isUndefined(normalized.ordinal)) { + mixed2 = ordinalToGregorian({ + ...gregorianToOrdinal(this.c), + ...normalized + }); + } else { + mixed2 = { + ...this.toObject(), + ...normalized + }; + if (isUndefined(normalized.day)) { + mixed2.day = Math.min(daysInMonth(mixed2.year, mixed2.month), mixed2.day); + } + } + const [ts, o2] = objToTS(mixed2, this.o, this.zone); + return clone4(this, { + ts, + o: o2 + }); } - } - function hasLocaleWeekInfo() { - try { - return typeof Intl !== "undefined" && !!Intl.Locale && (("weekInfo" in Intl.Locale.prototype) || ("getWeekInfo" in Intl.Locale.prototype)); - } catch (e3) { - return false; + plus(duration) { + if (!this.isValid) + return this; + const dur = Duration.fromDurationLike(duration); + return clone4(this, adjustTime(this, dur)); } - } - function maybeArray(thing) { - return Array.isArray(thing) ? thing : [thing]; - } - function bestBy(arr, by2, compare4) { - if (arr.length === 0) { - return; + minus(duration) { + if (!this.isValid) + return this; + const dur = Duration.fromDurationLike(duration).negate(); + return clone4(this, adjustTime(this, dur)); } - return arr.reduce((best, next) => { - const pair = [by2(next), next]; - if (!best) { - return pair; - } else if (compare4(best[0], pair[0]) === best[0]) { - return best; - } else { - return pair; + startOf(unit, { + useLocaleWeeks = false + } = {}) { + if (!this.isValid) + return this; + const o2 = {}, normalizedUnit = Duration.normalizeUnit(unit); + switch (normalizedUnit) { + case "years": + o2.month = 1; + case "quarters": + case "months": + o2.day = 1; + case "weeks": + case "days": + o2.hour = 0; + case "hours": + o2.minute = 0; + case "minutes": + o2.second = 0; + case "seconds": + o2.millisecond = 0; + break; } - }, null)[1]; - } - function pick(obj, keys) { - return keys.reduce((a2, k2) => { - a2[k2] = obj[k2]; - return a2; - }, {}); - } - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - function validateWeekSettings(settings) { - if (settings == null) { - return null; - } else if (typeof settings !== "object") { - throw new InvalidArgumentError("Week settings must be an object"); - } else { - if (!integerBetween(settings.firstDay, 1, 7) || !integerBetween(settings.minimalDays, 1, 7) || !Array.isArray(settings.weekend) || settings.weekend.some((v2) => !integerBetween(v2, 1, 7))) { - throw new InvalidArgumentError("Invalid week settings"); + if (normalizedUnit === "weeks") { + if (useLocaleWeeks) { + const startOfWeek = this.loc.getStartOfWeek(); + const { + weekday + } = this; + if (weekday < startOfWeek) { + o2.weekNumber = this.weekNumber - 1; + } + o2.weekday = startOfWeek; + } else { + o2.weekday = 1; + } } - return { - firstDay: settings.firstDay, - minimalDays: settings.minimalDays, - weekend: Array.from(settings.weekend) - }; - } - } - function integerBetween(thing, bottom, top) { - return isInteger(thing) && thing >= bottom && thing <= top; - } - function floorMod(x2, n3) { - return x2 - n3 * Math.floor(x2 / n3); - } - function padStart(input, n3 = 2) { - const isNeg = input < 0; - let padded; - if (isNeg) { - padded = "-" + ("" + -input).padStart(n3, "0"); - } else { - padded = ("" + input).padStart(n3, "0"); - } - return padded; - } - function parseInteger(string2) { - if (isUndefined(string2) || string2 === null || string2 === "") { - return; - } else { - return parseInt(string2, 10); + if (normalizedUnit === "quarters") { + const q2 = Math.ceil(this.month / 3); + o2.month = (q2 - 1) * 3 + 1; + } + return this.set(o2); } - } - function parseFloating(string2) { - if (isUndefined(string2) || string2 === null || string2 === "") { - return; - } else { - return parseFloat(string2); + endOf(unit, opts) { + return this.isValid ? this.plus({ + [unit]: 1 + }).startOf(unit, opts).minus(1) : this; } - } - function parseMillis(fraction) { - if (isUndefined(fraction) || fraction === null || fraction === "") { - return; - } else { - const f2 = parseFloat("0." + fraction) * 1000; - return Math.floor(f2); + toFormat(fmt, opts = {}) { + return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; } - } - function roundTo(number2, digits, rounding = "round") { - const factor = 10 ** digits; - switch (rounding) { - case "expand": - return number2 > 0 ? Math.ceil(number2 * factor) / factor : Math.floor(number2 * factor) / factor; - case "trunc": - return Math.trunc(number2 * factor) / factor; - case "round": - return Math.round(number2 * factor) / factor; - case "floor": - return Math.floor(number2 * factor) / factor; - case "ceil": - return Math.ceil(number2 * factor) / factor; - default: - throw new RangeError(`Value rounding ${rounding} is out of range`); + toLocaleString(formatOpts = DATE_SHORT, opts = {}) { + return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID; } - } - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - function daysInYear(year) { - return isLeapYear(year) ? 366 : 365; - } - function daysInMonth(year, month) { - const modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; - if (modMonth === 2) { - return isLeapYear(modYear) ? 29 : 28; - } else { - return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; + toLocaleParts(opts = {}) { + return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; } - } - function objToLocalTS(obj) { - let d2 = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); - if (obj.year < 100 && obj.year >= 0) { - d2 = new Date(d2); - d2.setUTCFullYear(obj.year, obj.month - 1, obj.day); + toISO({ + format = "extended", + suppressSeconds = false, + suppressMilliseconds = false, + includeOffset = true, + extendedZone = false, + precision = "milliseconds" + } = {}) { + if (!this.isValid) { + return null; + } + precision = normalizeUnit(precision); + const ext = format === "extended"; + let c2 = toISODate(this, ext, precision); + if (orderedUnits.indexOf(precision) >= 3) + c2 += "T"; + c2 += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision); + return c2; } - return +d2; - } - function firstWeekOffset(year, minDaysInFirstWeek, startOfWeek) { - const fwdlw = isoWeekdayToLocal(dayOfWeek(year, 1, minDaysInFirstWeek), startOfWeek); - return -fwdlw + minDaysInFirstWeek - 1; - } - function weeksInWeekYear(weekYear, minDaysInFirstWeek = 4, startOfWeek = 1) { - const weekOffset = firstWeekOffset(weekYear, minDaysInFirstWeek, startOfWeek); - const weekOffsetNext = firstWeekOffset(weekYear + 1, minDaysInFirstWeek, startOfWeek); - return (daysInYear(weekYear) - weekOffset + weekOffsetNext) / 7; - } - function untruncateYear(year) { - if (year > 99) { - return year; - } else - return year > Settings.twoDigitCutoffYear ? 1900 + year : 2000 + year; - } - function parseZoneInfo(ts, offsetFormat, locale2, timeZone = null) { - const date3 = new Date(ts), intlOpts = { - hourCycle: "h23", - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit" - }; - if (timeZone) { - intlOpts.timeZone = timeZone; + toISODate({ + format = "extended", + precision = "day" + } = {}) { + if (!this.isValid) { + return null; + } + return toISODate(this, format === "extended", normalizeUnit(precision)); } - const modified = { - timeZoneName: offsetFormat, - ...intlOpts - }; - const parsed = new Intl.DateTimeFormat(locale2, modified).formatToParts(date3).find((m2) => m2.type.toLowerCase() === "timezonename"); - return parsed ? parsed.value : null; - } - function signedOffset(offHourStr, offMinuteStr) { - let offHour = parseInt(offHourStr, 10); - if (Number.isNaN(offHour)) { - offHour = 0; + toISOWeekDate() { + return toTechFormat(this, "kkkk-'W'WW-c"); } - const offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 || Object.is(offHour, -0) ? -offMin : offMin; - return offHour * 60 + offMinSigned; - } - function asNumber(value) { - const numericValue = Number(value); - if (typeof value === "boolean" || value === "" || !Number.isFinite(numericValue)) - throw new InvalidArgumentError(`Invalid unit value ${value}`); - return numericValue; - } - function normalizeObject(obj, normalizer) { - const normalized = {}; - for (const u2 in obj) { - if (hasOwnProperty(obj, u2)) { - const v2 = obj[u2]; - if (v2 === undefined || v2 === null) - continue; - normalized[normalizer(u2)] = asNumber(v2); + toISOTime({ + suppressMilliseconds = false, + suppressSeconds = false, + includeOffset = true, + includePrefix = false, + extendedZone = false, + format = "extended", + precision = "milliseconds" + } = {}) { + if (!this.isValid) { + return null; } + precision = normalizeUnit(precision); + let c2 = includePrefix && orderedUnits.indexOf(precision) >= 3 ? "T" : ""; + return c2 + toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision); } - return normalized; - } - function formatOffset(offset2, format) { - const hours = Math.trunc(Math.abs(offset2 / 60)), minutes = Math.trunc(Math.abs(offset2 % 60)), sign2 = offset2 >= 0 ? "+" : "-"; - switch (format) { - case "short": - return `${sign2}${padStart(hours, 2)}:${padStart(minutes, 2)}`; - case "narrow": - return `${sign2}${hours}${minutes > 0 ? `:${minutes}` : ""}`; - case "techie": - return `${sign2}${padStart(hours, 2)}${padStart(minutes, 2)}`; - default: - throw new RangeError(`Value format ${format} is out of range for property format`); + toRFC2822() { + return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); } - } - function timeObject(obj) { - return pick(obj, ["hour", "minute", "second", "millisecond"]); - } - var monthsLong = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; - var monthsShort = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; - var monthsNarrow = ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"]; - function months(length) { - switch (length) { - case "narrow": - return [...monthsNarrow]; - case "short": - return [...monthsShort]; - case "long": - return [...monthsLong]; - case "numeric": - return ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]; - case "2-digit": - return ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"]; - default: - return null; + toHTTP() { + return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); } - } - var weekdaysLong = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; - var weekdaysShort = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; - var weekdaysNarrow = ["M", "T", "W", "T", "F", "S", "S"]; - function weekdays(length) { - switch (length) { - case "narrow": - return [...weekdaysNarrow]; - case "short": - return [...weekdaysShort]; - case "long": - return [...weekdaysLong]; - case "numeric": - return ["1", "2", "3", "4", "5", "6", "7"]; - default: + toSQLDate() { + if (!this.isValid) { return null; + } + return toISODate(this, true); } - } - var meridiems = ["AM", "PM"]; - var erasLong = ["Before Christ", "Anno Domini"]; - var erasShort = ["BC", "AD"]; - var erasNarrow = ["B", "A"]; - function eras(length) { - switch (length) { - case "narrow": - return [...erasNarrow]; - case "short": - return [...erasShort]; - case "long": - return [...erasLong]; - default: - return null; + toSQLTime({ + includeOffset = true, + includeZone = false, + includeOffsetSpace = true + } = {}) { + let fmt = "HH:mm:ss.SSS"; + if (includeZone || includeOffset) { + if (includeOffsetSpace) { + fmt += " "; + } + if (includeZone) { + fmt += "z"; + } else if (includeOffset) { + fmt += "ZZ"; + } + } + return toTechFormat(this, fmt, true); } - } - function meridiemForDateTime(dt) { - return meridiems[dt.hour < 12 ? 0 : 1]; - } - function weekdayForDateTime(dt, length) { - return weekdays(length)[dt.weekday - 1]; - } - function monthForDateTime(dt, length) { - return months(length)[dt.month - 1]; - } - function eraForDateTime(dt, length) { - return eras(length)[dt.year < 0 ? 0 : 1]; - } - function formatRelativeTime(unit, count, numeric2 = "always", narrow = false) { - const units = { - years: ["year", "yr."], - quarters: ["quarter", "qtr."], - months: ["month", "mo."], - weeks: ["week", "wk."], - days: ["day", "day", "days"], - hours: ["hour", "hr."], - minutes: ["minute", "min."], - seconds: ["second", "sec."] - }; - const lastable = ["hours", "minutes", "seconds"].indexOf(unit) === -1; - if (numeric2 === "auto" && lastable) { - const isDay = unit === "days"; - switch (count) { - case 1: - return isDay ? "tomorrow" : `next ${units[unit][0]}`; - case -1: - return isDay ? "yesterday" : `last ${units[unit][0]}`; - case 0: - return isDay ? "today" : `this ${units[unit][0]}`; + toSQL(opts = {}) { + if (!this.isValid) { + return null; } + return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; } - const isInPast = Object.is(count, -0) || count < 0, fmtValue = Math.abs(count), singular = fmtValue === 1, lilUnits = units[unit], fmtUnit = narrow ? singular ? lilUnits[1] : lilUnits[2] || lilUnits[1] : singular ? units[unit][0] : unit; - return isInPast ? `${fmtValue} ${fmtUnit} ago` : `in ${fmtValue} ${fmtUnit}`; - } - function stringifyTokens(splits, tokenToString) { - let s3 = ""; - for (const token of splits) { - if (token.literal) { - s3 += token.val; + toString() { + return this.isValid ? this.toISO() : INVALID; + } + [Symbol.for("nodejs.util.inspect.custom")]() { + if (this.isValid) { + return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`; } else { - s3 += tokenToString(token.val); + return `DateTime { Invalid, reason: ${this.invalidReason} }`; } } - return s3; - } - var macroTokenToFormatOpts = { - D: DATE_SHORT, - DD: DATE_MED, - DDD: DATE_FULL, - DDDD: DATE_HUGE, - t: TIME_SIMPLE, - tt: TIME_WITH_SECONDS, - ttt: TIME_WITH_SHORT_OFFSET, - tttt: TIME_WITH_LONG_OFFSET, - T: TIME_24_SIMPLE, - TT: TIME_24_WITH_SECONDS, - TTT: TIME_24_WITH_SHORT_OFFSET, - TTTT: TIME_24_WITH_LONG_OFFSET, - f: DATETIME_SHORT, - ff: DATETIME_MED, - fff: DATETIME_FULL, - ffff: DATETIME_HUGE, - F: DATETIME_SHORT_WITH_SECONDS, - FF: DATETIME_MED_WITH_SECONDS, - FFF: DATETIME_FULL_WITH_SECONDS, - FFFF: DATETIME_HUGE_WITH_SECONDS - }; - - class Formatter { - static create(locale2, opts = {}) { - return new Formatter(locale2, opts); + valueOf() { + return this.toMillis(); } - static parseFormat(fmt) { - let current = null, currentFull = "", bracketed = false; - const splits = []; - for (let i2 = 0;i2 < fmt.length; i2++) { - const c2 = fmt.charAt(i2); - if (c2 === "'") { - if (currentFull.length > 0 || bracketed) { - splits.push({ - literal: bracketed || /^\s+$/.test(currentFull), - val: currentFull === "" ? "'" : currentFull - }); - } - current = null; - currentFull = ""; - bracketed = !bracketed; - } else if (bracketed) { - currentFull += c2; - } else if (c2 === current) { - currentFull += c2; - } else { - if (currentFull.length > 0) { - splits.push({ - literal: /^\s+$/.test(currentFull), - val: currentFull - }); - } - currentFull = c2; - current = c2; - } + toMillis() { + return this.isValid ? this.ts : NaN; + } + toSeconds() { + return this.isValid ? this.ts / 1000 : NaN; + } + toUnixInteger() { + return this.isValid ? Math.floor(this.ts / 1000) : NaN; + } + toJSON() { + return this.toISO(); + } + toBSON() { + return this.toJSDate(); + } + toObject(opts = {}) { + if (!this.isValid) + return {}; + const base = { + ...this.c + }; + if (opts.includeConfig) { + base.outputCalendar = this.outputCalendar; + base.numberingSystem = this.loc.numberingSystem; + base.locale = this.loc.locale; } - if (currentFull.length > 0) { - splits.push({ - literal: bracketed || /^\s+$/.test(currentFull), - val: currentFull - }); + return base; + } + toJSDate() { + return new Date(this.isValid ? this.ts : NaN); + } + diff(otherDateTime, unit = "milliseconds", opts = {}) { + if (!this.isValid || !otherDateTime.isValid) { + return Duration.invalid("created by diffing an invalid DateTime"); } - return splits; + const durOpts = { + locale: this.locale, + numberingSystem: this.numberingSystem, + ...opts + }; + const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts); + return otherIsLater ? diffed.negate() : diffed; } - static macroTokenToFormatOpts(token) { - return macroTokenToFormatOpts[token]; + diffNow(unit = "milliseconds", opts = {}) { + return this.diff(DateTime.now(), unit, opts); } - constructor(locale2, formatOpts) { - this.opts = formatOpts; - this.loc = locale2; - this.systemLoc = null; + until(otherDateTime) { + return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; } - formatWithSystemDefault(dt, opts) { - if (this.systemLoc === null) { - this.systemLoc = this.loc.redefaultToSystem(); + hasSame(otherDateTime, unit, opts) { + if (!this.isValid) + return false; + const inputMs = otherDateTime.valueOf(); + const adjustedToZone = this.setZone(otherDateTime.zone, { + keepLocalTime: true + }); + return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts); + } + equals(other) { + return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); + } + toRelative(options = {}) { + if (!this.isValid) + return null; + const base = options.base || DateTime.fromObject({}, { + zone: this.zone + }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; + let units = ["years", "months", "days", "hours", "minutes", "seconds"]; + let unit = options.unit; + if (Array.isArray(options.unit)) { + units = options.unit; + unit = undefined; } - const df = this.systemLoc.dtFormatter(dt, { - ...this.opts, - ...opts + return diffRelative(base, this.plus(padding), { + ...options, + numeric: "always", + units, + unit }); - return df.format(); } - dtFormatter(dt, opts = {}) { - return this.loc.dtFormatter(dt, { - ...this.opts, - ...opts + toRelativeCalendar(options = {}) { + if (!this.isValid) + return null; + return diffRelative(options.base || DateTime.fromObject({}, { + zone: this.zone + }), this, { + ...options, + numeric: "auto", + units: ["years", "months", "days"], + calendary: true }); } - formatDateTime(dt, opts) { - return this.dtFormatter(dt, opts).format(); + static min(...dateTimes) { + if (!dateTimes.every(DateTime.isDateTime)) { + throw new InvalidArgumentError("min requires all arguments be DateTimes"); + } + return bestBy(dateTimes, (i2) => i2.valueOf(), Math.min); } - formatDateTimeParts(dt, opts) { - return this.dtFormatter(dt, opts).formatToParts(); + static max(...dateTimes) { + if (!dateTimes.every(DateTime.isDateTime)) { + throw new InvalidArgumentError("max requires all arguments be DateTimes"); + } + return bestBy(dateTimes, (i2) => i2.valueOf(), Math.max); } - formatInterval(interval2, opts) { - const df = this.dtFormatter(interval2.start, opts); - return df.dtf.formatRange(interval2.start.toJSDate(), interval2.end.toJSDate()); + static fromFormatExplain(text3, fmt, options = {}) { + const { + locale: locale2 = null, + numberingSystem = null + } = options, localeToUse = Locale.fromOpts({ + locale: locale2, + numberingSystem, + defaultToEN: true + }); + return explainFromTokens(localeToUse, text3, fmt); } - resolvedOptions(dt, opts) { - return this.dtFormatter(dt, opts).resolvedOptions(); + static fromStringExplain(text3, fmt, options = {}) { + return DateTime.fromFormatExplain(text3, fmt, options); } - num(n3, p2 = 0, signDisplay = undefined) { - if (this.opts.forceSimple) { - return padStart(n3, p2); + static buildFormatParser(fmt, options = {}) { + const { + locale: locale2 = null, + numberingSystem = null + } = options, localeToUse = Locale.fromOpts({ + locale: locale2, + numberingSystem, + defaultToEN: true + }); + return new TokenParser(localeToUse, fmt); + } + static fromFormatParser(text3, formatParser, opts = {}) { + if (isUndefined(text3) || isUndefined(formatParser)) { + throw new InvalidArgumentError("fromFormatParser requires an input string and a format parser"); } - const opts = { - ...this.opts - }; - if (p2 > 0) { - opts.padTo = p2; + const { + locale: locale2 = null, + numberingSystem = null + } = opts, localeToUse = Locale.fromOpts({ + locale: locale2, + numberingSystem, + defaultToEN: true + }); + if (!localeToUse.equals(formatParser.locale)) { + throw new InvalidArgumentError(`fromFormatParser called with a locale of ${localeToUse}, ` + `but the format parser was created for ${formatParser.locale}`); } - if (signDisplay) { - opts.signDisplay = signDisplay; + const { + result, + zone, + specificOffset, + invalidReason + } = formatParser.explainFromTokens(text3); + if (invalidReason) { + return DateTime.invalid(invalidReason); + } else { + return parseDataToDateTime(result, zone, opts, `format ${formatParser.format}`, text3, specificOffset); } - return this.loc.numberFormatter(opts).format(n3); } - formatDateTimeFromString(dt, fmt) { - const knownEnglish = this.loc.listingMode() === "en", useDateTimeFormatter = this.loc.outputCalendar && this.loc.outputCalendar !== "gregory", string2 = (opts, extract) => this.loc.extract(dt, opts, extract), formatOffset2 = (opts) => { - if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { - return "Z"; - } - return dt.isValid ? dt.zone.formatOffset(dt.ts, opts.format) : ""; - }, meridiem = () => knownEnglish ? meridiemForDateTime(dt) : string2({ - hour: "numeric", - hourCycle: "h12" - }, "dayperiod"), month = (length, standalone) => knownEnglish ? monthForDateTime(dt, length) : string2(standalone ? { - month: length - } : { - month: length, - day: "numeric" - }, "month"), weekday = (length, standalone) => knownEnglish ? weekdayForDateTime(dt, length) : string2(standalone ? { - weekday: length - } : { - weekday: length, - month: "long", - day: "numeric" - }, "weekday"), maybeMacro = (token) => { - const formatOpts = Formatter.macroTokenToFormatOpts(token); - if (formatOpts) { - return this.formatWithSystemDefault(dt, formatOpts); - } else { - return token; - } - }, era = (length) => knownEnglish ? eraForDateTime(dt, length) : string2({ - era: length - }, "era"), tokenToString = (token) => { - switch (token) { - case "S": - return this.num(dt.millisecond); - case "u": - case "SSS": - return this.num(dt.millisecond, 3); - case "s": - return this.num(dt.second); - case "ss": - return this.num(dt.second, 2); - case "uu": - return this.num(Math.floor(dt.millisecond / 10), 2); - case "uuu": - return this.num(Math.floor(dt.millisecond / 100)); - case "m": - return this.num(dt.minute); - case "mm": - return this.num(dt.minute, 2); - case "h": - return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); - case "hh": - return this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); - case "H": - return this.num(dt.hour); - case "HH": - return this.num(dt.hour, 2); - case "Z": - return formatOffset2({ - format: "narrow", - allowZ: this.opts.allowZ - }); - case "ZZ": - return formatOffset2({ - format: "short", - allowZ: this.opts.allowZ - }); - case "ZZZ": - return formatOffset2({ - format: "techie", - allowZ: this.opts.allowZ - }); - case "ZZZZ": - return dt.zone.offsetName(dt.ts, { - format: "short", - locale: this.loc.locale - }); - case "ZZZZZ": - return dt.zone.offsetName(dt.ts, { - format: "long", - locale: this.loc.locale - }); - case "z": - return dt.zoneName; - case "a": - return meridiem(); - case "d": - return useDateTimeFormatter ? string2({ - day: "numeric" - }, "day") : this.num(dt.day); - case "dd": - return useDateTimeFormatter ? string2({ - day: "2-digit" - }, "day") : this.num(dt.day, 2); - case "c": - return this.num(dt.weekday); - case "ccc": - return weekday("short", true); - case "cccc": - return weekday("long", true); - case "ccccc": - return weekday("narrow", true); - case "E": - return this.num(dt.weekday); - case "EEE": - return weekday("short", false); - case "EEEE": - return weekday("long", false); - case "EEEEE": - return weekday("narrow", false); - case "L": - return useDateTimeFormatter ? string2({ - month: "numeric", - day: "numeric" - }, "month") : this.num(dt.month); - case "LL": - return useDateTimeFormatter ? string2({ - month: "2-digit", - day: "numeric" - }, "month") : this.num(dt.month, 2); - case "LLL": - return month("short", true); - case "LLLL": - return month("long", true); - case "LLLLL": - return month("narrow", true); - case "M": - return useDateTimeFormatter ? string2({ - month: "numeric" - }, "month") : this.num(dt.month); - case "MM": - return useDateTimeFormatter ? string2({ - month: "2-digit" - }, "month") : this.num(dt.month, 2); - case "MMM": - return month("short", false); - case "MMMM": - return month("long", false); - case "MMMMM": - return month("narrow", false); - case "y": - return useDateTimeFormatter ? string2({ - year: "numeric" - }, "year") : this.num(dt.year); - case "yy": - return useDateTimeFormatter ? string2({ - year: "2-digit" - }, "year") : this.num(dt.year.toString().slice(-2), 2); - case "yyyy": - return useDateTimeFormatter ? string2({ - year: "numeric" - }, "year") : this.num(dt.year, 4); - case "yyyyyy": - return useDateTimeFormatter ? string2({ - year: "numeric" - }, "year") : this.num(dt.year, 6); - case "G": - return era("short"); - case "GG": - return era("long"); - case "GGGGG": - return era("narrow"); - case "kk": - return this.num(dt.weekYear.toString().slice(-2), 2); - case "kkkk": - return this.num(dt.weekYear, 4); - case "W": - return this.num(dt.weekNumber); - case "WW": - return this.num(dt.weekNumber, 2); - case "n": - return this.num(dt.localWeekNumber); - case "nn": - return this.num(dt.localWeekNumber, 2); - case "ii": - return this.num(dt.localWeekYear.toString().slice(-2), 2); - case "iiii": - return this.num(dt.localWeekYear, 4); - case "o": - return this.num(dt.ordinal); - case "ooo": - return this.num(dt.ordinal, 3); - case "q": - return this.num(dt.quarter); - case "qq": - return this.num(dt.quarter, 2); - case "X": - return this.num(Math.floor(dt.ts / 1000)); - case "x": - return this.num(dt.ts); - default: - return maybeMacro(token); - } - }; - return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); + static get DATE_SHORT() { + return DATE_SHORT; } - formatDurationFromString(dur, fmt) { - const invertLargest = this.opts.signMode === "negativeLargestOnly" ? -1 : 1; - const tokenToField = (token) => { - switch (token[0]) { - case "S": - return "milliseconds"; - case "s": - return "seconds"; - case "m": - return "minutes"; - case "h": - return "hours"; - case "d": - return "days"; - case "w": - return "weeks"; - case "M": - return "months"; - case "y": - return "years"; - default: - return null; - } - }, tokenToString = (lildur, info) => (token) => { - const mapped = tokenToField(token); - if (mapped) { - const inversionFactor = info.isNegativeDuration && mapped !== info.largestUnit ? invertLargest : 1; - let signDisplay; - if (this.opts.signMode === "negativeLargestOnly" && mapped !== info.largestUnit) { - signDisplay = "never"; - } else if (this.opts.signMode === "all") { - signDisplay = "always"; - } else { - signDisplay = "auto"; - } - return this.num(lildur.get(mapped) * inversionFactor, token.length, signDisplay); - } else { - return token; - } - }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce((found, { - literal, - val - }) => literal ? found : found.concat(val), []), collapsed = dur.shiftTo(...realTokens.map(tokenToField).filter((t9) => t9)), durationInfo = { - isNegativeDuration: collapsed < 0, - largestUnit: Object.keys(collapsed.values)[0] - }; - return stringifyTokens(tokens, tokenToString(collapsed, durationInfo)); + static get DATE_MED() { + return DATE_MED; } - } - var ianaRegex = /[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/; - function combineRegexes(...regexes) { - const full = regexes.reduce((f2, r2) => f2 + r2.source, ""); - return RegExp(`^${full}$`); - } - function combineExtractors(...extractors) { - return (m2) => extractors.reduce(([mergedVals, mergedZone, cursor], ex) => { - const [val, zone, next] = ex(m2, cursor); - return [{ - ...mergedVals, - ...val - }, zone || mergedZone, next]; - }, [{}, null, 1]).slice(0, 2); - } - function parse2(s3, ...patterns) { - if (s3 == null) { - return [null, null]; + static get DATE_MED_WITH_WEEKDAY() { + return DATE_MED_WITH_WEEKDAY; } - for (const [regex, extractor] of patterns) { - const m2 = regex.exec(s3); - if (m2) { - return extractor(m2); - } + static get DATE_FULL() { + return DATE_FULL; } - return [null, null]; - } - function simpleParse(...keys) { - return (match2, cursor) => { - const ret = {}; - let i2; - for (i2 = 0;i2 < keys.length; i2++) { - ret[keys[i2]] = parseInteger(match2[cursor + i2]); - } - return [ret, null, cursor + i2]; - }; - } - var offsetRegex = /(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/; - var isoExtendedZone = `(?:${offsetRegex.source}?(?:\\[(${ianaRegex.source})\\])?)?`; - var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/; - var isoTimeRegex = RegExp(`${isoTimeBaseRegex.source}${isoExtendedZone}`); - var isoTimeExtensionRegex = RegExp(`(?:[Tt]${isoTimeRegex.source})?`); - var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; - var isoWeekRegex = /(\d{4})-?W(\d\d)(?:-?(\d))?/; - var isoOrdinalRegex = /(\d{4})-?(\d{3})/; - var extractISOWeekData = simpleParse("weekYear", "weekNumber", "weekDay"); - var extractISOOrdinalData = simpleParse("year", "ordinal"); - var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; - var sqlTimeRegex = RegExp(`${isoTimeBaseRegex.source} ?(?:${offsetRegex.source}|(${ianaRegex.source}))?`); - var sqlTimeExtensionRegex = RegExp(`(?: ${sqlTimeRegex.source})?`); - function int(match2, pos, fallback) { - const m2 = match2[pos]; - return isUndefined(m2) ? fallback : parseInteger(m2); - } - function extractISOYmd(match2, cursor) { - const item = { - year: int(match2, cursor), - month: int(match2, cursor + 1, 1), - day: int(match2, cursor + 2, 1) - }; - return [item, null, cursor + 3]; - } - function extractISOTime(match2, cursor) { - const item = { - hours: int(match2, cursor, 0), - minutes: int(match2, cursor + 1, 0), - seconds: int(match2, cursor + 2, 0), - milliseconds: parseMillis(match2[cursor + 3]) - }; - return [item, null, cursor + 4]; - } - function extractISOOffset(match2, cursor) { - const local = !match2[cursor] && !match2[cursor + 1], fullOffset = signedOffset(match2[cursor + 1], match2[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); - return [{}, zone, cursor + 3]; - } - function extractIANAZone(match2, cursor) { - const zone = match2[cursor] ? IANAZone.create(match2[cursor]) : null; - return [{}, zone, cursor + 1]; - } - var isoTimeOnly = RegExp(`^T?${isoTimeBaseRegex.source}$`); - var isoDuration = /^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/; - function extractISODuration(match2) { - const [s3, yearStr, monthStr, weekStr, dayStr, hourStr, minuteStr, secondStr, millisecondsStr] = match2; - const hasNegativePrefix = s3[0] === "-"; - const negativeSeconds = secondStr && secondStr[0] === "-"; - const maybeNegate = (num, force = false) => num !== undefined && (force || num && hasNegativePrefix) ? -num : num; - return [{ - years: maybeNegate(parseFloating(yearStr)), - months: maybeNegate(parseFloating(monthStr)), - weeks: maybeNegate(parseFloating(weekStr)), - days: maybeNegate(parseFloating(dayStr)), - hours: maybeNegate(parseFloating(hourStr)), - minutes: maybeNegate(parseFloating(minuteStr)), - seconds: maybeNegate(parseFloating(secondStr), secondStr === "-0"), - milliseconds: maybeNegate(parseMillis(millisecondsStr), negativeSeconds) - }]; - } - var obsOffsets = { - GMT: 0, - EDT: -4 * 60, - EST: -5 * 60, - CDT: -5 * 60, - CST: -6 * 60, - MDT: -6 * 60, - MST: -7 * 60, - PDT: -7 * 60, - PST: -8 * 60 - }; - function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { - const result = { - year: yearStr.length === 2 ? untruncateYear(parseInteger(yearStr)) : parseInteger(yearStr), - month: monthsShort.indexOf(monthStr) + 1, - day: parseInteger(dayStr), - hour: parseInteger(hourStr), - minute: parseInteger(minuteStr) - }; - if (secondStr) - result.second = parseInteger(secondStr); - if (weekdayStr) { - result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; + static get DATE_HUGE() { + return DATE_HUGE; } - return result; - } - var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; - function extractRFC2822(match2) { - const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr, obsOffset, milOffset, offHourStr, offMinuteStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - let offset2; - if (obsOffset) { - offset2 = obsOffsets[obsOffset]; - } else if (milOffset) { - offset2 = 0; - } else { - offset2 = signedOffset(offHourStr, offMinuteStr); + static get TIME_SIMPLE() { + return TIME_SIMPLE; } - return [result, new FixedOffsetZone(offset2)]; - } - function preprocessRFC2822(s3) { - return s3.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").trim(); - } - var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; - var rfc850 = /^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; - var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; - function extractRFC1123Or850(match2) { - const [, weekdayStr, dayStr, monthStr, yearStr, hourStr, minuteStr, secondStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - return [result, FixedOffsetZone.utcInstance]; - } - function extractASCII(match2) { - const [, weekdayStr, monthStr, dayStr, hourStr, minuteStr, secondStr, yearStr] = match2, result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); - return [result, FixedOffsetZone.utcInstance]; - } - var isoYmdWithTimeExtensionRegex = combineRegexes(isoYmdRegex, isoTimeExtensionRegex); - var isoWeekWithTimeExtensionRegex = combineRegexes(isoWeekRegex, isoTimeExtensionRegex); - var isoOrdinalWithTimeExtensionRegex = combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex); - var isoTimeCombinedRegex = combineRegexes(isoTimeRegex); - var extractISOYmdTimeAndOffset = combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone); - var extractISOWeekTimeAndOffset = combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset, extractIANAZone); - var extractISOOrdinalDateAndTime = combineExtractors(extractISOOrdinalData, extractISOTime, extractISOOffset, extractIANAZone); - var extractISOTimeAndOffset = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); - function parseISODate(s3) { - return parse2(s3, [isoYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [isoWeekWithTimeExtensionRegex, extractISOWeekTimeAndOffset], [isoOrdinalWithTimeExtensionRegex, extractISOOrdinalDateAndTime], [isoTimeCombinedRegex, extractISOTimeAndOffset]); - } - function parseRFC2822Date(s3) { - return parse2(preprocessRFC2822(s3), [rfc2822, extractRFC2822]); - } - function parseHTTPDate(s3) { - return parse2(s3, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); - } - function parseISODuration(s3) { - return parse2(s3, [isoDuration, extractISODuration]); - } - var extractISOTimeOnly = combineExtractors(extractISOTime); - function parseISOTimeOnly(s3) { - return parse2(s3, [isoTimeOnly, extractISOTimeOnly]); - } - var sqlYmdWithTimeExtensionRegex = combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex); - var sqlTimeCombinedRegex = combineRegexes(sqlTimeRegex); - var extractISOTimeOffsetAndIANAZone = combineExtractors(extractISOTime, extractISOOffset, extractIANAZone); - function parseSQL(s3) { - return parse2(s3, [sqlYmdWithTimeExtensionRegex, extractISOYmdTimeAndOffset], [sqlTimeCombinedRegex, extractISOTimeOffsetAndIANAZone]); - } - var INVALID$2 = "Invalid Duration"; - var lowOrderMatrix = { - weeks: { - days: 7, - hours: 7 * 24, - minutes: 7 * 24 * 60, - seconds: 7 * 24 * 60 * 60, - milliseconds: 7 * 24 * 60 * 60 * 1000 - }, - days: { - hours: 24, - minutes: 24 * 60, - seconds: 24 * 60 * 60, - milliseconds: 24 * 60 * 60 * 1000 - }, - hours: { - minutes: 60, - seconds: 60 * 60, - milliseconds: 60 * 60 * 1000 - }, - minutes: { - seconds: 60, - milliseconds: 60 * 1000 - }, - seconds: { - milliseconds: 1000 + static get TIME_WITH_SECONDS() { + return TIME_WITH_SECONDS; } - }; - var casualMatrix = { - years: { - quarters: 4, - months: 12, - weeks: 52, - days: 365, - hours: 365 * 24, - minutes: 365 * 24 * 60, - seconds: 365 * 24 * 60 * 60, - milliseconds: 365 * 24 * 60 * 60 * 1000 - }, - quarters: { - months: 3, - weeks: 13, - days: 91, - hours: 91 * 24, - minutes: 91 * 24 * 60, - seconds: 91 * 24 * 60 * 60, - milliseconds: 91 * 24 * 60 * 60 * 1000 - }, - months: { - weeks: 4, - days: 30, - hours: 30 * 24, - minutes: 30 * 24 * 60, - seconds: 30 * 24 * 60 * 60, - milliseconds: 30 * 24 * 60 * 60 * 1000 - }, - ...lowOrderMatrix - }; - var daysInYearAccurate = 146097 / 400; - var daysInMonthAccurate = 146097 / 4800; - var accurateMatrix = { - years: { - quarters: 4, - months: 12, - weeks: daysInYearAccurate / 7, - days: daysInYearAccurate, - hours: daysInYearAccurate * 24, - minutes: daysInYearAccurate * 24 * 60, - seconds: daysInYearAccurate * 24 * 60 * 60, - milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 - }, - quarters: { - months: 3, - weeks: daysInYearAccurate / 28, - days: daysInYearAccurate / 4, - hours: daysInYearAccurate * 24 / 4, - minutes: daysInYearAccurate * 24 * 60 / 4, - seconds: daysInYearAccurate * 24 * 60 * 60 / 4, - milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4 - }, - months: { - weeks: daysInMonthAccurate / 7, - days: daysInMonthAccurate, - hours: daysInMonthAccurate * 24, - minutes: daysInMonthAccurate * 24 * 60, - seconds: daysInMonthAccurate * 24 * 60 * 60, - milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 - }, - ...lowOrderMatrix - }; - var orderedUnits$1 = ["years", "quarters", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"]; - var reverseUnits = orderedUnits$1.slice(0).reverse(); - function clone$1(dur, alts, clear = false) { - const conf = { - values: clear ? alts.values : { - ...dur.values, - ...alts.values || {} - }, - loc: dur.loc.clone(alts.loc), - conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy, - matrix: alts.matrix || dur.matrix - }; - return new Duration(conf); - } - function durationToMillis(matrix, vals) { - var _vals$milliseconds; - let sum = (_vals$milliseconds = vals.milliseconds) != null ? _vals$milliseconds : 0; - for (const unit of reverseUnits.slice(1)) { - if (vals[unit]) { - sum += vals[unit] * matrix[unit]["milliseconds"]; - } + static get TIME_WITH_SHORT_OFFSET() { + return TIME_WITH_SHORT_OFFSET; } - return sum; - } - function normalizeValues(matrix, vals) { - const factor = durationToMillis(matrix, vals) < 0 ? -1 : 1; - orderedUnits$1.reduceRight((previous, current) => { - if (!isUndefined(vals[current])) { - if (previous) { - const previousVal = vals[previous] * factor; - const conv = matrix[current][previous]; - const rollUp = Math.floor(previousVal / conv); - vals[current] += rollUp * factor; - vals[previous] -= rollUp * conv * factor; - } - return current; - } else { - return previous; - } - }, null); - orderedUnits$1.reduce((previous, current) => { - if (!isUndefined(vals[current])) { - if (previous) { - const fraction = vals[previous] % 1; - vals[previous] -= fraction; - vals[current] += fraction * matrix[previous][current]; - } - return current; - } else { - return previous; - } - }, null); - } - function removeZeroes(vals) { - const newVals = {}; - for (const [key, value] of Object.entries(vals)) { - if (value !== 0) { - newVals[key] = value; - } + static get TIME_WITH_LONG_OFFSET() { + return TIME_WITH_LONG_OFFSET; } - return newVals; - } - - class Duration { - constructor(config) { - const accurate = config.conversionAccuracy === "longterm" || false; - let matrix = accurate ? accurateMatrix : casualMatrix; - if (config.matrix) { - matrix = config.matrix; - } - this.values = config.values; - this.loc = config.loc || Locale.create(); - this.conversionAccuracy = accurate ? "longterm" : "casual"; - this.invalid = config.invalid || null; - this.matrix = matrix; - this.isLuxonDuration = true; + static get TIME_24_SIMPLE() { + return TIME_24_SIMPLE; } - static fromMillis(count, opts) { - return Duration.fromObject({ - milliseconds: count - }, opts); + static get TIME_24_WITH_SECONDS() { + return TIME_24_WITH_SECONDS; } - static fromObject(obj, opts = {}) { - if (obj == null || typeof obj !== "object") { - throw new InvalidArgumentError(`Duration.fromObject: argument expected to be an object, got ${obj === null ? "null" : typeof obj}`); - } - return new Duration({ - values: normalizeObject(obj, Duration.normalizeUnit), - loc: Locale.fromObject(opts), - conversionAccuracy: opts.conversionAccuracy, - matrix: opts.matrix - }); + static get TIME_24_WITH_SHORT_OFFSET() { + return TIME_24_WITH_SHORT_OFFSET; } - static fromDurationLike(durationLike) { - if (isNumber(durationLike)) { - return Duration.fromMillis(durationLike); - } else if (Duration.isDuration(durationLike)) { - return durationLike; - } else if (typeof durationLike === "object") { - return Duration.fromObject(durationLike); - } else { - throw new InvalidArgumentError(`Unknown duration argument ${durationLike} of type ${typeof durationLike}`); - } + static get TIME_24_WITH_LONG_OFFSET() { + return TIME_24_WITH_LONG_OFFSET; } - static fromISO(text2, opts) { - const [parsed] = parseISODuration(text2); - if (parsed) { - return Duration.fromObject(parsed, opts); - } else { - return Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); - } + static get DATETIME_SHORT() { + return DATETIME_SHORT; } - static fromISOTime(text2, opts) { - const [parsed] = parseISOTimeOnly(text2); - if (parsed) { - return Duration.fromObject(parsed, opts); - } else { - return Duration.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); - } + static get DATETIME_SHORT_WITH_SECONDS() { + return DATETIME_SHORT_WITH_SECONDS; } - static invalid(reason, explanation = null) { - if (!reason) { - throw new InvalidArgumentError("need to specify a reason the Duration is invalid"); - } - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - if (Settings.throwOnInvalid) { - throw new InvalidDurationError(invalid); - } else { - return new Duration({ - invalid - }); - } + static get DATETIME_MED() { + return DATETIME_MED; } - static normalizeUnit(unit) { - const normalized = { - year: "years", - years: "years", - quarter: "quarters", - quarters: "quarters", - month: "months", - months: "months", - week: "weeks", - weeks: "weeks", - day: "days", - days: "days", - hour: "hours", - hours: "hours", - minute: "minutes", - minutes: "minutes", - second: "seconds", - seconds: "seconds", - millisecond: "milliseconds", - milliseconds: "milliseconds" - }[unit ? unit.toLowerCase() : unit]; - if (!normalized) - throw new InvalidUnitError(unit); - return normalized; + static get DATETIME_MED_WITH_SECONDS() { + return DATETIME_MED_WITH_SECONDS; } - static isDuration(o2) { - return o2 && o2.isLuxonDuration || false; + static get DATETIME_MED_WITH_WEEKDAY() { + return DATETIME_MED_WITH_WEEKDAY; } - get locale() { - return this.isValid ? this.loc.locale : null; + static get DATETIME_FULL() { + return DATETIME_FULL; } - get numberingSystem() { - return this.isValid ? this.loc.numberingSystem : null; + static get DATETIME_FULL_WITH_SECONDS() { + return DATETIME_FULL_WITH_SECONDS; } - toFormat(fmt, opts = {}) { - const fmtOpts = { - ...opts, - floor: opts.round !== false && opts.floor !== false - }; - return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$2; + static get DATETIME_HUGE() { + return DATETIME_HUGE; } - toHuman(opts = {}) { - if (!this.isValid) - return INVALID$2; - const showZeros = opts.showZeros !== false; - const l3 = orderedUnits$1.map((unit) => { - const val = this.values[unit]; - if (isUndefined(val) || val === 0 && !showZeros) { - return null; - } - return this.loc.numberFormatter({ - style: "unit", - unitDisplay: "long", - ...opts, - unit: unit.slice(0, -1) - }).format(val); - }).filter((n3) => n3); - return this.loc.listFormatter({ - type: "conjunction", - style: opts.listStyle || "narrow", - ...opts - }).format(l3); + static get DATETIME_HUGE_WITH_SECONDS() { + return DATETIME_HUGE_WITH_SECONDS; } - toObject() { - if (!this.isValid) - return {}; - return { - ...this.values - }; + } + function friendlyDateTime(dateTimeish) { + if (DateTime.isDateTime(dateTimeish)) { + return dateTimeish; + } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { + return DateTime.fromJSDate(dateTimeish); + } else if (dateTimeish && typeof dateTimeish === "object") { + return DateTime.fromObject(dateTimeish); + } else { + throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`); } - toISO() { - if (!this.isValid) - return null; - let s3 = "P"; - if (this.years !== 0) - s3 += this.years + "Y"; - if (this.months !== 0 || this.quarters !== 0) - s3 += this.months + this.quarters * 3 + "M"; - if (this.weeks !== 0) - s3 += this.weeks + "W"; - if (this.days !== 0) - s3 += this.days + "D"; - if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0) - s3 += "T"; - if (this.hours !== 0) - s3 += this.hours + "H"; - if (this.minutes !== 0) - s3 += this.minutes + "M"; - if (this.seconds !== 0 || this.milliseconds !== 0) - s3 += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S"; - if (s3 === "P") - s3 += "T0S"; - return s3; + } + var VERSION = "3.7.2"; + exports.DateTime = DateTime; + exports.Duration = Duration; + exports.FixedOffsetZone = FixedOffsetZone; + exports.IANAZone = IANAZone; + exports.Info = Info; + exports.Interval = Interval; + exports.InvalidZone = InvalidZone; + exports.Settings = Settings; + exports.SystemZone = SystemZone; + exports.VERSION = VERSION; + exports.Zone = Zone; +}); + +// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/date.js +var require_date = __commonJS((exports, module) => { + var luxon = require_luxon(); + CronDate.prototype.addYear = function() { + this._date = this._date.plus({ years: 1 }); + }; + CronDate.prototype.addMonth = function() { + this._date = this._date.plus({ months: 1 }).startOf("month"); + }; + CronDate.prototype.addDay = function() { + this._date = this._date.plus({ days: 1 }).startOf("day"); + }; + CronDate.prototype.addHour = function() { + var prev = this._date; + this._date = this._date.plus({ hours: 1 }).startOf("hour"); + if (this._date <= prev) { + this._date = this._date.plus({ hours: 1 }); } - toISOTime(opts = {}) { - if (!this.isValid) - return null; - const millis = this.toMillis(); - if (millis < 0 || millis >= 86400000) - return null; - opts = { - suppressMilliseconds: false, - suppressSeconds: false, - includePrefix: false, - format: "extended", - ...opts, - includeOffset: false - }; - const dateTime = DateTime.fromMillis(millis, { - zone: "UTC" - }); - return dateTime.toISOTime(opts); + }; + CronDate.prototype.addMinute = function() { + var prev = this._date; + this._date = this._date.plus({ minutes: 1 }).startOf("minute"); + if (this._date < prev) { + this._date = this._date.plus({ hours: 1 }); } - toJSON() { - return this.toISO(); + }; + CronDate.prototype.addSecond = function() { + var prev = this._date; + this._date = this._date.plus({ seconds: 1 }).startOf("second"); + if (this._date < prev) { + this._date = this._date.plus({ hours: 1 }); } - toString() { - return this.toISO(); + }; + CronDate.prototype.subtractYear = function() { + this._date = this._date.minus({ years: 1 }); + }; + CronDate.prototype.subtractMonth = function() { + this._date = this._date.minus({ months: 1 }).endOf("month").startOf("second"); + }; + CronDate.prototype.subtractDay = function() { + this._date = this._date.minus({ days: 1 }).endOf("day").startOf("second"); + }; + CronDate.prototype.subtractHour = function() { + var prev = this._date; + this._date = this._date.minus({ hours: 1 }).endOf("hour").startOf("second"); + if (this._date >= prev) { + this._date = this._date.minus({ hours: 1 }); } - [Symbol.for("nodejs.util.inspect.custom")]() { - if (this.isValid) { - return `Duration { values: ${JSON.stringify(this.values)} }`; - } else { - return `Duration { Invalid, reason: ${this.invalidReason} }`; - } + }; + CronDate.prototype.subtractMinute = function() { + var prev = this._date; + this._date = this._date.minus({ minutes: 1 }).endOf("minute").startOf("second"); + if (this._date > prev) { + this._date = this._date.minus({ hours: 1 }); } - toMillis() { - if (!this.isValid) - return NaN; - return durationToMillis(this.matrix, this.values); + }; + CronDate.prototype.subtractSecond = function() { + var prev = this._date; + this._date = this._date.minus({ seconds: 1 }).startOf("second"); + if (this._date > prev) { + this._date = this._date.minus({ hours: 1 }); } - valueOf() { - return this.toMillis(); + }; + CronDate.prototype.getDate = function() { + return this._date.day; + }; + CronDate.prototype.getFullYear = function() { + return this._date.year; + }; + CronDate.prototype.getDay = function() { + var weekday = this._date.weekday; + return weekday == 7 ? 0 : weekday; + }; + CronDate.prototype.getMonth = function() { + return this._date.month - 1; + }; + CronDate.prototype.getHours = function() { + return this._date.hour; + }; + CronDate.prototype.getMinutes = function() { + return this._date.minute; + }; + CronDate.prototype.getSeconds = function() { + return this._date.second; + }; + CronDate.prototype.getMilliseconds = function() { + return this._date.millisecond; + }; + CronDate.prototype.getTime = function() { + return this._date.valueOf(); + }; + CronDate.prototype.getUTCDate = function() { + return this._getUTC().day; + }; + CronDate.prototype.getUTCFullYear = function() { + return this._getUTC().year; + }; + CronDate.prototype.getUTCDay = function() { + var weekday = this._getUTC().weekday; + return weekday == 7 ? 0 : weekday; + }; + CronDate.prototype.getUTCMonth = function() { + return this._getUTC().month - 1; + }; + CronDate.prototype.getUTCHours = function() { + return this._getUTC().hour; + }; + CronDate.prototype.getUTCMinutes = function() { + return this._getUTC().minute; + }; + CronDate.prototype.getUTCSeconds = function() { + return this._getUTC().second; + }; + CronDate.prototype.toISOString = function() { + return this._date.toUTC().toISO(); + }; + CronDate.prototype.toJSON = function() { + return this._date.toJSON(); + }; + CronDate.prototype.setDate = function(d2) { + this._date = this._date.set({ day: d2 }); + }; + CronDate.prototype.setFullYear = function(y2) { + this._date = this._date.set({ year: y2 }); + }; + CronDate.prototype.setDay = function(d2) { + this._date = this._date.set({ weekday: d2 }); + }; + CronDate.prototype.setMonth = function(m2) { + this._date = this._date.set({ month: m2 + 1 }); + }; + CronDate.prototype.setHours = function(h2) { + this._date = this._date.set({ hour: h2 }); + }; + CronDate.prototype.setMinutes = function(m2) { + this._date = this._date.set({ minute: m2 }); + }; + CronDate.prototype.setSeconds = function(s2) { + this._date = this._date.set({ second: s2 }); + }; + CronDate.prototype.setMilliseconds = function(s2) { + this._date = this._date.set({ millisecond: s2 }); + }; + CronDate.prototype._getUTC = function() { + return this._date.toUTC(); + }; + CronDate.prototype.toString = function() { + return this.toDate().toString(); + }; + CronDate.prototype.toDate = function() { + return this._date.toJSDate(); + }; + CronDate.prototype.isLastDayOfMonth = function() { + var newDate = this._date.plus({ days: 1 }).startOf("day"); + return this._date.month !== newDate.month; + }; + CronDate.prototype.isLastWeekdayOfMonth = function() { + var newDate = this._date.plus({ days: 7 }).startOf("day"); + return this._date.month !== newDate.month; + }; + function CronDate(timestamp3, tz) { + var dateOpts = { zone: tz }; + if (!timestamp3) { + this._date = luxon.DateTime.local(); + } else if (timestamp3 instanceof CronDate) { + this._date = timestamp3._date; + } else if (timestamp3 instanceof Date) { + this._date = luxon.DateTime.fromJSDate(timestamp3, dateOpts); + } else if (typeof timestamp3 === "number") { + this._date = luxon.DateTime.fromMillis(timestamp3, dateOpts); + } else if (typeof timestamp3 === "string") { + this._date = luxon.DateTime.fromISO(timestamp3, dateOpts); + this._date.isValid || (this._date = luxon.DateTime.fromRFC2822(timestamp3, dateOpts)); + this._date.isValid || (this._date = luxon.DateTime.fromSQL(timestamp3, dateOpts)); + this._date.isValid || (this._date = luxon.DateTime.fromFormat(timestamp3, "EEE, d MMM yyyy HH:mm:ss", dateOpts)); } - plus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration), result = {}; - for (const k2 of orderedUnits$1) { - if (hasOwnProperty(dur.values, k2) || hasOwnProperty(this.values, k2)) { - result[k2] = dur.get(k2) + this.get(k2); - } - } - return clone$1(this, { - values: result - }, true); + if (!this._date || !this._date.isValid) { + throw new Error("CronDate: unhandled timestamp: " + JSON.stringify(timestamp3)); } - minus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration); - return this.plus(dur.negate()); + if (tz && tz !== this._date.zoneName) { + this._date = this._date.setZone(tz); } - mapUnits(fn) { - if (!this.isValid) - return this; - const result = {}; - for (const k2 of Object.keys(this.values)) { - result[k2] = asNumber(fn(this.values[k2], k2)); + } + module.exports = CronDate; +}); + +// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/field_compactor.js +var require_field_compactor = __commonJS((exports, module) => { + function buildRange(item) { + return { + start: item, + count: 1 + }; + } + function completeRangeWithItem(range, item) { + range.end = item; + range.step = item - range.start; + range.count = 2; + } + function finalizeCurrentRange(results, currentRange, currentItemRange) { + if (currentRange) { + if (currentRange.count === 2) { + results.push(buildRange(currentRange.start)); + results.push(buildRange(currentRange.end)); + } else { + results.push(currentRange); } - return clone$1(this, { - values: result - }, true); - } - get(unit) { - return this[Duration.normalizeUnit(unit)]; - } - set(values) { - if (!this.isValid) - return this; - const mixed2 = { - ...this.values, - ...normalizeObject(values, Duration.normalizeUnit) - }; - return clone$1(this, { - values: mixed2 - }); - } - reconfigure({ - locale: locale2, - numberingSystem, - conversionAccuracy, - matrix - } = {}) { - const loc = this.loc.clone({ - locale: locale2, - numberingSystem - }); - const opts = { - loc, - matrix, - conversionAccuracy - }; - return clone$1(this, opts); } - as(unit) { - return this.isValid ? this.shiftTo(unit).get(unit) : NaN; + if (currentItemRange) { + results.push(currentItemRange); } - normalize() { - if (!this.isValid) - return this; - const vals = this.toObject(); - normalizeValues(this.matrix, vals); - return clone$1(this, { - values: vals - }, true); + } + function compactField(arr) { + var results = []; + var currentRange = undefined; + for (var i2 = 0;i2 < arr.length; i2++) { + var currentItem = arr[i2]; + if (typeof currentItem !== "number") { + finalizeCurrentRange(results, currentRange, buildRange(currentItem)); + currentRange = undefined; + } else if (!currentRange) { + currentRange = buildRange(currentItem); + } else if (currentRange.count === 1) { + completeRangeWithItem(currentRange, currentItem); + } else { + if (currentRange.step === currentItem - currentRange.end) { + currentRange.count++; + currentRange.end = currentItem; + } else if (currentRange.count === 2) { + results.push(buildRange(currentRange.start)); + currentRange = buildRange(currentRange.end); + completeRangeWithItem(currentRange, currentItem); + } else { + finalizeCurrentRange(results, currentRange); + currentRange = buildRange(currentItem); + } + } } - rescale() { - if (!this.isValid) - return this; - const vals = removeZeroes(this.normalize().shiftToAll().toObject()); - return clone$1(this, { - values: vals - }, true); + finalizeCurrentRange(results, currentRange); + return results; + } + module.exports = compactField; +}); + +// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/field_stringify.js +var require_field_stringify = __commonJS((exports, module) => { + var compactField = require_field_compactor(); + function stringifyField(arr, min, max) { + var ranges = compactField(arr); + if (ranges.length === 1) { + var singleRange = ranges[0]; + var step = singleRange.step; + if (step === 1 && singleRange.start === min && singleRange.end === max) { + return "*"; + } + if (step !== 1 && singleRange.start === min && singleRange.end === max - step + 1) { + return "*/" + step; + } } - shiftTo(...units) { - if (!this.isValid) - return this; - if (units.length === 0) { - return this; + var result = []; + for (var i2 = 0, l2 = ranges.length;i2 < l2; ++i2) { + var range = ranges[i2]; + if (range.count === 1) { + result.push(range.start); + continue; } - units = units.map((u2) => Duration.normalizeUnit(u2)); - const built = {}, accumulated = {}, vals = this.toObject(); - let lastUnit; - for (const k2 of orderedUnits$1) { - if (units.indexOf(k2) >= 0) { - lastUnit = k2; - let own = 0; - for (const ak2 in accumulated) { - own += this.matrix[ak2][k2] * accumulated[ak2]; - accumulated[ak2] = 0; - } - if (isNumber(vals[k2])) { - own += vals[k2]; - } - const i2 = Math.trunc(own); - built[k2] = i2; - accumulated[k2] = (own * 1000 - i2 * 1000) / 1000; - } else if (isNumber(vals[k2])) { - accumulated[k2] = vals[k2]; - } + var step = range.step; + if (range.step === 1) { + result.push(range.start + "-" + range.end); + continue; } - for (const key in accumulated) { - if (accumulated[key] !== 0) { - built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; - } + var multiplier = range.start == 0 ? range.count - 1 : range.count; + if (range.step * multiplier > range.end) { + result = result.concat(Array.from({ length: range.end - range.start + 1 }).map(function(_, index3) { + var value = range.start + index3; + if ((value - range.start) % range.step === 0) { + return value; + } + return null; + }).filter(function(value) { + return value != null; + })); + } else if (range.end === max - range.step + 1) { + result.push(range.start + "/" + range.step); + } else { + result.push(range.start + "-" + range.end + "/" + range.step); } - normalizeValues(this.matrix, built); - return clone$1(this, { - values: built - }, true); - } - shiftToAll() { - if (!this.isValid) - return this; - return this.shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds"); } - negate() { - if (!this.isValid) - return this; - const negated = {}; - for (const k2 of Object.keys(this.values)) { - negated[k2] = this.values[k2] === 0 ? 0 : -this.values[k2]; - } - return clone$1(this, { - values: negated - }, true); - } - removeZeros() { - if (!this.isValid) - return this; - const vals = removeZeroes(this.values); - return clone$1(this, { - values: vals - }, true); - } - get years() { - return this.isValid ? this.values.years || 0 : NaN; - } - get quarters() { - return this.isValid ? this.values.quarters || 0 : NaN; - } - get months() { - return this.isValid ? this.values.months || 0 : NaN; - } - get weeks() { - return this.isValid ? this.values.weeks || 0 : NaN; - } - get days() { - return this.isValid ? this.values.days || 0 : NaN; - } - get hours() { - return this.isValid ? this.values.hours || 0 : NaN; - } - get minutes() { - return this.isValid ? this.values.minutes || 0 : NaN; - } - get seconds() { - return this.isValid ? this.values.seconds || 0 : NaN; + return result.join(","); + } + module.exports = stringifyField; +}); + +// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/expression.js +var require_expression = __commonJS((exports, module) => { + var CronDate = require_date(); + var stringifyField = require_field_stringify(); + var LOOP_LIMIT = 1e4; + function CronExpression(fields, options) { + this._options = options; + this._utc = options.utc || false; + this._tz = this._utc ? "UTC" : options.tz; + this._currentDate = new CronDate(options.currentDate, this._tz); + this._startDate = options.startDate ? new CronDate(options.startDate, this._tz) : null; + this._endDate = options.endDate ? new CronDate(options.endDate, this._tz) : null; + this._isIterator = options.iterator || false; + this._hasIterated = false; + this._nthDayOfWeek = options.nthDayOfWeek || 0; + this.fields = CronExpression._freezeFields(fields); + } + CronExpression.map = ["second", "minute", "hour", "dayOfMonth", "month", "dayOfWeek"]; + CronExpression.predefined = { + "@yearly": "0 0 1 1 *", + "@monthly": "0 0 1 * *", + "@weekly": "0 0 * * 0", + "@daily": "0 0 * * *", + "@hourly": "0 * * * *" + }; + CronExpression.constraints = [ + { min: 0, max: 59, chars: [] }, + { min: 0, max: 59, chars: [] }, + { min: 0, max: 23, chars: [] }, + { min: 1, max: 31, chars: ["L"] }, + { min: 1, max: 12, chars: [] }, + { min: 0, max: 7, chars: ["L"] } + ]; + CronExpression.daysInMonth = [ + 31, + 29, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + CronExpression.aliases = { + month: { + jan: 1, + feb: 2, + mar: 3, + apr: 4, + may: 5, + jun: 6, + jul: 7, + aug: 8, + sep: 9, + oct: 10, + nov: 11, + dec: 12 + }, + dayOfWeek: { + sun: 0, + mon: 1, + tue: 2, + wed: 3, + thu: 4, + fri: 5, + sat: 6 } - get milliseconds() { - return this.isValid ? this.values.milliseconds || 0 : NaN; + }; + CronExpression.parseDefaults = ["0", "*", "*", "*", "*", "*"]; + CronExpression.standardValidCharacters = /^[,*\d/-]+$/; + CronExpression.dayOfWeekValidCharacters = /^[?,*\dL#/-]+$/; + CronExpression.dayOfMonthValidCharacters = /^[?,*\dL/-]+$/; + CronExpression.validCharacters = { + second: CronExpression.standardValidCharacters, + minute: CronExpression.standardValidCharacters, + hour: CronExpression.standardValidCharacters, + dayOfMonth: CronExpression.dayOfMonthValidCharacters, + month: CronExpression.standardValidCharacters, + dayOfWeek: CronExpression.dayOfWeekValidCharacters + }; + CronExpression._isValidConstraintChar = function _isValidConstraintChar(constraints, value) { + if (typeof value !== "string") { + return false; } - get isValid() { - return this.invalid === null; + return constraints.chars.some(function(char3) { + return value.indexOf(char3) > -1; + }); + }; + CronExpression._parseField = function _parseField(field, value, constraints) { + switch (field) { + case "month": + case "dayOfWeek": + var aliases = CronExpression.aliases[field]; + value = value.replace(/[a-z]{3}/gi, function(match) { + match = match.toLowerCase(); + if (typeof aliases[match] !== "undefined") { + return aliases[match]; + } else { + throw new Error('Validation error, cannot resolve alias "' + match + '"'); + } + }); + break; } - get invalidReason() { - return this.invalid ? this.invalid.reason : null; + if (!CronExpression.validCharacters[field].test(value)) { + throw new Error("Invalid characters, got value: " + value); } - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; + if (value.indexOf("*") !== -1) { + value = value.replace(/\*/g, constraints.min + "-" + constraints.max); + } else if (value.indexOf("?") !== -1) { + value = value.replace(/\?/g, constraints.min + "-" + constraints.max); } - equals(other) { - if (!this.isValid || !other.isValid) { - return false; - } - if (!this.loc.equals(other.loc)) { - return false; - } - function eq2(v1, v2) { - if (v1 === undefined || v1 === 0) - return v2 === undefined || v2 === 0; - return v1 === v2; - } - for (const u2 of orderedUnits$1) { - if (!eq2(this.values[u2], other.values[u2])) { - return false; + function parseSequence(val) { + var stack = []; + function handleResult(result) { + if (result instanceof Array) { + for (var i3 = 0, c3 = result.length;i3 < c3; i3++) { + var value2 = result[i3]; + if (CronExpression._isValidConstraintChar(constraints, value2)) { + stack.push(value2); + continue; + } + if (typeof value2 !== "number" || Number.isNaN(value2) || value2 < constraints.min || value2 > constraints.max) { + throw new Error("Constraint error, got value " + value2 + " expected range " + constraints.min + "-" + constraints.max); + } + stack.push(value2); + } + } else { + if (CronExpression._isValidConstraintChar(constraints, result)) { + stack.push(result); + return; + } + var numResult = +result; + if (Number.isNaN(numResult) || numResult < constraints.min || numResult > constraints.max) { + throw new Error("Constraint error, got value " + result + " expected range " + constraints.min + "-" + constraints.max); + } + if (field === "dayOfWeek") { + numResult = numResult % 7; + } + stack.push(numResult); } } - return true; - } - } - var INVALID$1 = "Invalid Interval"; - function validateStartEnd(start, end) { - if (!start || !start.isValid) { - return Interval.invalid("missing or invalid start"); - } else if (!end || !end.isValid) { - return Interval.invalid("missing or invalid end"); - } else if (end < start) { - return Interval.invalid("end before start", `The end of an interval must be after its start, but you had start=${start.toISO()} and end=${end.toISO()}`); - } else { - return null; - } - } - - class Interval { - constructor(config) { - this.s = config.start; - this.e = config.end; - this.invalid = config.invalid || null; - this.isLuxonInterval = true; - } - static invalid(reason, explanation = null) { - if (!reason) { - throw new InvalidArgumentError("need to specify a reason the Interval is invalid"); + var atoms = val.split(","); + if (!atoms.every(function(atom) { + return atom.length > 0; + })) { + throw new Error("Invalid list value format"); } - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - if (Settings.throwOnInvalid) { - throw new InvalidIntervalError(invalid); + if (atoms.length > 1) { + for (var i2 = 0, c2 = atoms.length;i2 < c2; i2++) { + handleResult(parseRepeat(atoms[i2])); + } } else { - return new Interval({ - invalid - }); + handleResult(parseRepeat(val)); } + stack.sort(CronExpression._sortCompareFn); + return stack; } - static fromDateTimes(start, end) { - const builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); - const validateError = validateStartEnd(builtStart, builtEnd); - if (validateError == null) { - return new Interval({ - start: builtStart, - end: builtEnd - }); - } else { - return validateError; + function parseRepeat(val) { + var repeatInterval = 1; + var atoms = val.split("/"); + if (atoms.length > 2) { + throw new Error("Invalid repeat: " + val); } + if (atoms.length > 1) { + if (atoms[0] == +atoms[0]) { + atoms = [atoms[0] + "-" + constraints.max, atoms[1]]; + } + return parseRange(atoms[0], atoms[atoms.length - 1]); + } + return parseRange(val, repeatInterval); } - static after(start, duration) { - const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(start); - return Interval.fromDateTimes(dt, dt.plus(dur)); - } - static before(end, duration) { - const dur = Duration.fromDurationLike(duration), dt = friendlyDateTime(end); - return Interval.fromDateTimes(dt.minus(dur), dt); - } - static fromISO(text2, opts) { - const [s3, e3] = (text2 || "").split("/", 2); - if (s3 && e3) { - let start, startIsValid; - try { - start = DateTime.fromISO(s3, opts); - startIsValid = start.isValid; - } catch (e4) { - startIsValid = false; + function parseRange(val, repeatInterval) { + var stack = []; + var atoms = val.split("-"); + if (atoms.length > 1) { + if (atoms.length < 2) { + return +val; } - let end, endIsValid; - try { - end = DateTime.fromISO(e3, opts); - endIsValid = end.isValid; - } catch (e4) { - endIsValid = false; + if (!atoms[0].length) { + if (!atoms[1].length) { + throw new Error("Invalid range: " + val); + } + return +val; } - if (startIsValid && endIsValid) { - return Interval.fromDateTimes(start, end); + var min = +atoms[0]; + var max = +atoms[1]; + if (Number.isNaN(min) || Number.isNaN(max) || min < constraints.min || max > constraints.max) { + throw new Error("Constraint error, got range " + min + "-" + max + " expected range " + constraints.min + "-" + constraints.max); + } else if (min > max) { + throw new Error("Invalid range: " + val); } - if (startIsValid) { - const dur = Duration.fromISO(e3, opts); - if (dur.isValid) { - return Interval.after(start, dur); - } - } else if (endIsValid) { - const dur = Duration.fromISO(s3, opts); - if (dur.isValid) { - return Interval.before(end, dur); + var repeatIndex = +repeatInterval; + if (Number.isNaN(repeatIndex) || repeatIndex <= 0) { + throw new Error("Constraint error, cannot repeat at every " + repeatIndex + " time."); + } + if (field === "dayOfWeek" && max % 7 === 0) { + stack.push(0); + } + for (var index3 = min, count2 = max;index3 <= count2; index3++) { + var exists2 = stack.indexOf(index3) !== -1; + if (!exists2 && repeatIndex > 0 && repeatIndex % repeatInterval === 0) { + repeatIndex = 1; + stack.push(index3); + } else { + repeatIndex++; } } + return stack; } - return Interval.invalid("unparsable", `the input "${text2}" can't be parsed as ISO 8601`); - } - static isInterval(o2) { - return o2 && o2.isLuxonInterval || false; - } - get start() { - return this.isValid ? this.s : null; - } - get end() { - return this.isValid ? this.e : null; - } - get lastDateTime() { - return this.isValid ? this.e ? this.e.minus(1) : null : null; - } - get isValid() { - return this.invalidReason === null; + return Number.isNaN(+val) ? val : +val; } - get invalidReason() { - return this.invalid ? this.invalid.reason : null; + return parseSequence(value); + }; + CronExpression._sortCompareFn = function(a2, b2) { + var aIsNumber = typeof a2 === "number"; + var bIsNumber = typeof b2 === "number"; + if (aIsNumber && bIsNumber) { + return a2 - b2; } - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; + if (!aIsNumber && bIsNumber) { + return 1; } - length(unit = "milliseconds") { - return this.isValid ? this.toDuration(...[unit]).get(unit) : NaN; + if (aIsNumber && !bIsNumber) { + return -1; } - count(unit = "milliseconds", opts) { - if (!this.isValid) - return NaN; - const start = this.start.startOf(unit, opts); - let end; - if (opts != null && opts.useLocaleWeeks) { - end = this.end.reconfigure({ - locale: start.locale - }); - } else { - end = this.end; + return a2.localeCompare(b2); + }; + CronExpression._handleMaxDaysInMonth = function(mappedFields) { + if (mappedFields.month.length === 1) { + var daysInMonth = CronExpression.daysInMonth[mappedFields.month[0] - 1]; + if (mappedFields.dayOfMonth[0] > daysInMonth) { + throw new Error("Invalid explicit day of month definition"); } - end = end.startOf(unit, opts); - return Math.floor(end.diff(start, unit).get(unit)) + (end.valueOf() !== this.end.valueOf()); + return mappedFields.dayOfMonth.filter(function(dayOfMonth) { + return dayOfMonth === "L" ? true : dayOfMonth <= daysInMonth; + }).sort(CronExpression._sortCompareFn); } - hasSame(unit) { - return this.isValid ? this.isEmpty() || this.e.minus(1).hasSame(this.s, unit) : false; + }; + CronExpression._freezeFields = function(fields) { + for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; ++i2) { + var field = CronExpression.map[i2]; + var value = fields[field]; + fields[field] = Object.freeze(value); } - isEmpty() { - return this.s.valueOf() === this.e.valueOf(); + return Object.freeze(fields); + }; + CronExpression.prototype._applyTimezoneShift = function(currentDate, dateMathVerb, method) { + if (method === "Month" || method === "Day") { + var prevTime = currentDate.getTime(); + currentDate[dateMathVerb + method](); + var currTime = currentDate.getTime(); + if (prevTime === currTime) { + if (currentDate.getMinutes() === 0 && currentDate.getSeconds() === 0) { + currentDate.addHour(); + } else if (currentDate.getMinutes() === 59 && currentDate.getSeconds() === 59) { + currentDate.subtractHour(); + } + } + } else { + var previousHour = currentDate.getHours(); + currentDate[dateMathVerb + method](); + var currentHour = currentDate.getHours(); + var diff = currentHour - previousHour; + if (diff === 2) { + if (this.fields.hour.length !== 24) { + this._dstStart = currentHour; + } + } else if (diff === 0 && currentDate.getMinutes() === 0 && currentDate.getSeconds() === 0) { + if (this.fields.hour.length !== 24) { + this._dstEnd = currentHour; + } + } } - isAfter(dateTime) { - if (!this.isValid) - return false; - return this.s > dateTime; + }; + CronExpression.prototype._findSchedule = function _findSchedule(reverse) { + function matchSchedule(value, sequence) { + for (var i2 = 0, c2 = sequence.length;i2 < c2; i2++) { + if (sequence[i2] >= value) { + return sequence[i2] === value; + } + } + return sequence[0] === value; } - isBefore(dateTime) { - if (!this.isValid) - return false; - return this.e <= dateTime; + function isNthDayMatch(date4, nthDayOfWeek) { + if (nthDayOfWeek < 6) { + if (date4.getDate() < 8 && nthDayOfWeek === 1) { + return true; + } + var offset = date4.getDate() % 7 ? 1 : 0; + var adjustedDate = date4.getDate() - date4.getDate() % 7; + var occurrence = Math.floor(adjustedDate / 7) + offset; + return occurrence === nthDayOfWeek; + } + return false; } - contains(dateTime) { - if (!this.isValid) - return false; - return this.s <= dateTime && this.e > dateTime; + function isLInExpressions(expressions) { + return expressions.length > 0 && expressions.some(function(expression) { + return typeof expression === "string" && expression.indexOf("L") >= 0; + }); } - set({ - start, - end - } = {}) { - if (!this.isValid) - return this; - return Interval.fromDateTimes(start || this.s, end || this.e); + reverse = reverse || false; + var dateMathVerb = reverse ? "subtract" : "add"; + var currentDate = new CronDate(this._currentDate, this._tz); + var startDate = this._startDate; + var endDate = this._endDate; + var startTimestamp = currentDate.getTime(); + var stepCount = 0; + function isLastWeekdayOfMonthMatch(expressions) { + return expressions.some(function(expression) { + if (!isLInExpressions([expression])) { + return false; + } + var weekday = Number.parseInt(expression[0]) % 7; + if (Number.isNaN(weekday)) { + throw new Error("Invalid last weekday of the month expression: " + expression); + } + return currentDate.getDay() === weekday && currentDate.isLastWeekdayOfMonth(); + }); } - splitAt(...dateTimes) { - if (!this.isValid) - return []; - const sorted = dateTimes.map(friendlyDateTime).filter((d2) => this.contains(d2)).sort((a2, b2) => a2.toMillis() - b2.toMillis()), results = []; - let { - s: s3 - } = this, i2 = 0; - while (s3 < this.e) { - const added = sorted[i2] || this.e, next = +added > +this.e ? this.e : added; - results.push(Interval.fromDateTimes(s3, next)); - s3 = next; - i2 += 1; + while (stepCount < LOOP_LIMIT) { + stepCount++; + if (reverse) { + if (startDate && currentDate.getTime() - startDate.getTime() < 0) { + throw new Error("Out of the timespan range"); + } + } else { + if (endDate && endDate.getTime() - currentDate.getTime() < 0) { + throw new Error("Out of the timespan range"); + } } - return results; - } - splitBy(duration) { - const dur = Duration.fromDurationLike(duration); - if (!this.isValid || !dur.isValid || dur.as("milliseconds") === 0) { - return []; + var dayOfMonthMatch = matchSchedule(currentDate.getDate(), this.fields.dayOfMonth); + if (isLInExpressions(this.fields.dayOfMonth)) { + dayOfMonthMatch = dayOfMonthMatch || currentDate.isLastDayOfMonth(); } - let { - s: s3 - } = this, idx = 1, next; - const results = []; - while (s3 < this.e) { - const added = this.start.plus(dur.mapUnits((x2) => x2 * idx)); - next = +added > +this.e ? this.e : added; - results.push(Interval.fromDateTimes(s3, next)); - s3 = next; - idx += 1; + var dayOfWeekMatch = matchSchedule(currentDate.getDay(), this.fields.dayOfWeek); + if (isLInExpressions(this.fields.dayOfWeek)) { + dayOfWeekMatch = dayOfWeekMatch || isLastWeekdayOfMonthMatch(this.fields.dayOfWeek); } - return results; + var isDayOfMonthWildcardMatch = this.fields.dayOfMonth.length >= CronExpression.daysInMonth[currentDate.getMonth()]; + var isDayOfWeekWildcardMatch = this.fields.dayOfWeek.length === CronExpression.constraints[5].max - CronExpression.constraints[5].min + 1; + var currentHour = currentDate.getHours(); + if (!dayOfMonthMatch && (!dayOfWeekMatch || isDayOfWeekWildcardMatch)) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); + continue; + } + if (!isDayOfMonthWildcardMatch && isDayOfWeekWildcardMatch && !dayOfMonthMatch) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); + continue; + } + if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && !dayOfWeekMatch) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); + continue; + } + if (this._nthDayOfWeek > 0 && !isNthDayMatch(currentDate, this._nthDayOfWeek)) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); + continue; + } + if (!matchSchedule(currentDate.getMonth() + 1, this.fields.month)) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Month"); + continue; + } + if (!matchSchedule(currentHour, this.fields.hour)) { + if (this._dstStart !== currentHour) { + this._dstStart = null; + this._applyTimezoneShift(currentDate, dateMathVerb, "Hour"); + continue; + } else if (!matchSchedule(currentHour - 1, this.fields.hour)) { + currentDate[dateMathVerb + "Hour"](); + continue; + } + } else if (this._dstEnd === currentHour) { + if (!reverse) { + this._dstEnd = null; + this._applyTimezoneShift(currentDate, "add", "Hour"); + continue; + } + } + if (!matchSchedule(currentDate.getMinutes(), this.fields.minute)) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Minute"); + continue; + } + if (!matchSchedule(currentDate.getSeconds(), this.fields.second)) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Second"); + continue; + } + if (startTimestamp === currentDate.getTime()) { + if (dateMathVerb === "add" || currentDate.getMilliseconds() === 0) { + this._applyTimezoneShift(currentDate, dateMathVerb, "Second"); + } else { + currentDate.setMilliseconds(0); + } + continue; + } + break; } - divideEqually(numberOfParts) { - if (!this.isValid) - return []; - return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); + if (stepCount >= LOOP_LIMIT) { + throw new Error("Invalid expression, loop limit exceeded"); } - overlaps(other) { - return this.e > other.s && this.s < other.e; + this._currentDate = new CronDate(currentDate, this._tz); + this._hasIterated = true; + return currentDate; + }; + CronExpression.prototype.next = function next() { + var schedule = this._findSchedule(); + if (this._isIterator) { + return { + value: schedule, + done: !this.hasNext() + }; } - abutsStart(other) { - if (!this.isValid) - return false; - return +this.e === +other.s; + return schedule; + }; + CronExpression.prototype.prev = function prev() { + var schedule = this._findSchedule(true); + if (this._isIterator) { + return { + value: schedule, + done: !this.hasPrev() + }; } - abutsEnd(other) { - if (!this.isValid) - return false; - return +other.e === +this.s; + return schedule; + }; + CronExpression.prototype.hasNext = function() { + var current = this._currentDate; + var hasIterated = this._hasIterated; + try { + this._findSchedule(); + return true; + } catch (err) { + return false; + } finally { + this._currentDate = current; + this._hasIterated = hasIterated; } - engulfs(other) { - if (!this.isValid) - return false; - return this.s <= other.s && this.e >= other.e; + }; + CronExpression.prototype.hasPrev = function() { + var current = this._currentDate; + var hasIterated = this._hasIterated; + try { + this._findSchedule(true); + return true; + } catch (err) { + return false; + } finally { + this._currentDate = current; + this._hasIterated = hasIterated; } - equals(other) { - if (!this.isValid || !other.isValid) { - return false; + }; + CronExpression.prototype.iterate = function iterate(steps, callback) { + var dates = []; + if (steps >= 0) { + for (var i2 = 0, c2 = steps;i2 < c2; i2++) { + try { + var item = this.next(); + dates.push(item); + if (callback) { + callback(item, i2); + } + } catch (err) { + break; + } + } + } else { + for (var i2 = 0, c2 = steps;i2 > c2; i2--) { + try { + var item = this.prev(); + dates.push(item); + if (callback) { + callback(item, i2); + } + } catch (err) { + break; + } } - return this.s.equals(other.s) && this.e.equals(other.e); } - intersection(other) { - if (!this.isValid) - return this; - const s3 = this.s > other.s ? this.s : other.s, e3 = this.e < other.e ? this.e : other.e; - if (s3 >= e3) { - return null; - } else { - return Interval.fromDateTimes(s3, e3); + return dates; + }; + CronExpression.prototype.reset = function reset(newDate) { + this._currentDate = new CronDate(newDate || this._options.currentDate); + }; + CronExpression.prototype.stringify = function stringify(includeSeconds) { + var resultArr = []; + for (var i2 = includeSeconds ? 0 : 1, c2 = CronExpression.map.length;i2 < c2; ++i2) { + var field = CronExpression.map[i2]; + var value = this.fields[field]; + var constraint = CronExpression.constraints[i2]; + if (field === "dayOfMonth" && this.fields.month.length === 1) { + constraint = { min: 1, max: CronExpression.daysInMonth[this.fields.month[0] - 1] }; + } else if (field === "dayOfWeek") { + constraint = { min: 0, max: 6 }; + value = value[value.length - 1] === 7 ? value.slice(0, -1) : value; } + resultArr.push(stringifyField(value, constraint.min, constraint.max)); } - union(other) { - if (!this.isValid) - return this; - const s3 = this.s < other.s ? this.s : other.s, e3 = this.e > other.e ? this.e : other.e; - return Interval.fromDateTimes(s3, e3); + return resultArr.join(" "); + }; + CronExpression.parse = function parse2(expression, options) { + var self2 = this; + if (typeof options === "function") { + options = {}; } - static merge(intervals) { - const [found, final] = intervals.sort((a2, b2) => a2.s - b2.s).reduce(([sofar, current], item) => { - if (!current) { - return [sofar, item]; - } else if (current.overlaps(item) || current.abutsStart(item)) { - return [sofar, current.union(item)]; + function parse3(expression2, options2) { + if (!options2) { + options2 = {}; + } + if (typeof options2.currentDate === "undefined") { + options2.currentDate = new CronDate(undefined, self2._tz); + } + if (CronExpression.predefined[expression2]) { + expression2 = CronExpression.predefined[expression2]; + } + var fields = []; + var atoms = (expression2 + "").trim().split(/\s+/); + if (atoms.length > 6) { + throw new Error("Invalid cron expression"); + } + var start = CronExpression.map.length - atoms.length; + for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; ++i2) { + var field = CronExpression.map[i2]; + var value = atoms[atoms.length > c2 ? i2 : i2 - start]; + if (i2 < start || !value) { + fields.push(CronExpression._parseField(field, CronExpression.parseDefaults[i2], CronExpression.constraints[i2])); } else { - return [sofar.concat([current]), item]; + var val = field === "dayOfWeek" ? parseNthDay(value) : value; + fields.push(CronExpression._parseField(field, val, CronExpression.constraints[i2])); } - }, [[], null]); - if (final) { - found.push(final); } - return found; - } - static xor(intervals) { - let start = null, currentCount = 0; - const results = [], ends = intervals.map((i2) => [{ - time: i2.s, - type: "s" - }, { - time: i2.e, - type: "e" - }]), flattened = Array.prototype.concat(...ends), arr = flattened.sort((a2, b2) => a2.time - b2.time); - for (const i2 of arr) { - currentCount += i2.type === "s" ? 1 : -1; - if (currentCount === 1) { - start = i2.time; - } else { - if (start && +start !== +i2.time) { - results.push(Interval.fromDateTimes(start, i2.time)); + var mappedFields = {}; + for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; i2++) { + var key = CronExpression.map[i2]; + mappedFields[key] = fields[i2]; + } + var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields); + mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth; + return new CronExpression(mappedFields, options2); + function parseNthDay(val2) { + var atoms2 = val2.split("#"); + if (atoms2.length > 1) { + var nthValue = +atoms2[atoms2.length - 1]; + if (/,/.test(val2)) { + throw new Error("Constraint error, invalid dayOfWeek `#` and `,` " + "special characters are incompatible"); } - start = null; + if (/\//.test(val2)) { + throw new Error("Constraint error, invalid dayOfWeek `#` and `/` " + "special characters are incompatible"); + } + if (/-/.test(val2)) { + throw new Error("Constraint error, invalid dayOfWeek `#` and `-` " + "special characters are incompatible"); + } + if (atoms2.length > 2 || Number.isNaN(nthValue) || (nthValue < 1 || nthValue > 5)) { + throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)"); + } + options2.nthDayOfWeek = nthValue; + return atoms2[0]; } + return val2; } - return Interval.merge(results); - } - difference(...intervals) { - return Interval.xor([this].concat(intervals)).map((i2) => this.intersection(i2)).filter((i2) => i2 && !i2.isEmpty()); } - toString() { - if (!this.isValid) - return INVALID$1; - return `[${this.s.toISO()} \u2013 ${this.e.toISO()})`; + return parse3(expression, options); + }; + CronExpression.fieldsToExpression = function fieldsToExpression(fields, options) { + function validateConstraints(field2, values2, constraints) { + if (!values2) { + throw new Error("Validation error, Field " + field2 + " is missing"); + } + if (values2.length === 0) { + throw new Error("Validation error, Field " + field2 + " contains no values"); + } + for (var i3 = 0, c3 = values2.length;i3 < c3; i3++) { + var value = values2[i3]; + if (CronExpression._isValidConstraintChar(constraints, value)) { + continue; + } + if (typeof value !== "number" || Number.isNaN(value) || value < constraints.min || value > constraints.max) { + throw new Error("Constraint error, got value " + value + " expected range " + constraints.min + "-" + constraints.max); + } + } } - [Symbol.for("nodejs.util.inspect.custom")]() { - if (this.isValid) { - return `Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`; - } else { - return `Interval { Invalid, reason: ${this.invalidReason} }`; + var mappedFields = {}; + for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; ++i2) { + var field = CronExpression.map[i2]; + var values = fields[field]; + validateConstraints(field, values, CronExpression.constraints[i2]); + var copy = []; + var j2 = -1; + while (++j2 < values.length) { + copy[j2] = values[j2]; + } + values = copy.sort(CronExpression._sortCompareFn).filter(function(item, pos, ary) { + return !pos || item !== ary[pos - 1]; + }); + if (values.length !== copy.length) { + throw new Error("Validation error, Field " + field + " contains duplicate values"); } + mappedFields[field] = values; } - toLocaleString(formatOpts = DATE_SHORT, opts = {}) { - return this.isValid ? Formatter.create(this.s.loc.clone(opts), formatOpts).formatInterval(this) : INVALID$1; + var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields); + mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth; + return new CronExpression(mappedFields, options || {}); + }; + module.exports = CronExpression; +}); + +// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/parser.js +var require_parser3 = __commonJS((exports, module) => { + var CronExpression = require_expression(); + function CronParser() {} + CronParser._parseEntry = function _parseEntry(entry) { + var atoms = entry.split(" "); + if (atoms.length === 6) { + return { + interval: CronExpression.parse(entry) + }; + } else if (atoms.length > 6) { + return { + interval: CronExpression.parse(atoms.slice(0, 6).join(" ")), + command: atoms.slice(6, atoms.length) + }; + } else { + throw new Error("Invalid entry: " + entry); } - toISO(opts) { - if (!this.isValid) - return INVALID$1; - return `${this.s.toISO(opts)}/${this.e.toISO(opts)}`; + }; + CronParser.parseExpression = function parseExpression(expression, options) { + return CronExpression.parse(expression, options); + }; + CronParser.fieldsToExpression = function fieldsToExpression(fields, options) { + return CronExpression.fieldsToExpression(fields, options); + }; + CronParser.parseString = function parseString(data) { + var blocks = data.split(` +`); + var response = { + variables: {}, + expressions: [], + errors: {} + }; + for (var i2 = 0, c2 = blocks.length;i2 < c2; i2++) { + var block = blocks[i2]; + var matches = null; + var entry = block.trim(); + if (entry.length > 0) { + if (entry.match(/^#/)) { + continue; + } else if (matches = entry.match(/^(.*)=(.*)$/)) { + response.variables[matches[1]] = matches[2]; + } else { + var result = null; + try { + result = CronParser._parseEntry("0 " + entry); + response.expressions.push(result.interval); + } catch (err) { + response.errors[entry] = err; + } + } + } } - toISODate() { - if (!this.isValid) - return INVALID$1; - return `${this.s.toISODate()}/${this.e.toISODate()}`; + return response; + }; + CronParser.parseFile = function parseFile(filePath, callback) { + __require("fs").readFile(filePath, function(err, data) { + if (err) { + callback(err); + return; + } + return callback(null, CronParser.parseString(data.toString())); + }); + }; + module.exports = CronParser; +}); + +// node_modules/.pnpm/delayed-stream@1.0.0/node_modules/delayed-stream/lib/delayed_stream.js +var require_delayed_stream = __commonJS((exports, module) => { + var Stream = __require("stream").Stream; + var util = __require("util"); + module.exports = DelayedStream; + function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; + } + util.inherits(DelayedStream, Stream); + DelayedStream.create = function(source, options) { + var delayedStream = new this; + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - toISOTime(opts) { - if (!this.isValid) - return INVALID$1; - return `${this.s.toISOTime(opts)}/${this.e.toISOTime(opts)}`; + delayedStream.source = source; + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + source.on("error", function() {}); + if (delayedStream.pauseStream) { + source.pause(); } - toFormat(dateFormat, { - separator = " \u2013 " - } = {}) { - if (!this.isValid) - return INVALID$1; - return `${this.s.toFormat(dateFormat)}${separator}${this.e.toFormat(dateFormat)}`; + return delayedStream; + }; + Object.defineProperty(DelayedStream.prototype, "readable", { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; } - toDuration(unit, opts) { - if (!this.isValid) { - return Duration.invalid(this.invalidReason); - } - return this.e.diff(this.s, unit, opts); + }); + DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); + }; + DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); } - mapEndpoints(mapFn) { - return Interval.fromDateTimes(mapFn(this.s), mapFn(this.e)); + this.source.resume(); + }; + DelayedStream.prototype.pause = function() { + this.source.pause(); + }; + DelayedStream.prototype.release = function() { + this._released = true; + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; + }; + DelayedStream.prototype.pipe = function() { + var r2 = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r2; + }; + DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; } - } - - class Info { - static hasDST(zone = Settings.defaultZone) { - const proto = DateTime.now().setZone(zone).set({ - month: 12 - }); - return !zone.isUniversal && proto.offset !== proto.set({ - month: 6 - }).offset; + if (args[0] === "data") { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); } - static isValidIANAZone(zone) { - return IANAZone.isValidZone(zone); + this._bufferedEvents.push(args); + }; + DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; } - static normalizeZone(input) { - return normalizeZone(input, Settings.defaultZone); + if (this.dataSize <= this.maxDataSize) { + return; } - static getStartOfWeek({ - locale: locale2 = null, - locObj = null - } = {}) { - return (locObj || Locale.create(locale2)).getStartOfWeek(); - } - static getMinimumDaysInFirstWeek({ - locale: locale2 = null, - locObj = null - } = {}) { - return (locObj || Locale.create(locale2)).getMinDaysInFirstWeek(); - } - static getWeekendWeekdays({ - locale: locale2 = null, - locObj = null - } = {}) { - return (locObj || Locale.create(locale2)).getWeekendDays().slice(); - } - static months(length = "long", { - locale: locale2 = null, - numberingSystem = null, - locObj = null, - outputCalendar = "gregory" - } = {}) { - return (locObj || Locale.create(locale2, numberingSystem, outputCalendar)).months(length); - } - static monthsFormat(length = "long", { - locale: locale2 = null, - numberingSystem = null, - locObj = null, - outputCalendar = "gregory" - } = {}) { - return (locObj || Locale.create(locale2, numberingSystem, outputCalendar)).months(length, true); - } - static weekdays(length = "long", { - locale: locale2 = null, - numberingSystem = null, - locObj = null - } = {}) { - return (locObj || Locale.create(locale2, numberingSystem, null)).weekdays(length); - } - static weekdaysFormat(length = "long", { - locale: locale2 = null, - numberingSystem = null, - locObj = null - } = {}) { - return (locObj || Locale.create(locale2, numberingSystem, null)).weekdays(length, true); - } - static meridiems({ - locale: locale2 = null - } = {}) { - return Locale.create(locale2).meridiems(); - } - static eras(length = "short", { - locale: locale2 = null - } = {}) { - return Locale.create(locale2, null, "gregory").eras(length); - } - static features() { - return { - relative: hasRelative(), - localeWeek: hasLocaleWeekInfo() - }; - } - } - function dayDiff(earlier, later) { - const utcDayStart = (dt) => dt.toUTC(0, { - keepLocalTime: true - }).startOf("day").valueOf(), ms = utcDayStart(later) - utcDayStart(earlier); - return Math.floor(Duration.fromMillis(ms).as("days")); + this._maxDataSizeExceeded = true; + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this.emit("error", new Error(message)); + }; +}); + +// node_modules/.pnpm/combined-stream@1.0.8/node_modules/combined-stream/lib/combined_stream.js +var require_combined_stream = __commonJS((exports, module) => { + var util = __require("util"); + var Stream = __require("stream").Stream; + var DelayedStream = require_delayed_stream(); + module.exports = CombinedStream; + function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; } - function highOrderDiffs(cursor, later, units) { - const differs = [["years", (a2, b2) => b2.year - a2.year], ["quarters", (a2, b2) => b2.quarter - a2.quarter + (b2.year - a2.year) * 4], ["months", (a2, b2) => b2.month - a2.month + (b2.year - a2.year) * 12], ["weeks", (a2, b2) => { - const days = dayDiff(a2, b2); - return (days - days % 7) / 7; - }], ["days", dayDiff]]; - const results = {}; - const earlier = cursor; - let lowestOrder, highWater; - for (const [unit, differ] of differs) { - if (units.indexOf(unit) >= 0) { - lowestOrder = unit; - results[unit] = differ(cursor, later); - highWater = earlier.plus(results); - if (highWater > later) { - results[unit]--; - cursor = earlier.plus(results); - if (cursor > later) { - highWater = cursor; - results[unit]--; - cursor = earlier.plus(results); - } - } else { - cursor = highWater; - } - } + util.inherits(CombinedStream, Stream); + CombinedStream.create = function(options) { + var combinedStream = new this; + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; } - return [cursor, results, highWater, lowestOrder]; - } - function diff(earlier, later, units, opts) { - let [cursor, results, highWater, lowestOrder] = highOrderDiffs(earlier, later, units); - const remainingMillis = later - cursor; - const lowerOrderUnits = units.filter((u2) => ["hours", "minutes", "seconds", "milliseconds"].indexOf(u2) >= 0); - if (lowerOrderUnits.length === 0) { - if (highWater < later) { - highWater = cursor.plus({ - [lowestOrder]: 1 + return combinedStream; + }; + CombinedStream.isStreamLike = function(stream) { + return typeof stream !== "function" && typeof stream !== "string" && typeof stream !== "boolean" && typeof stream !== "number" && !Buffer.isBuffer(stream); + }; + CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams }); + stream.on("data", this._checkDataSize.bind(this)); + stream = newStream; } - if (highWater !== cursor) { - results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); - } - } - const duration = Duration.fromObject(results, opts); - if (lowerOrderUnits.length > 0) { - return Duration.fromMillis(remainingMillis, opts).shiftTo(...lowerOrderUnits).plus(duration); - } else { - return duration; - } - } - var MISSING_FTP = "missing Intl.DateTimeFormat.formatToParts support"; - function intUnit(regex, post = (i2) => i2) { - return { - regex, - deser: ([s3]) => post(parseDigits(s3)) - }; - } - var NBSP = String.fromCharCode(160); - var spaceOrNBSP = `[ ${NBSP}]`; - var spaceOrNBSPRegExp = new RegExp(spaceOrNBSP, "g"); - function fixListRegex(s3) { - return s3.replace(/\./g, "\\.?").replace(spaceOrNBSPRegExp, spaceOrNBSP); - } - function stripInsensitivities(s3) { - return s3.replace(/\./g, "").replace(spaceOrNBSPRegExp, " ").toLowerCase(); - } - function oneOf(strings, startIndex) { - if (strings === null) { - return null; - } else { - return { - regex: RegExp(strings.map(fixListRegex).join("|")), - deser: ([s3]) => strings.findIndex((i2) => stripInsensitivities(s3) === stripInsensitivities(i2)) + startIndex - }; - } - } - function offset(regex, groups) { - return { - regex, - deser: ([, h2, m2]) => signedOffset(h2, m2), - groups - }; - } - function simple(regex) { - return { - regex, - deser: ([s3]) => s3 - }; - } - function escapeToken(value) { - return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); - } - function unitForToken(token, loc) { - const one = digitRegex(loc), two = digitRegex(loc, "{2}"), three = digitRegex(loc, "{3}"), four = digitRegex(loc, "{4}"), six = digitRegex(loc, "{6}"), oneOrTwo = digitRegex(loc, "{1,2}"), oneToThree = digitRegex(loc, "{1,3}"), oneToSix = digitRegex(loc, "{1,6}"), oneToNine = digitRegex(loc, "{1,9}"), twoToFour = digitRegex(loc, "{2,4}"), fourToSix = digitRegex(loc, "{4,6}"), literal = (t9) => ({ - regex: RegExp(escapeToken(t9.val)), - deser: ([s3]) => s3, - literal: true - }), unitate = (t9) => { - if (token.literal) { - return literal(t9); - } - switch (t9.val) { - case "G": - return oneOf(loc.eras("short"), 0); - case "GG": - return oneOf(loc.eras("long"), 0); - case "y": - return intUnit(oneToSix); - case "yy": - return intUnit(twoToFour, untruncateYear); - case "yyyy": - return intUnit(four); - case "yyyyy": - return intUnit(fourToSix); - case "yyyyyy": - return intUnit(six); - case "M": - return intUnit(oneOrTwo); - case "MM": - return intUnit(two); - case "MMM": - return oneOf(loc.months("short", true), 1); - case "MMMM": - return oneOf(loc.months("long", true), 1); - case "L": - return intUnit(oneOrTwo); - case "LL": - return intUnit(two); - case "LLL": - return oneOf(loc.months("short", false), 1); - case "LLLL": - return oneOf(loc.months("long", false), 1); - case "d": - return intUnit(oneOrTwo); - case "dd": - return intUnit(two); - case "o": - return intUnit(oneToThree); - case "ooo": - return intUnit(three); - case "HH": - return intUnit(two); - case "H": - return intUnit(oneOrTwo); - case "hh": - return intUnit(two); - case "h": - return intUnit(oneOrTwo); - case "mm": - return intUnit(two); - case "m": - return intUnit(oneOrTwo); - case "q": - return intUnit(oneOrTwo); - case "qq": - return intUnit(two); - case "s": - return intUnit(oneOrTwo); - case "ss": - return intUnit(two); - case "S": - return intUnit(oneToThree); - case "SSS": - return intUnit(three); - case "u": - return simple(oneToNine); - case "uu": - return simple(oneOrTwo); - case "uuu": - return intUnit(one); - case "a": - return oneOf(loc.meridiems(), 0); - case "kkkk": - return intUnit(four); - case "kk": - return intUnit(twoToFour, untruncateYear); - case "W": - return intUnit(oneOrTwo); - case "WW": - return intUnit(two); - case "E": - case "c": - return intUnit(one); - case "EEE": - return oneOf(loc.weekdays("short", false), 1); - case "EEEE": - return oneOf(loc.weekdays("long", false), 1); - case "ccc": - return oneOf(loc.weekdays("short", true), 1); - case "cccc": - return oneOf(loc.weekdays("long", true), 1); - case "Z": - case "ZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(?::(${two.source}))?`), 2); - case "ZZZ": - return offset(new RegExp(`([+-]${oneOrTwo.source})(${two.source})?`), 2); - case "z": - return simple(/[a-z_+-/]{1,256}?/i); - case " ": - return simple(/[^\S\n\r]/); - default: - return literal(t9); + this._handleErrors(stream); + if (this.pauseStreams) { + stream.pause(); } - }; - const unit = unitate(token) || { - invalidReason: MISSING_FTP - }; - unit.token = token; - return unit; - } - var partTypeStyleToTokenVal = { - year: { - "2-digit": "yy", - numeric: "yyyyy" - }, - month: { - numeric: "M", - "2-digit": "MM", - short: "MMM", - long: "MMMM" - }, - day: { - numeric: "d", - "2-digit": "dd" - }, - weekday: { - short: "EEE", - long: "EEEE" - }, - dayperiod: "a", - dayPeriod: "a", - hour12: { - numeric: "h", - "2-digit": "hh" - }, - hour24: { - numeric: "H", - "2-digit": "HH" - }, - minute: { - numeric: "m", - "2-digit": "mm" - }, - second: { - numeric: "s", - "2-digit": "ss" - }, - timeZoneName: { - long: "ZZZZZ", - short: "ZZZ" } + this._streams.push(stream); + return this; }; - function tokenForPart(part, formatOpts, resolvedOpts) { - const { - type, - value - } = part; - if (type === "literal") { - const isSpace = /^\s+$/.test(value); - return { - literal: !isSpace, - val: isSpace ? " " : value - }; - } - const style = formatOpts[type]; - let actualType = type; - if (type === "hour") { - if (formatOpts.hour12 != null) { - actualType = formatOpts.hour12 ? "hour12" : "hour24"; - } else if (formatOpts.hourCycle != null) { - if (formatOpts.hourCycle === "h11" || formatOpts.hourCycle === "h12") { - actualType = "hour12"; - } else { - actualType = "hour24"; - } - } else { - actualType = resolvedOpts.hour12 ? "hour12" : "hour24"; - } - } - let val = partTypeStyleToTokenVal[actualType]; - if (typeof val === "object") { - val = val[style]; - } - if (val) { - return { - literal: false, - val - }; - } - return; - } - function buildRegex(units) { - const re = units.map((u2) => u2.regex).reduce((f2, r2) => `${f2}(${r2.source})`, ""); - return [`^${re}$`, units]; - } - function match(input, regex, handlers) { - const matches = input.match(regex); - if (matches) { - const all = {}; - let matchIndex = 1; - for (const i2 in handlers) { - if (hasOwnProperty(handlers, i2)) { - const h2 = handlers[i2], groups = h2.groups ? h2.groups + 1 : 1; - if (!h2.literal && h2.token) { - all[h2.token.val[0]] = h2.deser(matches.slice(matchIndex, matchIndex + groups)); - } - matchIndex += groups; - } - } - return [matches, all]; - } else { - return [matches, {}]; - } - } - function dateTimeFromMatches(matches) { - const toField = (token) => { - switch (token) { - case "S": - return "millisecond"; - case "s": - return "second"; - case "m": - return "minute"; - case "h": - case "H": - return "hour"; - case "d": - return "day"; - case "o": - return "ordinal"; - case "L": - case "M": - return "month"; - case "y": - return "year"; - case "E": - case "c": - return "weekday"; - case "W": - return "weekNumber"; - case "k": - return "weekYear"; - case "q": - return "quarter"; - default: - return null; - } - }; - let zone = null; - let specificOffset; - if (!isUndefined(matches.z)) { - zone = IANAZone.create(matches.z); - } - if (!isUndefined(matches.Z)) { - if (!zone) { - zone = new FixedOffsetZone(matches.Z); - } - specificOffset = matches.Z; - } - if (!isUndefined(matches.q)) { - matches.M = (matches.q - 1) * 3 + 1; - } - if (!isUndefined(matches.h)) { - if (matches.h < 12 && matches.a === 1) { - matches.h += 12; - } else if (matches.h === 12 && matches.a === 0) { - matches.h = 0; - } - } - if (matches.G === 0 && matches.y) { - matches.y = -matches.y; - } - if (!isUndefined(matches.u)) { - matches.S = parseMillis(matches.u); - } - const vals = Object.keys(matches).reduce((r2, k2) => { - const f2 = toField(k2); - if (f2) { - r2[f2] = matches[k2]; - } - return r2; - }, {}); - return [vals, zone, specificOffset]; - } - var dummyDateTimeCache = null; - function getDummyDateTime() { - if (!dummyDateTimeCache) { - dummyDateTimeCache = DateTime.fromMillis(1555555555555); + CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; + }; + CombinedStream.prototype._getNext = function() { + this._currentStream = null; + if (this._insideLoop) { + this._pendingNext = true; + return; } - return dummyDateTimeCache; - } - function maybeExpandMacroToken(token, locale2) { - if (token.literal) { - return token; + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; } - const formatOpts = Formatter.macroTokenToFormatOpts(token.val); - const tokens = formatOptsToTokens(formatOpts, locale2); - if (tokens == null || tokens.includes(undefined)) { - return token; + }; + CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); + if (typeof stream == "undefined") { + this.end(); + return; } - return tokens; - } - function expandMacroTokens(tokens, locale2) { - return Array.prototype.concat(...tokens.map((t9) => maybeExpandMacroToken(t9, locale2))); - } - - class TokenParser { - constructor(locale2, format) { - this.locale = locale2; - this.format = format; - this.tokens = expandMacroTokens(Formatter.parseFormat(format), locale2); - this.units = this.tokens.map((t9) => unitForToken(t9, locale2)); - this.disqualifyingUnit = this.units.find((t9) => t9.invalidReason); - if (!this.disqualifyingUnit) { - const [regexString, handlers] = buildRegex(this.units); - this.regex = RegExp(regexString, "i"); - this.handlers = handlers; - } + if (typeof stream !== "function") { + this._pipeNext(stream); + return; } - explainFromTokens(input) { - if (!this.isValid) { - return { - input, - tokens: this.tokens, - invalidReason: this.invalidReason - }; - } else { - const [rawMatches, matches] = match(input, this.regex, this.handlers), [result, zone, specificOffset] = matches ? dateTimeFromMatches(matches) : [null, null, undefined]; - if (hasOwnProperty(matches, "a") && hasOwnProperty(matches, "H")) { - throw new ConflictingSpecificationError("Can't include meridiem when specifying 24-hour format"); - } - return { - input, - tokens: this.tokens, - regex: this.regex, - rawMatches, - matches, - result, - zone, - specificOffset - }; + var getStream = stream; + getStream(function(stream2) { + var isStreamLike = CombinedStream.isStreamLike(stream2); + if (isStreamLike) { + stream2.on("data", this._checkDataSize.bind(this)); + this._handleErrors(stream2); } + this._pipeNext(stream2); + }.bind(this)); + }; + CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on("end", this._getNext.bind(this)); + stream.pipe(this, { end: false }); + return; } - get isValid() { - return !this.disqualifyingUnit; - } - get invalidReason() { - return this.disqualifyingUnit ? this.disqualifyingUnit.invalidReason : null; - } - } - function explainFromTokens(locale2, input, format) { - const parser = new TokenParser(locale2, format); - return parser.explainFromTokens(input); - } - function parseFromTokens(locale2, input, format) { - const { - result, - zone, - specificOffset, - invalidReason - } = explainFromTokens(locale2, input, format); - return [result, zone, specificOffset, invalidReason]; - } - function formatOptsToTokens(formatOpts, locale2) { - if (!formatOpts) { - return null; - } - const formatter = Formatter.create(locale2, formatOpts); - const df = formatter.dtFormatter(getDummyDateTime()); - const parts = df.formatToParts(); - const resolvedOpts = df.resolvedOptions(); - return parts.map((p2) => tokenForPart(p2, formatOpts, resolvedOpts)); - } - var INVALID = "Invalid DateTime"; - var MAX_DATE = 8640000000000000; - function unsupportedZone(zone) { - return new Invalid("unsupported zone", `the zone "${zone.name}" is not supported`); - } - function possiblyCachedWeekData(dt) { - if (dt.weekData === null) { - dt.weekData = gregorianToWeek(dt.c); - } - return dt.weekData; - } - function possiblyCachedLocalWeekData(dt) { - if (dt.localWeekData === null) { - dt.localWeekData = gregorianToWeek(dt.c, dt.loc.getMinDaysInFirstWeek(), dt.loc.getStartOfWeek()); - } - return dt.localWeekData; - } - function clone4(inst, alts) { - const current = { - ts: inst.ts, - zone: inst.zone, - c: inst.c, - o: inst.o, - loc: inst.loc, - invalid: inst.invalid - }; - return new DateTime({ - ...current, - ...alts, - old: current + var value = stream; + this.write(value); + this._getNext(); + }; + CombinedStream.prototype._handleErrors = function(stream) { + var self2 = this; + stream.on("error", function(err) { + self2._emitError(err); }); - } - function fixOffset(localTS, o2, tz) { - let utcGuess = localTS - o2 * 60 * 1000; - const o22 = tz.offset(utcGuess); - if (o2 === o22) { - return [utcGuess, o2]; - } - utcGuess -= (o22 - o2) * 60 * 1000; - const o3 = tz.offset(utcGuess); - if (o22 === o3) { - return [utcGuess, o22]; - } - return [localTS - Math.min(o22, o3) * 60 * 1000, Math.max(o22, o3)]; - } - function tsToObj(ts, offset2) { - ts += offset2 * 60 * 1000; - const d2 = new Date(ts); - return { - year: d2.getUTCFullYear(), - month: d2.getUTCMonth() + 1, - day: d2.getUTCDate(), - hour: d2.getUTCHours(), - minute: d2.getUTCMinutes(), - second: d2.getUTCSeconds(), - millisecond: d2.getUTCMilliseconds() - }; - } - function objToTS(obj, offset2, zone) { - return fixOffset(objToLocalTS(obj), offset2, zone); - } - function adjustTime(inst, dur) { - const oPre = inst.o, year = inst.c.year + Math.trunc(dur.years), month = inst.c.month + Math.trunc(dur.months) + Math.trunc(dur.quarters) * 3, c2 = { - ...inst.c, - year, - month, - day: Math.min(inst.c.day, daysInMonth(year, month)) + Math.trunc(dur.days) + Math.trunc(dur.weeks) * 7 - }, millisToAdd = Duration.fromObject({ - years: dur.years - Math.trunc(dur.years), - quarters: dur.quarters - Math.trunc(dur.quarters), - months: dur.months - Math.trunc(dur.months), - weeks: dur.weeks - Math.trunc(dur.weeks), - days: dur.days - Math.trunc(dur.days), - hours: dur.hours, - minutes: dur.minutes, - seconds: dur.seconds, - milliseconds: dur.milliseconds - }).as("milliseconds"), localTS = objToLocalTS(c2); - let [ts, o2] = fixOffset(localTS, oPre, inst.zone); - if (millisToAdd !== 0) { - ts += millisToAdd; - o2 = inst.zone.offset(ts); - } - return { - ts, - o: o2 - }; - } - function parseDataToDateTime(parsed, parsedZone, opts, format, text2, specificOffset) { - const { - setZone, - zone - } = opts; - if (parsed && Object.keys(parsed).length !== 0 || parsedZone) { - const interpretationZone = parsedZone || zone, inst = DateTime.fromObject(parsed, { - ...opts, - zone: interpretationZone, - specificOffset - }); - return setZone ? inst : inst.setZone(zone); - } else { - return DateTime.invalid(new Invalid("unparsable", `the input "${text2}" can't be parsed as ${format}`)); - } - } - function toTechFormat(dt, format, allowZ = true) { - return dt.isValid ? Formatter.create(Locale.create("en-US"), { - allowZ, - forceSimple: true - }).formatDateTimeFromString(dt, format) : null; - } - function toISODate(o2, extended, precision) { - const longFormat = o2.c.year > 9999 || o2.c.year < 0; - let c2 = ""; - if (longFormat && o2.c.year >= 0) - c2 += "+"; - c2 += padStart(o2.c.year, longFormat ? 6 : 4); - if (precision === "year") - return c2; - if (extended) { - c2 += "-"; - c2 += padStart(o2.c.month); - if (precision === "month") - return c2; - c2 += "-"; - } else { - c2 += padStart(o2.c.month); - if (precision === "month") - return c2; - } - c2 += padStart(o2.c.day); - return c2; - } - function toISOTime(o2, extended, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision) { - let showSeconds = !suppressSeconds || o2.c.millisecond !== 0 || o2.c.second !== 0, c2 = ""; - switch (precision) { - case "day": - case "month": - case "year": - break; - default: - c2 += padStart(o2.c.hour); - if (precision === "hour") - break; - if (extended) { - c2 += ":"; - c2 += padStart(o2.c.minute); - if (precision === "minute") - break; - if (showSeconds) { - c2 += ":"; - c2 += padStart(o2.c.second); - } - } else { - c2 += padStart(o2.c.minute); - if (precision === "minute") - break; - if (showSeconds) { - c2 += padStart(o2.c.second); - } - } - if (precision === "second") - break; - if (showSeconds && (!suppressMilliseconds || o2.c.millisecond !== 0)) { - c2 += "."; - c2 += padStart(o2.c.millisecond, 3); - } - } - if (includeOffset) { - if (o2.isOffsetFixed && o2.offset === 0 && !extendedZone) { - c2 += "Z"; - } else if (o2.o < 0) { - c2 += "-"; - c2 += padStart(Math.trunc(-o2.o / 60)); - c2 += ":"; - c2 += padStart(Math.trunc(-o2.o % 60)); - } else { - c2 += "+"; - c2 += padStart(Math.trunc(o2.o / 60)); - c2 += ":"; - c2 += padStart(Math.trunc(o2.o % 60)); - } + }; + CombinedStream.prototype.write = function(data) { + this.emit("data", data); + }; + CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; } - if (extendedZone) { - c2 += "[" + o2.zone.ianaName + "]"; + if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") + this._currentStream.pause(); + this.emit("pause"); + }; + CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); } - return c2; - } - var defaultUnitValues = { - month: 1, - day: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 + if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") + this._currentStream.resume(); + this.emit("resume"); }; - var defaultWeekUnitValues = { - weekNumber: 1, - weekday: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 + CombinedStream.prototype.end = function() { + this._reset(); + this.emit("end"); }; - var defaultOrdinalUnitValues = { - ordinal: 1, - hour: 0, - minute: 0, - second: 0, - millisecond: 0 + CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit("close"); }; - var orderedUnits = ["year", "month", "day", "hour", "minute", "second", "millisecond"]; - var orderedWeekUnits = ["weekYear", "weekNumber", "weekday", "hour", "minute", "second", "millisecond"]; - var orderedOrdinalUnits = ["year", "ordinal", "hour", "minute", "second", "millisecond"]; - function normalizeUnit(unit) { - const normalized = { - year: "year", - years: "year", - month: "month", - months: "month", - day: "day", - days: "day", - hour: "hour", - hours: "hour", - minute: "minute", - minutes: "minute", - quarter: "quarter", - quarters: "quarter", - second: "second", - seconds: "second", - millisecond: "millisecond", - milliseconds: "millisecond", - weekday: "weekday", - weekdays: "weekday", - weeknumber: "weekNumber", - weeksnumber: "weekNumber", - weeknumbers: "weekNumber", - weekyear: "weekYear", - weekyears: "weekYear", - ordinal: "ordinal" - }[unit.toLowerCase()]; - if (!normalized) - throw new InvalidUnitError(unit); - return normalized; - } - function normalizeUnitWithLocalWeeks(unit) { - switch (unit.toLowerCase()) { - case "localweekday": - case "localweekdays": - return "localWeekday"; - case "localweeknumber": - case "localweeknumbers": - return "localWeekNumber"; - case "localweekyear": - case "localweekyears": - return "localWeekYear"; - default: - return normalizeUnit(unit); - } - } - function guessOffsetForZone(zone) { - if (zoneOffsetTs === undefined) { - zoneOffsetTs = Settings.now(); - } - if (zone.type !== "iana") { - return zone.offset(zoneOffsetTs); - } - const zoneName = zone.name; - let offsetGuess = zoneOffsetGuessCache.get(zoneName); - if (offsetGuess === undefined) { - offsetGuess = zone.offset(zoneOffsetTs); - zoneOffsetGuessCache.set(zoneName, offsetGuess); - } - return offsetGuess; - } - function quickDT(obj, opts) { - const zone = normalizeZone(opts.zone, Settings.defaultZone); - if (!zone.isValid) { - return DateTime.invalid(unsupportedZone(zone)); + CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; + }; + CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; } - const loc = Locale.fromObject(opts); - let ts, o2; - if (!isUndefined(obj.year)) { - for (const u2 of orderedUnits) { - if (isUndefined(obj[u2])) { - obj[u2] = defaultUnitValues[u2]; - } - } - const invalid = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); - if (invalid) { - return DateTime.invalid(invalid); + var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; + this._emitError(new Error(message)); + }; + CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; + var self2 = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; } - const offsetProvis = guessOffsetForZone(zone); - [ts, o2] = objToTS(obj, offsetProvis, zone); - } else { - ts = Settings.now(); - } - return new DateTime({ - ts, - zone, - loc, - o: o2 + self2.dataSize += stream.dataSize; }); - } - function diffRelative(start, end, opts) { - const round = isUndefined(opts.round) ? true : opts.round, rounding = isUndefined(opts.rounding) ? "trunc" : opts.rounding, format = (c2, unit) => { - c2 = roundTo(c2, round || opts.calendary ? 0 : 2, opts.calendary ? "round" : rounding); - const formatter = end.loc.clone(opts).relFormatter(opts); - return formatter.format(c2, unit); - }, differ = (unit) => { - if (opts.calendary) { - if (!end.hasSame(start, unit)) { - return end.startOf(unit).diff(start.startOf(unit), unit).get(unit); - } else - return 0; - } else { - return end.diff(start, unit).get(unit); - } - }; - if (opts.unit) { - return format(differ(opts.unit), opts.unit); - } - for (const unit of opts.units) { - const count = differ(unit); - if (Math.abs(count) >= 1) { - return format(count, unit); - } - } - return format(start > end ? -0 : 0, opts.units[opts.units.length - 1]); - } - function lastOpts(argList) { - let opts = {}, args; - if (argList.length > 0 && typeof argList[argList.length - 1] === "object") { - opts = argList[argList.length - 1]; - args = Array.from(argList).slice(0, argList.length - 1); - } else { - args = Array.from(argList); + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; } - return [opts, args]; - } - var zoneOffsetTs; - var zoneOffsetGuessCache = new Map; - - class DateTime { - constructor(config) { - const zone = config.zone || Settings.defaultZone; - let invalid = config.invalid || (Number.isNaN(config.ts) ? new Invalid("invalid input") : null) || (!zone.isValid ? unsupportedZone(zone) : null); - this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; - let c2 = null, o2 = null; - if (!invalid) { - const unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); - if (unchanged) { - [c2, o2] = [config.old.c, config.old.o]; - } else { - const ot = isNumber(config.o) && !config.old ? config.o : zone.offset(this.ts); - c2 = tsToObj(this.ts, ot); - invalid = Number.isNaN(c2.year) ? new Invalid("invalid input") : null; - c2 = invalid ? null : c2; - o2 = invalid ? null : ot; - } - } - this._zone = zone; - this.loc = config.loc || Locale.create(); - this.invalid = invalid; - this.weekData = null; - this.localWeekData = null; - this.c = c2; - this.o = o2; - this.isLuxonDateTime = true; - } - static now() { - return new DateTime({}); - } - static local() { - const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; - return quickDT({ - year, - month, - day, - hour, - minute, - second, - millisecond - }, opts); - } - static utc() { - const [opts, args] = lastOpts(arguments), [year, month, day, hour, minute, second, millisecond] = args; - opts.zone = FixedOffsetZone.utcInstance; - return quickDT({ - year, - month, - day, - hour, - minute, - second, - millisecond - }, opts); - } - static fromJSDate(date3, options = {}) { - const ts = isDate2(date3) ? date3.valueOf() : NaN; - if (Number.isNaN(ts)) { - return DateTime.invalid("invalid input"); - } - const zoneToUse = normalizeZone(options.zone, Settings.defaultZone); - if (!zoneToUse.isValid) { - return DateTime.invalid(unsupportedZone(zoneToUse)); - } - return new DateTime({ - ts, - zone: zoneToUse, - loc: Locale.fromObject(options) - }); - } - static fromMillis(milliseconds, options = {}) { - if (!isNumber(milliseconds)) { - throw new InvalidArgumentError(`fromMillis requires a numerical input, but received a ${typeof milliseconds} with value ${milliseconds}`); - } else if (milliseconds < -MAX_DATE || milliseconds > MAX_DATE) { - return DateTime.invalid("Timestamp out of range"); - } else { - return new DateTime({ - ts: milliseconds, - zone: normalizeZone(options.zone, Settings.defaultZone), - loc: Locale.fromObject(options) - }); - } - } - static fromSeconds(seconds, options = {}) { - if (!isNumber(seconds)) { - throw new InvalidArgumentError("fromSeconds requires a numerical input"); - } else { - return new DateTime({ - ts: seconds * 1000, - zone: normalizeZone(options.zone, Settings.defaultZone), - loc: Locale.fromObject(options) - }); - } - } - static fromObject(obj, opts = {}) { - obj = obj || {}; - const zoneToUse = normalizeZone(opts.zone, Settings.defaultZone); - if (!zoneToUse.isValid) { - return DateTime.invalid(unsupportedZone(zoneToUse)); - } - const loc = Locale.fromObject(opts); - const normalized = normalizeObject(obj, normalizeUnitWithLocalWeeks); - const { - minDaysInFirstWeek, - startOfWeek - } = usesLocalWeekValues(normalized, loc); - const tsNow = Settings.now(), offsetProvis = !isUndefined(opts.specificOffset) ? opts.specificOffset : zoneToUse.offset(tsNow), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; - if ((containsGregor || containsOrdinal) && definiteWeekDef) { - throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); - } - if (containsGregorMD && containsOrdinal) { - throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); - } - const useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; - let units, defaultValues, objNow = tsToObj(tsNow, offsetProvis); - if (useWeekData) { - units = orderedWeekUnits; - defaultValues = defaultWeekUnitValues; - objNow = gregorianToWeek(objNow, minDaysInFirstWeek, startOfWeek); - } else if (containsOrdinal) { - units = orderedOrdinalUnits; - defaultValues = defaultOrdinalUnitValues; - objNow = gregorianToOrdinal(objNow); - } else { - units = orderedUnits; - defaultValues = defaultUnitValues; - } - let foundFirst = false; - for (const u2 of units) { - const v2 = normalized[u2]; - if (!isUndefined(v2)) { - foundFirst = true; - } else if (foundFirst) { - normalized[u2] = defaultValues[u2]; - } else { - normalized[u2] = objNow[u2]; - } - } - const higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalid = higherOrderInvalid || hasInvalidTimeData(normalized); - if (invalid) { - return DateTime.invalid(invalid); - } - const gregorian = useWeekData ? weekToGregorian(normalized, minDaysInFirstWeek, startOfWeek) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, [tsFinal, offsetFinal] = objToTS(gregorian, offsetProvis, zoneToUse), inst = new DateTime({ - ts: tsFinal, - zone: zoneToUse, - o: offsetFinal, - loc - }); - if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { - return DateTime.invalid("mismatched weekday", `you can't specify both a weekday of ${normalized.weekday} and a date of ${inst.toISO()}`); - } - if (!inst.isValid) { - return DateTime.invalid(inst.invalid); - } - return inst; - } - static fromISO(text2, opts = {}) { - const [vals, parsedZone] = parseISODate(text2); - return parseDataToDateTime(vals, parsedZone, opts, "ISO 8601", text2); - } - static fromRFC2822(text2, opts = {}) { - const [vals, parsedZone] = parseRFC2822Date(text2); - return parseDataToDateTime(vals, parsedZone, opts, "RFC 2822", text2); - } - static fromHTTP(text2, opts = {}) { - const [vals, parsedZone] = parseHTTPDate(text2); - return parseDataToDateTime(vals, parsedZone, opts, "HTTP", opts); - } - static fromFormat(text2, fmt, opts = {}) { - if (isUndefined(text2) || isUndefined(fmt)) { - throw new InvalidArgumentError("fromFormat requires an input string and a format"); - } - const { - locale: locale2 = null, - numberingSystem = null - } = opts, localeToUse = Locale.fromOpts({ - locale: locale2, - numberingSystem, - defaultToEN: true - }), [vals, parsedZone, specificOffset, invalid] = parseFromTokens(localeToUse, text2, fmt); - if (invalid) { - return DateTime.invalid(invalid); - } else { - return parseDataToDateTime(vals, parsedZone, opts, `format ${fmt}`, text2, specificOffset); - } - } - static fromString(text2, fmt, opts = {}) { - return DateTime.fromFormat(text2, fmt, opts); - } - static fromSQL(text2, opts = {}) { - const [vals, parsedZone] = parseSQL(text2); - return parseDataToDateTime(vals, parsedZone, opts, "SQL", text2); - } - static invalid(reason, explanation = null) { - if (!reason) { - throw new InvalidArgumentError("need to specify a reason the DateTime is invalid"); - } - const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation); - if (Settings.throwOnInvalid) { - throw new InvalidDateTimeError(invalid); - } else { - return new DateTime({ - invalid - }); - } - } - static isDateTime(o2) { - return o2 && o2.isLuxonDateTime || false; - } - static parseFormatForOpts(formatOpts, localeOpts = {}) { - const tokenList = formatOptsToTokens(formatOpts, Locale.fromObject(localeOpts)); - return !tokenList ? null : tokenList.map((t9) => t9 ? t9.val : null).join(""); - } - static expandFormat(fmt, localeOpts = {}) { - const expanded = expandMacroTokens(Formatter.parseFormat(fmt), Locale.fromObject(localeOpts)); - return expanded.map((t9) => t9.val).join(""); - } - static resetCache() { - zoneOffsetTs = undefined; - zoneOffsetGuessCache.clear(); - } - get(unit) { - return this[unit]; - } - get isValid() { - return this.invalid === null; - } - get invalidReason() { - return this.invalid ? this.invalid.reason : null; - } - get invalidExplanation() { - return this.invalid ? this.invalid.explanation : null; - } - get locale() { - return this.isValid ? this.loc.locale : null; - } - get numberingSystem() { - return this.isValid ? this.loc.numberingSystem : null; - } - get outputCalendar() { - return this.isValid ? this.loc.outputCalendar : null; - } - get zone() { - return this._zone; - } - get zoneName() { - return this.isValid ? this.zone.name : null; - } - get year() { - return this.isValid ? this.c.year : NaN; - } - get quarter() { - return this.isValid ? Math.ceil(this.c.month / 3) : NaN; - } - get month() { - return this.isValid ? this.c.month : NaN; - } - get day() { - return this.isValid ? this.c.day : NaN; - } - get hour() { - return this.isValid ? this.c.hour : NaN; - } - get minute() { - return this.isValid ? this.c.minute : NaN; - } - get second() { - return this.isValid ? this.c.second : NaN; - } - get millisecond() { - return this.isValid ? this.c.millisecond : NaN; - } - get weekYear() { - return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; - } - get weekNumber() { - return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; - } - get weekday() { - return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; - } - get isWeekend() { - return this.isValid && this.loc.getWeekendDays().includes(this.weekday); - } - get localWeekday() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekday : NaN; - } - get localWeekNumber() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekNumber : NaN; - } - get localWeekYear() { - return this.isValid ? possiblyCachedLocalWeekData(this).weekYear : NaN; - } - get ordinal() { - return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; - } - get monthShort() { - return this.isValid ? Info.months("short", { - locObj: this.loc - })[this.month - 1] : null; - } - get monthLong() { - return this.isValid ? Info.months("long", { - locObj: this.loc - })[this.month - 1] : null; - } - get weekdayShort() { - return this.isValid ? Info.weekdays("short", { - locObj: this.loc - })[this.weekday - 1] : null; - } - get weekdayLong() { - return this.isValid ? Info.weekdays("long", { - locObj: this.loc - })[this.weekday - 1] : null; - } - get offset() { - return this.isValid ? +this.o : NaN; - } - get offsetNameShort() { - if (this.isValid) { - return this.zone.offsetName(this.ts, { - format: "short", - locale: this.locale - }); - } else { - return null; - } - } - get offsetNameLong() { - if (this.isValid) { - return this.zone.offsetName(this.ts, { - format: "long", - locale: this.locale - }); - } else { - return null; - } - } - get isOffsetFixed() { - return this.isValid ? this.zone.isUniversal : null; - } - get isInDST() { - if (this.isOffsetFixed) { - return false; - } else { - return this.offset > this.set({ - month: 1, - day: 1 - }).offset || this.offset > this.set({ - month: 5 - }).offset; - } - } - getPossibleOffsets() { - if (!this.isValid || this.isOffsetFixed) { - return [this]; - } - const dayMs = 86400000; - const minuteMs = 60000; - const localTS = objToLocalTS(this.c); - const oEarlier = this.zone.offset(localTS - dayMs); - const oLater = this.zone.offset(localTS + dayMs); - const o1 = this.zone.offset(localTS - oEarlier * minuteMs); - const o2 = this.zone.offset(localTS - oLater * minuteMs); - if (o1 === o2) { - return [this]; - } - const ts1 = localTS - o1 * minuteMs; - const ts2 = localTS - o2 * minuteMs; - const c1 = tsToObj(ts1, o1); - const c2 = tsToObj(ts2, o2); - if (c1.hour === c2.hour && c1.minute === c2.minute && c1.second === c2.second && c1.millisecond === c2.millisecond) { - return [clone4(this, { - ts: ts1 - }), clone4(this, { - ts: ts2 - })]; - } - return [this]; - } - get isInLeapYear() { - return isLeapYear(this.year); - } - get daysInMonth() { - return daysInMonth(this.year, this.month); - } - get daysInYear() { - return this.isValid ? daysInYear(this.year) : NaN; - } - get weeksInWeekYear() { - return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; - } - get weeksInLocalWeekYear() { - return this.isValid ? weeksInWeekYear(this.localWeekYear, this.loc.getMinDaysInFirstWeek(), this.loc.getStartOfWeek()) : NaN; - } - resolvedLocaleOptions(opts = {}) { - const { - locale: locale2, - numberingSystem, - calendar - } = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this); - return { - locale: locale2, - numberingSystem, - outputCalendar: calendar - }; - } - toUTC(offset2 = 0, opts = {}) { - return this.setZone(FixedOffsetZone.instance(offset2), opts); - } - toLocal() { - return this.setZone(Settings.defaultZone); - } - setZone(zone, { - keepLocalTime = false, - keepCalendarTime = false - } = {}) { - zone = normalizeZone(zone, Settings.defaultZone); - if (zone.equals(this.zone)) { - return this; - } else if (!zone.isValid) { - return DateTime.invalid(unsupportedZone(zone)); - } else { - let newTS = this.ts; - if (keepLocalTime || keepCalendarTime) { - const offsetGuess = zone.offset(this.ts); - const asObj = this.toObject(); - [newTS] = objToTS(asObj, offsetGuess, zone); - } - return clone4(this, { - ts: newTS, - zone - }); - } - } - reconfigure({ - locale: locale2, - numberingSystem, - outputCalendar - } = {}) { - const loc = this.loc.clone({ - locale: locale2, - numberingSystem, - outputCalendar - }); - return clone4(this, { - loc - }); - } - setLocale(locale2) { - return this.reconfigure({ - locale: locale2 - }); - } - set(values) { - if (!this.isValid) - return this; - const normalized = normalizeObject(values, normalizeUnitWithLocalWeeks); - const { - minDaysInFirstWeek, - startOfWeek - } = usesLocalWeekValues(normalized, this.loc); - const settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber; - if ((containsGregor || containsOrdinal) && definiteWeekDef) { - throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); - } - if (containsGregorMD && containsOrdinal) { - throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); - } - let mixed2; - if (settingWeekStuff) { - mixed2 = weekToGregorian({ - ...gregorianToWeek(this.c, minDaysInFirstWeek, startOfWeek), - ...normalized - }, minDaysInFirstWeek, startOfWeek); - } else if (!isUndefined(normalized.ordinal)) { - mixed2 = ordinalToGregorian({ - ...gregorianToOrdinal(this.c), - ...normalized - }); - } else { - mixed2 = { - ...this.toObject(), - ...normalized - }; - if (isUndefined(normalized.day)) { - mixed2.day = Math.min(daysInMonth(mixed2.year, mixed2.month), mixed2.day); - } - } - const [ts, o2] = objToTS(mixed2, this.o, this.zone); - return clone4(this, { - ts, - o: o2 - }); - } - plus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration); - return clone4(this, adjustTime(this, dur)); - } - minus(duration) { - if (!this.isValid) - return this; - const dur = Duration.fromDurationLike(duration).negate(); - return clone4(this, adjustTime(this, dur)); - } - startOf(unit, { - useLocaleWeeks = false - } = {}) { - if (!this.isValid) - return this; - const o2 = {}, normalizedUnit = Duration.normalizeUnit(unit); - switch (normalizedUnit) { - case "years": - o2.month = 1; - case "quarters": - case "months": - o2.day = 1; - case "weeks": - case "days": - o2.hour = 0; - case "hours": - o2.minute = 0; - case "minutes": - o2.second = 0; - case "seconds": - o2.millisecond = 0; - break; - } - if (normalizedUnit === "weeks") { - if (useLocaleWeeks) { - const startOfWeek = this.loc.getStartOfWeek(); - const { - weekday - } = this; - if (weekday < startOfWeek) { - o2.weekNumber = this.weekNumber - 1; - } - o2.weekday = startOfWeek; - } else { - o2.weekday = 1; - } - } - if (normalizedUnit === "quarters") { - const q2 = Math.ceil(this.month / 3); - o2.month = (q2 - 1) * 3 + 1; - } - return this.set(o2); - } - endOf(unit, opts) { - return this.isValid ? this.plus({ - [unit]: 1 - }).startOf(unit, opts).minus(1) : this; - } - toFormat(fmt, opts = {}) { - return this.isValid ? Formatter.create(this.loc.redefaultToEN(opts)).formatDateTimeFromString(this, fmt) : INVALID; - } - toLocaleString(formatOpts = DATE_SHORT, opts = {}) { - return this.isValid ? Formatter.create(this.loc.clone(opts), formatOpts).formatDateTime(this) : INVALID; - } - toLocaleParts(opts = {}) { - return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; - } - toISO({ - format = "extended", - suppressSeconds = false, - suppressMilliseconds = false, - includeOffset = true, - extendedZone = false, - precision = "milliseconds" - } = {}) { - if (!this.isValid) { - return null; - } - precision = normalizeUnit(precision); - const ext = format === "extended"; - let c2 = toISODate(this, ext, precision); - if (orderedUnits.indexOf(precision) >= 3) - c2 += "T"; - c2 += toISOTime(this, ext, suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision); - return c2; - } - toISODate({ - format = "extended", - precision = "day" - } = {}) { - if (!this.isValid) { - return null; - } - return toISODate(this, format === "extended", normalizeUnit(precision)); - } - toISOWeekDate() { - return toTechFormat(this, "kkkk-'W'WW-c"); - } - toISOTime({ - suppressMilliseconds = false, - suppressSeconds = false, - includeOffset = true, - includePrefix = false, - extendedZone = false, - format = "extended", - precision = "milliseconds" - } = {}) { - if (!this.isValid) { - return null; - } - precision = normalizeUnit(precision); - let c2 = includePrefix && orderedUnits.indexOf(precision) >= 3 ? "T" : ""; - return c2 + toISOTime(this, format === "extended", suppressSeconds, suppressMilliseconds, includeOffset, extendedZone, precision); - } - toRFC2822() { - return toTechFormat(this, "EEE, dd LLL yyyy HH:mm:ss ZZZ", false); - } - toHTTP() { - return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); - } - toSQLDate() { - if (!this.isValid) { - return null; - } - return toISODate(this, true); - } - toSQLTime({ - includeOffset = true, - includeZone = false, - includeOffsetSpace = true - } = {}) { - let fmt = "HH:mm:ss.SSS"; - if (includeZone || includeOffset) { - if (includeOffsetSpace) { - fmt += " "; - } - if (includeZone) { - fmt += "z"; - } else if (includeOffset) { - fmt += "ZZ"; - } - } - return toTechFormat(this, fmt, true); - } - toSQL(opts = {}) { - if (!this.isValid) { - return null; - } - return `${this.toSQLDate()} ${this.toSQLTime(opts)}`; - } - toString() { - return this.isValid ? this.toISO() : INVALID; - } - [Symbol.for("nodejs.util.inspect.custom")]() { - if (this.isValid) { - return `DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`; - } else { - return `DateTime { Invalid, reason: ${this.invalidReason} }`; - } - } - valueOf() { - return this.toMillis(); - } - toMillis() { - return this.isValid ? this.ts : NaN; - } - toSeconds() { - return this.isValid ? this.ts / 1000 : NaN; - } - toUnixInteger() { - return this.isValid ? Math.floor(this.ts / 1000) : NaN; - } - toJSON() { - return this.toISO(); - } - toBSON() { - return this.toJSDate(); - } - toObject(opts = {}) { - if (!this.isValid) - return {}; - const base = { - ...this.c - }; - if (opts.includeConfig) { - base.outputCalendar = this.outputCalendar; - base.numberingSystem = this.loc.numberingSystem; - base.locale = this.loc.locale; - } - return base; - } - toJSDate() { - return new Date(this.isValid ? this.ts : NaN); - } - diff(otherDateTime, unit = "milliseconds", opts = {}) { - if (!this.isValid || !otherDateTime.isValid) { - return Duration.invalid("created by diffing an invalid DateTime"); - } - const durOpts = { - locale: this.locale, - numberingSystem: this.numberingSystem, - ...opts - }; - const units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = diff(earlier, later, units, durOpts); - return otherIsLater ? diffed.negate() : diffed; - } - diffNow(unit = "milliseconds", opts = {}) { - return this.diff(DateTime.now(), unit, opts); - } - until(otherDateTime) { - return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; - } - hasSame(otherDateTime, unit, opts) { - if (!this.isValid) - return false; - const inputMs = otherDateTime.valueOf(); - const adjustedToZone = this.setZone(otherDateTime.zone, { - keepLocalTime: true - }); - return adjustedToZone.startOf(unit, opts) <= inputMs && inputMs <= adjustedToZone.endOf(unit, opts); - } - equals(other) { - return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); - } - toRelative(options = {}) { - if (!this.isValid) - return null; - const base = options.base || DateTime.fromObject({}, { - zone: this.zone - }), padding = options.padding ? this < base ? -options.padding : options.padding : 0; - let units = ["years", "months", "days", "hours", "minutes", "seconds"]; - let unit = options.unit; - if (Array.isArray(options.unit)) { - units = options.unit; - unit = undefined; - } - return diffRelative(base, this.plus(padding), { - ...options, - numeric: "always", - units, - unit - }); - } - toRelativeCalendar(options = {}) { - if (!this.isValid) - return null; - return diffRelative(options.base || DateTime.fromObject({}, { - zone: this.zone - }), this, { - ...options, - numeric: "auto", - units: ["years", "months", "days"], - calendary: true - }); - } - static min(...dateTimes) { - if (!dateTimes.every(DateTime.isDateTime)) { - throw new InvalidArgumentError("min requires all arguments be DateTimes"); - } - return bestBy(dateTimes, (i2) => i2.valueOf(), Math.min); - } - static max(...dateTimes) { - if (!dateTimes.every(DateTime.isDateTime)) { - throw new InvalidArgumentError("max requires all arguments be DateTimes"); - } - return bestBy(dateTimes, (i2) => i2.valueOf(), Math.max); - } - static fromFormatExplain(text2, fmt, options = {}) { - const { - locale: locale2 = null, - numberingSystem = null - } = options, localeToUse = Locale.fromOpts({ - locale: locale2, - numberingSystem, - defaultToEN: true - }); - return explainFromTokens(localeToUse, text2, fmt); - } - static fromStringExplain(text2, fmt, options = {}) { - return DateTime.fromFormatExplain(text2, fmt, options); - } - static buildFormatParser(fmt, options = {}) { - const { - locale: locale2 = null, - numberingSystem = null - } = options, localeToUse = Locale.fromOpts({ - locale: locale2, - numberingSystem, - defaultToEN: true - }); - return new TokenParser(localeToUse, fmt); - } - static fromFormatParser(text2, formatParser, opts = {}) { - if (isUndefined(text2) || isUndefined(formatParser)) { - throw new InvalidArgumentError("fromFormatParser requires an input string and a format parser"); - } - const { - locale: locale2 = null, - numberingSystem = null - } = opts, localeToUse = Locale.fromOpts({ - locale: locale2, - numberingSystem, - defaultToEN: true - }); - if (!localeToUse.equals(formatParser.locale)) { - throw new InvalidArgumentError(`fromFormatParser called with a locale of ${localeToUse}, ` + `but the format parser was created for ${formatParser.locale}`); - } - const { - result, - zone, - specificOffset, - invalidReason - } = formatParser.explainFromTokens(text2); - if (invalidReason) { - return DateTime.invalid(invalidReason); - } else { - return parseDataToDateTime(result, zone, opts, `format ${formatParser.format}`, text2, specificOffset); - } - } - static get DATE_SHORT() { - return DATE_SHORT; - } - static get DATE_MED() { - return DATE_MED; - } - static get DATE_MED_WITH_WEEKDAY() { - return DATE_MED_WITH_WEEKDAY; - } - static get DATE_FULL() { - return DATE_FULL; - } - static get DATE_HUGE() { - return DATE_HUGE; - } - static get TIME_SIMPLE() { - return TIME_SIMPLE; - } - static get TIME_WITH_SECONDS() { - return TIME_WITH_SECONDS; - } - static get TIME_WITH_SHORT_OFFSET() { - return TIME_WITH_SHORT_OFFSET; - } - static get TIME_WITH_LONG_OFFSET() { - return TIME_WITH_LONG_OFFSET; - } - static get TIME_24_SIMPLE() { - return TIME_24_SIMPLE; - } - static get TIME_24_WITH_SECONDS() { - return TIME_24_WITH_SECONDS; - } - static get TIME_24_WITH_SHORT_OFFSET() { - return TIME_24_WITH_SHORT_OFFSET; - } - static get TIME_24_WITH_LONG_OFFSET() { - return TIME_24_WITH_LONG_OFFSET; - } - static get DATETIME_SHORT() { - return DATETIME_SHORT; - } - static get DATETIME_SHORT_WITH_SECONDS() { - return DATETIME_SHORT_WITH_SECONDS; - } - static get DATETIME_MED() { - return DATETIME_MED; - } - static get DATETIME_MED_WITH_SECONDS() { - return DATETIME_MED_WITH_SECONDS; - } - static get DATETIME_MED_WITH_WEEKDAY() { - return DATETIME_MED_WITH_WEEKDAY; - } - static get DATETIME_FULL() { - return DATETIME_FULL; - } - static get DATETIME_FULL_WITH_SECONDS() { - return DATETIME_FULL_WITH_SECONDS; - } - static get DATETIME_HUGE() { - return DATETIME_HUGE; - } - static get DATETIME_HUGE_WITH_SECONDS() { - return DATETIME_HUGE_WITH_SECONDS; - } - } - function friendlyDateTime(dateTimeish) { - if (DateTime.isDateTime(dateTimeish)) { - return dateTimeish; - } else if (dateTimeish && dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { - return DateTime.fromJSDate(dateTimeish); - } else if (dateTimeish && typeof dateTimeish === "object") { - return DateTime.fromObject(dateTimeish); - } else { - throw new InvalidArgumentError(`Unknown datetime argument: ${dateTimeish}, of type ${typeof dateTimeish}`); - } - } - var VERSION = "3.7.2"; - exports.DateTime = DateTime; - exports.Duration = Duration; - exports.FixedOffsetZone = FixedOffsetZone; - exports.IANAZone = IANAZone; - exports.Info = Info; - exports.Interval = Interval; - exports.InvalidZone = InvalidZone; - exports.Settings = Settings; - exports.SystemZone = SystemZone; - exports.VERSION = VERSION; - exports.Zone = Zone; -}); - -// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/date.js -var require_date2 = __commonJS((exports, module) => { - var luxon = require_luxon(); - CronDate.prototype.addYear = function() { - this._date = this._date.plus({ years: 1 }); - }; - CronDate.prototype.addMonth = function() { - this._date = this._date.plus({ months: 1 }).startOf("month"); - }; - CronDate.prototype.addDay = function() { - this._date = this._date.plus({ days: 1 }).startOf("day"); - }; - CronDate.prototype.addHour = function() { - var prev = this._date; - this._date = this._date.plus({ hours: 1 }).startOf("hour"); - if (this._date <= prev) { - this._date = this._date.plus({ hours: 1 }); - } - }; - CronDate.prototype.addMinute = function() { - var prev = this._date; - this._date = this._date.plus({ minutes: 1 }).startOf("minute"); - if (this._date < prev) { - this._date = this._date.plus({ hours: 1 }); - } - }; - CronDate.prototype.addSecond = function() { - var prev = this._date; - this._date = this._date.plus({ seconds: 1 }).startOf("second"); - if (this._date < prev) { - this._date = this._date.plus({ hours: 1 }); - } - }; - CronDate.prototype.subtractYear = function() { - this._date = this._date.minus({ years: 1 }); - }; - CronDate.prototype.subtractMonth = function() { - this._date = this._date.minus({ months: 1 }).endOf("month").startOf("second"); - }; - CronDate.prototype.subtractDay = function() { - this._date = this._date.minus({ days: 1 }).endOf("day").startOf("second"); - }; - CronDate.prototype.subtractHour = function() { - var prev = this._date; - this._date = this._date.minus({ hours: 1 }).endOf("hour").startOf("second"); - if (this._date >= prev) { - this._date = this._date.minus({ hours: 1 }); - } - }; - CronDate.prototype.subtractMinute = function() { - var prev = this._date; - this._date = this._date.minus({ minutes: 1 }).endOf("minute").startOf("second"); - if (this._date > prev) { - this._date = this._date.minus({ hours: 1 }); - } - }; - CronDate.prototype.subtractSecond = function() { - var prev = this._date; - this._date = this._date.minus({ seconds: 1 }).startOf("second"); - if (this._date > prev) { - this._date = this._date.minus({ hours: 1 }); - } - }; - CronDate.prototype.getDate = function() { - return this._date.day; - }; - CronDate.prototype.getFullYear = function() { - return this._date.year; - }; - CronDate.prototype.getDay = function() { - var weekday = this._date.weekday; - return weekday == 7 ? 0 : weekday; - }; - CronDate.prototype.getMonth = function() { - return this._date.month - 1; - }; - CronDate.prototype.getHours = function() { - return this._date.hour; - }; - CronDate.prototype.getMinutes = function() { - return this._date.minute; - }; - CronDate.prototype.getSeconds = function() { - return this._date.second; - }; - CronDate.prototype.getMilliseconds = function() { - return this._date.millisecond; - }; - CronDate.prototype.getTime = function() { - return this._date.valueOf(); - }; - CronDate.prototype.getUTCDate = function() { - return this._getUTC().day; - }; - CronDate.prototype.getUTCFullYear = function() { - return this._getUTC().year; - }; - CronDate.prototype.getUTCDay = function() { - var weekday = this._getUTC().weekday; - return weekday == 7 ? 0 : weekday; - }; - CronDate.prototype.getUTCMonth = function() { - return this._getUTC().month - 1; - }; - CronDate.prototype.getUTCHours = function() { - return this._getUTC().hour; - }; - CronDate.prototype.getUTCMinutes = function() { - return this._getUTC().minute; - }; - CronDate.prototype.getUTCSeconds = function() { - return this._getUTC().second; - }; - CronDate.prototype.toISOString = function() { - return this._date.toUTC().toISO(); - }; - CronDate.prototype.toJSON = function() { - return this._date.toJSON(); - }; - CronDate.prototype.setDate = function(d2) { - this._date = this._date.set({ day: d2 }); - }; - CronDate.prototype.setFullYear = function(y2) { - this._date = this._date.set({ year: y2 }); - }; - CronDate.prototype.setDay = function(d2) { - this._date = this._date.set({ weekday: d2 }); - }; - CronDate.prototype.setMonth = function(m2) { - this._date = this._date.set({ month: m2 + 1 }); - }; - CronDate.prototype.setHours = function(h2) { - this._date = this._date.set({ hour: h2 }); - }; - CronDate.prototype.setMinutes = function(m2) { - this._date = this._date.set({ minute: m2 }); - }; - CronDate.prototype.setSeconds = function(s2) { - this._date = this._date.set({ second: s2 }); - }; - CronDate.prototype.setMilliseconds = function(s2) { - this._date = this._date.set({ millisecond: s2 }); - }; - CronDate.prototype._getUTC = function() { - return this._date.toUTC(); - }; - CronDate.prototype.toString = function() { - return this.toDate().toString(); - }; - CronDate.prototype.toDate = function() { - return this._date.toJSDate(); - }; - CronDate.prototype.isLastDayOfMonth = function() { - var newDate = this._date.plus({ days: 1 }).startOf("day"); - return this._date.month !== newDate.month; - }; - CronDate.prototype.isLastWeekdayOfMonth = function() { - var newDate = this._date.plus({ days: 7 }).startOf("day"); - return this._date.month !== newDate.month; - }; - function CronDate(timestamp2, tz) { - var dateOpts = { zone: tz }; - if (!timestamp2) { - this._date = luxon.DateTime.local(); - } else if (timestamp2 instanceof CronDate) { - this._date = timestamp2._date; - } else if (timestamp2 instanceof Date) { - this._date = luxon.DateTime.fromJSDate(timestamp2, dateOpts); - } else if (typeof timestamp2 === "number") { - this._date = luxon.DateTime.fromMillis(timestamp2, dateOpts); - } else if (typeof timestamp2 === "string") { - this._date = luxon.DateTime.fromISO(timestamp2, dateOpts); - this._date.isValid || (this._date = luxon.DateTime.fromRFC2822(timestamp2, dateOpts)); - this._date.isValid || (this._date = luxon.DateTime.fromSQL(timestamp2, dateOpts)); - this._date.isValid || (this._date = luxon.DateTime.fromFormat(timestamp2, "EEE, d MMM yyyy HH:mm:ss", dateOpts)); - } - if (!this._date || !this._date.isValid) { - throw new Error("CronDate: unhandled timestamp: " + JSON.stringify(timestamp2)); - } - if (tz && tz !== this._date.zoneName) { - this._date = this._date.setZone(tz); - } - } - module.exports = CronDate; -}); - -// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/field_compactor.js -var require_field_compactor = __commonJS((exports, module) => { - function buildRange(item) { - return { - start: item, - count: 1 - }; - } - function completeRangeWithItem(range, item) { - range.end = item; - range.step = item - range.start; - range.count = 2; - } - function finalizeCurrentRange(results, currentRange, currentItemRange) { - if (currentRange) { - if (currentRange.count === 2) { - results.push(buildRange(currentRange.start)); - results.push(buildRange(currentRange.end)); - } else { - results.push(currentRange); - } - } - if (currentItemRange) { - results.push(currentItemRange); - } - } - function compactField(arr) { - var results = []; - var currentRange = undefined; - for (var i2 = 0;i2 < arr.length; i2++) { - var currentItem = arr[i2]; - if (typeof currentItem !== "number") { - finalizeCurrentRange(results, currentRange, buildRange(currentItem)); - currentRange = undefined; - } else if (!currentRange) { - currentRange = buildRange(currentItem); - } else if (currentRange.count === 1) { - completeRangeWithItem(currentRange, currentItem); - } else { - if (currentRange.step === currentItem - currentRange.end) { - currentRange.count++; - currentRange.end = currentItem; - } else if (currentRange.count === 2) { - results.push(buildRange(currentRange.start)); - currentRange = buildRange(currentRange.end); - completeRangeWithItem(currentRange, currentItem); - } else { - finalizeCurrentRange(results, currentRange); - currentRange = buildRange(currentItem); - } - } - } - finalizeCurrentRange(results, currentRange); - return results; - } - module.exports = compactField; -}); - -// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/field_stringify.js -var require_field_stringify = __commonJS((exports, module) => { - var compactField = require_field_compactor(); - function stringifyField(arr, min, max) { - var ranges = compactField(arr); - if (ranges.length === 1) { - var singleRange = ranges[0]; - var step = singleRange.step; - if (step === 1 && singleRange.start === min && singleRange.end === max) { - return "*"; - } - if (step !== 1 && singleRange.start === min && singleRange.end === max - step + 1) { - return "*/" + step; - } - } - var result = []; - for (var i2 = 0, l2 = ranges.length;i2 < l2; ++i2) { - var range = ranges[i2]; - if (range.count === 1) { - result.push(range.start); - continue; - } - var step = range.step; - if (range.step === 1) { - result.push(range.start + "-" + range.end); - continue; - } - var multiplier = range.start == 0 ? range.count - 1 : range.count; - if (range.step * multiplier > range.end) { - result = result.concat(Array.from({ length: range.end - range.start + 1 }).map(function(_, index2) { - var value = range.start + index2; - if ((value - range.start) % range.step === 0) { - return value; - } - return null; - }).filter(function(value) { - return value != null; - })); - } else if (range.end === max - range.step + 1) { - result.push(range.start + "/" + range.step); - } else { - result.push(range.start + "-" + range.end + "/" + range.step); - } - } - return result.join(","); - } - module.exports = stringifyField; -}); - -// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/expression.js -var require_expression = __commonJS((exports, module) => { - var CronDate = require_date2(); - var stringifyField = require_field_stringify(); - var LOOP_LIMIT = 1e4; - function CronExpression(fields, options) { - this._options = options; - this._utc = options.utc || false; - this._tz = this._utc ? "UTC" : options.tz; - this._currentDate = new CronDate(options.currentDate, this._tz); - this._startDate = options.startDate ? new CronDate(options.startDate, this._tz) : null; - this._endDate = options.endDate ? new CronDate(options.endDate, this._tz) : null; - this._isIterator = options.iterator || false; - this._hasIterated = false; - this._nthDayOfWeek = options.nthDayOfWeek || 0; - this.fields = CronExpression._freezeFields(fields); - } - CronExpression.map = ["second", "minute", "hour", "dayOfMonth", "month", "dayOfWeek"]; - CronExpression.predefined = { - "@yearly": "0 0 1 1 *", - "@monthly": "0 0 1 * *", - "@weekly": "0 0 * * 0", - "@daily": "0 0 * * *", - "@hourly": "0 * * * *" - }; - CronExpression.constraints = [ - { min: 0, max: 59, chars: [] }, - { min: 0, max: 59, chars: [] }, - { min: 0, max: 23, chars: [] }, - { min: 1, max: 31, chars: ["L"] }, - { min: 1, max: 12, chars: [] }, - { min: 0, max: 7, chars: ["L"] } - ]; - CronExpression.daysInMonth = [ - 31, - 29, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - CronExpression.aliases = { - month: { - jan: 1, - feb: 2, - mar: 3, - apr: 4, - may: 5, - jun: 6, - jul: 7, - aug: 8, - sep: 9, - oct: 10, - nov: 11, - dec: 12 - }, - dayOfWeek: { - sun: 0, - mon: 1, - tue: 2, - wed: 3, - thu: 4, - fri: 5, - sat: 6 - } - }; - CronExpression.parseDefaults = ["0", "*", "*", "*", "*", "*"]; - CronExpression.standardValidCharacters = /^[,*\d/-]+$/; - CronExpression.dayOfWeekValidCharacters = /^[?,*\dL#/-]+$/; - CronExpression.dayOfMonthValidCharacters = /^[?,*\dL/-]+$/; - CronExpression.validCharacters = { - second: CronExpression.standardValidCharacters, - minute: CronExpression.standardValidCharacters, - hour: CronExpression.standardValidCharacters, - dayOfMonth: CronExpression.dayOfMonthValidCharacters, - month: CronExpression.standardValidCharacters, - dayOfWeek: CronExpression.dayOfWeekValidCharacters - }; - CronExpression._isValidConstraintChar = function _isValidConstraintChar(constraints, value) { - if (typeof value !== "string") { - return false; - } - return constraints.chars.some(function(char2) { - return value.indexOf(char2) > -1; - }); - }; - CronExpression._parseField = function _parseField(field, value, constraints) { - switch (field) { - case "month": - case "dayOfWeek": - var aliases = CronExpression.aliases[field]; - value = value.replace(/[a-z]{3}/gi, function(match) { - match = match.toLowerCase(); - if (typeof aliases[match] !== "undefined") { - return aliases[match]; - } else { - throw new Error('Validation error, cannot resolve alias "' + match + '"'); - } - }); - break; - } - if (!CronExpression.validCharacters[field].test(value)) { - throw new Error("Invalid characters, got value: " + value); - } - if (value.indexOf("*") !== -1) { - value = value.replace(/\*/g, constraints.min + "-" + constraints.max); - } else if (value.indexOf("?") !== -1) { - value = value.replace(/\?/g, constraints.min + "-" + constraints.max); - } - function parseSequence(val) { - var stack = []; - function handleResult(result) { - if (result instanceof Array) { - for (var i3 = 0, c3 = result.length;i3 < c3; i3++) { - var value2 = result[i3]; - if (CronExpression._isValidConstraintChar(constraints, value2)) { - stack.push(value2); - continue; - } - if (typeof value2 !== "number" || Number.isNaN(value2) || value2 < constraints.min || value2 > constraints.max) { - throw new Error("Constraint error, got value " + value2 + " expected range " + constraints.min + "-" + constraints.max); - } - stack.push(value2); - } - } else { - if (CronExpression._isValidConstraintChar(constraints, result)) { - stack.push(result); - return; - } - var numResult = +result; - if (Number.isNaN(numResult) || numResult < constraints.min || numResult > constraints.max) { - throw new Error("Constraint error, got value " + result + " expected range " + constraints.min + "-" + constraints.max); - } - if (field === "dayOfWeek") { - numResult = numResult % 7; - } - stack.push(numResult); - } - } - var atoms = val.split(","); - if (!atoms.every(function(atom) { - return atom.length > 0; - })) { - throw new Error("Invalid list value format"); - } - if (atoms.length > 1) { - for (var i2 = 0, c2 = atoms.length;i2 < c2; i2++) { - handleResult(parseRepeat(atoms[i2])); - } - } else { - handleResult(parseRepeat(val)); - } - stack.sort(CronExpression._sortCompareFn); - return stack; - } - function parseRepeat(val) { - var repeatInterval = 1; - var atoms = val.split("/"); - if (atoms.length > 2) { - throw new Error("Invalid repeat: " + val); - } - if (atoms.length > 1) { - if (atoms[0] == +atoms[0]) { - atoms = [atoms[0] + "-" + constraints.max, atoms[1]]; - } - return parseRange(atoms[0], atoms[atoms.length - 1]); - } - return parseRange(val, repeatInterval); - } - function parseRange(val, repeatInterval) { - var stack = []; - var atoms = val.split("-"); - if (atoms.length > 1) { - if (atoms.length < 2) { - return +val; - } - if (!atoms[0].length) { - if (!atoms[1].length) { - throw new Error("Invalid range: " + val); - } - return +val; - } - var min = +atoms[0]; - var max = +atoms[1]; - if (Number.isNaN(min) || Number.isNaN(max) || min < constraints.min || max > constraints.max) { - throw new Error("Constraint error, got range " + min + "-" + max + " expected range " + constraints.min + "-" + constraints.max); - } else if (min > max) { - throw new Error("Invalid range: " + val); - } - var repeatIndex = +repeatInterval; - if (Number.isNaN(repeatIndex) || repeatIndex <= 0) { - throw new Error("Constraint error, cannot repeat at every " + repeatIndex + " time."); - } - if (field === "dayOfWeek" && max % 7 === 0) { - stack.push(0); - } - for (var index2 = min, count = max;index2 <= count; index2++) { - var exists2 = stack.indexOf(index2) !== -1; - if (!exists2 && repeatIndex > 0 && repeatIndex % repeatInterval === 0) { - repeatIndex = 1; - stack.push(index2); - } else { - repeatIndex++; - } - } - return stack; - } - return Number.isNaN(+val) ? val : +val; - } - return parseSequence(value); - }; - CronExpression._sortCompareFn = function(a2, b2) { - var aIsNumber = typeof a2 === "number"; - var bIsNumber = typeof b2 === "number"; - if (aIsNumber && bIsNumber) { - return a2 - b2; - } - if (!aIsNumber && bIsNumber) { - return 1; - } - if (aIsNumber && !bIsNumber) { - return -1; - } - return a2.localeCompare(b2); - }; - CronExpression._handleMaxDaysInMonth = function(mappedFields) { - if (mappedFields.month.length === 1) { - var daysInMonth = CronExpression.daysInMonth[mappedFields.month[0] - 1]; - if (mappedFields.dayOfMonth[0] > daysInMonth) { - throw new Error("Invalid explicit day of month definition"); - } - return mappedFields.dayOfMonth.filter(function(dayOfMonth) { - return dayOfMonth === "L" ? true : dayOfMonth <= daysInMonth; - }).sort(CronExpression._sortCompareFn); - } - }; - CronExpression._freezeFields = function(fields) { - for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; ++i2) { - var field = CronExpression.map[i2]; - var value = fields[field]; - fields[field] = Object.freeze(value); - } - return Object.freeze(fields); - }; - CronExpression.prototype._applyTimezoneShift = function(currentDate, dateMathVerb, method) { - if (method === "Month" || method === "Day") { - var prevTime = currentDate.getTime(); - currentDate[dateMathVerb + method](); - var currTime = currentDate.getTime(); - if (prevTime === currTime) { - if (currentDate.getMinutes() === 0 && currentDate.getSeconds() === 0) { - currentDate.addHour(); - } else if (currentDate.getMinutes() === 59 && currentDate.getSeconds() === 59) { - currentDate.subtractHour(); - } - } - } else { - var previousHour = currentDate.getHours(); - currentDate[dateMathVerb + method](); - var currentHour = currentDate.getHours(); - var diff = currentHour - previousHour; - if (diff === 2) { - if (this.fields.hour.length !== 24) { - this._dstStart = currentHour; - } - } else if (diff === 0 && currentDate.getMinutes() === 0 && currentDate.getSeconds() === 0) { - if (this.fields.hour.length !== 24) { - this._dstEnd = currentHour; - } - } - } - }; - CronExpression.prototype._findSchedule = function _findSchedule(reverse) { - function matchSchedule(value, sequence) { - for (var i2 = 0, c2 = sequence.length;i2 < c2; i2++) { - if (sequence[i2] >= value) { - return sequence[i2] === value; - } - } - return sequence[0] === value; - } - function isNthDayMatch(date3, nthDayOfWeek) { - if (nthDayOfWeek < 6) { - if (date3.getDate() < 8 && nthDayOfWeek === 1) { - return true; - } - var offset = date3.getDate() % 7 ? 1 : 0; - var adjustedDate = date3.getDate() - date3.getDate() % 7; - var occurrence = Math.floor(adjustedDate / 7) + offset; - return occurrence === nthDayOfWeek; - } - return false; - } - function isLInExpressions(expressions) { - return expressions.length > 0 && expressions.some(function(expression) { - return typeof expression === "string" && expression.indexOf("L") >= 0; - }); - } - reverse = reverse || false; - var dateMathVerb = reverse ? "subtract" : "add"; - var currentDate = new CronDate(this._currentDate, this._tz); - var startDate = this._startDate; - var endDate = this._endDate; - var startTimestamp = currentDate.getTime(); - var stepCount = 0; - function isLastWeekdayOfMonthMatch(expressions) { - return expressions.some(function(expression) { - if (!isLInExpressions([expression])) { - return false; - } - var weekday = Number.parseInt(expression[0]) % 7; - if (Number.isNaN(weekday)) { - throw new Error("Invalid last weekday of the month expression: " + expression); - } - return currentDate.getDay() === weekday && currentDate.isLastWeekdayOfMonth(); - }); - } - while (stepCount < LOOP_LIMIT) { - stepCount++; - if (reverse) { - if (startDate && currentDate.getTime() - startDate.getTime() < 0) { - throw new Error("Out of the timespan range"); - } - } else { - if (endDate && endDate.getTime() - currentDate.getTime() < 0) { - throw new Error("Out of the timespan range"); - } - } - var dayOfMonthMatch = matchSchedule(currentDate.getDate(), this.fields.dayOfMonth); - if (isLInExpressions(this.fields.dayOfMonth)) { - dayOfMonthMatch = dayOfMonthMatch || currentDate.isLastDayOfMonth(); - } - var dayOfWeekMatch = matchSchedule(currentDate.getDay(), this.fields.dayOfWeek); - if (isLInExpressions(this.fields.dayOfWeek)) { - dayOfWeekMatch = dayOfWeekMatch || isLastWeekdayOfMonthMatch(this.fields.dayOfWeek); - } - var isDayOfMonthWildcardMatch = this.fields.dayOfMonth.length >= CronExpression.daysInMonth[currentDate.getMonth()]; - var isDayOfWeekWildcardMatch = this.fields.dayOfWeek.length === CronExpression.constraints[5].max - CronExpression.constraints[5].min + 1; - var currentHour = currentDate.getHours(); - if (!dayOfMonthMatch && (!dayOfWeekMatch || isDayOfWeekWildcardMatch)) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); - continue; - } - if (!isDayOfMonthWildcardMatch && isDayOfWeekWildcardMatch && !dayOfMonthMatch) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); - continue; - } - if (isDayOfMonthWildcardMatch && !isDayOfWeekWildcardMatch && !dayOfWeekMatch) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); - continue; - } - if (this._nthDayOfWeek > 0 && !isNthDayMatch(currentDate, this._nthDayOfWeek)) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Day"); - continue; - } - if (!matchSchedule(currentDate.getMonth() + 1, this.fields.month)) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Month"); - continue; - } - if (!matchSchedule(currentHour, this.fields.hour)) { - if (this._dstStart !== currentHour) { - this._dstStart = null; - this._applyTimezoneShift(currentDate, dateMathVerb, "Hour"); - continue; - } else if (!matchSchedule(currentHour - 1, this.fields.hour)) { - currentDate[dateMathVerb + "Hour"](); - continue; - } - } else if (this._dstEnd === currentHour) { - if (!reverse) { - this._dstEnd = null; - this._applyTimezoneShift(currentDate, "add", "Hour"); - continue; - } - } - if (!matchSchedule(currentDate.getMinutes(), this.fields.minute)) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Minute"); - continue; - } - if (!matchSchedule(currentDate.getSeconds(), this.fields.second)) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Second"); - continue; - } - if (startTimestamp === currentDate.getTime()) { - if (dateMathVerb === "add" || currentDate.getMilliseconds() === 0) { - this._applyTimezoneShift(currentDate, dateMathVerb, "Second"); - } else { - currentDate.setMilliseconds(0); - } - continue; - } - break; - } - if (stepCount >= LOOP_LIMIT) { - throw new Error("Invalid expression, loop limit exceeded"); - } - this._currentDate = new CronDate(currentDate, this._tz); - this._hasIterated = true; - return currentDate; - }; - CronExpression.prototype.next = function next() { - var schedule = this._findSchedule(); - if (this._isIterator) { - return { - value: schedule, - done: !this.hasNext() - }; - } - return schedule; - }; - CronExpression.prototype.prev = function prev() { - var schedule = this._findSchedule(true); - if (this._isIterator) { - return { - value: schedule, - done: !this.hasPrev() - }; - } - return schedule; - }; - CronExpression.prototype.hasNext = function() { - var current = this._currentDate; - var hasIterated = this._hasIterated; - try { - this._findSchedule(); - return true; - } catch (err) { - return false; - } finally { - this._currentDate = current; - this._hasIterated = hasIterated; - } - }; - CronExpression.prototype.hasPrev = function() { - var current = this._currentDate; - var hasIterated = this._hasIterated; - try { - this._findSchedule(true); - return true; - } catch (err) { - return false; - } finally { - this._currentDate = current; - this._hasIterated = hasIterated; - } - }; - CronExpression.prototype.iterate = function iterate(steps, callback) { - var dates = []; - if (steps >= 0) { - for (var i2 = 0, c2 = steps;i2 < c2; i2++) { - try { - var item = this.next(); - dates.push(item); - if (callback) { - callback(item, i2); - } - } catch (err) { - break; - } - } - } else { - for (var i2 = 0, c2 = steps;i2 > c2; i2--) { - try { - var item = this.prev(); - dates.push(item); - if (callback) { - callback(item, i2); - } - } catch (err) { - break; - } - } - } - return dates; - }; - CronExpression.prototype.reset = function reset(newDate) { - this._currentDate = new CronDate(newDate || this._options.currentDate); - }; - CronExpression.prototype.stringify = function stringify(includeSeconds) { - var resultArr = []; - for (var i2 = includeSeconds ? 0 : 1, c2 = CronExpression.map.length;i2 < c2; ++i2) { - var field = CronExpression.map[i2]; - var value = this.fields[field]; - var constraint = CronExpression.constraints[i2]; - if (field === "dayOfMonth" && this.fields.month.length === 1) { - constraint = { min: 1, max: CronExpression.daysInMonth[this.fields.month[0] - 1] }; - } else if (field === "dayOfWeek") { - constraint = { min: 0, max: 6 }; - value = value[value.length - 1] === 7 ? value.slice(0, -1) : value; - } - resultArr.push(stringifyField(value, constraint.min, constraint.max)); - } - return resultArr.join(" "); - }; - CronExpression.parse = function parse2(expression, options) { - var self2 = this; - if (typeof options === "function") { - options = {}; - } - function parse3(expression2, options2) { - if (!options2) { - options2 = {}; - } - if (typeof options2.currentDate === "undefined") { - options2.currentDate = new CronDate(undefined, self2._tz); - } - if (CronExpression.predefined[expression2]) { - expression2 = CronExpression.predefined[expression2]; - } - var fields = []; - var atoms = (expression2 + "").trim().split(/\s+/); - if (atoms.length > 6) { - throw new Error("Invalid cron expression"); - } - var start = CronExpression.map.length - atoms.length; - for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; ++i2) { - var field = CronExpression.map[i2]; - var value = atoms[atoms.length > c2 ? i2 : i2 - start]; - if (i2 < start || !value) { - fields.push(CronExpression._parseField(field, CronExpression.parseDefaults[i2], CronExpression.constraints[i2])); - } else { - var val = field === "dayOfWeek" ? parseNthDay(value) : value; - fields.push(CronExpression._parseField(field, val, CronExpression.constraints[i2])); - } - } - var mappedFields = {}; - for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; i2++) { - var key = CronExpression.map[i2]; - mappedFields[key] = fields[i2]; - } - var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields); - mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth; - return new CronExpression(mappedFields, options2); - function parseNthDay(val2) { - var atoms2 = val2.split("#"); - if (atoms2.length > 1) { - var nthValue = +atoms2[atoms2.length - 1]; - if (/,/.test(val2)) { - throw new Error("Constraint error, invalid dayOfWeek `#` and `,` " + "special characters are incompatible"); - } - if (/\//.test(val2)) { - throw new Error("Constraint error, invalid dayOfWeek `#` and `/` " + "special characters are incompatible"); - } - if (/-/.test(val2)) { - throw new Error("Constraint error, invalid dayOfWeek `#` and `-` " + "special characters are incompatible"); - } - if (atoms2.length > 2 || Number.isNaN(nthValue) || (nthValue < 1 || nthValue > 5)) { - throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)"); - } - options2.nthDayOfWeek = nthValue; - return atoms2[0]; - } - return val2; - } - } - return parse3(expression, options); - }; - CronExpression.fieldsToExpression = function fieldsToExpression(fields, options) { - function validateConstraints(field2, values2, constraints) { - if (!values2) { - throw new Error("Validation error, Field " + field2 + " is missing"); - } - if (values2.length === 0) { - throw new Error("Validation error, Field " + field2 + " contains no values"); - } - for (var i3 = 0, c3 = values2.length;i3 < c3; i3++) { - var value = values2[i3]; - if (CronExpression._isValidConstraintChar(constraints, value)) { - continue; - } - if (typeof value !== "number" || Number.isNaN(value) || value < constraints.min || value > constraints.max) { - throw new Error("Constraint error, got value " + value + " expected range " + constraints.min + "-" + constraints.max); - } - } - } - var mappedFields = {}; - for (var i2 = 0, c2 = CronExpression.map.length;i2 < c2; ++i2) { - var field = CronExpression.map[i2]; - var values = fields[field]; - validateConstraints(field, values, CronExpression.constraints[i2]); - var copy = []; - var j2 = -1; - while (++j2 < values.length) { - copy[j2] = values[j2]; - } - values = copy.sort(CronExpression._sortCompareFn).filter(function(item, pos, ary) { - return !pos || item !== ary[pos - 1]; - }); - if (values.length !== copy.length) { - throw new Error("Validation error, Field " + field + " contains duplicate values"); - } - mappedFields[field] = values; - } - var dayOfMonth = CronExpression._handleMaxDaysInMonth(mappedFields); - mappedFields.dayOfMonth = dayOfMonth || mappedFields.dayOfMonth; - return new CronExpression(mappedFields, options || {}); - }; - module.exports = CronExpression; -}); - -// node_modules/.pnpm/cron-parser@4.9.0/node_modules/cron-parser/lib/parser.js -var require_parser3 = __commonJS((exports, module) => { - var CronExpression = require_expression(); - function CronParser() {} - CronParser._parseEntry = function _parseEntry(entry) { - var atoms = entry.split(" "); - if (atoms.length === 6) { - return { - interval: CronExpression.parse(entry) - }; - } else if (atoms.length > 6) { - return { - interval: CronExpression.parse(atoms.slice(0, 6).join(" ")), - command: atoms.slice(6, atoms.length) - }; - } else { - throw new Error("Invalid entry: " + entry); - } - }; - CronParser.parseExpression = function parseExpression(expression, options) { - return CronExpression.parse(expression, options); - }; - CronParser.fieldsToExpression = function fieldsToExpression(fields, options) { - return CronExpression.fieldsToExpression(fields, options); - }; - CronParser.parseString = function parseString(data) { - var blocks = data.split(` -`); - var response = { - variables: {}, - expressions: [], - errors: {} - }; - for (var i2 = 0, c2 = blocks.length;i2 < c2; i2++) { - var block = blocks[i2]; - var matches = null; - var entry = block.trim(); - if (entry.length > 0) { - if (entry.match(/^#/)) { - continue; - } else if (matches = entry.match(/^(.*)=(.*)$/)) { - response.variables[matches[1]] = matches[2]; - } else { - var result = null; - try { - result = CronParser._parseEntry("0 " + entry); - response.expressions.push(result.interval); - } catch (err) { - response.errors[entry] = err; - } - } - } - } - return response; - }; - CronParser.parseFile = function parseFile(filePath, callback) { - __require("fs").readFile(filePath, function(err, data) { - if (err) { - callback(err); - return; - } - return callback(null, CronParser.parseString(data.toString())); - }); - }; - module.exports = CronParser; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/repeatable.js -var require_repeatable = __commonJS((exports, module) => { - var _ = require_lodash11(); - var parser = require_parser3(); - var crypto3 = __require("crypto"); - var Job = require_job(); - module.exports = function(Queue) { - Queue.prototype.nextRepeatableJob = function(name, data, opts, skipCheckExists) { - const client = this.client; - const repeat = opts.repeat; - const prevMillis = opts.prevMillis || 0; - if (!prevMillis && opts.jobId) { - repeat.jobId = opts.jobId; - } - const currentCount = repeat.count ? repeat.count + 1 : 1; - if (!_.isUndefined(repeat.limit) && currentCount > repeat.limit) { - return Promise.resolve(); - } - let now = Date.now(); - if (!_.isUndefined(repeat.endDate) && now > new Date(repeat.endDate)) { - return Promise.resolve(); - } - now = prevMillis < now ? now : prevMillis; - const nextMillis = getNextMillis(now, repeat); - if (nextMillis) { - const jobId = repeat.jobId ? repeat.jobId + ":" : ":"; - const repeatKey = getRepeatKey(name, repeat, jobId); - const createNextJob = () => { - return client.zadd(this.keys.repeat, nextMillis, repeatKey).then(() => { - const customId = getRepeatJobId(name, jobId, nextMillis, md5(repeatKey)); - now = Date.now(); - const delay = nextMillis - now; - return Job.create(this, name, data, _.defaultsDeep({ - repeat: { - count: currentCount, - key: repeatKey - }, - jobId: customId, - delay: delay < 0 ? 0 : delay, - timestamp: now, - prevMillis: nextMillis - }, opts)); - }); - }; - if (skipCheckExists) { - return createNextJob(); - } - return client.zscore(this.keys.repeat, repeatKey).then((repeatableExists) => { - if (repeatableExists) { - return createNextJob(); - } - return Promise.resolve(); - }); - } else { - return Promise.resolve(); - } - }; - Queue.prototype.removeRepeatable = function(name, repeat) { - if (typeof name !== "string") { - repeat = name; - name = Job.DEFAULT_JOB_NAME; - } - return this.isReady().then(() => { - const jobId = repeat.jobId ? repeat.jobId + ":" : ":"; - const repeatJobKey = getRepeatKey(name, repeat, jobId); - const repeatJobId = getRepeatJobId(name, jobId, "", md5(repeatJobKey)); - const queueKey = this.keys[""]; - return this.client.removeRepeatable(this.keys.repeat, this.keys.delayed, repeatJobId, repeatJobKey, queueKey); - }); - }; - Queue.prototype.removeRepeatableByKey = function(repeatJobKey) { - const repeatMeta = this._keyToData(repeatJobKey); - const queueKey = this.keys[""]; - const jobId = repeatMeta.id ? repeatMeta.id + ":" : ":"; - const repeatJobId = getRepeatJobId(repeatMeta.name || Job.DEFAULT_JOB_NAME, jobId, "", md5(repeatJobKey)); - return this.isReady().then(() => { - return this.client.removeRepeatable(this.keys.repeat, this.keys.delayed, repeatJobId, repeatJobKey, queueKey); - }); - }; - Queue.prototype._keyToData = function(key) { - const data = key.split(":"); - return { - key, - name: data[0], - id: data[1] || null, - endDate: parseInt(data[2]) || null, - tz: data[3] || null, - cron: data[4] - }; - }; - Queue.prototype.getRepeatableJobs = function(start, end, asc2) { - const key = this.keys.repeat; - start = start || 0; - end = end || -1; - return (asc2 ? this.client.zrange(key, start, end, "WITHSCORES") : this.client.zrevrange(key, start, end, "WITHSCORES")).then((result) => { - const jobs = []; - for (let i2 = 0;i2 < result.length; i2 += 2) { - const data = this._keyToData(result[i2]); - jobs.push({ - key: data.key, - name: data.name, - id: data.id, - endDate: data.endDate, - tz: data.cron ? data.tz : null, - cron: data.cron || null, - every: !data.cron ? parseInt(data.tz) : null, - next: parseInt(result[i2 + 1]) - }); - } - return jobs; - }); - }; - Queue.prototype.getRepeatableCount = function() { - return this.client.zcard(this.toKey("repeat")); - }; - function getRepeatJobId(name, jobId, nextMillis, namespace) { - return "repeat:" + md5(name + jobId + namespace) + ":" + nextMillis; - } - function getRepeatKey(name, repeat, jobId) { - const endDate = repeat.endDate ? new Date(repeat.endDate).getTime() + ":" : ":"; - const tz = repeat.tz ? repeat.tz + ":" : ":"; - const suffix = repeat.cron ? tz + repeat.cron : String(repeat.every); - return name + ":" + jobId + endDate + suffix; - } - function getNextMillis(millis, opts) { - if (opts.cron && opts.every) { - throw new Error("Both .cron and .every options are defined for this repeatable job"); - } - if (opts.every) { - return Math.floor(millis / opts.every) * opts.every + opts.every; - } - const currentDate = opts.startDate && new Date(opts.startDate) > new Date(millis) ? new Date(opts.startDate) : new Date(millis); - const interval2 = parser.parseExpression(opts.cron, _.defaults({ - currentDate - }, opts)); - try { - return interval2.next().getTime(); - } catch (e3) {} - } - function md5(str) { - return crypto3.createHash("md5").update(str).digest("hex"); - } - }; -}); - -// node_modules/.pnpm/get-port@5.1.1/node_modules/get-port/index.js -var require_get_port = __commonJS((exports, module) => { - var net = __require("net"); - - class Locked extends Error { - constructor(port) { - super(`${port} is locked`); - } - } - var lockedPorts = { - old: new Set, - young: new Set - }; - var releaseOldLockedPortsIntervalMs = 1000 * 15; - var interval2; - var getAvailablePort = (options) => new Promise((resolve, reject) => { - const server = net.createServer(); - server.unref(); - server.on("error", reject); - server.listen(options, () => { - const { port } = server.address(); - server.close(() => { - resolve(port); - }); - }); - }); - var portCheckSequence = function* (ports) { - if (ports) { - yield* ports; - } - yield 0; - }; - module.exports = async (options) => { - let ports; - if (options) { - ports = typeof options.port === "number" ? [options.port] : options.port; - } - if (interval2 === undefined) { - interval2 = setInterval(() => { - lockedPorts.old = lockedPorts.young; - lockedPorts.young = new Set; - }, releaseOldLockedPortsIntervalMs); - if (interval2.unref) { - interval2.unref(); - } - } - for (const port of portCheckSequence(ports)) { - try { - let availablePort = await getAvailablePort({ ...options, port }); - while (lockedPorts.old.has(availablePort) || lockedPorts.young.has(availablePort)) { - if (port !== 0) { - throw new Locked(port); - } - availablePort = await getAvailablePort({ ...options, port }); - } - lockedPorts.young.add(availablePort); - return availablePort; - } catch (error) { - if (!["EADDRINUSE", "EACCES"].includes(error.code) && !(error instanceof Locked)) { - throw error; - } - } - } - throw new Error("No available ports found"); - }; - module.exports.makeRange = (from, to) => { - if (!Number.isInteger(from) || !Number.isInteger(to)) { - throw new TypeError("`from` and `to` must be integer numbers"); - } - if (from < 1024 || from > 65535) { - throw new RangeError("`from` must be between 1024 and 65535"); - } - if (to < 1024 || to > 65536) { - throw new RangeError("`to` must be between 1024 and 65536"); - } - if (to < from) { - throw new RangeError("`to` must be greater than or equal to `from`"); - } - const generator = function* (from2, to2) { - for (let port = from2;port <= to2; port++) { - yield port; - } - }; - return generator(from, to); - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/process/utils.js -var require_utils13 = __commonJS((exports, module) => { - function hasProcessExited(child) { - return !!(child.exitCode !== null || child.signalCode); - } - function onExitOnce(child) { - return new Promise((resolve) => { - child.once("exit", () => resolve()); - }); - } - function killAsync(child, signal, timeoutMs) { - if (hasProcessExited(child)) { - return Promise.resolve(child); - } - let onExit = onExitOnce(child); - child.kill(signal || "SIGKILL"); - if (timeoutMs === 0 || isFinite(timeoutMs)) { - const timeout = setTimeout(() => { - if (!hasProcessExited(child)) { - child.kill("SIGKILL"); - } - }, timeoutMs); - onExit = onExit.then(() => { - clearTimeout(timeout); - }); - } - return onExit; - } - var asyncSend = (proc, msg) => { - return new Promise((resolve, reject) => { - proc.send(msg, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); - }; - module.exports = { - killAsync, - asyncSend - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/process/child-pool.js -var require_child_pool = __commonJS((exports, module) => { - var __dirname = "/Users/shivamverma/Desktop/CodeSM/backend/node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/process"; - var fork = __require("child_process").fork; - var path2 = __require("path"); - var _ = require_lodash11(); - var getPort = require_get_port(); - var { killAsync } = require_utils13(); - var CHILD_KILL_TIMEOUT = 30000; - var ChildPool = function ChildPool2() { - if (!(this instanceof ChildPool2)) { - return new ChildPool2; - } - this.retained = {}; - this.free = {}; - }; - var convertExecArgv = function(execArgv) { - const standard = []; - const promises = []; - _.forEach(execArgv, (arg) => { - if (arg.indexOf("--inspect") === -1) { - standard.push(arg); - } else { - const argName = arg.split("=")[0]; - promises.push(getPort().then((port) => { - return `${argName}=${port}`; - })); - } - }); - return Promise.all(promises).then((convertedArgs) => { - return standard.concat(convertedArgs); - }); - }; - ChildPool.prototype.retain = function(processFile) { - const _this = this; - let child = _this.getFree(processFile).pop(); - if (child) { - _this.retained[child.pid] = child; - return Promise.resolve(child); - } - return convertExecArgv(process.execArgv).then((execArgv) => { - child = fork(path2.join(__dirname, "./master.js"), { - execArgv - }); - child.processFile = processFile; - _this.retained[child.pid] = child; - child.on("exit", _this.remove.bind(_this, child)); - return initChild(child, child.processFile).then(() => { - return child; - }).catch((err) => { - this.remove(child); - throw err; - }); - }); - }; - ChildPool.prototype.release = function(child) { - delete this.retained[child.pid]; - this.getFree(child.processFile).push(child); - }; - ChildPool.prototype.remove = function(child) { - delete this.retained[child.pid]; - const free = this.getFree(child.processFile); - const childIndex = free.indexOf(child); - if (childIndex > -1) { - free.splice(childIndex, 1); - } - }; - ChildPool.prototype.kill = function(child, signal) { - this.remove(child); - return killAsync(child, signal || "SIGKILL", CHILD_KILL_TIMEOUT); - }; - ChildPool.prototype.clean = function() { - const children = _.values(this.retained).concat(this.getAllFree()); - this.retained = {}; - this.free = {}; - const allKillPromises = []; - children.forEach((child) => { - allKillPromises.push(this.kill(child, "SIGTERM")); - }); - return Promise.all(allKillPromises).then(() => {}); - }; - ChildPool.prototype.getFree = function(id) { - return this.free[id] = this.free[id] || []; - }; - ChildPool.prototype.getAllFree = function() { - return _.flatten(_.values(this.free)); - }; - async function initChild(child, processFile) { - const onComplete = new Promise((resolve, reject) => { - const onMessageHandler = (msg) => { - if (msg.cmd === "init-complete") { - resolve(); - } else if (msg.cmd === "error") { - reject(msg.error); - } - child.off("message", onMessageHandler); - }; - child.on("message", onMessageHandler); - }); - await new Promise((resolve) => child.send({ cmd: "init", value: processFile }, resolve)); - await onComplete; - } - function ChildPoolSingleton(isSharedChildPool = false) { - if (isSharedChildPool === false) { - return new ChildPool; - } else if (!(this instanceof ChildPool) && ChildPoolSingleton.instance === undefined) { - ChildPoolSingleton.instance = new ChildPool; - } - return ChildPoolSingleton.instance; - } - module.exports = ChildPoolSingleton; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/process/sandbox.js -var require_sandbox = __commonJS((exports, module) => { - var { asyncSend } = require_utils13(); - module.exports = function(processFile, childPool) { - return function process2(job) { - return childPool.retain(processFile).then(async (child) => { - let msgHandler; - let exitHandler; - await asyncSend(child, { - cmd: "start", - job - }); - const done = new Promise((resolve, reject) => { - msgHandler = function(msg) { - switch (msg.cmd) { - case "completed": - resolve(msg.value); - break; - case "failed": - case "error": { - const err = new Error; - Object.assign(err, msg.value); - reject(err); - break; - } - case "progress": - job.progress(msg.value); - break; - case "update": - job.update(msg.value); - break; - case "discard": - job.discard(); - break; - case "log": - job.log(msg.value); - break; - } - }; - exitHandler = (exitCode, signal) => { - reject(new Error("Unexpected exit code: " + exitCode + " signal: " + signal)); - }; - child.on("message", msgHandler); - child.on("exit", exitHandler); - }); - return done.finally(() => { - child.removeListener("message", msgHandler); - child.removeListener("exit", exitHandler); - if (child.exitCode !== null || /SIG.*/.test(child.signalCode)) { - childPool.remove(child); - } else { - childPool.release(child); - } - }); - }); - }; - }; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/lib/queue.js -var require_queue = __commonJS((exports, module) => { - var Redis = require_built3(); - var EventEmitter = __require("events"); - var _ = require_lodash11(); - var fs3 = __require("fs"); - var path2 = __require("path"); - var util = __require("util"); - var url = __require("url"); - var Job = require_job(); - var scripts = require_scripts(); - var errors = require_errors11(); - var utils = require_utils12(); - var TimerManager = require_timer_manager(); - var { promisify: promisify2 } = __require("util"); - var { pTimeout } = require_p_timeout(); - var semver = require_semver2(); - var debuglog = __require("util").debuglog("bull"); - var uuid2 = require_dist7(); - var commands = require_scripts2(); - var MINIMUM_REDIS_VERSION = "2.8.18"; - var Queue = function Queue2(name, url2, opts) { - if (!(this instanceof Queue2)) { - return new Queue2(name, url2, opts); - } - if (_.isString(url2)) { - const clonedOpts = _.cloneDeep(opts || {}); - opts = { - ...clonedOpts, - redis: { - ...redisOptsFromUrl(url2), - ...clonedOpts.redis - } - }; - } else { - opts = _.cloneDeep(url2 || {}); - } - if (!_.isObject(opts)) { - throw TypeError("Options must be a valid object"); - } - if (opts.limiter) { - if (opts.limiter.max && opts.limiter.duration) { - this.limiter = opts.limiter; - } else { - throw new TypeError("Limiter requires `max` and `duration` options"); - } - } - if (opts.defaultJobOptions) { - this.defaultJobOptions = opts.defaultJobOptions; - } - this.name = name; - this.token = uuid2.v4(); - opts.redis = { - enableReadyCheck: false, - ..._.isString(opts.redis) ? { ...redisOptsFromUrl(opts.redis) } : opts.redis - }; - _.defaults(opts.redis, { - port: 6379, - host: "127.0.0.1", - db: opts.redis.db || opts.redis.DB, - retryStrategy: function(times) { - return Math.min(Math.exp(times), 20000); - } - }); - this.keyPrefix = opts.redis.keyPrefix || opts.prefix || "bull"; - delete opts.redis.keyPrefix; - this.clients = []; - const loadCommands = (providedScripts, client) => { - const finalScripts = providedScripts || scripts; - for (const property in finalScripts) { - if (!client[finalScripts[property].name]) { - client.defineCommand(finalScripts[property].name, { - numberOfKeys: finalScripts[property].keys, - lua: finalScripts[property].content - }); - } - } - }; - const lazyClient = redisClientGetter(this, opts, (type, client) => { - const handler = this.emit.bind(this, "error"); - client.on("error", handler); - this.once("close", () => client.removeListener("error", handler)); - if (type === "client") { - this._initializing = (async () => loadCommands(commands, client))().then(() => { - debuglog(name + " queue ready"); - }, (err) => { - this.emit("error", new Error("Error initializing Lua scripts")); - throw err; - }); - this._initializing.catch(() => {}); - } - }); - Object.defineProperties(this, { - client: { - get: lazyClient("client") - }, - eclient: { - get: lazyClient("subscriber") - }, - bclient: { - get: lazyClient("bclient") - } - }); - if (opts.skipVersionCheck !== true) { - getRedisVersion(this.client).then((version2) => { - if (semver.lt(version2, MINIMUM_REDIS_VERSION)) { - this.emit("error", new Error("Redis version needs to be greater than " + MINIMUM_REDIS_VERSION + ". Current: " + version2)); - } - }).catch(() => {}); - } - this.handlers = {}; - this.delayTimer; - this.processing = []; - this.retrieving = 0; - this.drained = true; - this.settings = _.defaults(opts.settings, { - lockDuration: 30000, - stalledInterval: 30000, - maxStalledCount: 1, - guardInterval: 5000, - retryProcessDelay: 5000, - drainDelay: 5, - backoffStrategies: {}, - isSharedChildPool: false - }); - this.metrics = opts.metrics; - this.settings.lockRenewTime = this.settings.lockRenewTime || this.settings.lockDuration / 2; - this.on("error", () => {}); - this.timers = new TimerManager; - this.moveUnlockedJobsToWait = this.moveUnlockedJobsToWait.bind(this); - this.processJob = this.processJob.bind(this); - this.getJobFromId = Job.fromId.bind(null, this); - const keys = {}; - _.each([ - "", - "active", - "wait", - "waiting", - "paused", - "resumed", - "meta-paused", - "active", - "id", - "delayed", - "priority", - "stalled-check", - "completed", - "failed", - "stalled", - "repeat", - "limiter", - "drained", - "duplicated", - "progress", - "de" - ], (key) => { - keys[key] = this.toKey(key); - }); - this.keys = keys; - }; - function redisClientGetter(queue, options, initCallback) { - const createClient = _.isFunction(options.createClient) ? options.createClient : function(type, config) { - if (["bclient", "subscriber"].includes(type)) { - return new Redis({ ...config, maxRetriesPerRequest: null }); - } else { - return new Redis(config); - } - }; - const connections = {}; - return function(type) { - return function() { - if (connections[type] != null) { - return connections[type]; - } - const clientOptions = _.assign({}, options.redis); - const client = connections[type] = createClient(type, clientOptions); - const opts = client.options.redisOptions || client.options; - if (["bclient", "subscriber"].includes(type) && (opts.enableReadyCheck || opts.maxRetriesPerRequest)) { - throw new Error(errors.Messages.MISSING_REDIS_OPTS); - } - queue[type + "Initialized"] = true; - if (!options.createClient) { - queue.clients.push(client); - } - return initCallback(type, client), client; - }; - }; - } - function redisOptsFromUrl(urlString) { - let redisOpts = {}; - try { - const redisUrl = url.parse(urlString, true, true); - redisOpts.port = parseInt(redisUrl.port || "6379", 10); - redisOpts.host = redisUrl.hostname; - redisOpts.db = redisUrl.pathname ? redisUrl.pathname.split("/")[1] : 0; - if (redisUrl.auth) { - const columnIndex = redisUrl.auth.indexOf(":"); - redisOpts.password = redisUrl.auth.slice(columnIndex + 1); - if (columnIndex > 0) { - redisOpts.username = redisUrl.auth.slice(0, columnIndex); - } - } - if (redisUrl.query) { - redisOpts = { ...redisOpts, ...redisUrl.query }; - } - } catch (e3) { - throw new Error(e3.message); - } - return redisOpts; - } - util.inherits(Queue, EventEmitter); - require_getters()(Queue); - require_worker()(Queue); - require_repeatable()(Queue); - Queue.prototype.off = Queue.prototype.removeListener; - var _on = Queue.prototype.on; - Queue.prototype.on = function(eventName) { - this._registerEvent(eventName); - return _on.apply(this, arguments); - }; - var _once = Queue.prototype.once; - Queue.prototype.once = function(eventName) { - this._registerEvent(eventName); - return _once.apply(this, arguments); - }; - Queue.prototype._initProcess = function() { - if (!this._initializingProcess) { - this.delayedTimestamp = Number.MAX_VALUE; - this._initializingProcess = this.isReady().then(() => { - return this._registerEvent("delayed"); - }).then(() => { - return this.updateDelayTimer(); - }); - this.errorRetryTimer = {}; - } - return this._initializingProcess; - }; - Queue.prototype._setupQueueEventListeners = function() { - const activeKey = this.keys.active; - const stalledKey = this.keys.stalled; - const progressKey = this.keys.progress; - const delayedKey = this.keys.delayed; - const pausedKey = this.keys.paused; - const resumedKey = this.keys.resumed; - const waitingKey = this.keys.waiting; - const completedKey = this.keys.completed; - const failedKey = this.keys.failed; - const drainedKey = this.keys.drained; - const duplicatedKey = this.keys.duplicated; - const debouncedKey = this.keys.de + "bounced"; - const pmessageHandler = (pattern, channel, message) => { - const keyAndToken = channel.split("@"); - const key = keyAndToken[0]; - const token = keyAndToken[1]; - switch (key) { - case activeKey: - utils.emitSafe(this, "global:active", message, "waiting"); - break; - case waitingKey: - if (this.token === token) { - utils.emitSafe(this, "waiting", message, null); - } - token && utils.emitSafe(this, "global:waiting", message, null); - break; - case stalledKey: - if (this.token === token) { - utils.emitSafe(this, "stalled", message); - } - utils.emitSafe(this, "global:stalled", message); - break; - case duplicatedKey: - if (this.token === token) { - utils.emitSafe(this, "duplicated", message); - } - utils.emitSafe(this, "global:duplicated", message); - break; - case debouncedKey: - if (this.token === token) { - utils.emitSafe(this, "debounced", message); - } - utils.emitSafe(this, "global:debounced", message); - break; - } - }; - const messageHandler = (channel, message) => { - const key = channel.split("@")[0]; - switch (key) { - case progressKey: { - try { - const { progress, jobId } = JSON.parse(message); - utils.emitSafe(this, "global:progress", jobId, progress); - } catch (err) { - const commaPos = message.indexOf(","); - const jobId = message.substring(0, commaPos); - const progress = message.substring(commaPos + 1); - utils.emitSafe(this, "global:progress", jobId, JSON.parse(progress)); - } - break; - } - case delayedKey: { - const newDelayedTimestamp = _.ceil(message); - if (newDelayedTimestamp < this.delayedTimestamp) { - this.delayedTimestamp = newDelayedTimestamp; - this.updateDelayTimer(); - } - break; - } - case pausedKey: - case resumedKey: - utils.emitSafe(this, "global:" + message); - break; - case completedKey: { - const data = JSON.parse(message); - utils.emitSafe(this, "global:completed", data.jobId, data.val, "active"); - break; - } - case failedKey: { - const data = JSON.parse(message); - utils.emitSafe(this, "global:failed", data.jobId, data.val, "active"); - break; - } - case drainedKey: - utils.emitSafe(this, "global:drained"); - break; - } - }; - this.eclient.on("pmessage", pmessageHandler); - this.eclient.on("message", messageHandler); - this.once("close", () => { - this.eclient.removeListener("pmessage", pmessageHandler); - this.eclient.removeListener("message", messageHandler); - }); - }; - Queue.prototype._registerEvent = function(eventName) { - const internalEvents = ["waiting", "delayed", "duplicated", "debounced"]; - if (eventName.startsWith("global:") || internalEvents.indexOf(eventName) !== -1) { - if (!this.registeredEvents) { - this._setupQueueEventListeners(); - this.registeredEvents = this.registeredEvents || {}; - } - const _eventName = eventName.replace("global:", ""); - if (!this.registeredEvents[_eventName]) { - return utils.isRedisReady(this.eclient).then(() => { - const channel = this.toKey(_eventName); - if (["active", "waiting", "stalled", "duplicated", "debounced"].indexOf(_eventName) !== -1) { - return this.registeredEvents[_eventName] = this.eclient.psubscribe(channel + "*"); - } else { - return this.registeredEvents[_eventName] = this.eclient.subscribe(channel); - } - }).then(() => { - utils.emitSafe(this, "registered:" + eventName); - }); - } else { - return this.registeredEvents[_eventName]; - } - } - return Promise.resolve(); - }; - Queue.ErrorMessages = errors.Messages; - Queue.prototype.isReady = async function() { - await this._initializing; - return this; - }; - async function redisClientDisconnect(client) { - if (client.status !== "end") { - let _resolve, _reject; - return new Promise((resolve, reject) => { - _resolve = resolve; - _reject = reject; - client.once("end", _resolve); - pTimeout(client.quit().catch((err) => { - if (err.message !== "Connection is closed.") { - throw err; - } - }), 500).catch(() => {}).finally(() => { - client.once("error", _reject); - client.disconnect(); - if (["connecting", "reconnecting"].includes(client.status)) { - resolve(); - } - }); - }).finally(() => { - client.removeListener("end", _resolve); - client.removeListener("error", _reject); - }); - } - } - Queue.prototype.disconnect = async function() { - await Promise.all(this.clients.map((client) => client.blocked ? client.disconnect() : redisClientDisconnect(client))); - }; - Queue.prototype.removeJobs = function(pattern) { - return Job.remove(this, pattern); - }; - Queue.prototype.close = function(doNotWaitJobs) { - let isReady = true; - if (this.closing) { - return this.closing; - } - return this.closing = this.isReady().then(this._initializingProcess).catch(() => { - isReady = false; - }).then(() => isReady && this.pause(true, doNotWaitJobs)).catch(() => { - return; - }).finally(() => this._clearTimers()).then(() => { - if (!this.childPool) { - return; - } - const cleanPromise = this.childPool.clean().catch(() => {}); - if (doNotWaitJobs) { - return; - } - return cleanPromise; - }).then(async () => this.disconnect(), (err) => console.error(err)).finally(() => { - this.closed = true; - utils.emitSafe(this, "close"); - }); - }; - Queue.prototype._clearTimers = function() { - _.each(this.errorRetryTimer, (timer) => { - clearTimeout(timer); - }); - clearTimeout(this.delayTimer); - clearInterval(this.guardianTimer); - clearInterval(this.moveUnlockedJobsToWaitInterval); - this.timers.clearAll(); - return this.timers.whenIdle(); - }; - Queue.prototype.process = function(name, concurrency, handler) { - switch (arguments.length) { - case 1: - handler = name; - concurrency = 1; - name = Job.DEFAULT_JOB_NAME; - break; - case 2: - handler = concurrency; - if (typeof name === "string") { - concurrency = 1; - } else { - concurrency = name; - name = Job.DEFAULT_JOB_NAME; - } - break; - } - this.setHandler(name, handler); - return this._initProcess().then(() => { - return this.start(concurrency, name); - }); - }; - Queue.prototype.start = function(concurrency, name) { - return this.run(concurrency, name).catch((err) => { - utils.emitSafe(this, "error", err, "error running queue"); - throw err; - }); - }; - Queue.prototype.setHandler = function(name, handler) { - if (!handler) { - throw new Error("Cannot set an undefined handler"); - } - if (this.handlers[name]) { - throw new Error("Cannot define the same handler twice " + name); - } - this.setWorkerName(); - if (typeof handler === "string") { - const supportedFileTypes = [".js", ".ts", ".flow", ".cjs"]; - const processorFile = handler + (supportedFileTypes.includes(path2.extname(handler)) ? "" : ".js"); - if (!fs3.existsSync(processorFile)) { - throw new Error("File " + processorFile + " does not exist"); - } - const isSharedChildPool = this.settings.isSharedChildPool; - this.childPool = this.childPool || require_child_pool()(isSharedChildPool); - const sandbox = require_sandbox(); - this.handlers[name] = sandbox(handler, this.childPool).bind(this); - } else { - handler = handler.bind(this); - if (handler.length > 1) { - this.handlers[name] = promisify2(handler); - } else { - this.handlers[name] = function() { - try { - return Promise.resolve(handler.apply(null, arguments)); - } catch (err) { - return Promise.reject(err); - } - }; - } - } - }; - Queue.prototype.add = function(name, data, opts) { - if (typeof name !== "string") { - opts = data; - data = name; - name = Job.DEFAULT_JOB_NAME; - } - opts = _.cloneDeep({ ...this.defaultJobOptions, ...opts }); - opts.jobId = jobIdForGroup(this.limiter, opts, data); - if (opts.repeat) { - return this.isReady().then(() => { - return this.nextRepeatableJob(name, data, opts, true); - }); - } else { - return Job.create(this, name, data, opts); - } - }; - Queue.prototype.retryJobs = async function(opts = {}) { - let cursor = 0; - do { - cursor = await scripts.retryJobs(this, opts.count); - } while (cursor); - }; - Queue.prototype.removeDebounceKey = (id) => { - return exports.client.del(`${exports.keys.de}:${id}`); - }; - Queue.prototype.addBulk = function(jobs) { - const decoratedJobs = jobs.map((job) => { - const jobId = jobIdForGroup(this.limiter, job.opts, job.data); - return { - ...job, - name: typeof job.name !== "string" ? Job.DEFAULT_JOB_NAME : job.name, - opts: { - ...this.defaultJobOptions, - ...job.opts, - jobId - } - }; - }); - return Job.createBulk(this, decoratedJobs); - }; - Queue.prototype.empty = function() { - const queueKeys = this.keys; - let multi = this.multi(); - multi.lrange(queueKeys.wait, 0, -1); - multi.lrange(queueKeys.paused, 0, -1); - multi.keys(this.toKey("*:limited")); - multi.del(queueKeys.wait, queueKeys.paused, queueKeys["meta-paused"], queueKeys.delayed, queueKeys.priority, queueKeys.limiter, `${queueKeys.limiter}:index`); - return multi.exec().then((res) => { - let [waiting, paused, limited] = res; - waiting = waiting[1]; - paused = paused[1]; - limited = limited[1]; - const jobKeys = paused.concat(waiting).map(this.toKey, this); - if (jobKeys.length || limited.length) { - multi = this.multi(); - for (let i2 = 0;i2 < jobKeys.length; i2 += 1e4) { - multi.del.apply(multi, jobKeys.slice(i2, i2 + 1e4)); - } - for (let i2 = 0;i2 < limited.length; i2 += 1e4) { - multi.del.apply(multi, limited.slice(i2, i2 + 1e4)); - } - return multi.exec(); - } - }); - }; - Queue.prototype.pause = function(isLocal, doNotWaitActive) { - return this.isReady().then(() => { - if (isLocal) { - if (!this.paused) { - this.paused = new Promise((resolve) => { - this.resumeLocal = function() { - this.paused = null; - resolve(); - }; - }); - } - if (!this.bclientInitialized) { - return; - } - if (doNotWaitActive) { - return redisClientDisconnect(this.bclient).then(() => this.bclient.connect()); - } - return this.whenCurrentJobsFinished(); - } else { - return scripts.pause(this, true); - } - }).then(() => { - return utils.emitSafe(this, "paused"); - }); - }; - Queue.prototype.resume = function(isLocal) { - return this.isReady().then(() => { - if (isLocal) { - if (this.resumeLocal) { - this.resumeLocal(); - } - } else { - return scripts.pause(this, false); - } - }).then(() => { - utils.emitSafe(this, "resumed"); - }); - }; - Queue.prototype.isPaused = async function(isLocal) { - if (isLocal) { - return !!this.paused; - } else { - await this.isReady(); - const multi = this.multi(); - multi.exists(this.keys["meta-paused"]); - multi.hexists(this.toKey("meta"), "paused"); - const [[, isPaused], [, isPausedNew]] = await multi.exec(); - return !!(isPaused || isPausedNew); - } - }; - Queue.prototype.run = function(concurrency, handlerName) { - if (!Number.isInteger(concurrency)) { - throw new Error("Cannot set Float as concurrency"); - } - const promises = []; - return this.isReady().then(() => { - return this.moveUnlockedJobsToWait(); - }).then(() => { - return utils.isRedisReady(this.bclient); - }).then(() => { - while (concurrency--) { - promises.push(new Promise((resolve) => { - this.processJobs(`${handlerName}:${concurrency}`, resolve); - })); - } - this.startMoveUnlockedJobsToWait(); - return Promise.all(promises); - }); - }; - Queue.prototype.updateDelayTimer = function() { - if (this.closing) { - return Promise.resolve(); - } - return scripts.updateDelaySet(this, Date.now()).then((nextTimestamp) => { - this.delayedTimestamp = nextTimestamp ? nextTimestamp / 4096 : Number.MAX_VALUE; - if (this.delayTimer) { - clearTimeout(this.delayTimer); - } - const delay = _.min([ - this.delayedTimestamp - Date.now(), - this.settings.guardInterval - ]); - if (delay <= 0) { - this.updateDelayTimer(); - } else { - this.delayTimer = setTimeout(() => this.updateDelayTimer(), delay); - } - return null; - }).catch((err) => { - utils.emitSafe(this, "error", err, "Error updating the delay timer"); - if (this.delayTimer) { - clearTimeout(this.delayTimer); - } - this.delayTimer = setTimeout(() => this.updateDelayTimer(), this.settings.guardInterval); - }); - }; - Queue.prototype.moveUnlockedJobsToWait = function() { - if (this.closing) { - return Promise.resolve(); - } - return scripts.moveUnlockedJobsToWait(this).then(([failed, stalled]) => { - const handleFailedJobs = failed.map((jobId) => { - return this.getJobFromId(jobId).then((job) => { - utils.emitSafe(this, "failed", job, new Error("job stalled more than allowable limit"), "active"); - return null; - }); - }); - const handleStalledJobs = stalled.map((jobId) => { - return this.getJobFromId(jobId).then((job) => { - if (job !== null) { - utils.emitSafe(this, "stalled", job); - } - return null; - }); - }); - return Promise.all(handleFailedJobs.concat(handleStalledJobs)); - }).catch((err) => { - utils.emitSafe(this, "error", err, "Failed to handle unlocked job in active"); - }); - }; - Queue.prototype.startMoveUnlockedJobsToWait = function() { - clearInterval(this.moveUnlockedJobsToWaitInterval); - if (this.settings.stalledInterval > 0 && !this.closing) { - this.moveUnlockedJobsToWaitInterval = setInterval(this.moveUnlockedJobsToWait, this.settings.stalledInterval); - } - }; - Queue.prototype.processJobs = function(index2, resolve, job) { - const processJobs = this.processJobs.bind(this, index2, resolve); - process.nextTick(() => { - this._processJobOnNextTick(processJobs, index2, resolve, job); - }); - }; - Queue.prototype._processJobOnNextTick = function(processJobs, index2, resolve, job) { - if (!this.closing) { - (this.paused || Promise.resolve()).then(() => { - const gettingNextJob = job ? Promise.resolve(job) : this.getNextJob(); - return this.processing[index2] = gettingNextJob.then(this.processJob).then(processJobs, (err) => { - if (!(this.closing && err.message === "Connection is closed.")) { - utils.emitSafe(this, "error", err, "Error processing job"); - clearTimeout(this.errorRetryTimer[index2]); - this.errorRetryTimer[index2] = setTimeout(() => { - processJobs(); - }, this.settings.retryProcessDelay); - } - return null; - }); - }).catch((err) => { - utils.emitSafe(this, "error", err, "Error processing job"); - }); - } else { - resolve(this.closing); - } - }; - Queue.prototype.processJob = function(job, notFetch = false) { - let lockRenewId; - let timerStopped = false; - if (!job) { - return Promise.resolve(); - } - const lockExtender = () => { - lockRenewId = this.timers.set("lockExtender", this.settings.lockRenewTime, () => { - scripts.extendLock(this, job.id, this.settings.lockDuration).then((lock) => { - if (lock && !timerStopped) { - lockExtender(); - } - }).catch((err) => { - utils.emitSafe(this, "lock-extension-failed", job, err); - }); - }); - }; - const timeoutMs = job.opts.timeout; - const stopTimer = () => { - timerStopped = true; - this.timers.clear(lockRenewId); - }; - const handleCompleted = (result) => { - return job.moveToCompleted(result, undefined, notFetch).then((jobData) => { - utils.emitSafe(this, "completed", job, result, "active"); - return jobData ? this.nextJobFromJobData(jobData[0], jobData[1]) : null; - }); - }; - const handleFailed = (err) => { - const error = err; - return job.moveToFailed(err).then((jobData) => { - utils.emitSafe(this, "failed", job, error, "active"); - return jobData ? this.nextJobFromJobData(jobData[0], jobData[1]) : null; - }); - }; - lockExtender(); - const handler = this.handlers[job.name] || this.handlers["*"]; - if (!handler) { - return handleFailed(new Error("Missing process handler for job type " + job.name)); - } else { - let jobPromise = handler(job); - if (timeoutMs) { - jobPromise = pTimeout(jobPromise, timeoutMs); - } - utils.emitSafe(this, "active", job, jobPromise, "waiting"); - return jobPromise.then(handleCompleted).catch(handleFailed).finally(() => { - stopTimer(); - }); - } - }; - Queue.prototype.multi = function() { - return this.client.multi(); - }; - Queue.prototype.getNextJob = async function() { - if (this.closing) { - return Promise.resolve(); - } - if (this.drained) { - try { - this.bclient.blocked = true; - const jobId = await this.bclient.brpoplpush(this.keys.wait, this.keys.active, this.settings.drainDelay); - this.bclient.blocked = false; - if (jobId) { - return this.moveToActive(jobId); - } - } catch (err) { - if (!(this.paused && err.message === "Connection is closed.")) { - throw err; - } - } - } else { - return this.moveToActive(); - } - }; - Queue.prototype.moveToActive = async function(jobId) { - await this.isReady(); - return scripts.moveToActive(this, jobId).then(([jobData, jobId2]) => { - return this.nextJobFromJobData(jobData, jobId2); - }); - }; - Queue.prototype.nextJobFromJobData = function(jobData, jobId) { - if (jobData) { - this.drained = false; - const job = Job.fromJSON(this, jobData, jobId); - if (job.opts.repeat) { - return this.nextRepeatableJob(job.name, job.data, job.opts).then(() => { - return job; - }); - } - return job; - } else { - this.drained = true; - utils.emitSafe(this, "drained"); - return null; - } - }; - Queue.prototype.retryJob = function(job) { - return job.retry(); - }; - Queue.prototype.toKey = function(queueType) { - return [this.keyPrefix, this.name, queueType].join(":"); - }; - Queue.prototype.clean = function(grace, type, limit) { - return this.isReady().then(() => { - if (grace === undefined || grace === null) { - throw new Error("You must define a grace period."); - } - if (!type) { - type = "completed"; - } - if (_.indexOf(["completed", "wait", "active", "paused", "delayed", "failed"], type) === -1) { - throw new Error("Cannot clean unknown queue type " + type); - } - return scripts.cleanJobsInSet(this, type, Date.now() - grace, limit).then((jobs) => { - utils.emitSafe(this, "cleaned", jobs, type); - return jobs; - }).catch((err) => { - utils.emitSafe(this, "error", err); - throw err; - }); - }); - }; - Queue.prototype.obliterate = async function(opts) { - await this.pause(); - let cursor = 0; - do { - cursor = await scripts.obliterate(this, { - force: false, - count: 1000, - ...opts - }); - } while (cursor); - }; - Queue.prototype.whenCurrentJobsFinished = function() { - if (!this.bclientInitialized) { - return Promise.resolve(); - } - const forcedReconnection = redisClientDisconnect(this.bclient).then(() => { - return this.bclient.connect(); - }); - return Promise.all(Object.values(this.processing)).then(() => forcedReconnection); - }; - function getRedisVersion(client) { - return client.info().then((doc) => { - const prefix = "redis_version:"; - const lines = doc.split(`\r -`); - for (let i2 = 0;i2 < lines.length; i2++) { - if (lines[i2].indexOf(prefix) === 0) { - return lines[i2].substr(prefix.length); - } - } - }); - } - function jobIdForGroup(limiter, opts, data) { - const jobId = opts && opts.jobId; - const groupKey = _.get(limiter, "groupKey"); - if (groupKey) { - return `${jobId || uuid2.v4()}:${_.get(data, groupKey)}`; - } - return jobId; - } - module.exports = Queue; -}); - -// node_modules/.pnpm/bull@4.16.5/node_modules/bull/index.js -var require_bull = __commonJS((exports, module) => { - module.exports = require_queue(); - module.exports.Job = require_job(); - module.exports.utils = require_utils12(); -}); - -// node_modules/.pnpm/delayed-stream@1.0.0/node_modules/delayed-stream/lib/delayed_stream.js -var require_delayed_stream = __commonJS((exports, module) => { - var Stream = __require("stream").Stream; - var util = __require("util"); - module.exports = DelayedStream; - function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; - } - util.inherits(DelayedStream, Stream); - DelayedStream.create = function(source, options) { - var delayedStream = new this; - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } - delayedStream.source = source; - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; - source.on("error", function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } - return delayedStream; - }; - Object.defineProperty(DelayedStream.prototype, "readable", { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } - }); - DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); - }; - DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } - this.source.resume(); - }; - DelayedStream.prototype.pause = function() { - this.source.pause(); - }; - DelayedStream.prototype.release = function() { - this._released = true; - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; - }; - DelayedStream.prototype.pipe = function() { - var r2 = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r2; - }; - DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } - if (args[0] === "data") { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } - this._bufferedEvents.push(args); - }; - DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } - if (this.dataSize <= this.maxDataSize) { - return; - } - this._maxDataSizeExceeded = true; - var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; - this.emit("error", new Error(message)); - }; -}); - -// node_modules/.pnpm/combined-stream@1.0.8/node_modules/combined-stream/lib/combined_stream.js -var require_combined_stream = __commonJS((exports, module) => { - var util = __require("util"); - var Stream = __require("stream").Stream; - var DelayedStream = require_delayed_stream(); - module.exports = CombinedStream; - function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; - } - util.inherits(CombinedStream, Stream); - CombinedStream.create = function(options) { - var combinedStream = new this; - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } - return combinedStream; - }; - CombinedStream.isStreamLike = function(stream) { - return typeof stream !== "function" && typeof stream !== "string" && typeof stream !== "boolean" && typeof stream !== "number" && !Buffer.isBuffer(stream); - }; - CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams - }); - stream.on("data", this._checkDataSize.bind(this)); - stream = newStream; - } - this._handleErrors(stream); - if (this.pauseStreams) { - stream.pause(); - } - } - this._streams.push(stream); - return this; - }; - CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; - }; - CombinedStream.prototype._getNext = function() { - this._currentStream = null; - if (this._insideLoop) { - this._pendingNext = true; - return; - } - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } - }; - CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); - if (typeof stream == "undefined") { - this.end(); - return; - } - if (typeof stream !== "function") { - this._pipeNext(stream); - return; - } - var getStream = stream; - getStream(function(stream2) { - var isStreamLike = CombinedStream.isStreamLike(stream2); - if (isStreamLike) { - stream2.on("data", this._checkDataSize.bind(this)); - this._handleErrors(stream2); - } - this._pipeNext(stream2); - }.bind(this)); - }; - CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on("end", this._getNext.bind(this)); - stream.pipe(this, { end: false }); - return; - } - var value = stream; - this.write(value); - this._getNext(); - }; - CombinedStream.prototype._handleErrors = function(stream) { - var self2 = this; - stream.on("error", function(err) { - self2._emitError(err); - }); - }; - CombinedStream.prototype.write = function(data) { - this.emit("data", data); - }; - CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } - if (this.pauseStreams && this._currentStream && typeof this._currentStream.pause == "function") - this._currentStream.pause(); - this.emit("pause"); - }; - CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } - if (this.pauseStreams && this._currentStream && typeof this._currentStream.resume == "function") - this._currentStream.resume(); - this.emit("resume"); - }; - CombinedStream.prototype.end = function() { - this._reset(); - this.emit("end"); - }; - CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit("close"); - }; - CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; - }; - CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } - var message = "DelayedStream#maxDataSize of " + this.maxDataSize + " bytes exceeded."; - this._emitError(new Error(message)); - }; - CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; - var self2 = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; - } - self2.dataSize += stream.dataSize; - }); - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } - }; - CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit("error", err); - }; -}); + }; + CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit("error", err); + }; +}); // node_modules/.pnpm/mime-db@1.52.0/node_modules/mime-db/db.json -var require_db3 = __commonJS((exports, module) => { +var require_db2 = __commonJS((exports, module) => { module.exports = { "application/1d-interleaved-parityfec": { source: "iana" @@ -150771,8677 +126368,13534 @@ var require_db3 = __commonJS((exports, module) => { "x-shader/x-vertex": { compressible: true } - }; -}); - -// node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js -var require_mime_types3 = __commonJS((exports) => { - /*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - var db2 = require_db3(); - var extname = __require("path").extname; - var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; - var TEXT_TYPE_REGEXP = /^text\//i; - exports.charset = charset; - exports.charsets = { lookup: charset }; - exports.contentType = contentType; - exports.extension = extension; - exports.extensions = Object.create(null); - exports.lookup = lookup; - exports.types = Object.create(null); - populateMaps(exports.extensions, exports.types); - function charset(type) { - if (!type || typeof type !== "string") { - return false; + }; +}); + +// node_modules/.pnpm/mime-types@2.1.35/node_modules/mime-types/index.js +var require_mime_types3 = __commonJS((exports) => { + /*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + var db2 = require_db2(); + var extname = __require("path").extname; + var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/; + var TEXT_TYPE_REGEXP = /^text\//i; + exports.charset = charset; + exports.charsets = { lookup: charset }; + exports.contentType = contentType; + exports.extension = extension; + exports.extensions = Object.create(null); + exports.lookup = lookup; + exports.types = Object.create(null); + populateMaps(exports.extensions, exports.types); + function charset(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var mime = match && db2[match[1].toLowerCase()]; + if (mime && mime.charset) { + return mime.charset; + } + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return "UTF-8"; + } + return false; + } + function contentType(str) { + if (!str || typeof str !== "string") { + return false; + } + var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str; + if (!mime) { + return false; + } + if (mime.indexOf("charset") === -1) { + var charset2 = exports.charset(mime); + if (charset2) + mime += "; charset=" + charset2.toLowerCase(); + } + return mime; + } + function extension(type) { + if (!type || typeof type !== "string") { + return false; + } + var match = EXTRACT_TYPE_REGEXP.exec(type); + var exts = match && exports.extensions[match[1].toLowerCase()]; + if (!exts || !exts.length) { + return false; + } + return exts[0]; + } + function lookup(path2) { + if (!path2 || typeof path2 !== "string") { + return false; + } + var extension2 = extname("x." + path2).toLowerCase().substr(1); + if (!extension2) { + return false; + } + return exports.types[extension2] || false; + } + function populateMaps(extensions2, types7) { + var preference = ["nginx", "apache", undefined, "iana"]; + Object.keys(db2).forEach(function forEachMimeType(type) { + var mime = db2[type]; + var exts = mime.extensions; + if (!exts || !exts.length) { + return; + } + extensions2[type] = exts; + for (var i2 = 0;i2 < exts.length; i2++) { + var extension2 = exts[i2]; + if (types7[extension2]) { + var from = preference.indexOf(db2[types7[extension2]].source); + var to = preference.indexOf(mime.source); + if (types7[extension2] !== "application/octet-stream" && (from > to || from === to && types7[extension2].substr(0, 12) === "application/")) { + continue; + } + } + types7[extension2] = type; + } + }); + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/defer.js +var require_defer = __commonJS((exports, module) => { + module.exports = defer; + function defer(fn) { + var nextTick2 = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null; + if (nextTick2) { + nextTick2(fn); + } else { + setTimeout(fn, 0); + } + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/async.js +var require_async = __commonJS((exports, module) => { + var defer = require_defer(); + module.exports = async; + function async(callback) { + var isAsync = false; + defer(function() { + isAsync = true; + }); + return function async_callback(err, result) { + if (isAsync) { + callback(err, result); + } else { + defer(function nextTick_callback() { + callback(err, result); + }); + } + }; + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/abort.js +var require_abort = __commonJS((exports, module) => { + module.exports = abort; + function abort(state) { + Object.keys(state.jobs).forEach(clean3.bind(state)); + state.jobs = {}; + } + function clean3(key) { + if (typeof this.jobs[key] == "function") { + this.jobs[key](); + } + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/iterate.js +var require_iterate = __commonJS((exports, module) => { + var async = require_async(); + var abort = require_abort(); + module.exports = iterate; + function iterate(list, iterator2, state, callback) { + var key = state["keyedList"] ? state["keyedList"][state.index] : state.index; + state.jobs[key] = runJob(iterator2, key, list[key], function(error, output) { + if (!(key in state.jobs)) { + return; + } + delete state.jobs[key]; + if (error) { + abort(state); + } else { + state.results[key] = output; + } + callback(error, state.results); + }); + } + function runJob(iterator2, key, item, callback) { + var aborter; + if (iterator2.length == 2) { + aborter = iterator2(item, async(callback)); + } else { + aborter = iterator2(item, key, async(callback)); + } + return aborter; + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/state.js +var require_state2 = __commonJS((exports, module) => { + module.exports = state; + function state(list, sortMethod) { + var isNamedList = !Array.isArray(list), initState = { + index: 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs: {}, + results: isNamedList ? {} : [], + size: isNamedList ? Object.keys(list).length : list.length + }; + if (sortMethod) { + initState.keyedList.sort(isNamedList ? sortMethod : function(a2, b2) { + return sortMethod(list[a2], list[b2]); + }); + } + return initState; + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/terminator.js +var require_terminator = __commonJS((exports, module) => { + var abort = require_abort(); + var async = require_async(); + module.exports = terminator; + function terminator(callback) { + if (!Object.keys(this.jobs).length) { + return; + } + this.index = this.size; + abort(this); + async(callback)(null, this.results); + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/parallel.js +var require_parallel2 = __commonJS((exports, module) => { + var iterate = require_iterate(); + var initState = require_state2(); + var terminator = require_terminator(); + module.exports = parallel; + function parallel(list, iterator2, callback) { + var state = initState(list); + while (state.index < (state["keyedList"] || list).length) { + iterate(list, iterator2, state, function(error, result) { + if (error) { + callback(error, result); + return; + } + if (Object.keys(state.jobs).length === 0) { + callback(null, state.results); + return; + } + }); + state.index++; + } + return terminator.bind(state, callback); + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/serialOrdered.js +var require_serialOrdered = __commonJS((exports, module) => { + var iterate = require_iterate(); + var initState = require_state2(); + var terminator = require_terminator(); + module.exports = serialOrdered; + module.exports.ascending = ascending; + module.exports.descending = descending; + function serialOrdered(list, iterator2, sortMethod, callback) { + var state = initState(list, sortMethod); + iterate(list, iterator2, state, function iteratorHandler(error, result) { + if (error) { + callback(error, result); + return; + } + state.index++; + if (state.index < (state["keyedList"] || list).length) { + iterate(list, iterator2, state, iteratorHandler); + return; + } + callback(null, state.results); + }); + return terminator.bind(state, callback); + } + function ascending(a2, b2) { + return a2 < b2 ? -1 : a2 > b2 ? 1 : 0; + } + function descending(a2, b2) { + return -1 * ascending(a2, b2); + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/serial.js +var require_serial = __commonJS((exports, module) => { + var serialOrdered = require_serialOrdered(); + module.exports = serial3; + function serial3(list, iterator2, callback) { + return serialOrdered(list, iterator2, null, callback); + } +}); + +// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/index.js +var require_asynckit = __commonJS((exports, module) => { + module.exports = { + parallel: require_parallel2(), + serial: require_serial(), + serialOrdered: require_serialOrdered() + }; +}); + +// node_modules/.pnpm/has-tostringtag@1.0.2/node_modules/has-tostringtag/shams.js +var require_shams2 = __commonJS((exports, module) => { + var hasSymbols = require_shams(); + module.exports = function hasToStringTagShams() { + return hasSymbols() && !!Symbol.toStringTag; + }; +}); + +// node_modules/.pnpm/es-set-tostringtag@2.1.0/node_modules/es-set-tostringtag/index.js +var require_es_set_tostringtag = __commonJS((exports, module) => { + var GetIntrinsic = require_get_intrinsic(); + var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); + var hasToStringTag = require_shams2()(); + var hasOwn = require_hasown(); + var $TypeError = require_type(); + var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null; + module.exports = function setToStringTag(object2, value) { + var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; + var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; + if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") { + throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans"); + } + if (toStringTag2 && (overrideIfSet || !hasOwn(object2, toStringTag2))) { + if ($defineProperty) { + $defineProperty(object2, toStringTag2, { + configurable: !nonConfigurable, + enumerable: false, + value, + writable: false + }); + } else { + object2[toStringTag2] = value; + } + } + }; +}); + +// node_modules/.pnpm/form-data@4.0.5/node_modules/form-data/lib/populate.js +var require_populate = __commonJS((exports, module) => { + module.exports = function(dst, src2) { + Object.keys(src2).forEach(function(prop) { + dst[prop] = dst[prop] || src2[prop]; + }); + return dst; + }; +}); + +// node_modules/.pnpm/form-data@4.0.5/node_modules/form-data/lib/form_data.js +var require_form_data = __commonJS((exports, module) => { + var CombinedStream = require_combined_stream(); + var util = __require("util"); + var path2 = __require("path"); + var http = __require("http"); + var https = __require("https"); + var parseUrl3 = __require("url").parse; + var fs3 = __require("fs"); + var Stream = __require("stream").Stream; + var crypto3 = __require("crypto"); + var mime = require_mime_types3(); + var asynckit = require_asynckit(); + var setToStringTag = require_es_set_tostringtag(); + var hasOwn = require_hasown(); + var populate = require_populate(); + function FormData2(options) { + if (!(this instanceof FormData2)) { + return new FormData2(options); + } + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; + CombinedStream.call(this); + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } + } + util.inherits(FormData2, CombinedStream); + FormData2.LINE_BREAK = `\r +`; + FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream"; + FormData2.prototype.append = function(field, value, options) { + options = options || {}; + if (typeof options === "string") { + options = { filename: options }; + } + var append = CombinedStream.prototype.append.bind(this); + if (typeof value === "number" || value == null) { + value = String(value); + } + if (Array.isArray(value)) { + this._error(new Error("Arrays are not supported.")); + return; + } + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); + append(header); + append(value); + append(footer); + this._trackLength(header, value, options); + }; + FormData2.prototype._trackLength = function(header, value, options) { + var valueLength = 0; + if (options.knownLength != null) { + valueLength += Number(options.knownLength); + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === "string") { + valueLength = Buffer.byteLength(value); + } + this._valueLength += valueLength; + this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length; + if (!value || !value.path && !(value.readable && hasOwn(value, "httpVersion")) && !(value instanceof Stream)) { + return; + } + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } + }; + FormData2.prototype._lengthRetriever = function(value, callback) { + if (hasOwn(value, "fd")) { + if (value.end != null && value.end != Infinity && value.start != null) { + callback(null, value.end + 1 - (value.start ? value.start : 0)); + } else { + fs3.stat(value.path, function(err, stat) { + if (err) { + callback(err); + return; + } + var fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } + } else if (hasOwn(value, "httpVersion")) { + callback(null, Number(value.headers["content-length"])); + } else if (hasOwn(value, "httpModule")) { + value.on("response", function(response) { + value.pause(); + callback(null, Number(response.headers["content-length"])); + }); + value.resume(); + } else { + callback("Unknown stream"); + } + }; + FormData2.prototype._multiPartHeader = function(field, value, options) { + if (typeof options.header === "string") { + return options.header; + } + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); + var contents = ""; + var headers = { + "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []), + "Content-Type": [].concat(contentType || []) + }; + if (typeof options.header === "object") { + populate(headers, options.header); + } + var header; + for (var prop in headers) { + if (hasOwn(headers, prop)) { + header = headers[prop]; + if (header == null) { + continue; + } + if (!Array.isArray(header)) { + header = [header]; + } + if (header.length) { + contents += prop + ": " + header.join("; ") + FormData2.LINE_BREAK; + } + } + } + return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK; + }; + FormData2.prototype._getContentDisposition = function(value, options) { + var filename; + if (typeof options.filepath === "string") { + filename = path2.normalize(options.filepath).replace(/\\/g, "/"); + } else if (options.filename || value && (value.name || value.path)) { + filename = path2.basename(options.filename || value && (value.name || value.path)); + } else if (value && value.readable && hasOwn(value, "httpVersion")) { + filename = path2.basename(value.client._httpMessage.path || ""); + } + if (filename) { + return 'filename="' + filename + '"'; + } + }; + FormData2.prototype._getContentType = function(value, options) { + var contentType = options.contentType; + if (!contentType && value && value.name) { + contentType = mime.lookup(value.name); + } + if (!contentType && value && value.path) { + contentType = mime.lookup(value.path); + } + if (!contentType && value && value.readable && hasOwn(value, "httpVersion")) { + contentType = value.headers["content-type"]; + } + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } + if (!contentType && value && typeof value === "object") { + contentType = FormData2.DEFAULT_CONTENT_TYPE; + } + return contentType; + }; + FormData2.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData2.LINE_BREAK; + var lastPart = this._streams.length === 0; + if (lastPart) { + footer += this._lastBoundary(); + } + next(footer); + }.bind(this); + }; + FormData2.prototype._lastBoundary = function() { + return "--" + this.getBoundary() + "--" + FormData2.LINE_BREAK; + }; + FormData2.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + "content-type": "multipart/form-data; boundary=" + this.getBoundary() + }; + for (header in userHeaders) { + if (hasOwn(userHeaders, header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } + return formHeaders; + }; + FormData2.prototype.setBoundary = function(boundary) { + if (typeof boundary !== "string") { + throw new TypeError("FormData boundary must be a string"); + } + this._boundary = boundary; + }; + FormData2.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } + return this._boundary; + }; + FormData2.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc(0); + var boundary = this.getBoundary(); + for (var i2 = 0, len = this._streams.length;i2 < len; i2++) { + if (typeof this._streams[i2] !== "function") { + if (Buffer.isBuffer(this._streams[i2])) { + dataBuffer = Buffer.concat([dataBuffer, this._streams[i2]]); + } else { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i2])]); + } + if (typeof this._streams[i2] !== "string" || this._streams[i2].substring(2, boundary.length + 2) !== boundary) { + dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData2.LINE_BREAK)]); + } + } + } + return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); + }; + FormData2.prototype._generateBoundary = function() { + this._boundary = "--------------------------" + crypto3.randomBytes(12).toString("hex"); + }; + FormData2.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + if (!this.hasKnownLength()) { + this._error(new Error("Cannot calculate proper length in synchronous way.")); + } + return knownLength; + }; + FormData2.prototype.hasKnownLength = function() { + var hasKnownLength = true; + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } + return hasKnownLength; + }; + FormData2.prototype.getLength = function(cb2) { + var knownLength = this._overheadLength + this._valueLength; + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } + if (!this._valuesToMeasure.length) { + process.nextTick(cb2.bind(this, null, knownLength)); + return; + } + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb2(err); + return; + } + values.forEach(function(length) { + knownLength += length; + }); + cb2(null, knownLength); + }); + }; + FormData2.prototype.submit = function(params, cb2) { + var request2; + var options; + var defaults2 = { method: "post" }; + if (typeof params === "string") { + params = parseUrl3(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults2); + } else { + options = populate(params, defaults2); + if (!options.port) { + options.port = options.protocol === "https:" ? 443 : 80; + } + } + options.headers = this.getHeaders(params.headers); + if (options.protocol === "https:") { + request2 = https.request(options); + } else { + request2 = http.request(options); + } + this.getLength(function(err, length) { + if (err && err !== "Unknown stream") { + this._error(err); + return; + } + if (length) { + request2.setHeader("Content-Length", length); + } + this.pipe(request2); + if (cb2) { + var onResponse; + var callback = function(error, responce) { + request2.removeListener("error", callback); + request2.removeListener("response", onResponse); + return cb2.call(this, error, responce); + }; + onResponse = callback.bind(this, null); + request2.on("error", callback); + request2.on("response", onResponse); + } + }.bind(this)); + return request2; + }; + FormData2.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit("error", err); + } + }; + FormData2.prototype.toString = function() { + return "[object FormData]"; + }; + setToStringTag(FormData2.prototype, "FormData"); + module.exports = FormData2; +}); + +// node_modules/.pnpm/follow-redirects@1.16.0/node_modules/follow-redirects/debug.js +var require_debug3 = __commonJS((exports, module) => { + var debug; + module.exports = function() { + if (!debug) { + try { + debug = require_src()("follow-redirects"); + } catch (error) {} + if (typeof debug !== "function") { + debug = function() {}; + } + } + debug.apply(null, arguments); + }; +}); + +// node_modules/.pnpm/follow-redirects@1.16.0/node_modules/follow-redirects/index.js +var require_follow_redirects = __commonJS((exports, module) => { + var url2 = __require("url"); + var URL2 = url2.URL; + var http = __require("http"); + var https = __require("https"); + var Writable2 = __require("stream").Writable; + var assert = __require("assert"); + var debug = require_debug3(); + (function detectUnsupportedEnvironment() { + var looksLikeNode = typeof process !== "undefined"; + var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; + var looksLikeV8 = isFunction2(Error.captureStackTrace); + if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { + console.warn("The follow-redirects package should be excluded from browser builds."); + } + })(); + var useNativeURL = false; + try { + assert(new URL2("")); + } catch (error) { + useNativeURL = error.code === "ERR_INVALID_URL"; + } + var sensitiveHeaders = [ + "Authorization", + "Proxy-Authorization", + "Cookie" + ]; + var preservedUrlFields = [ + "auth", + "host", + "hostname", + "href", + "path", + "pathname", + "port", + "protocol", + "query", + "search", + "hash" + ]; + var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; + var eventHandlers = Object.create(null); + events.forEach(function(event) { + eventHandlers[event] = function(arg1, arg2, arg3) { + this._redirectable.emit(event, arg1, arg2, arg3); + }; + }); + var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError); + var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed"); + var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError); + var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit"); + var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); + var destroy = Writable2.prototype.destroy || noop2; + function RedirectableRequest(options, responseCallback) { + Writable2.call(this); + this._sanitizeOptions(options); + this._options = options; + this._ended = false; + this._ending = false; + this._redirectCount = 0; + this._redirects = []; + this._requestBodyLength = 0; + this._requestBodyBuffers = []; + if (responseCallback) { + this.on("response", responseCallback); + } + var self2 = this; + this._onNativeResponse = function(response) { + try { + self2._processResponse(response); + } catch (cause) { + self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause })); + } + }; + this._headerFilter = new RegExp("^(?:" + sensitiveHeaders.concat(options.sensitiveHeaders).map(escapeRegex).join("|") + ")$", "i"); + this._performRequest(); + } + RedirectableRequest.prototype = Object.create(Writable2.prototype); + RedirectableRequest.prototype.abort = function() { + destroyRequest(this._currentRequest); + this._currentRequest.abort(); + this.emit("abort"); + }; + RedirectableRequest.prototype.destroy = function(error) { + destroyRequest(this._currentRequest, error); + destroy.call(this, error); + return this; + }; + RedirectableRequest.prototype.write = function(data, encoding, callback) { + if (this._ending) { + throw new WriteAfterEndError; + } + if (!isString2(data) && !isBuffer2(data)) { + throw new TypeError("data should be a string, Buffer or Uint8Array"); + } + if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (data.length === 0) { + if (callback) { + callback(); + } + return; + } + if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { + this._requestBodyLength += data.length; + this._requestBodyBuffers.push({ data, encoding }); + this._currentRequest.write(data, encoding, callback); + } else { + this.emit("error", new MaxBodyLengthExceededError); + this.abort(); + } + }; + RedirectableRequest.prototype.end = function(data, encoding, callback) { + if (isFunction2(data)) { + callback = data; + data = encoding = null; + } else if (isFunction2(encoding)) { + callback = encoding; + encoding = null; + } + if (!data) { + this._ended = this._ending = true; + this._currentRequest.end(null, null, callback); + } else { + var self2 = this; + var currentRequest = this._currentRequest; + this.write(data, encoding, function() { + self2._ended = true; + currentRequest.end(null, null, callback); + }); + this._ending = true; + } + }; + RedirectableRequest.prototype.setHeader = function(name, value) { + this._options.headers[name] = value; + this._currentRequest.setHeader(name, value); + }; + RedirectableRequest.prototype.removeHeader = function(name) { + delete this._options.headers[name]; + this._currentRequest.removeHeader(name); + }; + RedirectableRequest.prototype.setTimeout = function(msecs, callback) { + var self2 = this; + function destroyOnTimeout(socket) { + socket.setTimeout(msecs); + socket.removeListener("timeout", socket.destroy); + socket.addListener("timeout", socket.destroy); + } + function startTimer(socket) { + if (self2._timeout) { + clearTimeout(self2._timeout); + } + self2._timeout = setTimeout(function() { + self2.emit("timeout"); + clearTimer(); + }, msecs); + destroyOnTimeout(socket); + } + function clearTimer() { + if (self2._timeout) { + clearTimeout(self2._timeout); + self2._timeout = null; + } + self2.removeListener("abort", clearTimer); + self2.removeListener("error", clearTimer); + self2.removeListener("response", clearTimer); + self2.removeListener("close", clearTimer); + if (callback) { + self2.removeListener("timeout", callback); + } + if (!self2.socket) { + self2._currentRequest.removeListener("socket", startTimer); + } + } + if (callback) { + this.on("timeout", callback); + } + if (this.socket) { + startTimer(this.socket); + } else { + this._currentRequest.once("socket", startTimer); + } + this.on("socket", destroyOnTimeout); + this.on("abort", clearTimer); + this.on("error", clearTimer); + this.on("response", clearTimer); + this.on("close", clearTimer); + return this; + }; + [ + "flushHeaders", + "getHeader", + "setNoDelay", + "setSocketKeepAlive" + ].forEach(function(method) { + RedirectableRequest.prototype[method] = function(a2, b2) { + return this._currentRequest[method](a2, b2); + }; + }); + ["aborted", "connection", "socket"].forEach(function(property) { + Object.defineProperty(RedirectableRequest.prototype, property, { + get: function() { + return this._currentRequest[property]; + } + }); + }); + RedirectableRequest.prototype._sanitizeOptions = function(options) { + if (!options.headers) { + options.headers = {}; + } + if (!isArray2(options.sensitiveHeaders)) { + options.sensitiveHeaders = []; + } + if (options.host) { + if (!options.hostname) { + options.hostname = options.host; + } + delete options.host; + } + if (!options.pathname && options.path) { + var searchPos = options.path.indexOf("?"); + if (searchPos < 0) { + options.pathname = options.path; + } else { + options.pathname = options.path.substring(0, searchPos); + options.search = options.path.substring(searchPos); + } + } + }; + RedirectableRequest.prototype._performRequest = function() { + var protocol = this._options.protocol; + var nativeProtocol = this._options.nativeProtocols[protocol]; + if (!nativeProtocol) { + throw new TypeError("Unsupported protocol " + protocol); + } + if (this._options.agents) { + var scheme = protocol.slice(0, -1); + this._options.agent = this._options.agents[scheme]; + } + var request2 = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); + request2._redirectable = this; + for (var event of events) { + request2.on(event, eventHandlers[event]); + } + this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : this._options.path; + if (this._isRedirect) { + var i2 = 0; + var self2 = this; + var buffers = this._requestBodyBuffers; + (function writeNext(error) { + if (request2 === self2._currentRequest) { + if (error) { + self2.emit("error", error); + } else if (i2 < buffers.length) { + var buffer = buffers[i2++]; + if (!request2.finished) { + request2.write(buffer.data, buffer.encoding, writeNext); + } + } else if (self2._ended) { + request2.end(); + } + } + })(); + } + }; + RedirectableRequest.prototype._processResponse = function(response) { + var statusCode = response.statusCode; + if (this._options.trackRedirects) { + this._redirects.push({ + url: this._currentUrl, + headers: response.headers, + statusCode + }); + } + var location = response.headers.location; + if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { + response.responseUrl = this._currentUrl; + response.redirects = this._redirects; + this.emit("response", response); + this._requestBodyBuffers = []; + return; + } + destroyRequest(this._currentRequest); + response.destroy(); + if (++this._redirectCount > this._options.maxRedirects) { + throw new TooManyRedirectsError; + } + var requestHeaders; + var beforeRedirect = this._options.beforeRedirect; + if (beforeRedirect) { + requestHeaders = Object.assign({ + Host: response.req.getHeader("host") + }, this._options.headers); + } + var method = this._options.method; + if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { + this._options.method = "GET"; + this._requestBodyBuffers = []; + removeMatchingHeaders(/^content-/i, this._options.headers); + } + var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); + var currentUrlParts = parseUrl4(this._currentUrl); + var currentHost = currentHostHeader || currentUrlParts.host; + var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost })); + var redirectUrl = resolveUrl(location, currentUrl); + debug("redirecting to", redirectUrl.href); + this._isRedirect = true; + spreadUrlObject(redirectUrl, this._options); + if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { + removeMatchingHeaders(this._headerFilter, this._options.headers); + } + if (isFunction2(beforeRedirect)) { + var responseDetails = { + headers: response.headers, + statusCode + }; + var requestDetails = { + url: currentUrl, + method, + headers: requestHeaders + }; + beforeRedirect(this._options, responseDetails, requestDetails); + this._sanitizeOptions(this._options); + } + this._performRequest(); + }; + function wrap(protocols) { + var exports2 = { + maxRedirects: 21, + maxBodyLength: 10 * 1024 * 1024 + }; + var nativeProtocols = {}; + Object.keys(protocols).forEach(function(scheme) { + var protocol = scheme + ":"; + var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; + var wrappedProtocol = exports2[scheme] = Object.create(nativeProtocol); + function request2(input, options, callback) { + if (isURL(input)) { + input = spreadUrlObject(input); + } else if (isString2(input)) { + input = spreadUrlObject(parseUrl4(input)); + } else { + callback = options; + options = validateUrl(input); + input = { protocol }; + } + if (isFunction2(options)) { + callback = options; + options = null; + } + options = Object.assign({ + maxRedirects: exports2.maxRedirects, + maxBodyLength: exports2.maxBodyLength + }, input, options); + options.nativeProtocols = nativeProtocols; + if (!isString2(options.host) && !isString2(options.hostname)) { + options.hostname = "::1"; + } + assert.equal(options.protocol, protocol, "protocol mismatch"); + debug("options", options); + return new RedirectableRequest(options, callback); + } + function get(input, options, callback) { + var wrappedRequest = wrappedProtocol.request(input, options, callback); + wrappedRequest.end(); + return wrappedRequest; + } + Object.defineProperties(wrappedProtocol, { + request: { value: request2, configurable: true, enumerable: true, writable: true }, + get: { value: get, configurable: true, enumerable: true, writable: true } + }); + }); + return exports2; + } + function noop2() {} + function parseUrl4(input) { + var parsed; + if (useNativeURL) { + parsed = new URL2(input); + } else { + parsed = validateUrl(url2.parse(input)); + if (!isString2(parsed.protocol)) { + throw new InvalidUrlError({ input }); + } + } + return parsed; + } + function resolveUrl(relative, base) { + return useNativeURL ? new URL2(relative, base) : parseUrl4(url2.resolve(base, relative)); + } + function validateUrl(input) { + if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { + throw new InvalidUrlError({ input: input.href || input }); + } + if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { + throw new InvalidUrlError({ input: input.href || input }); + } + return input; + } + function spreadUrlObject(urlObject, target2) { + var spread = target2 || {}; + for (var key of preservedUrlFields) { + spread[key] = urlObject[key]; + } + if (spread.hostname.startsWith("[")) { + spread.hostname = spread.hostname.slice(1, -1); + } + if (spread.port !== "") { + spread.port = Number(spread.port); + } + spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; + return spread; + } + function removeMatchingHeaders(regex, headers) { + var lastValue; + for (var header in headers) { + if (regex.test(header)) { + lastValue = headers[header]; + delete headers[header]; + } + } + return lastValue === null || typeof lastValue === "undefined" ? undefined : String(lastValue).trim(); + } + function createErrorType(code, message, baseClass) { + function CustomError(properties) { + if (isFunction2(Error.captureStackTrace)) { + Error.captureStackTrace(this, this.constructor); + } + Object.assign(this, properties || {}); + this.code = code; + this.message = this.cause ? message + ": " + this.cause.message : message; + } + CustomError.prototype = new (baseClass || Error); + Object.defineProperties(CustomError.prototype, { + constructor: { + value: CustomError, + enumerable: false + }, + name: { + value: "Error [" + code + "]", + enumerable: false + } + }); + return CustomError; + } + function destroyRequest(request2, error) { + for (var event of events) { + request2.removeListener(event, eventHandlers[event]); + } + request2.on("error", noop2); + request2.destroy(error); + } + function isSubdomain(subdomain, domain) { + assert(isString2(subdomain) && isString2(domain)); + var dot = subdomain.length - domain.length - 1; + return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); + } + function isArray2(value) { + return value instanceof Array; + } + function isString2(value) { + return typeof value === "string" || value instanceof String; + } + function isFunction2(value) { + return typeof value === "function"; + } + function isBuffer2(value) { + return typeof value === "object" && "length" in value; + } + function isURL(value) { + return URL2 && value instanceof URL2; + } + function escapeRegex(regex) { + return regex.replace(/[\]\\/()*+?.$]/g, "\\$&"); + } + module.exports = wrap({ http, https }); + module.exports.wrap = wrap; +}); + +// node_modules/.pnpm/cookie-signature@1.0.6/node_modules/cookie-signature/index.js +var require_cookie_signature2 = __commonJS((exports) => { + var crypto4 = __require("crypto"); + exports.sign = function(val, secret) { + if (typeof val != "string") + throw new TypeError("Cookie value must be provided as a string."); + if (typeof secret != "string") + throw new TypeError("Secret string must be provided."); + return val + "." + crypto4.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, ""); + }; + exports.unsign = function(val, secret) { + if (typeof val != "string") + throw new TypeError("Signed cookie string must be provided."); + if (typeof secret != "string") + throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf(".")), mac = exports.sign(str, secret); + return sha1(mac) == sha1(val) ? str : false; + }; + function sha1(str) { + return crypto4.createHash("sha1").update(str).digest("hex"); + } +}); + +// node_modules/.pnpm/cookie-parser@1.4.7/node_modules/cookie-parser/index.js +var require_cookie_parser = __commonJS((exports, module) => { + /*! + * cookie-parser + * Copyright(c) 2014 TJ Holowaychuk + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + var cookie = require_cookie(); + var signature = require_cookie_signature2(); + module.exports = cookieParser; + module.exports.JSONCookie = JSONCookie; + module.exports.JSONCookies = JSONCookies; + module.exports.signedCookie = signedCookie; + module.exports.signedCookies = signedCookies; + function cookieParser(secret, options) { + var secrets = !secret || Array.isArray(secret) ? secret || [] : [secret]; + return function cookieParser2(req, res, next) { + if (req.cookies) { + return next(); + } + var cookies = req.headers.cookie; + req.secret = secrets[0]; + req.cookies = Object.create(null); + req.signedCookies = Object.create(null); + if (!cookies) { + return next(); + } + req.cookies = cookie.parse(cookies, options); + if (secrets.length !== 0) { + req.signedCookies = signedCookies(req.cookies, secrets); + req.signedCookies = JSONCookies(req.signedCookies); + } + req.cookies = JSONCookies(req.cookies); + next(); + }; + } + function JSONCookie(str) { + if (typeof str !== "string" || str.substr(0, 2) !== "j:") { + return; + } + try { + return JSON.parse(str.slice(2)); + } catch (err) { + return; + } + } + function JSONCookies(obj) { + var cookies = Object.keys(obj); + var key; + var val; + for (var i2 = 0;i2 < cookies.length; i2++) { + key = cookies[i2]; + val = JSONCookie(obj[key]); + if (val) { + obj[key] = val; + } + } + return obj; + } + function signedCookie(str, secret) { + if (typeof str !== "string") { + return; + } + if (str.substr(0, 2) !== "s:") { + return str; + } + var secrets = !secret || Array.isArray(secret) ? secret || [] : [secret]; + for (var i2 = 0;i2 < secrets.length; i2++) { + var val = signature.unsign(str.slice(2), secrets[i2]); + if (val !== false) { + return val; + } + } + return false; + } + function signedCookies(obj, secret) { + var cookies = Object.keys(obj); + var dec; + var key; + var ret = Object.create(null); + var val; + for (var i2 = 0;i2 < cookies.length; i2++) { + key = cookies[i2]; + val = obj[key]; + dec = signedCookie(val, secret); + if (val !== dec) { + ret[key] = dec; + delete obj[key]; + } + } + return ret; + } +}); + +// src/index.ts +var import_express8 = __toESM(require_express(), 1); + +// src/loaders/express.ts +var import_cors = __toESM(require_lib3(), 1); +var import_express6 = __toESM(require_express(), 1); + +// src/api/auth/auth-route.ts +var import_express = __toESM(require_express(), 1); + +// node_modules/.pnpm/yup@1.7.1/node_modules/yup/index.esm.js +var import_property_expr = __toESM(require_property_expr(), 1); +var import_tiny_case = __toESM(require_tiny_case(), 1); +var import_toposort = __toESM(require_toposort(), 1); +var toString = Object.prototype.toString; +var errorToString = Error.prototype.toString; +var regExpToString = RegExp.prototype.toString; +var symbolToString = typeof Symbol !== "undefined" ? Symbol.prototype.toString : () => ""; +var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; +function printNumber(val) { + if (val != +val) + return "NaN"; + const isNegativeZero = val === 0 && 1 / val < 0; + return isNegativeZero ? "-0" : "" + val; +} +function printSimpleValue(val, quoteStrings = false) { + if (val == null || val === true || val === false) + return "" + val; + const typeOf = typeof val; + if (typeOf === "number") + return printNumber(val); + if (typeOf === "string") + return quoteStrings ? `"${val}"` : val; + if (typeOf === "function") + return "[Function " + (val.name || "anonymous") + "]"; + if (typeOf === "symbol") + return symbolToString.call(val).replace(SYMBOL_REGEXP, "Symbol($1)"); + const tag = toString.call(val).slice(8, -1); + if (tag === "Date") + return isNaN(val.getTime()) ? "" + val : val.toISOString(val); + if (tag === "Error" || val instanceof Error) + return "[" + errorToString.call(val) + "]"; + if (tag === "RegExp") + return regExpToString.call(val); + return null; +} +function printValue(value, quoteStrings) { + let result = printSimpleValue(value, quoteStrings); + if (result !== null) + return result; + return JSON.stringify(value, function(key, value2) { + let result2 = printSimpleValue(this[key], quoteStrings); + if (result2 !== null) + return result2; + return value2; + }, 2); +} +function toArray(value) { + return value == null ? [] : [].concat(value); +} +var _Symbol$toStringTag; +var _Symbol$hasInstance; +var _Symbol$toStringTag2; +var strReg = /\$\{\s*(\w+)\s*\}/g; +_Symbol$toStringTag = Symbol.toStringTag; + +class ValidationErrorNoStack { + constructor(errorOrErrors, value, field, type) { + this.name = undefined; + this.message = undefined; + this.value = undefined; + this.path = undefined; + this.type = undefined; + this.params = undefined; + this.errors = undefined; + this.inner = undefined; + this[_Symbol$toStringTag] = "Error"; + this.name = "ValidationError"; + this.value = value; + this.path = field; + this.type = type; + this.errors = []; + this.inner = []; + toArray(errorOrErrors).forEach((err) => { + if (ValidationError.isError(err)) { + this.errors.push(...err.errors); + const innerErrors = err.inner.length ? err.inner : [err]; + this.inner.push(...innerErrors); + } else { + this.errors.push(err); + } + }); + this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0]; + } +} +_Symbol$hasInstance = Symbol.hasInstance; +_Symbol$toStringTag2 = Symbol.toStringTag; + +class ValidationError extends Error { + static formatError(message, params) { + const path = params.label || params.path || "this"; + params = Object.assign({}, params, { + path, + originalPath: params.path + }); + if (typeof message === "string") + return message.replace(strReg, (_, key) => printValue(params[key])); + if (typeof message === "function") + return message(params); + return message; + } + static isError(err) { + return err && err.name === "ValidationError"; + } + constructor(errorOrErrors, value, field, type, disableStack) { + const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type); + if (disableStack) { + return errorNoStack; + } + super(); + this.value = undefined; + this.path = undefined; + this.type = undefined; + this.params = undefined; + this.errors = []; + this.inner = []; + this[_Symbol$toStringTag2] = "Error"; + this.name = errorNoStack.name; + this.message = errorNoStack.message; + this.type = errorNoStack.type; + this.value = errorNoStack.value; + this.path = errorNoStack.path; + this.errors = errorNoStack.errors; + this.inner = errorNoStack.inner; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, ValidationError); + } + } + static [_Symbol$hasInstance](inst) { + return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst); + } +} +var mixed = { + default: "${path} is invalid", + required: "${path} is a required field", + defined: "${path} must be defined", + notNull: "${path} cannot be null", + oneOf: "${path} must be one of the following values: ${values}", + notOneOf: "${path} must not be one of the following values: ${values}", + notType: ({ + path, + type, + value, + originalValue + }) => { + const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : "."; + return type !== "mixed" ? `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \`${printValue(value, true)}\`` + castMsg; + } +}; +var string = { + length: "${path} must be exactly ${length} characters", + min: "${path} must be at least ${min} characters", + max: "${path} must be at most ${max} characters", + matches: '${path} must match the following: "${regex}"', + email: "${path} must be a valid email", + url: "${path} must be a valid URL", + uuid: "${path} must be a valid UUID", + datetime: "${path} must be a valid ISO date-time", + datetime_precision: "${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits", + datetime_offset: '${path} must be a valid ISO date-time with UTC "Z" timezone', + trim: "${path} must be a trimmed string", + lowercase: "${path} must be a lowercase string", + uppercase: "${path} must be a upper case string" +}; +var number = { + min: "${path} must be greater than or equal to ${min}", + max: "${path} must be less than or equal to ${max}", + lessThan: "${path} must be less than ${less}", + moreThan: "${path} must be greater than ${more}", + positive: "${path} must be a positive number", + negative: "${path} must be a negative number", + integer: "${path} must be an integer" +}; +var date = { + min: "${path} field must be later than ${min}", + max: "${path} field must be at earlier than ${max}" +}; +var boolean = { + isValue: "${path} field must be ${value}" +}; +var object = { + noUnknown: "${path} field has unspecified keys: ${unknown}", + exact: "${path} object contains unknown properties: ${properties}" +}; +var array = { + min: "${path} field must have at least ${min} items", + max: "${path} field must have less than or equal to ${max} items", + length: "${path} must have ${length} items" +}; +var tuple = { + notType: (params) => { + const { + path, + value, + spec + } = params; + const typeLen = spec.types.length; + if (Array.isArray(value)) { + if (value.length < typeLen) + return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``; + if (value.length > typeLen) + return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``; + } + return ValidationError.formatError(mixed.notType, params); + } +}; +var locale = Object.assign(Object.create(null), { + mixed, + string, + number, + date, + object, + array, + boolean, + tuple +}); +var isSchema = (obj) => obj && obj.__isYupSchema__; + +class Condition { + static fromOptions(refs, config) { + if (!config.then && !config.otherwise) + throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions"); + let { + is, + then, + otherwise + } = config; + let check = typeof is === "function" ? is : (...values) => values.every((value) => value === is); + return new Condition(refs, (values, schema) => { + var _branch; + let branch = check(...values) ? then : otherwise; + return (_branch = branch == null ? undefined : branch(schema)) != null ? _branch : schema; + }); + } + constructor(refs, builder) { + this.fn = undefined; + this.refs = refs; + this.refs = refs; + this.fn = builder; + } + resolve(base, options) { + let values = this.refs.map((ref) => ref.getValue(options == null ? undefined : options.value, options == null ? undefined : options.parent, options == null ? undefined : options.context)); + let schema = this.fn(values, base, options); + if (schema === undefined || schema === base) { + return base; + } + if (!isSchema(schema)) + throw new TypeError("conditions must return a schema object"); + return schema.resolve(options); + } +} +var prefixes = { + context: "$", + value: "." +}; +class Reference { + constructor(key, options = {}) { + this.key = undefined; + this.isContext = undefined; + this.isValue = undefined; + this.isSibling = undefined; + this.path = undefined; + this.getter = undefined; + this.map = undefined; + if (typeof key !== "string") + throw new TypeError("ref must be a string, got: " + key); + this.key = key.trim(); + if (key === "") + throw new TypeError("ref must be a non-empty string"); + this.isContext = this.key[0] === prefixes.context; + this.isValue = this.key[0] === prefixes.value; + this.isSibling = !this.isContext && !this.isValue; + let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : ""; + this.path = this.key.slice(prefix.length); + this.getter = this.path && import_property_expr.getter(this.path, true); + this.map = options.map; + } + getValue(value, parent, context) { + let result = this.isContext ? context : this.isValue ? value : parent; + if (this.getter) + result = this.getter(result || {}); + if (this.map) + result = this.map(result); + return result; + } + cast(value, options) { + return this.getValue(value, options == null ? undefined : options.parent, options == null ? undefined : options.context); + } + resolve() { + return this; + } + describe() { + return { + type: "ref", + key: this.key + }; + } + toString() { + return `Ref(${this.key})`; + } + static isRef(value) { + return value && value.__isYupRef; + } +} +Reference.prototype.__isYupRef = true; +var isAbsent = (value) => value == null; +function createValidation(config) { + function validate({ + value, + path = "", + options, + originalValue, + schema + }, panic, next) { + const { + name, + test, + params, + message, + skipAbsent + } = config; + let { + parent, + context, + abortEarly = schema.spec.abortEarly, + disableStackTrace = schema.spec.disableStackTrace + } = options; + const resolveOptions = { + value, + parent, + context + }; + function createError(overrides = {}) { + const nextParams = resolveParams(Object.assign({ + value, + originalValue, + label: schema.spec.label, + path: overrides.path || path, + spec: schema.spec, + disableStackTrace: overrides.disableStackTrace || disableStackTrace + }, params, overrides.params), resolveOptions); + const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace); + error.params = nextParams; + return error; + } + const invalid = abortEarly ? panic : next; + let ctx = { + path, + parent, + type: name, + from: options.from, + createError, + resolve(item) { + return resolveMaybeRef(item, resolveOptions); + }, + options, + originalValue, + schema + }; + const handleResult = (validOrError) => { + if (ValidationError.isError(validOrError)) + invalid(validOrError); + else if (!validOrError) + invalid(createError()); + else + next(null); + }; + const handleError = (err) => { + if (ValidationError.isError(err)) + invalid(err); + else + panic(err); + }; + const shouldSkip = skipAbsent && isAbsent(value); + if (shouldSkip) { + return handleResult(true); + } + let result; + try { + var _result; + result = test.call(ctx, value, ctx); + if (typeof ((_result = result) == null ? undefined : _result.then) === "function") { + if (options.sync) { + throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`); + } + return Promise.resolve(result).then(handleResult, handleError); + } + } catch (err) { + handleError(err); + return; + } + handleResult(result); + } + validate.OPTIONS = config; + return validate; +} +function resolveParams(params, options) { + if (!params) + return params; + for (const key of Object.keys(params)) { + params[key] = resolveMaybeRef(params[key], options); + } + return params; +} +function resolveMaybeRef(item, options) { + return Reference.isRef(item) ? item.getValue(options.value, options.parent, options.context) : item; +} +function getIn(schema, path, value, context = value) { + let parent, lastPart, lastPartDebug; + if (!path) + return { + parent, + parentPath: path, + schema + }; + import_property_expr.forEach(path, (_part, isBracket, isArray) => { + let part = isBracket ? _part.slice(1, _part.length - 1) : _part; + schema = schema.resolve({ + context, + parent, + value + }); + let isTuple = schema.type === "tuple"; + let idx = isArray ? parseInt(part, 10) : 0; + if (schema.innerType || isTuple) { + if (isTuple && !isArray) + throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`); + if (value && idx >= value.length) { + throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `); + } + parent = value; + value = value && value[idx]; + schema = isTuple ? schema.spec.types[idx] : schema.innerType; + } + if (!isArray) { + if (!schema.fields || !schema.fields[part]) + throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: "${schema.type}")`); + parent = value; + value = value && value[part]; + schema = schema.fields[part]; + } + lastPart = part; + lastPartDebug = isBracket ? "[" + _part + "]" : "." + _part; + }); + return { + schema, + parent, + parentPath: lastPart + }; +} +class ReferenceSet extends Set { + describe() { + const description = []; + for (const item of this.values()) { + description.push(Reference.isRef(item) ? item.describe() : item); + } + return description; + } + resolveAll(resolve) { + let result = []; + for (const item of this.values()) { + result.push(resolve(item)); + } + return result; + } + clone() { + return new ReferenceSet(this.values()); + } + merge(newItems, removeItems) { + const next = this.clone(); + newItems.forEach((value) => next.add(value)); + removeItems.forEach((value) => next.delete(value)); + return next; + } +} +function clone(src, seen = new Map) { + if (isSchema(src) || !src || typeof src !== "object") + return src; + if (seen.has(src)) + return seen.get(src); + let copy; + if (src instanceof Date) { + copy = new Date(src.getTime()); + seen.set(src, copy); + } else if (src instanceof RegExp) { + copy = new RegExp(src); + seen.set(src, copy); + } else if (Array.isArray(src)) { + copy = new Array(src.length); + seen.set(src, copy); + for (let i = 0;i < src.length; i++) + copy[i] = clone(src[i], seen); + } else if (src instanceof Map) { + copy = new Map; + seen.set(src, copy); + for (const [k, v] of src.entries()) + copy.set(k, clone(v, seen)); + } else if (src instanceof Set) { + copy = new Set; + seen.set(src, copy); + for (const v of src) + copy.add(clone(v, seen)); + } else if (src instanceof Object) { + copy = {}; + seen.set(src, copy); + for (const [k, v] of Object.entries(src)) + copy[k] = clone(v, seen); + } else { + throw Error(`Unable to clone ${src}`); + } + return copy; +} +function createStandardPath(path) { + if (!(path != null && path.length)) { + return; + } + const segments = []; + let currentSegment = ""; + let inBrackets = false; + let inQuotes = false; + for (let i = 0;i < path.length; i++) { + const char = path[i]; + if (char === "[" && !inQuotes) { + if (currentSegment) { + segments.push(...currentSegment.split(".").filter(Boolean)); + currentSegment = ""; + } + inBrackets = true; + continue; + } + if (char === "]" && !inQuotes) { + if (currentSegment) { + if (/^\d+$/.test(currentSegment)) { + segments.push(currentSegment); + } else { + segments.push(currentSegment.replace(/^"|"$/g, "")); + } + currentSegment = ""; + } + inBrackets = false; + continue; + } + if (char === '"') { + inQuotes = !inQuotes; + continue; + } + if (char === "." && !inBrackets && !inQuotes) { + if (currentSegment) { + segments.push(currentSegment); + currentSegment = ""; + } + continue; + } + currentSegment += char; + } + if (currentSegment) { + segments.push(...currentSegment.split(".").filter(Boolean)); + } + return segments; +} +function createStandardIssues(error, parentPath) { + const path = parentPath ? `${parentPath}.${error.path}` : error.path; + return error.errors.map((err) => ({ + message: err, + path: createStandardPath(path) + })); +} +function issuesFromValidationError(error, parentPath) { + var _error$inner; + if (!((_error$inner = error.inner) != null && _error$inner.length) && error.errors.length) { + return createStandardIssues(error, parentPath); + } + const path = parentPath ? `${parentPath}.${error.path}` : error.path; + return error.inner.flatMap((err) => issuesFromValidationError(err, path)); +} + +class Schema { + constructor(options) { + this.type = undefined; + this.deps = []; + this.tests = undefined; + this.transforms = undefined; + this.conditions = []; + this._mutate = undefined; + this.internalTests = {}; + this._whitelist = new ReferenceSet; + this._blacklist = new ReferenceSet; + this.exclusiveTests = Object.create(null); + this._typeCheck = undefined; + this.spec = undefined; + this.tests = []; + this.transforms = []; + this.withMutation(() => { + this.typeError(mixed.notType); + }); + this.type = options.type; + this._typeCheck = options.check; + this.spec = Object.assign({ + strip: false, + strict: false, + abortEarly: true, + recursive: true, + disableStackTrace: false, + nullable: false, + optional: true, + coerce: true + }, options == null ? undefined : options.spec); + this.withMutation((s) => { + s.nonNullable(); + }); + } + get _type() { + return this.type; + } + clone(spec) { + if (this._mutate) { + if (spec) + Object.assign(this.spec, spec); + return this; + } + const next = Object.create(Object.getPrototypeOf(this)); + next.type = this.type; + next._typeCheck = this._typeCheck; + next._whitelist = this._whitelist.clone(); + next._blacklist = this._blacklist.clone(); + next.internalTests = Object.assign({}, this.internalTests); + next.exclusiveTests = Object.assign({}, this.exclusiveTests); + next.deps = [...this.deps]; + next.conditions = [...this.conditions]; + next.tests = [...this.tests]; + next.transforms = [...this.transforms]; + next.spec = clone(Object.assign({}, this.spec, spec)); + return next; + } + label(label) { + let next = this.clone(); + next.spec.label = label; + return next; + } + meta(...args) { + if (args.length === 0) + return this.spec.meta; + let next = this.clone(); + next.spec.meta = Object.assign(next.spec.meta || {}, args[0]); + return next; + } + withMutation(fn) { + let before = this._mutate; + this._mutate = true; + let result = fn(this); + this._mutate = before; + return result; + } + concat(schema) { + if (!schema || schema === this) + return this; + if (schema.type !== this.type && this.type !== "mixed") + throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`); + let base = this; + let combined = schema.clone(); + const mergedSpec = Object.assign({}, base.spec, combined.spec); + combined.spec = mergedSpec; + combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests); + combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist); + combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist); + combined.tests = base.tests; + combined.exclusiveTests = base.exclusiveTests; + combined.withMutation((next) => { + schema.tests.forEach((fn) => { + next.test(fn.OPTIONS); + }); + }); + combined.transforms = [...base.transforms, ...combined.transforms]; + return combined; + } + isType(v) { + if (v == null) { + if (this.spec.nullable && v === null) + return true; + if (this.spec.optional && v === undefined) + return true; + return false; + } + return this._typeCheck(v); + } + resolve(options) { + let schema = this; + if (schema.conditions.length) { + let conditions = schema.conditions; + schema = schema.clone(); + schema.conditions = []; + schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema); + schema = schema.resolve(options); + } + return schema; + } + resolveOptions(options) { + var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack; + return Object.assign({}, options, { + from: options.from || [], + strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict, + abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly, + recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive, + disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace + }); + } + cast(value, options = {}) { + let resolvedSchema = this.resolve(Object.assign({}, options, { + value + })); + let allowOptionality = options.assert === "ignore-optionality"; + let result = resolvedSchema._cast(value, options); + if (options.assert !== false && !resolvedSchema.isType(result)) { + if (allowOptionality && isAbsent(result)) { + return result; + } + let formattedValue = printValue(value); + let formattedResult = printValue(result); + throw new TypeError(`The value of ${options.path || "field"} could not be cast to a value ` + `that satisfies the schema type: "${resolvedSchema.type}". + +` + `attempted value: ${formattedValue} +` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : "")); + } + return result; + } + _cast(rawValue, options) { + let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this, options), rawValue); + if (value === undefined) { + value = this.getDefault(options); + } + return value; + } + _validate(_value, options = {}, panic, next) { + let { + path, + originalValue = _value, + strict = this.spec.strict + } = options; + let value = _value; + if (!strict) { + value = this._cast(value, Object.assign({ + assert: false + }, options)); + } + let initialTests = []; + for (let test of Object.values(this.internalTests)) { + if (test) + initialTests.push(test); + } + this.runTests({ + path, + value, + originalValue, + options, + tests: initialTests + }, panic, (initialErrors) => { + if (initialErrors.length) { + return next(initialErrors, value); + } + this.runTests({ + path, + value, + originalValue, + options, + tests: this.tests + }, panic, next); + }); + } + runTests(runOptions, panic, next) { + let fired = false; + let { + tests, + value, + originalValue, + path, + options + } = runOptions; + let panicOnce = (arg) => { + if (fired) + return; + fired = true; + panic(arg, value); + }; + let nextOnce = (arg) => { + if (fired) + return; + fired = true; + next(arg, value); + }; + let count = tests.length; + let nestedErrors = []; + if (!count) + return nextOnce([]); + let args = { + value, + originalValue, + path, + options, + schema: this + }; + for (let i = 0;i < tests.length; i++) { + const test = tests[i]; + test(args, panicOnce, function finishTestRun(err) { + if (err) { + Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err); + } + if (--count <= 0) { + nextOnce(nestedErrors); + } + }); + } + } + asNestedTest({ + key, + index, + parent, + parentPath, + originalParent, + options + }) { + const k = key != null ? key : index; + if (k == null) { + throw TypeError("Must include `key` or `index` for nested validations"); + } + const isIndex = typeof k === "number"; + let value = parent[k]; + const testOptions = Object.assign({}, options, { + strict: true, + parent, + value, + originalValue: originalParent[k], + key: undefined, + [isIndex ? "index" : "key"]: k, + path: isIndex || k.includes(".") ? `${parentPath || ""}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : "") + key + }); + return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next); + } + validate(value, options) { + var _options$disableStack2; + let schema = this.resolve(Object.assign({}, options, { + value + })); + let disableStackTrace = (_options$disableStack2 = options == null ? undefined : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace; + return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => { + if (ValidationError.isError(error)) + error.value = parsed; + reject(error); + }, (errors, validated) => { + if (errors.length) + reject(new ValidationError(errors, validated, undefined, undefined, disableStackTrace)); + else + resolve(validated); + })); + } + validateSync(value, options) { + var _options$disableStack3; + let schema = this.resolve(Object.assign({}, options, { + value + })); + let result; + let disableStackTrace = (_options$disableStack3 = options == null ? undefined : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace; + schema._validate(value, Object.assign({}, options, { + sync: true + }), (error, parsed) => { + if (ValidationError.isError(error)) + error.value = parsed; + throw error; + }, (errors, validated) => { + if (errors.length) + throw new ValidationError(errors, value, undefined, undefined, disableStackTrace); + result = validated; + }); + return result; + } + isValid(value, options) { + return this.validate(value, options).then(() => true, (err) => { + if (ValidationError.isError(err)) + return false; + throw err; + }); + } + isValidSync(value, options) { + try { + this.validateSync(value, options); + return true; + } catch (err) { + if (ValidationError.isError(err)) + return false; + throw err; + } + } + _getDefault(options) { + let defaultValue = this.spec.default; + if (defaultValue == null) { + return defaultValue; + } + return typeof defaultValue === "function" ? defaultValue.call(this, options) : clone(defaultValue); + } + getDefault(options) { + let schema = this.resolve(options || {}); + return schema._getDefault(options); + } + default(def) { + if (arguments.length === 0) { + return this._getDefault(); + } + let next = this.clone({ + default: def + }); + return next; + } + strict(isStrict = true) { + return this.clone({ + strict: isStrict + }); + } + nullability(nullable, message) { + const next = this.clone({ + nullable + }); + next.internalTests.nullable = createValidation({ + message, + name: "nullable", + test(value) { + return value === null ? this.schema.spec.nullable : true; + } + }); + return next; + } + optionality(optional, message) { + const next = this.clone({ + optional + }); + next.internalTests.optionality = createValidation({ + message, + name: "optionality", + test(value) { + return value === undefined ? this.schema.spec.optional : true; + } + }); + return next; + } + optional() { + return this.optionality(true); + } + defined(message = mixed.defined) { + return this.optionality(false, message); + } + nullable() { + return this.nullability(true); + } + nonNullable(message = mixed.notNull) { + return this.nullability(false, message); + } + required(message = mixed.required) { + return this.clone().withMutation((next) => next.nonNullable(message).defined(message)); + } + notRequired() { + return this.clone().withMutation((next) => next.nullable().optional()); + } + transform(fn) { + let next = this.clone(); + next.transforms.push(fn); + return next; + } + test(...args) { + let opts; + if (args.length === 1) { + if (typeof args[0] === "function") { + opts = { + test: args[0] + }; + } else { + opts = args[0]; + } + } else if (args.length === 2) { + opts = { + name: args[0], + test: args[1] + }; + } else { + opts = { + name: args[0], + message: args[1], + test: args[2] + }; + } + if (opts.message === undefined) + opts.message = mixed.default; + if (typeof opts.test !== "function") + throw new TypeError("`test` is a required parameters"); + let next = this.clone(); + let validate = createValidation(opts); + let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true; + if (opts.exclusive) { + if (!opts.name) + throw new TypeError("Exclusive tests must provide a unique `name` identifying the test"); + } + if (opts.name) + next.exclusiveTests[opts.name] = !!opts.exclusive; + next.tests = next.tests.filter((fn) => { + if (fn.OPTIONS.name === opts.name) { + if (isExclusive) + return false; + if (fn.OPTIONS.test === validate.OPTIONS.test) + return false; + } + return true; + }); + next.tests.push(validate); + return next; + } + when(keys, options) { + if (!Array.isArray(keys) && typeof keys !== "string") { + options = keys; + keys = "."; + } + let next = this.clone(); + let deps = toArray(keys).map((key) => new Reference(key)); + deps.forEach((dep) => { + if (dep.isSibling) + next.deps.push(dep.key); + }); + next.conditions.push(typeof options === "function" ? new Condition(deps, options) : Condition.fromOptions(deps, options)); + return next; + } + typeError(message) { + let next = this.clone(); + next.internalTests.typeError = createValidation({ + message, + name: "typeError", + skipAbsent: true, + test(value) { + if (!this.schema._typeCheck(value)) + return this.createError({ + params: { + type: this.schema.type + } + }); + return true; + } + }); + return next; + } + oneOf(enums, message = mixed.oneOf) { + let next = this.clone(); + enums.forEach((val) => { + next._whitelist.add(val); + next._blacklist.delete(val); + }); + next.internalTests.whiteList = createValidation({ + message, + name: "oneOf", + skipAbsent: true, + test(value) { + let valids = this.schema._whitelist; + let resolved = valids.resolveAll(this.resolve); + return resolved.includes(value) ? true : this.createError({ + params: { + values: Array.from(valids).join(", "), + resolved + } + }); + } + }); + return next; + } + notOneOf(enums, message = mixed.notOneOf) { + let next = this.clone(); + enums.forEach((val) => { + next._blacklist.add(val); + next._whitelist.delete(val); + }); + next.internalTests.blacklist = createValidation({ + message, + name: "notOneOf", + test(value) { + let invalids = this.schema._blacklist; + let resolved = invalids.resolveAll(this.resolve); + if (resolved.includes(value)) + return this.createError({ + params: { + values: Array.from(invalids).join(", "), + resolved + } + }); + return true; + } + }); + return next; + } + strip(strip = true) { + let next = this.clone(); + next.spec.strip = strip; + return next; + } + describe(options) { + const next = (options ? this.resolve(options) : this).clone(); + const { + label, + meta, + optional, + nullable + } = next.spec; + const description = { + meta, + label, + optional, + nullable, + default: next.getDefault(options), + type: next.type, + oneOf: next._whitelist.describe(), + notOneOf: next._blacklist.describe(), + tests: next.tests.filter((n, idx, list) => list.findIndex((c) => c.OPTIONS.name === n.OPTIONS.name) === idx).map((fn) => { + const params = fn.OPTIONS.params && options ? resolveParams(Object.assign({}, fn.OPTIONS.params), options) : fn.OPTIONS.params; + return { + name: fn.OPTIONS.name, + params + }; + }) + }; + return description; + } + get ["~standard"]() { + const schema = this; + const standard = { + version: 1, + vendor: "yup", + async validate(value) { + try { + const result = await schema.validate(value, { + abortEarly: false + }); + return { + value: result + }; + } catch (err) { + if (err instanceof ValidationError) { + return { + issues: issuesFromValidationError(err) + }; + } + throw err; + } + } + }; + return standard; + } +} +Schema.prototype.__isYupSchema__ = true; +for (const method of ["validate", "validateSync"]) + Schema.prototype[`${method}At`] = function(path, value, options = {}) { + const { + parent, + parentPath, + schema + } = getIn(this, path, value, options.context); + return schema[method](parent && parent[parentPath], Object.assign({}, options, { + parent, + path + })); + }; +for (const alias of ["equals", "is"]) + Schema.prototype[alias] = Schema.prototype.oneOf; +for (const alias of ["not", "nope"]) + Schema.prototype[alias] = Schema.prototype.notOneOf; +var returnsTrue = () => true; +function create$8(spec) { + return new MixedSchema(spec); +} + +class MixedSchema extends Schema { + constructor(spec) { + super(typeof spec === "function" ? { + type: "mixed", + check: spec + } : Object.assign({ + type: "mixed", + check: returnsTrue + }, spec)); + } +} +create$8.prototype = MixedSchema.prototype; +function create$7() { + return new BooleanSchema; +} + +class BooleanSchema extends Schema { + constructor() { + super({ + type: "boolean", + check(v) { + if (v instanceof Boolean) + v = v.valueOf(); + return typeof v === "boolean"; + } + }); + this.withMutation(() => { + this.transform((value, _raw) => { + if (this.spec.coerce && !this.isType(value)) { + if (/^(true|1)$/i.test(String(value))) + return true; + if (/^(false|0)$/i.test(String(value))) + return false; + } + return value; + }); + }); + } + isTrue(message = boolean.isValue) { + return this.test({ + message, + name: "is-value", + exclusive: true, + params: { + value: "true" + }, + test(value) { + return isAbsent(value) || value === true; + } + }); + } + isFalse(message = boolean.isValue) { + return this.test({ + message, + name: "is-value", + exclusive: true, + params: { + value: "false" + }, + test(value) { + return isAbsent(value) || value === false; + } + }); + } + default(def) { + return super.default(def); + } + defined(msg) { + return super.defined(msg); + } + optional() { + return super.optional(); + } + required(msg) { + return super.required(msg); + } + notRequired() { + return super.notRequired(); + } + nullable() { + return super.nullable(); + } + nonNullable(msg) { + return super.nonNullable(msg); + } + strip(v) { + return super.strip(v); + } +} +create$7.prototype = BooleanSchema.prototype; +var isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/; +function parseIsoDate(date2) { + const struct = parseDateStruct(date2); + if (!struct) + return Date.parse ? Date.parse(date2) : Number.NaN; + if (struct.z === undefined && struct.plusMinus === undefined) { + return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf(); + } + let totalMinutesOffset = 0; + if (struct.z !== "Z" && struct.plusMinus !== undefined) { + totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset; + if (struct.plusMinus === "+") + totalMinutesOffset = 0 - totalMinutesOffset; + } + return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond); +} +function parseDateStruct(date2) { + var _regexResult$7$length, _regexResult$; + const regexResult = isoReg.exec(date2); + if (!regexResult) + return null; + return { + year: toNumber(regexResult[1]), + month: toNumber(regexResult[2], 1) - 1, + day: toNumber(regexResult[3], 1), + hour: toNumber(regexResult[4]), + minute: toNumber(regexResult[5]), + second: toNumber(regexResult[6]), + millisecond: regexResult[7] ? toNumber(regexResult[7].substring(0, 3)) : 0, + precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? undefined : _regexResult$.length) != null ? _regexResult$7$length : undefined, + z: regexResult[8] || undefined, + plusMinus: regexResult[9] || undefined, + hourOffset: toNumber(regexResult[10]), + minuteOffset: toNumber(regexResult[11]) + }; +} +function toNumber(str, defaultValue = 0) { + return Number(str) || defaultValue; +} +var rEmail = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +var rUrl = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i; +var rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +var yearMonthDay = "^\\d{4}-\\d{2}-\\d{2}"; +var hourMinuteSecond = "\\d{2}:\\d{2}:\\d{2}"; +var zOrOffset = "(([+-]\\d{2}(:?\\d{2})?)|Z)"; +var rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\.\\d+)?${zOrOffset}$`); +var isTrimmed = (value) => isAbsent(value) || value === value.trim(); +var objStringTag = {}.toString(); +function create$6() { + return new StringSchema; +} + +class StringSchema extends Schema { + constructor() { + super({ + type: "string", + check(value) { + if (value instanceof String) + value = value.valueOf(); + return typeof value === "string"; + } + }); + this.withMutation(() => { + this.transform((value, _raw) => { + if (!this.spec.coerce || this.isType(value)) + return value; + if (Array.isArray(value)) + return value; + const strValue = value != null && value.toString ? value.toString() : value; + if (strValue === objStringTag) + return value; + return strValue; + }); + }); + } + required(message) { + return super.required(message).withMutation((schema) => schema.test({ + message: message || mixed.required, + name: "required", + skipAbsent: true, + test: (value) => !!value.length + })); + } + notRequired() { + return super.notRequired().withMutation((schema) => { + schema.tests = schema.tests.filter((t) => t.OPTIONS.name !== "required"); + return schema; + }); + } + length(length, message = string.length) { + return this.test({ + message, + name: "length", + exclusive: true, + params: { + length + }, + skipAbsent: true, + test(value) { + return value.length === this.resolve(length); + } + }); + } + min(min, message = string.min) { + return this.test({ + message, + name: "min", + exclusive: true, + params: { + min + }, + skipAbsent: true, + test(value) { + return value.length >= this.resolve(min); + } + }); + } + max(max, message = string.max) { + return this.test({ + name: "max", + exclusive: true, + message, + params: { + max + }, + skipAbsent: true, + test(value) { + return value.length <= this.resolve(max); + } + }); + } + matches(regex, options) { + let excludeEmptyString = false; + let message; + let name; + if (options) { + if (typeof options === "object") { + ({ + excludeEmptyString = false, + message, + name + } = options); + } else { + message = options; + } + } + return this.test({ + name: name || "matches", + message: message || string.matches, + params: { + regex + }, + skipAbsent: true, + test: (value) => value === "" && excludeEmptyString || value.search(regex) !== -1 + }); + } + email(message = string.email) { + return this.matches(rEmail, { + name: "email", + message, + excludeEmptyString: true + }); + } + url(message = string.url) { + return this.matches(rUrl, { + name: "url", + message, + excludeEmptyString: true + }); + } + uuid(message = string.uuid) { + return this.matches(rUUID, { + name: "uuid", + message, + excludeEmptyString: false + }); + } + datetime(options) { + let message = ""; + let allowOffset; + let precision; + if (options) { + if (typeof options === "object") { + ({ + message = "", + allowOffset = false, + precision = undefined + } = options); + } else { + message = options; + } + } + return this.matches(rIsoDateTime, { + name: "datetime", + message: message || string.datetime, + excludeEmptyString: true + }).test({ + name: "datetime_offset", + message: message || string.datetime_offset, + params: { + allowOffset + }, + skipAbsent: true, + test: (value) => { + if (!value || allowOffset) + return true; + const struct = parseDateStruct(value); + if (!struct) + return false; + return !!struct.z; + } + }).test({ + name: "datetime_precision", + message: message || string.datetime_precision, + params: { + precision + }, + skipAbsent: true, + test: (value) => { + if (!value || precision == undefined) + return true; + const struct = parseDateStruct(value); + if (!struct) + return false; + return struct.precision === precision; + } + }); + } + ensure() { + return this.default("").transform((val) => val === null ? "" : val); + } + trim(message = string.trim) { + return this.transform((val) => val != null ? val.trim() : val).test({ + message, + name: "trim", + test: isTrimmed + }); + } + lowercase(message = string.lowercase) { + return this.transform((value) => !isAbsent(value) ? value.toLowerCase() : value).test({ + message, + name: "string_case", + exclusive: true, + skipAbsent: true, + test: (value) => isAbsent(value) || value === value.toLowerCase() + }); + } + uppercase(message = string.uppercase) { + return this.transform((value) => !isAbsent(value) ? value.toUpperCase() : value).test({ + message, + name: "string_case", + exclusive: true, + skipAbsent: true, + test: (value) => isAbsent(value) || value === value.toUpperCase() + }); + } +} +create$6.prototype = StringSchema.prototype; +var isNaN$1 = (value) => value != +value; +function create$5() { + return new NumberSchema; +} + +class NumberSchema extends Schema { + constructor() { + super({ + type: "number", + check(value) { + if (value instanceof Number) + value = value.valueOf(); + return typeof value === "number" && !isNaN$1(value); + } + }); + this.withMutation(() => { + this.transform((value, _raw) => { + if (!this.spec.coerce) + return value; + let parsed = value; + if (typeof parsed === "string") { + parsed = parsed.replace(/\s/g, ""); + if (parsed === "") + return NaN; + parsed = +parsed; + } + if (this.isType(parsed) || parsed === null) + return parsed; + return parseFloat(parsed); + }); + }); + } + min(min, message = number.min) { + return this.test({ + message, + name: "min", + exclusive: true, + params: { + min + }, + skipAbsent: true, + test(value) { + return value >= this.resolve(min); + } + }); + } + max(max, message = number.max) { + return this.test({ + message, + name: "max", + exclusive: true, + params: { + max + }, + skipAbsent: true, + test(value) { + return value <= this.resolve(max); + } + }); + } + lessThan(less, message = number.lessThan) { + return this.test({ + message, + name: "max", + exclusive: true, + params: { + less + }, + skipAbsent: true, + test(value) { + return value < this.resolve(less); + } + }); + } + moreThan(more, message = number.moreThan) { + return this.test({ + message, + name: "min", + exclusive: true, + params: { + more + }, + skipAbsent: true, + test(value) { + return value > this.resolve(more); + } + }); + } + positive(msg = number.positive) { + return this.moreThan(0, msg); + } + negative(msg = number.negative) { + return this.lessThan(0, msg); + } + integer(message = number.integer) { + return this.test({ + name: "integer", + message, + skipAbsent: true, + test: (val) => Number.isInteger(val) + }); + } + truncate() { + return this.transform((value) => !isAbsent(value) ? value | 0 : value); + } + round(method) { + var _method; + let avail = ["ceil", "floor", "round", "trunc"]; + method = ((_method = method) == null ? undefined : _method.toLowerCase()) || "round"; + if (method === "trunc") + return this.truncate(); + if (avail.indexOf(method.toLowerCase()) === -1) + throw new TypeError("Only valid options for round() are: " + avail.join(", ")); + return this.transform((value) => !isAbsent(value) ? Math[method](value) : value); + } +} +create$5.prototype = NumberSchema.prototype; +var invalidDate = new Date(""); +var isDate = (obj) => Object.prototype.toString.call(obj) === "[object Date]"; +function create$4() { + return new DateSchema; +} + +class DateSchema extends Schema { + constructor() { + super({ + type: "date", + check(v) { + return isDate(v) && !isNaN(v.getTime()); + } + }); + this.withMutation(() => { + this.transform((value, _raw) => { + if (!this.spec.coerce || this.isType(value) || value === null) + return value; + value = parseIsoDate(value); + return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE; + }); + }); + } + prepareParam(ref, name) { + let param; + if (!Reference.isRef(ref)) { + let cast = this.cast(ref); + if (!this._typeCheck(cast)) + throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`); + param = cast; + } else { + param = ref; + } + return param; + } + min(min, message = date.min) { + let limit = this.prepareParam(min, "min"); + return this.test({ + message, + name: "min", + exclusive: true, + params: { + min + }, + skipAbsent: true, + test(value) { + return value >= this.resolve(limit); + } + }); + } + max(max, message = date.max) { + let limit = this.prepareParam(max, "max"); + return this.test({ + message, + name: "max", + exclusive: true, + params: { + max + }, + skipAbsent: true, + test(value) { + return value <= this.resolve(limit); + } + }); + } +} +DateSchema.INVALID_DATE = invalidDate; +create$4.prototype = DateSchema.prototype; +create$4.INVALID_DATE = invalidDate; +function sortFields(fields, excludedEdges = []) { + let edges = []; + let nodes = new Set; + let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`)); + function addNode(depPath, key) { + let node = import_property_expr.split(depPath)[0]; + nodes.add(node); + if (!excludes.has(`${key}-${node}`)) + edges.push([key, node]); + } + for (const key of Object.keys(fields)) { + let value = fields[key]; + nodes.add(key); + if (Reference.isRef(value) && value.isSibling) + addNode(value.path, key); + else if (isSchema(value) && "deps" in value) + value.deps.forEach((path) => addNode(path, key)); + } + return import_toposort.default.array(Array.from(nodes), edges).reverse(); +} +function findIndex(arr, err) { + let idx = Infinity; + arr.some((key, ii) => { + var _err$path; + if ((_err$path = err.path) != null && _err$path.includes(key)) { + idx = ii; + return true; + } + }); + return idx; +} +function sortByKeyOrder(keys) { + return (a, b) => { + return findIndex(keys, a) - findIndex(keys, b); + }; +} +var parseJson = (value, _, schema) => { + if (typeof value !== "string") { + return value; + } + let parsed = value; + try { + parsed = JSON.parse(value); + } catch (err) {} + return schema.isType(parsed) ? parsed : value; +}; +function deepPartial(schema) { + if ("fields" in schema) { + const partial = {}; + for (const [key, fieldSchema] of Object.entries(schema.fields)) { + partial[key] = deepPartial(fieldSchema); + } + return schema.setFields(partial); + } + if (schema.type === "array") { + const nextArray = schema.optional(); + if (nextArray.innerType) + nextArray.innerType = deepPartial(nextArray.innerType); + return nextArray; + } + if (schema.type === "tuple") { + return schema.optional().clone({ + types: schema.spec.types.map(deepPartial) + }); + } + if ("optional" in schema) { + return schema.optional(); + } + return schema; +} +var deepHas = (obj, p) => { + const path = [...import_property_expr.normalizePath(p)]; + if (path.length === 1) + return path[0] in obj; + let last = path.pop(); + let parent = import_property_expr.getter(import_property_expr.join(path), true)(obj); + return !!(parent && (last in parent)); +}; +var isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]"; +function unknown(ctx, value) { + let known = Object.keys(ctx.fields); + return Object.keys(value).filter((key) => known.indexOf(key) === -1); +} +var defaultSort = sortByKeyOrder([]); +function create$3(spec) { + return new ObjectSchema(spec); +} + +class ObjectSchema extends Schema { + constructor(spec) { + super({ + type: "object", + check(value) { + return isObject(value) || typeof value === "function"; + } + }); + this.fields = Object.create(null); + this._sortErrors = defaultSort; + this._nodes = []; + this._excludedEdges = []; + this.withMutation(() => { + if (spec) { + this.shape(spec); + } + }); + } + _cast(_value, options = {}) { + var _options$stripUnknown; + let value = super._cast(_value, options); + if (value === undefined) + return this.getDefault(options); + if (!this._typeCheck(value)) + return value; + let fields = this.fields; + let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown; + let props = [].concat(this._nodes, Object.keys(value).filter((v) => !this._nodes.includes(v))); + let intermediateValue = {}; + let innerOptions = Object.assign({}, options, { + parent: intermediateValue, + __validating: options.__validating || false + }); + let isChanged = false; + for (const prop of props) { + let field = fields[prop]; + let exists = prop in value; + let inputValue = value[prop]; + if (field) { + let fieldValue; + innerOptions.path = (options.path ? `${options.path}.` : "") + prop; + field = field.resolve({ + value: inputValue, + context: options.context, + parent: intermediateValue + }); + let fieldSpec = field instanceof Schema ? field.spec : undefined; + let strict = fieldSpec == null ? undefined : fieldSpec.strict; + if (fieldSpec != null && fieldSpec.strip) { + isChanged = isChanged || prop in value; + continue; + } + fieldValue = !options.__validating || !strict ? field.cast(inputValue, innerOptions) : inputValue; + if (fieldValue !== undefined) { + intermediateValue[prop] = fieldValue; + } + } else if (exists && !strip) { + intermediateValue[prop] = inputValue; + } + if (exists !== prop in intermediateValue || intermediateValue[prop] !== inputValue) { + isChanged = true; + } + } + return isChanged ? intermediateValue : value; + } + _validate(_value, options = {}, panic, next) { + let { + from = [], + originalValue = _value, + recursive = this.spec.recursive + } = options; + options.from = [{ + schema: this, + value: originalValue + }, ...from]; + options.__validating = true; + options.originalValue = originalValue; + super._validate(_value, options, panic, (objectErrors, value) => { + if (!recursive || !isObject(value)) { + next(objectErrors, value); + return; + } + originalValue = originalValue || value; + let tests = []; + for (let key of this._nodes) { + let field = this.fields[key]; + if (!field || Reference.isRef(field)) { + continue; + } + tests.push(field.asNestedTest({ + options, + key, + parent: value, + parentPath: options.path, + originalParent: originalValue + })); + } + this.runTests({ + tests, + value, + originalValue, + options + }, panic, (fieldErrors) => { + next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value); + }); + }); + } + clone(spec) { + const next = super.clone(spec); + next.fields = Object.assign({}, this.fields); + next._nodes = this._nodes; + next._excludedEdges = this._excludedEdges; + next._sortErrors = this._sortErrors; + return next; + } + concat(schema) { + let next = super.concat(schema); + let nextFields = next.fields; + for (let [field, schemaOrRef] of Object.entries(this.fields)) { + const target = nextFields[field]; + nextFields[field] = target === undefined ? schemaOrRef : target; + } + return next.withMutation((s) => s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges])); + } + _getDefault(options) { + if ("default" in this.spec) { + return super._getDefault(options); + } + if (!this._nodes.length) { + return; + } + let dft = {}; + this._nodes.forEach((key) => { + var _innerOptions; + const field = this.fields[key]; + let innerOptions = options; + if ((_innerOptions = innerOptions) != null && _innerOptions.value) { + innerOptions = Object.assign({}, innerOptions, { + parent: innerOptions.value, + value: innerOptions.value[key] + }); + } + dft[key] = field && "getDefault" in field ? field.getDefault(innerOptions) : undefined; + }); + return dft; + } + setFields(shape, excludedEdges) { + let next = this.clone(); + next.fields = shape; + next._nodes = sortFields(shape, excludedEdges); + next._sortErrors = sortByKeyOrder(Object.keys(shape)); + if (excludedEdges) + next._excludedEdges = excludedEdges; + return next; + } + shape(additions, excludes = []) { + return this.clone().withMutation((next) => { + let edges = next._excludedEdges; + if (excludes.length) { + if (!Array.isArray(excludes[0])) + excludes = [excludes]; + edges = [...next._excludedEdges, ...excludes]; + } + return next.setFields(Object.assign(next.fields, additions), edges); + }); + } + partial() { + const partial = {}; + for (const [key, schema] of Object.entries(this.fields)) { + partial[key] = "optional" in schema && schema.optional instanceof Function ? schema.optional() : schema; + } + return this.setFields(partial); + } + deepPartial() { + const next = deepPartial(this); + return next; + } + pick(keys) { + const picked = {}; + for (const key of keys) { + if (this.fields[key]) + picked[key] = this.fields[key]; + } + return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b))); + } + omit(keys) { + const remaining = []; + for (const key of Object.keys(this.fields)) { + if (keys.includes(key)) + continue; + remaining.push(key); + } + return this.pick(remaining); + } + from(from, to, alias) { + let fromGetter = import_property_expr.getter(from, true); + return this.transform((obj) => { + if (!obj) + return obj; + let newObj = obj; + if (deepHas(obj, from)) { + newObj = Object.assign({}, obj); + if (!alias) + delete newObj[from]; + newObj[to] = fromGetter(obj); + } + return newObj; + }); + } + json() { + return this.transform(parseJson); + } + exact(message) { + return this.test({ + name: "exact", + exclusive: true, + message: message || object.exact, + test(value) { + if (value == null) + return true; + const unknownKeys = unknown(this.schema, value); + return unknownKeys.length === 0 || this.createError({ + params: { + properties: unknownKeys.join(", ") + } + }); + } + }); + } + stripUnknown() { + return this.clone({ + noUnknown: true + }); + } + noUnknown(noAllow = true, message = object.noUnknown) { + if (typeof noAllow !== "boolean") { + message = noAllow; + noAllow = true; + } + let next = this.test({ + name: "noUnknown", + exclusive: true, + message, + test(value) { + if (value == null) + return true; + const unknownKeys = unknown(this.schema, value); + return !noAllow || unknownKeys.length === 0 || this.createError({ + params: { + unknown: unknownKeys.join(", ") + } + }); + } + }); + next.spec.noUnknown = noAllow; + return next; + } + unknown(allow = true, message = object.noUnknown) { + return this.noUnknown(!allow, message); + } + transformKeys(fn) { + return this.transform((obj) => { + if (!obj) + return obj; + const result = {}; + for (const key of Object.keys(obj)) + result[fn(key)] = obj[key]; + return result; + }); + } + camelCase() { + return this.transformKeys(import_tiny_case.camelCase); + } + snakeCase() { + return this.transformKeys(import_tiny_case.snakeCase); + } + constantCase() { + return this.transformKeys((key) => import_tiny_case.snakeCase(key).toUpperCase()); + } + describe(options) { + const next = (options ? this.resolve(options) : this).clone(); + const base = super.describe(options); + base.fields = {}; + for (const [key, value] of Object.entries(next.fields)) { + var _innerOptions2; + let innerOptions = options; + if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) { + innerOptions = Object.assign({}, innerOptions, { + parent: innerOptions.value, + value: innerOptions.value[key] + }); + } + base.fields[key] = value.describe(innerOptions); + } + return base; + } +} +create$3.prototype = ObjectSchema.prototype; +function create$2(type) { + return new ArraySchema(type); +} + +class ArraySchema extends Schema { + constructor(type) { + super({ + type: "array", + spec: { + types: type + }, + check(v) { + return Array.isArray(v); + } + }); + this.innerType = undefined; + this.innerType = type; + } + _cast(_value, _opts) { + const value = super._cast(_value, _opts); + if (!this._typeCheck(value) || !this.innerType) { + return value; + } + let isChanged = false; + const castArray = value.map((v, idx) => { + const castElement = this.innerType.cast(v, Object.assign({}, _opts, { + path: `${_opts.path || ""}[${idx}]`, + parent: value, + originalValue: v, + value: v, + index: idx + })); + if (castElement !== v) { + isChanged = true; + } + return castElement; + }); + return isChanged ? castArray : value; + } + _validate(_value, options = {}, panic, next) { + var _options$recursive; + let innerType = this.innerType; + let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive; + options.originalValue != null && options.originalValue; + super._validate(_value, options, panic, (arrayErrors, value) => { + var _options$originalValu2; + if (!recursive || !innerType || !this._typeCheck(value)) { + next(arrayErrors, value); + return; + } + let tests = new Array(value.length); + for (let index = 0;index < value.length; index++) { + var _options$originalValu; + tests[index] = innerType.asNestedTest({ + options, + index, + parent: value, + parentPath: options.path, + originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value + }); + } + this.runTests({ + value, + tests, + originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value, + options + }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(arrayErrors), value)); + }); + } + clone(spec) { + const next = super.clone(spec); + next.innerType = this.innerType; + return next; + } + json() { + return this.transform(parseJson); + } + concat(schema) { + let next = super.concat(schema); + next.innerType = this.innerType; + if (schema.innerType) + next.innerType = next.innerType ? next.innerType.concat(schema.innerType) : schema.innerType; + return next; + } + of(schema) { + let next = this.clone(); + if (!isSchema(schema)) + throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: " + printValue(schema)); + next.innerType = schema; + next.spec = Object.assign({}, next.spec, { + types: schema + }); + return next; + } + length(length, message = array.length) { + return this.test({ + message, + name: "length", + exclusive: true, + params: { + length + }, + skipAbsent: true, + test(value) { + return value.length === this.resolve(length); + } + }); + } + min(min, message) { + message = message || array.min; + return this.test({ + message, + name: "min", + exclusive: true, + params: { + min + }, + skipAbsent: true, + test(value) { + return value.length >= this.resolve(min); + } + }); + } + max(max, message) { + message = message || array.max; + return this.test({ + message, + name: "max", + exclusive: true, + params: { + max + }, + skipAbsent: true, + test(value) { + return value.length <= this.resolve(max); + } + }); + } + ensure() { + return this.default(() => []).transform((val, original) => { + if (this._typeCheck(val)) + return val; + return original == null ? [] : [].concat(original); + }); + } + compact(rejector) { + let reject = !rejector ? (v) => !!v : (v, i, a) => !rejector(v, i, a); + return this.transform((values) => values != null ? values.filter(reject) : values); + } + describe(options) { + const next = (options ? this.resolve(options) : this).clone(); + const base = super.describe(options); + if (next.innerType) { + var _innerOptions; + let innerOptions = options; + if ((_innerOptions = innerOptions) != null && _innerOptions.value) { + innerOptions = Object.assign({}, innerOptions, { + parent: innerOptions.value, + value: innerOptions.value[0] + }); + } + base.innerType = next.innerType.describe(innerOptions); + } + return base; + } +} +create$2.prototype = ArraySchema.prototype; +function create$1(schemas) { + return new TupleSchema(schemas); +} + +class TupleSchema extends Schema { + constructor(schemas) { + super({ + type: "tuple", + spec: { + types: schemas + }, + check(v) { + const types = this.spec.types; + return Array.isArray(v) && v.length === types.length; + } + }); + this.withMutation(() => { + this.typeError(tuple.notType); + }); + } + _cast(inputValue, options) { + const { + types + } = this.spec; + const value = super._cast(inputValue, options); + if (!this._typeCheck(value)) { + return value; + } + let isChanged = false; + const castArray = types.map((type, idx) => { + const castElement = type.cast(value[idx], Object.assign({}, options, { + path: `${options.path || ""}[${idx}]`, + parent: value, + originalValue: value[idx], + value: value[idx], + index: idx + })); + if (castElement !== value[idx]) + isChanged = true; + return castElement; + }); + return isChanged ? castArray : value; + } + _validate(_value, options = {}, panic, next) { + let itemTypes = this.spec.types; + super._validate(_value, options, panic, (tupleErrors, value) => { + var _options$originalValu2; + if (!this._typeCheck(value)) { + next(tupleErrors, value); + return; + } + let tests = []; + for (let [index, itemSchema] of itemTypes.entries()) { + var _options$originalValu; + tests[index] = itemSchema.asNestedTest({ + options, + index, + parent: value, + parentPath: options.path, + originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value + }); + } + this.runTests({ + value, + tests, + originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value, + options + }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(tupleErrors), value)); + }); + } + describe(options) { + const next = (options ? this.resolve(options) : this).clone(); + const base = super.describe(options); + base.innerType = next.spec.types.map((schema, index) => { + var _innerOptions; + let innerOptions = options; + if ((_innerOptions = innerOptions) != null && _innerOptions.value) { + innerOptions = Object.assign({}, innerOptions, { + parent: innerOptions.value, + value: innerOptions.value[index] + }); + } + return schema.describe(innerOptions); + }); + return base; + } +} +create$1.prototype = TupleSchema.prototype; + +// src/utils/ApiError.ts +class ApiError extends Error { + statusCode; + success; + data; + isOperational; + constructor(message, statusCode, data) { + super(message); + this.statusCode = statusCode; + this.success = statusCode >= 200 && statusCode < 300; + this.isOperational = true; + this.data = data; + Error.captureStackTrace(this, this.constructor); + } +} +var ApiError_default = ApiError; + +// src/utils/asyncHandler.ts +var asyncHandler = (fn) => { + return (req, res, next) => { + fn(req, res, next).catch((err) => { + next(err); + }); + }; +}; +var asyncHandler_default = asyncHandler; + +// src/shared/middleware.ts +var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); + +// node_modules/.pnpm/http-status@2.1.0/node_modules/http-status/dist/chunk-CUNVWAK5.js +var e = { "1xx": "Informational", "1xx_NAME": "INFORMATIONAL", "1xx_MESSAGE": "Indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response.", INFORMATIONAL: "1xx", "2xx": "Successful", "2xx_NAME": "SUCCESSFUL", "2xx_MESSAGE": "Indicates that the client's request was successfully received, understood, and accepted.", SUCCESSFUL: "2xx", "3xx": "Redirection", "3xx_NAME": "REDIRECTION", "3xx_MESSAGE": "Indicates that further action needs to be taken by the user agent in order to fulfill the request.", REDIRECTION: "3xx", "4xx": "Client Error", "4xx_NAME": "CLIENT_ERROR", "4xx_MESSAGE": "Indicates that the client seems to have erred.", CLIENT_ERROR: "4xx", "5xx": "Server Error", "5xx_NAME": "SERVER_ERROR", "5xx_MESSAGE": "Indicates that the server is aware that it has erred or is incapable of performing the requested method.", SERVER_ERROR: "5xx" }; +var t = { classes: e, 100: "Continue", "100_NAME": "CONTINUE", "100_MESSAGE": "The server has received the request headers and the client should proceed to send the request body.", "100_CLASS": e.INFORMATIONAL, CONTINUE: 100, 101: "Switching Protocols", "101_NAME": "SWITCHING_PROTOCOLS", "101_MESSAGE": "The requester has asked the server to switch protocols and the server has agreed to do so.", "101_CLASS": e.INFORMATIONAL, SWITCHING_PROTOCOLS: 101, 102: "Processing", "102_NAME": "PROCESSING", "102_MESSAGE": "A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[7] This prevents the client from timing out and assuming the request was lost.", "102_CLASS": e.INFORMATIONAL, PROCESSING: 102, 103: "Early Hints", "103_NAME": "EARLY_HINTS", "103_MESSAGE": "Used to return some response headers before final HTTP message.", "103_CLASS": e.INFORMATIONAL, EARLY_HINTS: 103, 200: "OK", "200_NAME": "OK", "200_MESSAGE": "Standard response for successful HTTP requests.", "200_CLASS": e.SUCCESSFUL, OK: 200, 201: "Created", "201_NAME": "CREATED", "201_MESSAGE": "The request has been fulfilled, resulting in the creation of a new resource.", "201_CLASS": e.SUCCESSFUL, CREATED: 201, 202: "Accepted", "202_NAME": "ACCEPTED", "202_MESSAGE": "The request has been accepted for processing, but the processing has not been completed.", "202_CLASS": e.SUCCESSFUL, ACCEPTED: 202, 203: "Non-Authoritative Information", "203_NAME": "NON_AUTHORITATIVE_INFORMATION", "203_MESSAGE": "The server is a transforming proxy (e.g. a Web accelerator) that received a 200 OK from its origin, but is returning a modified version of the origin's response.", "203_CLASS": e.SUCCESSFUL, NON_AUTHORITATIVE_INFORMATION: 203, 204: "No Content", "204_NAME": "NO_CONTENT", "204_MESSAGE": "The server successfully processed the request and is not returning any content.", "204_CLASS": e.SUCCESSFUL, NO_CONTENT: 204, 205: "Reset Content", "205_NAME": "RESET_CONTENT", "205_MESSAGE": "The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.", "205_CLASS": e.SUCCESSFUL, RESET_CONTENT: 205, 206: "Partial Content", "206_NAME": "PARTIAL_CONTENT", "206_MESSAGE": "The server is delivering only part of the resource (byte serving) due to a range header sent by the client.", "206_CLASS": e.SUCCESSFUL, PARTIAL_CONTENT: 206, 207: "Multi Status", "207_NAME": "MULTI_STATUS", "207_MESSAGE": "The message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.", "207_CLASS": e.SUCCESSFUL, MULTI_STATUS: 207, 208: "Already Reported", "208_NAME": "ALREADY_REPORTED", "208_MESSAGE": "The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, and are not being included again.", "208_CLASS": e.SUCCESSFUL, ALREADY_REPORTED: 208, 226: "IM Used", "226_NAME": "IM_USED", "226_MESSAGE": "The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.", "226_CLASS": e.SUCCESSFUL, IM_USED: 226, 300: "Multiple Choices", "300_NAME": "MULTIPLE_CHOICES", "300_MESSAGE": "Indicates multiple options for the resource from which the client may choose.", "300_CLASS": e.REDIRECTION, MULTIPLE_CHOICES: 300, 301: "Moved Permanently", "301_NAME": "MOVED_PERMANENTLY", "301_MESSAGE": "This and all future requests should be directed to the given URI.", "301_CLASS": e.REDIRECTION, MOVED_PERMANENTLY: 301, 302: "Found", "302_NAME": "FOUND", "302_MESSAGE": 'This is an example of industry practice contradicting the standard. The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours.', "302_CLASS": e.REDIRECTION, FOUND: 302, 303: "See Other", "303_NAME": "SEE_OTHER", "303_MESSAGE": "The response to the request can be found under another URI using the GET method.", "303_CLASS": e.REDIRECTION, SEE_OTHER: 303, 304: "Not Modified", "304_NAME": "NOT_MODIFIED", "304_MESSAGE": "Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.", "304_CLASS": e.REDIRECTION, NOT_MODIFIED: 304, 305: "Use Proxy", "305_NAME": "USE_PROXY", "305_MESSAGE": "The requested resource is available only through a proxy, the address for which is provided in the response.", "305_CLASS": e.REDIRECTION, USE_PROXY: 305, 306: "Switch Proxy", "306_NAME": "SWITCH_PROXY", "306_MESSAGE": 'No longer used. Originally meant "Subsequent requests should use the specified proxy.', "306_CLASS": e.REDIRECTION, SWITCH_PROXY: 306, 307: "Temporary Redirect", "307_NAME": "TEMPORARY_REDIRECT", "307_MESSAGE": "In this case, the request should be repeated with another URI; however, future requests should still use the original URI.", "307_CLASS": e.REDIRECTION, TEMPORARY_REDIRECT: 307, 308: "Permanent Redirect", "308_NAME": "PERMANENT_REDIRECT", "308_MESSAGE": "The request and all future requests should be repeated using another URI.", "308_CLASS": e.REDIRECTION, PERMANENT_REDIRECT: 308, 400: "Bad Request", "400_NAME": "BAD_REQUEST", "400_MESSAGE": "The server cannot or will not process the request due to an apparent client error.", "400_CLASS": e.CLIENT_ERROR, BAD_REQUEST: 400, 401: "Unauthorized", "401_NAME": "UNAUTHORIZED", "401_MESSAGE": "Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.", "401_CLASS": e.CLIENT_ERROR, UNAUTHORIZED: 401, 402: "Payment Required", "402_NAME": "PAYMENT_REQUIRED", "402_MESSAGE": "Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, as proposed for example by GNU Taler, but that has not yet happened, and this code is not usually used.", "402_CLASS": e.CLIENT_ERROR, PAYMENT_REQUIRED: 402, 403: "Forbidden", "403_NAME": "FORBIDDEN", "403_MESSAGE": "The request was valid, but the server is refusing action.", "403_CLASS": e.CLIENT_ERROR, FORBIDDEN: 403, 404: "Not Found", "404_NAME": "NOT_FOUND", "404_MESSAGE": "The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.", "404_CLASS": e.CLIENT_ERROR, NOT_FOUND: 404, 405: "Method Not Allowed", "405_NAME": "METHOD_NOT_ALLOWED", "405_MESSAGE": "A request method is not supported for the requested resource.", "405_CLASS": e.CLIENT_ERROR, METHOD_NOT_ALLOWED: 405, 406: "Not Acceptable", "406_NAME": "NOT_ACCEPTABLE", "406_MESSAGE": "The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.", "406_CLASS": e.CLIENT_ERROR, NOT_ACCEPTABLE: 406, 407: "Proxy Authentication Required", "407_NAME": "PROXY_AUTHENTICATION_REQUIRED", "407_MESSAGE": "The client must first authenticate itself with the proxy.", "407_CLASS": e.CLIENT_ERROR, PROXY_AUTHENTICATION_REQUIRED: 407, 408: "Request Time-out", "408_NAME": "REQUEST_TIMEOUT", "408_MESSAGE": "The server timed out waiting for the request.", "408_CLASS": e.CLIENT_ERROR, REQUEST_TIMEOUT: 408, 409: "Conflict", "409_NAME": "CONFLICT", "409_MESSAGE": "Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.", "409_CLASS": e.CLIENT_ERROR, CONFLICT: 409, 410: "Gone", "410_NAME": "GONE", "410_MESSAGE": "Indicates that the resource requested is no longer available and will not be available again.", "410_CLASS": e.CLIENT_ERROR, GONE: 410, 411: "Length Required", "411_NAME": "LENGTH_REQUIRED", "411_MESSAGE": "The request did not specify the length of its content, which is required by the requested resource.", "411_CLASS": e.CLIENT_ERROR, LENGTH_REQUIRED: 411, 412: "Precondition Failed", "412_NAME": "PRECONDITION_FAILED", "412_MESSAGE": "The server does not meet one of the preconditions that the requester put on the request.", "412_CLASS": e.CLIENT_ERROR, PRECONDITION_FAILED: 412, 413: "Request Entity Too Large", "413_NAME": "REQUEST_ENTITY_TOO_LARGE", "413_MESSAGE": 'The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".', "413_CLASS": e.CLIENT_ERROR, REQUEST_ENTITY_TOO_LARGE: 413, 414: "Request-URI Too Large", "414_NAME": "REQUEST_URI_TOO_LONG", "414_MESSAGE": "The URI provided was too long for the server to process.", "414_CLASS": e.CLIENT_ERROR, REQUEST_URI_TOO_LONG: 414, 415: "Unsupported Media Type", "415_NAME": "UNSUPPORTED_MEDIA_TYPE", "415_MESSAGE": "The request entity has a media type which the server or resource does not support.", "415_CLASS": e.CLIENT_ERROR, UNSUPPORTED_MEDIA_TYPE: 415, 416: "Requested Range not Satisfiable", "416_NAME": "REQUESTED_RANGE_NOT_SATISFIABLE", "416_MESSAGE": "The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.", "416_CLASS": e.CLIENT_ERROR, REQUESTED_RANGE_NOT_SATISFIABLE: 416, 417: "Expectation Failed", "417_NAME": "EXPECTATION_FAILED", "417_MESSAGE": "The server cannot meet the requirements of the Expect request-header field.", "417_CLASS": e.CLIENT_ERROR, EXPECTATION_FAILED: 417, 418: "I'm a teapot", "418_NAME": "IM_A_TEAPOT", "418_MESSAGE": `Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.`, "418_CLASS": e.CLIENT_ERROR, IM_A_TEAPOT: 418, 421: "Misdirected Request", "421_NAME": "MISDIRECTED_REQUEST", "421_MESSAGE": "The request was directed at a server that is not able to produce a response.", "421_CLASS": e.CLIENT_ERROR, MISDIRECTED_REQUEST: 421, 422: "Unprocessable Entity", "422_NAME": "UNPROCESSABLE_ENTITY", "422_MESSAGE": "The request was well-formed but was unable to be followed due to semantic errors.", "422_CLASS": e.CLIENT_ERROR, UNPROCESSABLE_ENTITY: 422, 423: "Locked", "423_NAME": "LOCKED", "423_MESSAGE": "The resource that is being accessed is locked.", "423_CLASS": e.CLIENT_ERROR, LOCKED: 423, 424: "Failed Dependency", "424_NAME": "FAILED_DEPENDENCY", "424_MESSAGE": "The request failed because it depended on another request and that request failed.", "424_CLASS": e.CLIENT_ERROR, FAILED_DEPENDENCY: 424, 425: "Too Early", "425_NAME": "TOO_EARLY", "425_MESSAGE": "The server is unwilling to risk processing a request that might be replayed.", "425_CLASS": e.CLIENT_ERROR, TOO_EARLY: 425, 426: "Upgrade Required", "426_NAME": "UPGRADE_REQUIRED", "426_MESSAGE": "The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.", "426_CLASS": e.CLIENT_ERROR, UPGRADE_REQUIRED: 426, 428: "Precondition Required", "428_NAME": "PRECONDITION_REQUIRED", "428_MESSAGE": "The origin server requires the request to be conditional.", "428_CLASS": e.CLIENT_ERROR, PRECONDITION_REQUIRED: 428, 429: "Too Many Requests", "429_NAME": "TOO_MANY_REQUESTS", "429_MESSAGE": "The user has sent too many requests in a given amount of time.", "429_CLASS": e.CLIENT_ERROR, TOO_MANY_REQUESTS: 429, 431: "Request Header Fields Too Large", "431_NAME": "REQUEST_HEADER_FIELDS_TOO_LARGE", "431_MESSAGE": "The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.", "431_CLASS": e.CLIENT_ERROR, REQUEST_HEADER_FIELDS_TOO_LARGE: 431, 451: "Unavailable For Legal Reasons", "451_NAME": "UNAVAILABLE_FOR_LEGAL_REASONS", "451_MESSAGE": "A server operator has received a legal demand to deny access to a resource or to a set of resources that includes the requested resource.", "451_CLASS": e.CLIENT_ERROR, UNAVAILABLE_FOR_LEGAL_REASONS: 451, 500: "Internal Server Error", "500_NAME": "INTERNAL_SERVER_ERROR", "500_MESSAGE": "A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.", "500_CLASS": e.SERVER_ERROR, INTERNAL_SERVER_ERROR: 500, 501: "Not Implemented", "501_NAME": "NOT_IMPLEMENTED", "501_MESSAGE": "The server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability.", "501_CLASS": e.SERVER_ERROR, NOT_IMPLEMENTED: 501, 502: "Bad Gateway", "502_NAME": "BAD_GATEWAY", "502_MESSAGE": "The server was acting as a gateway or proxy and received an invalid response from the upstream server.", "502_CLASS": e.SERVER_ERROR, BAD_GATEWAY: 502, 503: "Service Unavailable", "503_NAME": "SERVICE_UNAVAILABLE", "503_MESSAGE": "The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.", "503_CLASS": e.SERVER_ERROR, SERVICE_UNAVAILABLE: 503, 504: "Gateway Time-out", "504_NAME": "GATEWAY_TIMEOUT", "504_MESSAGE": "The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.", "504_CLASS": e.SERVER_ERROR, GATEWAY_TIMEOUT: 504, 505: "HTTP Version not Supported", "505_NAME": "HTTP_VERSION_NOT_SUPPORTED", "505_MESSAGE": "The server does not support the HTTP protocol version used in the request.", "505_CLASS": e.SERVER_ERROR, HTTP_VERSION_NOT_SUPPORTED: 505, 506: "Variant Also Negotiates", "506_NAME": "VARIANT_ALSO_NEGOTIATES", "506_MESSAGE": "Transparent content negotiation for the request results in a circular reference.", "506_CLASS": e.SERVER_ERROR, VARIANT_ALSO_NEGOTIATES: 506, 507: "Insufficient Storage", "507_NAME": "INSUFFICIENT_STORAGE", "507_MESSAGE": "The server is unable to store the representation needed to complete the request.", "507_CLASS": e.SERVER_ERROR, INSUFFICIENT_STORAGE: 507, 508: "Loop Detected", "508_NAME": "LOOP_DETECTED", "508_MESSAGE": "The server detected an infinite loop while processing the request.", "508_CLASS": e.SERVER_ERROR, LOOP_DETECTED: 508, 510: "Not Extended", "510_NAME": "NOT_EXTENDED", "510_MESSAGE": "Further extensions to the request are required for the server to fulfil it.", "510_CLASS": e.SERVER_ERROR, NOT_EXTENDED: 510, 511: "Network Authentication Required", "511_NAME": "NETWORK_AUTHENTICATION_REQUIRED", "511_MESSAGE": "The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network.", "511_CLASS": e.SERVER_ERROR, NETWORK_AUTHENTICATION_REQUIRED: 511, extra: { unofficial: { 103: "Checkpoint", "103_NAME": "CHECKPOINT", "103_MESSAGE": "Used in the resumable requests proposal to resume aborted PUT or POST requests.", "103_CLASS": e.INFORMATIONAL, CHECKPOINT: 103, 419: "Page Expired", "419_NAME": "PAGE_EXPIRED", "419_MESSAGE": "Used by the Laravel Framework when a CSRF Token is missing or expired.", "419_CLASS": e.CLIENT_ERROR, PAGE_EXPIRED: 419, 218: "This is fine", "218_NAME": "THIS_IS_FINE", "218_MESSAGE": "Used as a catch-all error condition for allowing response bodies to flow through Apache when ProxyErrorOverride is enabled. When ProxyErrorOverride is enabled in Apache, response bodies that contain a status code of 4xx or 5xx are automatically discarded by Apache in favor of a generic response or a custom response specified by the ErrorDocument directive.", "218_CLASS": e.SUCCESSFUL, THIS_IS_FINE: 218, 420: "Enhance Your Calm", "420_NAME": "ENHANCE_YOUR_CALM", "420_MESSAGE": "Returned by version 1 of the Twitter Search and Trends API when the client is being rate limited; versions 1.1 and later use the 429 Too Many Requests response code instead.", "420_CLASS": e.CLIENT_ERROR, ENHANCE_YOUR_CALM: 420, 450: "Blocked by Windows Parental Controls", "450_NAME": "BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS", "450_MESSAGE": "The Microsoft extension code indicated when Windows Parental Controls are turned on and are blocking access to the requested webpage.", "450_CLASS": e.CLIENT_ERROR, BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS: 450, 498: "Invalid Token", "498_NAME": "INVALID_TOKEN", "498_MESSAGE": "Returned by ArcGIS for Server. Code 498 indicates an expired or otherwise invalid token.", "498_CLASS": e.CLIENT_ERROR, INVALID_TOKEN: 498, 499: "Token Required", "499_NAME": "TOKEN_REQUIRED", "499_MESSAGE": "Returned by ArcGIS for Server. Code 499 indicates that a token is required but was not submitted.", "499_CLASS": e.CLIENT_ERROR, TOKEN_REQUIRED: 499, 509: "Bandwidth Limit Exceeded", "509_NAME": "BANDWIDTH_LIMIT_EXCEEDED", "509_MESSAGE": "The server has exceeded the bandwidth specified by the server administrator.", "509_CLASS": e.SERVER_ERROR, BANDWIDTH_LIMIT_EXCEEDED: 509, 530: "Site is frozen", "530_NAME": "SITE_IS_FROZEN", "530_MESSAGE": "Used by the Pantheon web platform to indicate a site that has been frozen due to inactivity.", "530_CLASS": e.SERVER_ERROR, SITE_IS_FROZEN: 530, 598: "Network read timeout error", "598_NAME": "NETWORK_READ_TIMEOUT_ERROR", "598_MESSAGE": "Used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.", "598_CLASS": e.SERVER_ERROR, NETWORK_READ_TIMEOUT_ERROR: 598 }, iis: { 440: "Login Time-out", "440_NAME": "LOGIN_TIME_OUT", "440_MESSAGE": "The client's session has expired and must log in again.", "440_CLASS": e.CLIENT_ERROR, LOGIN_TIME_OUT: 440, 449: "Retry With", "449_NAME": "RETRY_WITH", "449_MESSAGE": "The server cannot honour the request because the user has not provided the required information.", "449_CLASS": e.CLIENT_ERROR, RETRY_WITH: 449, 451: "Redirect", "451_NAME": "REDIRECT", "451_MESSAGE": "Used in Exchange ActiveSync when either a more efficient server is available or the server cannot access the users' mailbox.", "451_CLASS": e.CLIENT_ERROR, REDIRECT: 451 }, nginx: { 444: "No Response", "444_NAME": "NO_RESPONSE", "444_MESSAGE": "Used internally to instruct the server to return no information to the client and close the connection immediately.", "444_CLASS": e.CLIENT_ERROR, NO_RESPONSE: 444, 494: "Request header too large", "494_NAME": "REQUEST_HEADER_TOO_LARGE", "494_MESSAGE": "Client sent too large request or too long header line.", "494_CLASS": e.CLIENT_ERROR, REQUEST_HEADER_TOO_LARGE: 494, 495: "SSL Certificate Error", "495_NAME": "SSL_CERTIFICATE_ERROR", "495_MESSAGE": "An expansion of the 400 Bad Request response code, used when the client has provided an invalid client certificate.", "495_CLASS": e.CLIENT_ERROR, SSL_CERTIFICATE_ERROR: 495, 496: "SSL Certificate Required", "496_NAME": "SSL_CERTIFICATE_REQUIRED", "496_MESSAGE": "An expansion of the 400 Bad Request response code, used when a client certificate is required but not provided.", "496_CLASS": e.CLIENT_ERROR, SSL_CERTIFICATE_REQUIRED: 496, 497: "HTTP Request Sent to HTTPS Port", "497_NAME": "HTTP_REQUEST_SENT_TO_HTTPS_PORT", "497_MESSAGE": "An expansion of the 400 Bad Request response code, used when the client has made a HTTP request to a port listening for HTTPS requests.", "497_CLASS": e.CLIENT_ERROR, HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, 499: "Client Closed Request", "499_NAME": "CLIENT_CLOSED_REQUEST", "499_MESSAGE": "Used when the client has closed the request before the server could send a response.", "499_CLASS": e.CLIENT_ERROR, CLIENT_CLOSED_REQUEST: 499 }, cloudflare: { 520: "Unknown Error", "520_NAME": "UNKNOWN_ERROR", "520_MESSAGE": 'The 520 error is used as a "catch-all response for when the origin server returns something unexpected", listing connection resets, large headers, and empty or invalid responses as common triggers.', "520_CLASS": e.SERVER_ERROR, UNKNOWN_ERROR: 520, 521: "Web Server Is Down", "521_NAME": "WEB_SERVER_IS_DOWN", "521_MESSAGE": "The origin server has refused the connection from Cloudflare.", "521_CLASS": e.SERVER_ERROR, WEB_SERVER_IS_DOWN: 521, 522: "Connection Timed Out", "522_NAME": "CONNECTION_TIMED_OUT", "522_MESSAGE": "Cloudflare could not negotiate a TCP handshake with the origin server.", "522_CLASS": e.SERVER_ERROR, CONNECTION_TIMED_OUT: 522, 523: "Origin Is Unreachable", "523_NAME": "ORIGIN_IS_UNREACHABLE", "523_MESSAGE": "Cloudflare could not reach the origin server.", "523_CLASS": e.SERVER_ERROR, ORIGIN_IS_UNREACHABLE: 523, 524: "A Timeout Occurred", "524_NAME": "A_TIMEOUT_OCCURRED", "524_MESSAGE": "Cloudflare was able to complete a TCP connection to the origin server, but did not receive a timely HTTP response.", "524_CLASS": e.SERVER_ERROR, A_TIMEOUT_OCCURRED: 524, 525: "SSL Handshake Failed", "525_NAME": "SSL_HANDSHAKE_FAILED", "525_MESSAGE": "Cloudflare could not negotiate a SSL/TLS handshake with the origin server.", "525_CLASS": e.SERVER_ERROR, SSL_HANDSHAKE_FAILED: 525, 526: "Invalid SSL Certificate", "526_NAME": "INVALID_SSL_CERTIFICATE", "526_MESSAGE": "Cloudflare could not validate the SSL/TLS certificate that the origin server presented.", "526_CLASS": e.SERVER_ERROR, INVALID_SSL_CERTIFICATE: 526, 527: "Railgun Error", "527_NAME": "RAILGUN_ERROR", "527_MESSAGE": "Error 527 indicates that the request timed out or failed after the WAN connection had been established.", "527_CLASS": e.SERVER_ERROR, RAILGUN_ERROR: 527 } } }; +var E = t; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/entity.js +var entityKind = Symbol.for("drizzle:entityKind"); +var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind"); +function is(value, type) { + if (!value || typeof value !== "object") { + return false; + } + if (value instanceof type) { + return true; + } + if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { + throw new Error(`Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`); + } + let cls = Object.getPrototypeOf(value).constructor; + if (cls) { + while (cls) { + if (entityKind in cls && cls[entityKind] === type[entityKind]) { + return true; + } + cls = Object.getPrototypeOf(cls); + } + } + return false; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column.js +class Column { + constructor(table, config) { + this.table = table; + this.config = config; + this.name = config.name; + this.keyAsName = config.keyAsName; + this.notNull = config.notNull; + this.default = config.default; + this.defaultFn = config.defaultFn; + this.onUpdateFn = config.onUpdateFn; + this.hasDefault = config.hasDefault; + this.primary = config.primaryKey; + this.isUnique = config.isUnique; + this.uniqueName = config.uniqueName; + this.uniqueType = config.uniqueType; + this.dataType = config.dataType; + this.columnType = config.columnType; + this.generated = config.generated; + this.generatedIdentity = config.generatedIdentity; + } + static [entityKind] = "Column"; + name; + keyAsName; + primary; + notNull; + default; + defaultFn; + onUpdateFn; + hasDefault; + isUnique; + uniqueName; + uniqueType; + dataType; + columnType; + enumValues = undefined; + generated = undefined; + generatedIdentity = undefined; + config; + mapFromDriverValue(value) { + return value; + } + mapToDriverValue(value) { + return value; + } + shouldDisableInsert() { + return this.config.generated !== undefined && this.config.generated.type !== "byDefault"; + } +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column-builder.js +class ColumnBuilder { + static [entityKind] = "ColumnBuilder"; + config; + constructor(name, dataType, columnType) { + this.config = { + name, + keyAsName: name === "", + notNull: false, + default: undefined, + hasDefault: false, + primaryKey: false, + isUnique: false, + uniqueName: undefined, + uniqueType: undefined, + dataType, + columnType, + generated: undefined + }; + } + $type() { + return this; + } + notNull() { + this.config.notNull = true; + return this; + } + default(value) { + this.config.default = value; + this.config.hasDefault = true; + return this; + } + $defaultFn(fn) { + this.config.defaultFn = fn; + this.config.hasDefault = true; + return this; + } + $default = this.$defaultFn; + $onUpdateFn(fn) { + this.config.onUpdateFn = fn; + this.config.hasDefault = true; + return this; + } + $onUpdate = this.$onUpdateFn; + primaryKey() { + this.config.primaryKey = true; + this.config.notNull = true; + return this; + } + setName(name) { + if (this.config.name !== "") + return; + this.config.name = name; + } +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.utils.js +var TableName = Symbol.for("drizzle:Name"); + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/foreign-keys.js +class ForeignKeyBuilder { + static [entityKind] = "PgForeignKeyBuilder"; + reference; + _onUpdate = "no action"; + _onDelete = "no action"; + constructor(config, actions) { + this.reference = () => { + const { name, columns, foreignColumns } = config(); + return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; + }; + if (actions) { + this._onUpdate = actions.onUpdate; + this._onDelete = actions.onDelete; + } + } + onUpdate(action) { + this._onUpdate = action === undefined ? "no action" : action; + return this; + } + onDelete(action) { + this._onDelete = action === undefined ? "no action" : action; + return this; + } + build(table) { + return new ForeignKey(table, this); + } +} + +class ForeignKey { + constructor(table, builder) { + this.table = table; + this.reference = builder.reference; + this.onUpdate = builder._onUpdate; + this.onDelete = builder._onDelete; + } + static [entityKind] = "PgForeignKey"; + reference; + onUpdate; + onDelete; + getName() { + const { name, columns, foreignColumns } = this.reference(); + const columnNames = columns.map((column) => column.name); + const foreignColumnNames = foreignColumns.map((column) => column.name); + const chunks = [ + this.table[TableName], + ...columnNames, + foreignColumns[0].table[TableName], + ...foreignColumnNames + ]; + return name ?? `${chunks.join("_")}_fk`; + } +} +function foreignKey(config) { + function mappedConfig() { + const { name, columns, foreignColumns } = config; + return { + name, + columns, + foreignColumns + }; + } + return new ForeignKeyBuilder(mappedConfig); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing-utils.js +function iife(fn, ...args) { + return fn(...args); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/unique-constraint.js +function uniqueKeyName(table, columns) { + return `${table[TableName]}_${columns.join("_")}_unique`; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils/array.js +function parsePgArrayValue(arrayString, startFrom, inQuotes) { + for (let i = startFrom;i < arrayString.length; i++) { + const char = arrayString[i]; + if (char === "\\") { + i++; + continue; + } + if (char === '"') { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; + } + if (inQuotes) { + continue; + } + if (char === "," || char === "}") { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; + } + } + return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; +} +function parsePgNestedArray(arrayString, startFrom = 0) { + const result = []; + let i = startFrom; + let lastCharIsComma = false; + while (i < arrayString.length) { + const char = arrayString[i]; + if (char === ",") { + if (lastCharIsComma || i === startFrom) { + result.push(""); + } + lastCharIsComma = true; + i++; + continue; + } + lastCharIsComma = false; + if (char === "\\") { + i += 2; + continue; + } + if (char === '"') { + const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true); + result.push(value2); + i = startFrom2; + continue; + } + if (char === "}") { + return [result, i + 1]; + } + if (char === "{") { + const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1); + result.push(value2); + i = startFrom2; + continue; + } + const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false); + result.push(value); + i = newStartFrom; + } + return [result, i]; +} +function parsePgArray(arrayString) { + const [result] = parsePgNestedArray(arrayString, 1); + return result; +} +function makePgArray(array2) { + return `{${array2.map((item) => { + if (Array.isArray(item)) { + return makePgArray(item); + } + if (typeof item === "string") { + return `"${item.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`; + } + return `${item}`; + }).join(",")}}`; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/common.js +class PgColumnBuilder extends ColumnBuilder { + foreignKeyConfigs = []; + static [entityKind] = "PgColumnBuilder"; + array(size) { + return new PgArrayBuilder(this.config.name, this, size); + } + references(ref, actions = {}) { + this.foreignKeyConfigs.push({ ref, actions }); + return this; + } + unique(name, config) { + this.config.isUnique = true; + this.config.uniqueName = name; + this.config.uniqueType = config?.nulls; + return this; + } + generatedAlwaysAs(as) { + this.config.generated = { + as, + type: "always", + mode: "stored" + }; + return this; + } + buildForeignKeys(column, table) { + return this.foreignKeyConfigs.map(({ ref, actions }) => { + return iife((ref2, actions2) => { + const builder = new ForeignKeyBuilder(() => { + const foreignColumn = ref2(); + return { columns: [column], foreignColumns: [foreignColumn] }; + }); + if (actions2.onUpdate) { + builder.onUpdate(actions2.onUpdate); + } + if (actions2.onDelete) { + builder.onDelete(actions2.onDelete); + } + return builder.build(table); + }, ref, actions); + }); + } + buildExtraConfigColumn(table) { + return new ExtraConfigColumn(table, this.config); + } +} + +class PgColumn extends Column { + constructor(table, config) { + if (!config.uniqueName) { + config.uniqueName = uniqueKeyName(table, [config.name]); + } + super(table, config); + this.table = table; + } + static [entityKind] = "PgColumn"; +} + +class ExtraConfigColumn extends PgColumn { + static [entityKind] = "ExtraConfigColumn"; + getSQLType() { + return this.getSQLType(); + } + indexConfig = { + order: this.config.order ?? "asc", + nulls: this.config.nulls ?? "last", + opClass: this.config.opClass + }; + defaultConfig = { + order: "asc", + nulls: "last", + opClass: undefined + }; + asc() { + this.indexConfig.order = "asc"; + return this; + } + desc() { + this.indexConfig.order = "desc"; + return this; + } + nullsFirst() { + this.indexConfig.nulls = "first"; + return this; + } + nullsLast() { + this.indexConfig.nulls = "last"; + return this; + } + op(opClass) { + this.indexConfig.opClass = opClass; + return this; + } +} + +class IndexedColumn { + static [entityKind] = "IndexedColumn"; + constructor(name, keyAsName, type, indexConfig) { + this.name = name; + this.keyAsName = keyAsName; + this.type = type; + this.indexConfig = indexConfig; + } + name; + keyAsName; + type; + indexConfig; +} + +class PgArrayBuilder extends PgColumnBuilder { + static [entityKind] = "PgArrayBuilder"; + constructor(name, baseBuilder, size) { + super(name, "array", "PgArray"); + this.config.baseBuilder = baseBuilder; + this.config.size = size; + } + build(table) { + const baseColumn = this.config.baseBuilder.build(table); + return new PgArray(table, this.config, baseColumn); + } +} + +class PgArray extends PgColumn { + constructor(table, config, baseColumn, range) { + super(table, config); + this.baseColumn = baseColumn; + this.range = range; + this.size = config.size; + } + size; + static [entityKind] = "PgArray"; + getSQLType() { + return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + value = parsePgArray(value); + } + return value.map((v) => this.baseColumn.mapFromDriverValue(v)); + } + mapToDriverValue(value, isNestedArray = false) { + const a = value.map((v) => v === null ? null : is(this.baseColumn, PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)); + if (isNestedArray) + return a; + return makePgArray(a); + } +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/enum.js +class PgEnumObjectColumnBuilder extends PgColumnBuilder { + static [entityKind] = "PgEnumObjectColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumObjectColumn"); + this.config.enum = enumInstance; + } + build(table) { + return new PgEnumObjectColumn(table, this.config); + } +} + +class PgEnumObjectColumn extends PgColumn { + static [entityKind] = "PgEnumObjectColumn"; + enum; + enumValues = this.config.enum.enumValues; + constructor(table, config) { + super(table, config); + this.enum = config.enum; + } + getSQLType() { + return this.enum.enumName; + } +} +var isPgEnumSym = Symbol.for("drizzle:isPgEnum"); +function isPgEnum(obj) { + return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; +} + +class PgEnumColumnBuilder extends PgColumnBuilder { + static [entityKind] = "PgEnumColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumColumn"); + this.config.enum = enumInstance; + } + build(table) { + return new PgEnumColumn(table, this.config); + } +} + +class PgEnumColumn extends PgColumn { + static [entityKind] = "PgEnumColumn"; + enum = this.config.enum; + enumValues = this.config.enum.enumValues; + constructor(table, config) { + super(table, config); + this.enum = config.enum; + } + getSQLType() { + return this.enum.enumName; + } +} +function pgEnum(enumName, input) { + return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], undefined) : pgEnumObjectWithSchema(enumName, input, undefined); +} +function pgEnumWithSchema(enumName, values, schema) { + const enumInstance = Object.assign((name) => new PgEnumColumnBuilder(name ?? "", enumInstance), { + enumName, + enumValues: values, + schema, + [isPgEnumSym]: true + }); + return enumInstance; +} +function pgEnumObjectWithSchema(enumName, values, schema) { + const enumInstance = Object.assign((name) => new PgEnumObjectColumnBuilder(name ?? "", enumInstance), { + enumName, + enumValues: Object.values(values), + schema, + [isPgEnumSym]: true + }); + return enumInstance; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/subquery.js +class Subquery { + static [entityKind] = "Subquery"; + constructor(sql, fields, alias, isWith = false, usedTables = []) { + this._ = { + brand: "Subquery", + sql, + selectedFields: fields, + alias, + isWith, + usedTables + }; + } +} + +class WithSubquery extends Subquery { + static [entityKind] = "WithSubquery"; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/version.js +var version = "0.44.7"; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing.js +var otel; +var rawTracer; +var tracer = { + startActiveSpan(name, fn) { + if (!otel) { + return fn(); + } + if (!rawTracer) { + rawTracer = otel.trace.getTracer("drizzle-orm", version); + } + return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => { + try { + return fn(span); + } catch (e2) { + span.setStatus({ + code: otel2.SpanStatusCode.ERROR, + message: e2 instanceof Error ? e2.message : "Unknown error" + }); + throw e2; + } finally { + span.end(); + } + }), otel, rawTracer); + } +}; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/view-common.js +var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig"); + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.js +var Schema2 = Symbol.for("drizzle:Schema"); +var Columns = Symbol.for("drizzle:Columns"); +var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns"); +var OriginalName = Symbol.for("drizzle:OriginalName"); +var BaseName = Symbol.for("drizzle:BaseName"); +var IsAlias = Symbol.for("drizzle:IsAlias"); +var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder"); +var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable"); + +class Table { + static [entityKind] = "Table"; + static Symbol = { + Name: TableName, + Schema: Schema2, + OriginalName, + Columns, + ExtraConfigColumns, + BaseName, + IsAlias, + ExtraConfigBuilder + }; + [TableName]; + [OriginalName]; + [Schema2]; + [Columns]; + [ExtraConfigColumns]; + [BaseName]; + [IsAlias] = false; + [IsDrizzleTable] = true; + [ExtraConfigBuilder] = undefined; + constructor(name, schema, baseName) { + this[TableName] = this[OriginalName] = name; + this[Schema2] = schema; + this[BaseName] = baseName; + } +} +function getTableName(table) { + return table[TableName]; +} +function getTableUniqueName(table) { + return `${table[Schema2] ?? "public"}.${table[TableName]}`; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/sql.js +function isSQLWrapper(value) { + return value !== null && value !== undefined && typeof value.getSQL === "function"; +} +function mergeQueries(queries) { + const result = { sql: "", params: [] }; + for (const query of queries) { + result.sql += query.sql; + result.params.push(...query.params); + if (query.typings?.length) { + if (!result.typings) { + result.typings = []; + } + result.typings.push(...query.typings); + } + } + return result; +} + +class StringChunk { + static [entityKind] = "StringChunk"; + value; + constructor(value) { + this.value = Array.isArray(value) ? value : [value]; + } + getSQL() { + return new SQL([this]); + } +} + +class SQL { + constructor(queryChunks) { + this.queryChunks = queryChunks; + for (const chunk of queryChunks) { + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]); + } + } + } + static [entityKind] = "SQL"; + decoder = noopDecoder; + shouldInlineParams = false; + usedTables = []; + append(query) { + this.queryChunks.push(...query.queryChunks); + return this; + } + toQuery(config) { + return tracer.startActiveSpan("drizzle.buildSQL", (span) => { + const query = this.buildQueryFromSourceParams(this.queryChunks, config); + span?.setAttributes({ + "drizzle.query.text": query.sql, + "drizzle.query.params": JSON.stringify(query.params) + }); + return query; + }); + } + buildQueryFromSourceParams(chunks, _config) { + const config = Object.assign({}, _config, { + inlineParams: _config.inlineParams || this.shouldInlineParams, + paramStartIndex: _config.paramStartIndex || { value: 0 } + }); + const { + casing, + escapeName, + escapeParam, + prepareTyping, + inlineParams, + paramStartIndex + } = config; + return mergeQueries(chunks.map((chunk) => { + if (is(chunk, StringChunk)) { + return { sql: chunk.value.join(""), params: [] }; + } + if (is(chunk, Name)) { + return { sql: escapeName(chunk.value), params: [] }; + } + if (chunk === undefined) { + return { sql: "", params: [] }; + } + if (Array.isArray(chunk)) { + const result = [new StringChunk("(")]; + for (const [i, p] of chunk.entries()) { + result.push(p); + if (i < chunk.length - 1) { + result.push(new StringChunk(", ")); + } + } + result.push(new StringChunk(")")); + return this.buildQueryFromSourceParams(result, config); + } + if (is(chunk, SQL)) { + return this.buildQueryFromSourceParams(chunk.queryChunks, { + ...config, + inlineParams: inlineParams || chunk.shouldInlineParams + }); + } + if (is(chunk, Table)) { + const schemaName = chunk[Table.Symbol.Schema]; + const tableName = chunk[Table.Symbol.Name]; + return { + sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), + params: [] + }; + } + if (is(chunk, Column)) { + const columnName = casing.getColumnCasing(chunk); + if (_config.invokeSource === "indexes") { + return { sql: escapeName(columnName), params: [] }; + } + const schemaName = chunk.table[Table.Symbol.Schema]; + return { + sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), + params: [] + }; + } + if (is(chunk, View)) { + const schemaName = chunk[ViewBaseConfig].schema; + const viewName = chunk[ViewBaseConfig].name; + return { + sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), + params: [] + }; + } + if (is(chunk, Param)) { + if (is(chunk.value, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); + if (is(mappedValue, SQL)) { + return this.buildQueryFromSourceParams([mappedValue], config); + } + if (inlineParams) { + return { sql: this.mapInlineParam(mappedValue, config), params: [] }; + } + let typings = ["none"]; + if (prepareTyping) { + typings = [prepareTyping(chunk.encoder)]; + } + return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; + } + if (is(chunk, Placeholder)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + } + if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) { + return { sql: escapeName(chunk.fieldAlias), params: [] }; + } + if (is(chunk, Subquery)) { + if (chunk._.isWith) { + return { sql: escapeName(chunk._.alias), params: [] }; + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk._.sql, + new StringChunk(") "), + new Name(chunk._.alias) + ], config); + } + if (isPgEnum(chunk)) { + if (chunk.schema) { + return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; + } + return { sql: escapeName(chunk.enumName), params: [] }; + } + if (isSQLWrapper(chunk)) { + if (chunk.shouldOmitSQLParens?.()) { + return this.buildQueryFromSourceParams([chunk.getSQL()], config); + } + return this.buildQueryFromSourceParams([ + new StringChunk("("), + chunk.getSQL(), + new StringChunk(")") + ], config); + } + if (inlineParams) { + return { sql: this.mapInlineParam(chunk, config), params: [] }; + } + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + })); + } + mapInlineParam(chunk, { escapeString }) { + if (chunk === null) { + return "null"; + } + if (typeof chunk === "number" || typeof chunk === "boolean") { + return chunk.toString(); } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var mime = match && db2[match[1].toLowerCase()]; - if (mime && mime.charset) { - return mime.charset; + if (typeof chunk === "string") { + return escapeString(chunk); } - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return "UTF-8"; + if (typeof chunk === "object") { + const mappedValueAsString = chunk.toString(); + if (mappedValueAsString === "[object Object]") { + return escapeString(JSON.stringify(chunk)); + } + return escapeString(mappedValueAsString); } - return false; + throw new Error("Unexpected param value: " + chunk); } - function contentType(str) { - if (!str || typeof str !== "string") { - return false; - } - var mime = str.indexOf("/") === -1 ? exports.lookup(str) : str; - if (!mime) { - return false; + getSQL() { + return this; + } + as(alias) { + if (alias === undefined) { + return this; } - if (mime.indexOf("charset") === -1) { - var charset2 = exports.charset(mime); - if (charset2) - mime += "; charset=" + charset2.toLowerCase(); + return new SQL.Aliased(this, alias); + } + mapWith(decoder) { + this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder; + return this; + } + inlineParams() { + this.shouldInlineParams = true; + return this; + } + if(condition) { + return condition ? this : undefined; + } +} + +class Name { + constructor(value) { + this.value = value; + } + static [entityKind] = "Name"; + brand; + getSQL() { + return new SQL([this]); + } +} +function isDriverValueEncoder(value) { + return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; +} +var noopDecoder = { + mapFromDriverValue: (value) => value +}; +var noopEncoder = { + mapToDriverValue: (value) => value +}; +var noopMapper = { + ...noopDecoder, + ...noopEncoder +}; + +class Param { + constructor(value, encoder = noopEncoder) { + this.value = value; + this.encoder = encoder; + } + static [entityKind] = "Param"; + brand; + getSQL() { + return new SQL([this]); + } +} +function sql(strings, ...params) { + const queryChunks = []; + if (params.length > 0 || strings.length > 0 && strings[0] !== "") { + queryChunks.push(new StringChunk(strings[0])); + } + for (const [paramIndex, param2] of params.entries()) { + queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); + } + return new SQL(queryChunks); +} +((sql2) => { + function empty() { + return new SQL([]); + } + sql2.empty = empty; + function fromList(list) { + return new SQL(list); + } + sql2.fromList = fromList; + function raw(str) { + return new SQL([new StringChunk(str)]); + } + sql2.raw = raw; + function join2(chunks, separator) { + const result = []; + for (const [i, chunk] of chunks.entries()) { + if (i > 0 && separator !== undefined) { + result.push(separator); + } + result.push(chunk); } - return mime; + return new SQL(result); } - function extension(type) { - if (!type || typeof type !== "string") { - return false; + sql2.join = join2; + function identifier(value) { + return new Name(value); + } + sql2.identifier = identifier; + function placeholder2(name2) { + return new Placeholder(name2); + } + sql2.placeholder = placeholder2; + function param2(value, encoder) { + return new Param(value, encoder); + } + sql2.param = param2; +})(sql || (sql = {})); +((SQL2) => { + + class Aliased { + constructor(sql2, fieldAlias) { + this.sql = sql2; + this.fieldAlias = fieldAlias; } - var match = EXTRACT_TYPE_REGEXP.exec(type); - var exts = match && exports.extensions[match[1].toLowerCase()]; - if (!exts || !exts.length) { - return false; + static [entityKind] = "SQL.Aliased"; + isSelectionField = false; + getSQL() { + return this.sql; + } + clone() { + return new Aliased(this.sql, this.fieldAlias); } - return exts[0]; } - function lookup(path2) { - if (!path2 || typeof path2 !== "string") { - return false; + SQL2.Aliased = Aliased; +})(SQL || (SQL = {})); + +class Placeholder { + constructor(name2) { + this.name = name2; + } + static [entityKind] = "Placeholder"; + getSQL() { + return new SQL([this]); + } +} +function fillPlaceholders(params, values) { + return params.map((p) => { + if (is(p, Placeholder)) { + if (!(p.name in values)) { + throw new Error(`No value for placeholder "${p.name}" was provided`); + } + return values[p.name]; } - var extension2 = extname("x." + path2).toLowerCase().substr(1); - if (!extension2) { - return false; + if (is(p, Param) && is(p.value, Placeholder)) { + if (!(p.value.name in values)) { + throw new Error(`No value for placeholder "${p.value.name}" was provided`); + } + return p.encoder.mapToDriverValue(values[p.value.name]); } - return exports.types[extension2] || false; + return p; + }); +} +var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView"); + +class View { + static [entityKind] = "View"; + [ViewBaseConfig]; + [IsDrizzleView] = true; + constructor({ name: name2, schema, selectedFields, query }) { + this[ViewBaseConfig] = { + name: name2, + originalName: name2, + schema, + selectedFields, + query, + isExisting: !query, + isAlias: false + }; } - function populateMaps(extensions, types6) { - var preference = ["nginx", "apache", undefined, "iana"]; - Object.keys(db2).forEach(function forEachMimeType(type) { - var mime = db2[type]; - var exts = mime.extensions; - if (!exts || !exts.length) { - return; + getSQL() { + return new SQL([this]); + } +} +Column.prototype.getSQL = function() { + return new SQL([this]); +}; +Table.prototype.getSQL = function() { + return new SQL([this]); +}; +Subquery.prototype.getSQL = function() { + return new SQL([this]); +}; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/alias.js +class ColumnAliasProxyHandler { + constructor(table) { + this.table = table; + } + static [entityKind] = "ColumnAliasProxyHandler"; + get(columnObj, prop) { + if (prop === "table") { + return this.table; + } + return columnObj[prop]; + } +} + +class TableAliasProxyHandler { + constructor(alias, replaceOriginalName) { + this.alias = alias; + this.replaceOriginalName = replaceOriginalName; + } + static [entityKind] = "TableAliasProxyHandler"; + get(target, prop) { + if (prop === Table.Symbol.IsAlias) { + return true; + } + if (prop === Table.Symbol.Name) { + return this.alias; + } + if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { + return this.alias; + } + if (prop === ViewBaseConfig) { + return { + ...target[ViewBaseConfig], + name: this.alias, + isAlias: true + }; + } + if (prop === Table.Symbol.Columns) { + const columns = target[Table.Symbol.Columns]; + if (!columns) { + return columns; } - extensions[type] = exts; - for (var i2 = 0;i2 < exts.length; i2++) { - var extension2 = exts[i2]; - if (types6[extension2]) { - var from = preference.indexOf(db2[types6[extension2]].source); - var to = preference.indexOf(mime.source); - if (types6[extension2] !== "application/octet-stream" && (from > to || from === to && types6[extension2].substr(0, 12) === "application/")) { - continue; + const proxiedColumns = {}; + Object.keys(columns).map((key) => { + proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this))); + }); + return proxiedColumns; + } + const value = target[prop]; + if (is(value, Column)) { + return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); + } + return value; + } +} +function aliasedTable(table, tableAlias) { + return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)); +} +function aliasedTableColumn(column, tableAlias) { + return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false)))); +} +function mapColumnsInAliasedSQLToAlias(query, alias) { + return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); +} +function mapColumnsInSQLToAlias(query, alias) { + return sql.join(query.queryChunks.map((c) => { + if (is(c, Column)) { + return aliasedTableColumn(c, alias); + } + if (is(c, SQL)) { + return mapColumnsInSQLToAlias(c, alias); + } + if (is(c, SQL.Aliased)) { + return mapColumnsInAliasedSQLToAlias(c, alias); + } + return c; + })); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/utils.js +function mapResultRow(columns, row, joinsNotNullableMap) { + const nullifyMap = {}; + const result = columns.reduce((result2, { path, field }, columnIndex) => { + let decoder; + if (is(field, Column)) { + decoder = field; + } else if (is(field, SQL)) { + decoder = field.decoder; + } else { + decoder = field.sql.decoder; + } + let node = result2; + for (const [pathChunkIndex, pathChunk] of path.entries()) { + if (pathChunkIndex < path.length - 1) { + if (!(pathChunk in node)) { + node[pathChunk] = {}; + } + node = node[pathChunk]; + } else { + const rawValue = row[columnIndex]; + const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); + if (joinsNotNullableMap && is(field, Column) && path.length === 2) { + const objectName = path[0]; + if (!(objectName in nullifyMap)) { + nullifyMap[objectName] = value === null ? getTableName(field.table) : false; + } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { + nullifyMap[objectName] = false; } } - types6[extension2] = type; } - }); + } + return result2; + }, {}); + if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { + for (const [objectName, tableName] of Object.entries(nullifyMap)) { + if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { + result[objectName] = null; + } + } } -}); + return result; +} +function orderSelectedFields(fields, pathPrefix) { + return Object.entries(fields).reduce((result, [name, field]) => { + if (typeof name !== "string") { + return result; + } + const newPath = pathPrefix ? [...pathPrefix, name] : [name]; + if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) { + result.push({ path: newPath, field }); + } else if (is(field, Table)) { + result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); + } else { + result.push(...orderSelectedFields(field, newPath)); + } + return result; + }, []); +} +function haveSameKeys(left, right) { + const leftKeys = Object.keys(left); + const rightKeys = Object.keys(right); + if (leftKeys.length !== rightKeys.length) { + return false; + } + for (const [index, key] of leftKeys.entries()) { + if (key !== rightKeys[index]) { + return false; + } + } + return true; +} +function mapUpdateSet(table, values) { + const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => { + if (is(value, SQL) || is(value, Column)) { + return [key, value]; + } else { + return [key, new Param(value, table[Table.Symbol.Columns][key])]; + } + }); + if (entries.length === 0) { + throw new Error("No values to set"); + } + return Object.fromEntries(entries); +} +function applyMixins(baseClass, extendedClasses) { + for (const extendedClass of extendedClasses) { + for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { + if (name === "constructor") + continue; + Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)); + } + } +} +function getTableColumns(table) { + return table[Table.Symbol.Columns]; +} +function getTableLikeName(table) { + return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName]; +} +function getColumnNameAndConfig(a, b) { + return { + name: typeof a === "string" && a.length > 0 ? a : "", + config: typeof a === "object" ? a : b + }; +} +function isConfig(data) { + if (typeof data !== "object" || data === null) + return false; + if (data.constructor.name !== "Object") + return false; + if ("logger" in data) { + const type = typeof data["logger"]; + if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") + return false; + return true; + } + if ("schema" in data) { + const type = typeof data["schema"]; + if (type !== "object" && type !== "undefined") + return false; + return true; + } + if ("casing" in data) { + const type = typeof data["casing"]; + if (type !== "string" && type !== "undefined") + return false; + return true; + } + if ("mode" in data) { + if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined) + return false; + return true; + } + if ("connection" in data) { + const type = typeof data["connection"]; + if (type !== "string" && type !== "object" && type !== "undefined") + return false; + return true; + } + if ("client" in data) { + const type = typeof data["client"]; + if (type !== "object" && type !== "function" && type !== "undefined") + return false; + return true; + } + if (Object.keys(data).length === 0) + return true; + return false; +} +var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder; -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/defer.js -var require_defer = __commonJS((exports, module) => { - module.exports = defer; - function defer(fn) { - var nextTick2 = typeof setImmediate == "function" ? setImmediate : typeof process == "object" && typeof process.nextTick == "function" ? process.nextTick : null; - if (nextTick2) { - nextTick2(fn); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/int.common.js +class PgIntColumnBaseBuilder extends PgColumnBuilder { + static [entityKind] = "PgIntColumnBaseBuilder"; + generatedAlwaysAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "always", + sequenceName: name, + sequenceOptions: options + }; } else { - setTimeout(fn, 0); + this.config.generatedIdentity = { + type: "always" + }; } + this.config.hasDefault = true; + this.config.notNull = true; + return this; } -}); + generatedByDefaultAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "byDefault", + sequenceName: name, + sequenceOptions: options + }; + } else { + this.config.generatedIdentity = { + type: "byDefault" + }; + } + this.config.hasDefault = true; + this.config.notNull = true; + return this; + } +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/async.js -var require_async = __commonJS((exports, module) => { - var defer = require_defer(); - module.exports = async; - function async(callback) { - var isAsync = false; - defer(function() { - isAsync = true; - }); - return function async_callback(err, result) { - if (isAsync) { - callback(err, result); - } else { - defer(function nextTick_callback() { - callback(err, result); - }); - } - }; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigint.js +class PgBigInt53Builder extends PgIntColumnBaseBuilder { + static [entityKind] = "PgBigInt53Builder"; + constructor(name) { + super(name, "number", "PgBigInt53"); } -}); + build(table) { + return new PgBigInt53(table, this.config); + } +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/abort.js -var require_abort = __commonJS((exports, module) => { - module.exports = abort; - function abort(state) { - Object.keys(state.jobs).forEach(clean3.bind(state)); - state.jobs = {}; +class PgBigInt53 extends PgColumn { + static [entityKind] = "PgBigInt53"; + getSQLType() { + return "bigint"; } - function clean3(key) { - if (typeof this.jobs[key] == "function") { - this.jobs[key](); + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; } + return Number(value); } -}); +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/iterate.js -var require_iterate = __commonJS((exports, module) => { - var async = require_async(); - var abort = require_abort(); - module.exports = iterate; - function iterate(list, iterator2, state, callback) { - var key = state["keyedList"] ? state["keyedList"][state.index] : state.index; - state.jobs[key] = runJob(iterator2, key, list[key], function(error, output) { - if (!(key in state.jobs)) { - return; +class PgBigInt64Builder extends PgIntColumnBaseBuilder { + static [entityKind] = "PgBigInt64Builder"; + constructor(name) { + super(name, "bigint", "PgBigInt64"); + } + build(table) { + return new PgBigInt64(table, this.config); + } +} + +class PgBigInt64 extends PgColumn { + static [entityKind] = "PgBigInt64"; + getSQLType() { + return "bigint"; + } + mapFromDriverValue(value) { + return BigInt(value); + } +} +function bigint(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + if (config.mode === "number") { + return new PgBigInt53Builder(name); + } + return new PgBigInt64Builder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigserial.js +class PgBigSerial53Builder extends PgColumnBuilder { + static [entityKind] = "PgBigSerial53Builder"; + constructor(name) { + super(name, "number", "PgBigSerial53"); + this.config.hasDefault = true; + this.config.notNull = true; + } + build(table) { + return new PgBigSerial53(table, this.config); + } +} + +class PgBigSerial53 extends PgColumn { + static [entityKind] = "PgBigSerial53"; + getSQLType() { + return "bigserial"; + } + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; + } + return Number(value); + } +} + +class PgBigSerial64Builder extends PgColumnBuilder { + static [entityKind] = "PgBigSerial64Builder"; + constructor(name) { + super(name, "bigint", "PgBigSerial64"); + this.config.hasDefault = true; + } + build(table) { + return new PgBigSerial64(table, this.config); + } +} + +class PgBigSerial64 extends PgColumn { + static [entityKind] = "PgBigSerial64"; + getSQLType() { + return "bigserial"; + } + mapFromDriverValue(value) { + return BigInt(value); + } +} +function bigserial(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + if (config.mode === "number") { + return new PgBigSerial53Builder(name); + } + return new PgBigSerial64Builder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/boolean.js +class PgBooleanBuilder extends PgColumnBuilder { + static [entityKind] = "PgBooleanBuilder"; + constructor(name) { + super(name, "boolean", "PgBoolean"); + } + build(table) { + return new PgBoolean(table, this.config); + } +} + +class PgBoolean extends PgColumn { + static [entityKind] = "PgBoolean"; + getSQLType() { + return "boolean"; + } +} +function boolean2(name) { + return new PgBooleanBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/char.js +class PgCharBuilder extends PgColumnBuilder { + static [entityKind] = "PgCharBuilder"; + constructor(name, config) { + super(name, "string", "PgChar"); + this.config.length = config.length; + this.config.enumValues = config.enum; + } + build(table) { + return new PgChar(table, this.config); + } +} + +class PgChar extends PgColumn { + static [entityKind] = "PgChar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === undefined ? `char` : `char(${this.length})`; + } +} +function char(a, b = {}) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgCharBuilder(name, config); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/cidr.js +class PgCidrBuilder extends PgColumnBuilder { + static [entityKind] = "PgCidrBuilder"; + constructor(name) { + super(name, "string", "PgCidr"); + } + build(table) { + return new PgCidr(table, this.config); + } +} + +class PgCidr extends PgColumn { + static [entityKind] = "PgCidr"; + getSQLType() { + return "cidr"; + } +} +function cidr(name) { + return new PgCidrBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/custom.js +class PgCustomColumnBuilder extends PgColumnBuilder { + static [entityKind] = "PgCustomColumnBuilder"; + constructor(name, fieldConfig, customTypeParams) { + super(name, "custom", "PgCustomColumn"); + this.config.fieldConfig = fieldConfig; + this.config.customTypeParams = customTypeParams; + } + build(table) { + return new PgCustomColumn(table, this.config); + } +} + +class PgCustomColumn extends PgColumn { + static [entityKind] = "PgCustomColumn"; + sqlName; + mapTo; + mapFrom; + constructor(table, config) { + super(table, config); + this.sqlName = config.customTypeParams.dataType(config.fieldConfig); + this.mapTo = config.customTypeParams.toDriver; + this.mapFrom = config.customTypeParams.fromDriver; + } + getSQLType() { + return this.sqlName; + } + mapFromDriverValue(value) { + return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; + } + mapToDriverValue(value) { + return typeof this.mapTo === "function" ? this.mapTo(value) : value; + } +} +function customType(customTypeParams) { + return (a, b) => { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgCustomColumnBuilder(name, config, customTypeParams); + }; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.common.js +class PgDateColumnBaseBuilder extends PgColumnBuilder { + static [entityKind] = "PgDateColumnBaseBuilder"; + defaultNow() { + return this.default(sql`now()`); + } +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.js +class PgDateBuilder extends PgDateColumnBaseBuilder { + static [entityKind] = "PgDateBuilder"; + constructor(name) { + super(name, "date", "PgDate"); + } + build(table) { + return new PgDate(table, this.config); + } +} + +class PgDate extends PgColumn { + static [entityKind] = "PgDate"; + getSQLType() { + return "date"; + } + mapFromDriverValue(value) { + return new Date(value); + } + mapToDriverValue(value) { + return value.toISOString(); + } +} + +class PgDateStringBuilder extends PgDateColumnBaseBuilder { + static [entityKind] = "PgDateStringBuilder"; + constructor(name) { + super(name, "string", "PgDateString"); + } + build(table) { + return new PgDateString(table, this.config); + } +} + +class PgDateString extends PgColumn { + static [entityKind] = "PgDateString"; + getSQLType() { + return "date"; + } +} +function date2(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + if (config?.mode === "date") { + return new PgDateBuilder(name); + } + return new PgDateStringBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/double-precision.js +class PgDoublePrecisionBuilder extends PgColumnBuilder { + static [entityKind] = "PgDoublePrecisionBuilder"; + constructor(name) { + super(name, "number", "PgDoublePrecision"); + } + build(table) { + return new PgDoublePrecision(table, this.config); + } +} + +class PgDoublePrecision extends PgColumn { + static [entityKind] = "PgDoublePrecision"; + getSQLType() { + return "double precision"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseFloat(value); + } + return value; + } +} +function doublePrecision(name) { + return new PgDoublePrecisionBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/inet.js +class PgInetBuilder extends PgColumnBuilder { + static [entityKind] = "PgInetBuilder"; + constructor(name) { + super(name, "string", "PgInet"); + } + build(table) { + return new PgInet(table, this.config); + } +} + +class PgInet extends PgColumn { + static [entityKind] = "PgInet"; + getSQLType() { + return "inet"; + } +} +function inet(name) { + return new PgInetBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/integer.js +class PgIntegerBuilder extends PgIntColumnBaseBuilder { + static [entityKind] = "PgIntegerBuilder"; + constructor(name) { + super(name, "number", "PgInteger"); + } + build(table) { + return new PgInteger(table, this.config); + } +} + +class PgInteger extends PgColumn { + static [entityKind] = "PgInteger"; + getSQLType() { + return "integer"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseInt(value); + } + return value; + } +} +function integer(name) { + return new PgIntegerBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/interval.js +class PgIntervalBuilder extends PgColumnBuilder { + static [entityKind] = "PgIntervalBuilder"; + constructor(name, intervalConfig) { + super(name, "string", "PgInterval"); + this.config.intervalConfig = intervalConfig; + } + build(table) { + return new PgInterval(table, this.config); + } +} + +class PgInterval extends PgColumn { + static [entityKind] = "PgInterval"; + fields = this.config.intervalConfig.fields; + precision = this.config.intervalConfig.precision; + getSQLType() { + const fields = this.fields ? ` ${this.fields}` : ""; + const precision = this.precision ? `(${this.precision})` : ""; + return `interval${fields}${precision}`; + } +} +function interval(a, b = {}) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgIntervalBuilder(name, config); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/json.js +class PgJsonBuilder extends PgColumnBuilder { + static [entityKind] = "PgJsonBuilder"; + constructor(name) { + super(name, "json", "PgJson"); + } + build(table) { + return new PgJson(table, this.config); + } +} + +class PgJson extends PgColumn { + static [entityKind] = "PgJson"; + constructor(table, config) { + super(table, config); + } + getSQLType() { + return "json"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; } - delete state.jobs[key]; - if (error) { - abort(state); - } else { - state.results[key] = output; + } + return value; + } +} +function json(name) { + return new PgJsonBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/jsonb.js +class PgJsonbBuilder extends PgColumnBuilder { + static [entityKind] = "PgJsonbBuilder"; + constructor(name) { + super(name, "json", "PgJsonb"); + } + build(table) { + return new PgJsonb(table, this.config); + } +} + +class PgJsonb extends PgColumn { + static [entityKind] = "PgJsonb"; + constructor(table, config) { + super(table, config); + } + getSQLType() { + return "jsonb"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; } - callback(error, state.results); - }); - } - function runJob(iterator2, key, item, callback) { - var aborter; - if (iterator2.length == 2) { - aborter = iterator2(item, async(callback)); - } else { - aborter = iterator2(item, key, async(callback)); } - return aborter; + return value; } -}); +} +function jsonb(name) { + return new PgJsonbBuilder(name ?? ""); +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/state.js -var require_state2 = __commonJS((exports, module) => { - module.exports = state; - function state(list, sortMethod) { - var isNamedList = !Array.isArray(list), initState = { - index: 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs: {}, - results: isNamedList ? {} : [], - size: isNamedList ? Object.keys(list).length : list.length - }; - if (sortMethod) { - initState.keyedList.sort(isNamedList ? sortMethod : function(a2, b2) { - return sortMethod(list[a2], list[b2]); - }); - } - return initState; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/line.js +class PgLineBuilder extends PgColumnBuilder { + static [entityKind] = "PgLineBuilder"; + constructor(name) { + super(name, "array", "PgLine"); } -}); + build(table) { + return new PgLineTuple(table, this.config); + } +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/lib/terminator.js -var require_terminator = __commonJS((exports, module) => { - var abort = require_abort(); - var async = require_async(); - module.exports = terminator; - function terminator(callback) { - if (!Object.keys(this.jobs).length) { - return; - } - this.index = this.size; - abort(this); - async(callback)(null, this.results); +class PgLineTuple extends PgColumn { + static [entityKind] = "PgLine"; + getSQLType() { + return "line"; } -}); + mapFromDriverValue(value) { + const [a, b, c] = value.slice(1, -1).split(","); + return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)]; + } + mapToDriverValue(value) { + return `{${value[0]},${value[1]},${value[2]}}`; + } +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/parallel.js -var require_parallel2 = __commonJS((exports, module) => { - var iterate = require_iterate(); - var initState = require_state2(); - var terminator = require_terminator(); - module.exports = parallel; - function parallel(list, iterator2, callback) { - var state = initState(list); - while (state.index < (state["keyedList"] || list).length) { - iterate(list, iterator2, state, function(error, result) { - if (error) { - callback(error, result); - return; - } - if (Object.keys(state.jobs).length === 0) { - callback(null, state.results); - return; - } - }); - state.index++; - } - return terminator.bind(state, callback); +class PgLineABCBuilder extends PgColumnBuilder { + static [entityKind] = "PgLineABCBuilder"; + constructor(name) { + super(name, "json", "PgLineABC"); } -}); + build(table) { + return new PgLineABC(table, this.config); + } +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/serialOrdered.js -var require_serialOrdered = __commonJS((exports, module) => { - var iterate = require_iterate(); - var initState = require_state2(); - var terminator = require_terminator(); - module.exports = serialOrdered; - module.exports.ascending = ascending; - module.exports.descending = descending; - function serialOrdered(list, iterator2, sortMethod, callback) { - var state = initState(list, sortMethod); - iterate(list, iterator2, state, function iteratorHandler(error, result) { - if (error) { - callback(error, result); - return; - } - state.index++; - if (state.index < (state["keyedList"] || list).length) { - iterate(list, iterator2, state, iteratorHandler); - return; - } - callback(null, state.results); - }); - return terminator.bind(state, callback); +class PgLineABC extends PgColumn { + static [entityKind] = "PgLineABC"; + getSQLType() { + return "line"; } - function ascending(a2, b2) { - return a2 < b2 ? -1 : a2 > b2 ? 1 : 0; + mapFromDriverValue(value) { + const [a, b, c] = value.slice(1, -1).split(","); + return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) }; } - function descending(a2, b2) { - return -1 * ascending(a2, b2); + mapToDriverValue(value) { + return `{${value.a},${value.b},${value.c}}`; } -}); +} +function line(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + if (!config?.mode || config.mode === "tuple") { + return new PgLineBuilder(name); + } + return new PgLineABCBuilder(name); +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/serial.js -var require_serial2 = __commonJS((exports, module) => { - var serialOrdered = require_serialOrdered(); - module.exports = serial2; - function serial2(list, iterator2, callback) { - return serialOrdered(list, iterator2, null, callback); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr.js +class PgMacaddrBuilder extends PgColumnBuilder { + static [entityKind] = "PgMacaddrBuilder"; + constructor(name) { + super(name, "string", "PgMacaddr"); } -}); + build(table) { + return new PgMacaddr(table, this.config); + } +} -// node_modules/.pnpm/asynckit@0.4.0/node_modules/asynckit/index.js -var require_asynckit = __commonJS((exports, module) => { - module.exports = { - parallel: require_parallel2(), - serial: require_serial2(), - serialOrdered: require_serialOrdered() - }; -}); +class PgMacaddr extends PgColumn { + static [entityKind] = "PgMacaddr"; + getSQLType() { + return "macaddr"; + } +} +function macaddr(name) { + return new PgMacaddrBuilder(name ?? ""); +} -// node_modules/.pnpm/has-tostringtag@1.0.2/node_modules/has-tostringtag/shams.js -var require_shams2 = __commonJS((exports, module) => { - var hasSymbols = require_shams(); - module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; - }; -}); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr8.js +class PgMacaddr8Builder extends PgColumnBuilder { + static [entityKind] = "PgMacaddr8Builder"; + constructor(name) { + super(name, "string", "PgMacaddr8"); + } + build(table) { + return new PgMacaddr8(table, this.config); + } +} -// node_modules/.pnpm/es-set-tostringtag@2.1.0/node_modules/es-set-tostringtag/index.js -var require_es_set_tostringtag = __commonJS((exports, module) => { - var GetIntrinsic = require_get_intrinsic(); - var $defineProperty = GetIntrinsic("%Object.defineProperty%", true); - var hasToStringTag = require_shams2()(); - var hasOwn = require_hasown(); - var $TypeError = require_type(); - var toStringTag2 = hasToStringTag ? Symbol.toStringTag : null; - module.exports = function setToStringTag(object2, value) { - var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; - var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; - if (typeof overrideIfSet !== "undefined" && typeof overrideIfSet !== "boolean" || typeof nonConfigurable !== "undefined" && typeof nonConfigurable !== "boolean") { - throw new $TypeError("if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans"); - } - if (toStringTag2 && (overrideIfSet || !hasOwn(object2, toStringTag2))) { - if ($defineProperty) { - $defineProperty(object2, toStringTag2, { - configurable: !nonConfigurable, - enumerable: false, - value, - writable: false - }); - } else { - object2[toStringTag2] = value; - } - } - }; -}); +class PgMacaddr8 extends PgColumn { + static [entityKind] = "PgMacaddr8"; + getSQLType() { + return "macaddr8"; + } +} +function macaddr8(name) { + return new PgMacaddr8Builder(name ?? ""); +} -// node_modules/.pnpm/form-data@4.0.5/node_modules/form-data/lib/populate.js -var require_populate = __commonJS((exports, module) => { - module.exports = function(dst, src) { - Object.keys(src).forEach(function(prop) { - dst[prop] = dst[prop] || src[prop]; - }); - return dst; - }; -}); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/numeric.js +class PgNumericBuilder extends PgColumnBuilder { + static [entityKind] = "PgNumericBuilder"; + constructor(name, precision, scale) { + super(name, "string", "PgNumeric"); + this.config.precision = precision; + this.config.scale = scale; + } + build(table) { + return new PgNumeric(table, this.config); + } +} -// node_modules/.pnpm/form-data@4.0.5/node_modules/form-data/lib/form_data.js -var require_form_data = __commonJS((exports, module) => { - var CombinedStream = require_combined_stream(); - var util = __require("util"); - var path2 = __require("path"); - var http = __require("http"); - var https = __require("https"); - var parseUrl3 = __require("url").parse; - var fs3 = __require("fs"); - var Stream = __require("stream").Stream; - var crypto3 = __require("crypto"); - var mime = require_mime_types3(); - var asynckit = require_asynckit(); - var setToStringTag = require_es_set_tostringtag(); - var hasOwn = require_hasown(); - var populate = require_populate(); - function FormData2(options) { - if (!(this instanceof FormData2)) { - return new FormData2(options); - } - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - CombinedStream.call(this); - options = options || {}; - for (var option in options) { - this[option] = options[option]; - } +class PgNumeric extends PgColumn { + static [entityKind] = "PgNumeric"; + precision; + scale; + constructor(table, config) { + super(table, config); + this.precision = config.precision; + this.scale = config.scale; } - util.inherits(FormData2, CombinedStream); - FormData2.LINE_BREAK = `\r -`; - FormData2.DEFAULT_CONTENT_TYPE = "application/octet-stream"; - FormData2.prototype.append = function(field, value, options) { - options = options || {}; - if (typeof options === "string") { - options = { filename: options }; - } - var append = CombinedStream.prototype.append.bind(this); - if (typeof value === "number" || value == null) { - value = String(value); - } - if (Array.isArray(value)) { - this._error(new Error("Arrays are not supported.")); - return; - } - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - append(header); - append(value); - append(footer); - this._trackLength(header, value, options); - }; - FormData2.prototype._trackLength = function(header, value, options) { - var valueLength = 0; - if (options.knownLength != null) { - valueLength += Number(options.knownLength); - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === "string") { - valueLength = Buffer.byteLength(value); - } - this._valueLength += valueLength; - this._overheadLength += Buffer.byteLength(header) + FormData2.LINE_BREAK.length; - if (!value || !value.path && !(value.readable && hasOwn(value, "httpVersion")) && !(value instanceof Stream)) { - return; - } - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } - }; - FormData2.prototype._lengthRetriever = function(value, callback) { - if (hasOwn(value, "fd")) { - if (value.end != null && value.end != Infinity && value.start != null) { - callback(null, value.end + 1 - (value.start ? value.start : 0)); - } else { - fs3.stat(value.path, function(err, stat) { - if (err) { - callback(err); - return; - } - var fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - } else if (hasOwn(value, "httpVersion")) { - callback(null, Number(value.headers["content-length"])); - } else if (hasOwn(value, "httpModule")) { - value.on("response", function(response) { - value.pause(); - callback(null, Number(response.headers["content-length"])); - }); - value.resume(); - } else { - callback("Unknown stream"); - } - }; - FormData2.prototype._multiPartHeader = function(field, value, options) { - if (typeof options.header === "string") { - return options.header; - } - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - var contents = ""; - var headers = { - "Content-Disposition": ["form-data", 'name="' + field + '"'].concat(contentDisposition || []), - "Content-Type": [].concat(contentType || []) - }; - if (typeof options.header === "object") { - populate(headers, options.header); - } - var header; - for (var prop in headers) { - if (hasOwn(headers, prop)) { - header = headers[prop]; - if (header == null) { - continue; - } - if (!Array.isArray(header)) { - header = [header]; - } - if (header.length) { - contents += prop + ": " + header.join("; ") + FormData2.LINE_BREAK; - } - } - } - return "--" + this.getBoundary() + FormData2.LINE_BREAK + contents + FormData2.LINE_BREAK; - }; - FormData2.prototype._getContentDisposition = function(value, options) { - var filename; - if (typeof options.filepath === "string") { - filename = path2.normalize(options.filepath).replace(/\\/g, "/"); - } else if (options.filename || value && (value.name || value.path)) { - filename = path2.basename(options.filename || value && (value.name || value.path)); - } else if (value && value.readable && hasOwn(value, "httpVersion")) { - filename = path2.basename(value.client._httpMessage.path || ""); - } - if (filename) { - return 'filename="' + filename + '"'; - } - }; - FormData2.prototype._getContentType = function(value, options) { - var contentType = options.contentType; - if (!contentType && value && value.name) { - contentType = mime.lookup(value.name); - } - if (!contentType && value && value.path) { - contentType = mime.lookup(value.path); - } - if (!contentType && value && value.readable && hasOwn(value, "httpVersion")) { - contentType = value.headers["content-type"]; - } - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } - if (!contentType && value && typeof value === "object") { - contentType = FormData2.DEFAULT_CONTENT_TYPE; - } - return contentType; - }; - FormData2.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData2.LINE_BREAK; - var lastPart = this._streams.length === 0; - if (lastPart) { - footer += this._lastBoundary(); - } - next(footer); - }.bind(this); - }; - FormData2.prototype._lastBoundary = function() { - return "--" + this.getBoundary() + "--" + FormData2.LINE_BREAK; - }; - FormData2.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - "content-type": "multipart/form-data; boundary=" + this.getBoundary() - }; - for (header in userHeaders) { - if (hasOwn(userHeaders, header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - return formHeaders; - }; - FormData2.prototype.setBoundary = function(boundary) { - if (typeof boundary !== "string") { - throw new TypeError("FormData boundary must be a string"); - } - this._boundary = boundary; - }; - FormData2.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } - return this._boundary; - }; - FormData2.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc(0); - var boundary = this.getBoundary(); - for (var i2 = 0, len = this._streams.length;i2 < len; i2++) { - if (typeof this._streams[i2] !== "function") { - if (Buffer.isBuffer(this._streams[i2])) { - dataBuffer = Buffer.concat([dataBuffer, this._streams[i2]]); - } else { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i2])]); - } - if (typeof this._streams[i2] !== "string" || this._streams[i2].substring(2, boundary.length + 2) !== boundary) { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData2.LINE_BREAK)]); - } - } - } - return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); - }; - FormData2.prototype._generateBoundary = function() { - this._boundary = "--------------------------" + crypto3.randomBytes(12).toString("hex"); - }; - FormData2.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - if (!this.hasKnownLength()) { - this._error(new Error("Cannot calculate proper length in synchronous way.")); - } - return knownLength; - }; - FormData2.prototype.hasKnownLength = function() { - var hasKnownLength = true; - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - return hasKnownLength; - }; - FormData2.prototype.getLength = function(cb2) { - var knownLength = this._overheadLength + this._valueLength; - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - if (!this._valuesToMeasure.length) { - process.nextTick(cb2.bind(this, null, knownLength)); - return; - } - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb2(err); - return; - } - values.forEach(function(length) { - knownLength += length; - }); - cb2(null, knownLength); - }); - }; - FormData2.prototype.submit = function(params, cb2) { - var request2; - var options; - var defaults2 = { method: "post" }; - if (typeof params === "string") { - params = parseUrl3(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults2); - } else { - options = populate(params, defaults2); - if (!options.port) { - options.port = options.protocol === "https:" ? 443 : 80; - } - } - options.headers = this.getHeaders(params.headers); - if (options.protocol === "https:") { - request2 = https.request(options); + mapFromDriverValue(value) { + if (typeof value === "string") + return value; + return String(value); + } + getSQLType() { + if (this.precision !== undefined && this.scale !== undefined) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === undefined) { + return "numeric"; } else { - request2 = http.request(options); - } - this.getLength(function(err, length) { - if (err && err !== "Unknown stream") { - this._error(err); - return; - } - if (length) { - request2.setHeader("Content-Length", length); - } - this.pipe(request2); - if (cb2) { - var onResponse; - var callback = function(error, responce) { - request2.removeListener("error", callback); - request2.removeListener("response", onResponse); - return cb2.call(this, error, responce); - }; - onResponse = callback.bind(this, null); - request2.on("error", callback); - request2.on("response", onResponse); - } - }.bind(this)); - return request2; - }; - FormData2.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit("error", err); + return `numeric(${this.precision})`; } - }; - FormData2.prototype.toString = function() { - return "[object FormData]"; - }; - setToStringTag(FormData2.prototype, "FormData"); - module.exports = FormData2; -}); + } +} -// node_modules/.pnpm/follow-redirects@1.16.0/node_modules/follow-redirects/debug.js -var require_debug3 = __commonJS((exports, module) => { - var debug; - module.exports = function() { - if (!debug) { - try { - debug = require_src()("follow-redirects"); - } catch (error) {} - if (typeof debug !== "function") { - debug = function() {}; - } - } - debug.apply(null, arguments); - }; -}); +class PgNumericNumberBuilder extends PgColumnBuilder { + static [entityKind] = "PgNumericNumberBuilder"; + constructor(name, precision, scale) { + super(name, "number", "PgNumericNumber"); + this.config.precision = precision; + this.config.scale = scale; + } + build(table) { + return new PgNumericNumber(table, this.config); + } +} -// node_modules/.pnpm/follow-redirects@1.16.0/node_modules/follow-redirects/index.js -var require_follow_redirects = __commonJS((exports, module) => { - var url2 = __require("url"); - var URL2 = url2.URL; - var http = __require("http"); - var https = __require("https"); - var Writable2 = __require("stream").Writable; - var assert = __require("assert"); - var debug = require_debug3(); - (function detectUnsupportedEnvironment() { - var looksLikeNode = typeof process !== "undefined"; - var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction2(Error.captureStackTrace); - if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { - console.warn("The follow-redirects package should be excluded from browser builds."); - } - })(); - var useNativeURL = false; - try { - assert(new URL2("")); - } catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; +class PgNumericNumber extends PgColumn { + static [entityKind] = "PgNumericNumber"; + precision; + scale; + constructor(table, config) { + super(table, config); + this.precision = config.precision; + this.scale = config.scale; } - var sensitiveHeaders = [ - "Authorization", - "Proxy-Authorization", - "Cookie" - ]; - var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash" - ]; - var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; - var eventHandlers = Object.create(null); - events.forEach(function(event) { - eventHandlers[event] = function(arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; - }); - var InvalidUrlError = createErrorType("ERR_INVALID_URL", "Invalid URL", TypeError); - var RedirectionError = createErrorType("ERR_FR_REDIRECTION_FAILURE", "Redirected request failed"); - var TooManyRedirectsError = createErrorType("ERR_FR_TOO_MANY_REDIRECTS", "Maximum number of redirects exceeded", RedirectionError); - var MaxBodyLengthExceededError = createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED", "Request body larger than maxBodyLength limit"); - var WriteAfterEndError = createErrorType("ERR_STREAM_WRITE_AFTER_END", "write after end"); - var destroy = Writable2.prototype.destroy || noop2; - function RedirectableRequest(options, responseCallback) { - Writable2.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - if (responseCallback) { - this.on("response", responseCallback); - } - var self2 = this; - this._onNativeResponse = function(response) { - try { - self2._processResponse(response); - } catch (cause) { - self2.emit("error", cause instanceof RedirectionError ? cause : new RedirectionError({ cause })); - } - }; - this._headerFilter = new RegExp("^(?:" + sensitiveHeaders.concat(options.sensitiveHeaders).map(escapeRegex).join("|") + ")$", "i"); - this._performRequest(); + mapFromDriverValue(value) { + if (typeof value === "number") + return value; + return Number(value); } - RedirectableRequest.prototype = Object.create(Writable2.prototype); - RedirectableRequest.prototype.abort = function() { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); - }; - RedirectableRequest.prototype.destroy = function(error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; - }; - RedirectableRequest.prototype.write = function(data, encoding, callback) { - if (this._ending) { - throw new WriteAfterEndError; - } - if (!isString2(data) && !isBuffer2(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction2(encoding)) { - callback = encoding; - encoding = null; - } - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data, encoding }); - this._currentRequest.write(data, encoding, callback); - } else { - this.emit("error", new MaxBodyLengthExceededError); - this.abort(); - } - }; - RedirectableRequest.prototype.end = function(data, encoding, callback) { - if (isFunction2(data)) { - callback = data; - data = encoding = null; - } else if (isFunction2(encoding)) { - callback = encoding; - encoding = null; - } - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } else { - var self2 = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function() { - self2._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } - }; - RedirectableRequest.prototype.setHeader = function(name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); - }; - RedirectableRequest.prototype.removeHeader = function(name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); - }; - RedirectableRequest.prototype.setTimeout = function(msecs, callback) { - var self2 = this; - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - function startTimer(socket) { - if (self2._timeout) { - clearTimeout(self2._timeout); - } - self2._timeout = setTimeout(function() { - self2.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - function clearTimer() { - if (self2._timeout) { - clearTimeout(self2._timeout); - self2._timeout = null; - } - self2.removeListener("abort", clearTimer); - self2.removeListener("error", clearTimer); - self2.removeListener("response", clearTimer); - self2.removeListener("close", clearTimer); - if (callback) { - self2.removeListener("timeout", callback); - } - if (!self2.socket) { - self2._currentRequest.removeListener("socket", startTimer); - } - } - if (callback) { - this.on("timeout", callback); - } - if (this.socket) { - startTimer(this.socket); + mapToDriverValue = String; + getSQLType() { + if (this.precision !== undefined && this.scale !== undefined) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === undefined) { + return "numeric"; } else { - this._currentRequest.once("socket", startTimer); - } - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - return this; - }; - [ - "flushHeaders", - "getHeader", - "setNoDelay", - "setSocketKeepAlive" - ].forEach(function(method) { - RedirectableRequest.prototype[method] = function(a2, b2) { - return this._currentRequest[method](a2, b2); - }; - }); - ["aborted", "connection", "socket"].forEach(function(property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function() { - return this._currentRequest[property]; - } - }); - }); - RedirectableRequest.prototype._sanitizeOptions = function(options) { - if (!options.headers) { - options.headers = {}; - } - if (!isArray2(options.sensitiveHeaders)) { - options.sensitiveHeaders = []; - } - if (options.host) { - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } - }; - RedirectableRequest.prototype._performRequest = function() { - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } - var request2 = this._currentRequest = nativeProtocol.request(this._options, this._onNativeResponse); - request2._redirectable = this; - for (var event of events) { - request2.on(event, eventHandlers[event]); - } - this._currentUrl = /^\//.test(this._options.path) ? url2.format(this._options) : this._options.path; - if (this._isRedirect) { - var i2 = 0; - var self2 = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - if (request2 === self2._currentRequest) { - if (error) { - self2.emit("error", error); - } else if (i2 < buffers.length) { - var buffer = buffers[i2++]; - if (!request2.finished) { - request2.write(buffer.data, buffer.encoding, writeNext); - } - } else if (self2._ended) { - request2.end(); - } - } - })(); - } - }; - RedirectableRequest.prototype._processResponse = function(response) { - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode - }); - } - var location = response.headers.location; - if (!location || this._options.followRedirects === false || statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - this._requestBodyBuffers = []; - return; - } - destroyRequest(this._currentRequest); - response.destroy(); - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError; - } - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - Host: response.req.getHeader("host") - }, this._options.headers); - } - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || statusCode === 303 && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - var currentUrlParts = parseUrl4(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : url2.format(Object.assign(currentUrlParts, { host: currentHost })); - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - if (redirectUrl.protocol !== currentUrlParts.protocol && redirectUrl.protocol !== "https:" || redirectUrl.host !== currentHost && !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(this._headerFilter, this._options.headers); - } - if (isFunction2(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode - }; - var requestDetails = { - url: currentUrl, - method, - headers: requestHeaders - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); + return `numeric(${this.precision})`; } - this._performRequest(); - }; - function wrap(protocols) { - var exports2 = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024 - }; - var nativeProtocols = {}; - Object.keys(protocols).forEach(function(scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports2[scheme] = Object.create(nativeProtocol); - function request2(input, options, callback) { - if (isURL(input)) { - input = spreadUrlObject(input); - } else if (isString2(input)) { - input = spreadUrlObject(parseUrl4(input)); - } else { - callback = options; - options = validateUrl(input); - input = { protocol }; - } - if (isFunction2(options)) { - callback = options; - options = null; - } - options = Object.assign({ - maxRedirects: exports2.maxRedirects, - maxBodyLength: exports2.maxBodyLength - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString2(options.host) && !isString2(options.hostname)) { - options.hostname = "::1"; - } - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - Object.defineProperties(wrappedProtocol, { - request: { value: request2, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true } - }); - }); - return exports2; } - function noop2() {} - function parseUrl4(input) { - var parsed; - if (useNativeURL) { - parsed = new URL2(input); +} + +class PgNumericBigIntBuilder extends PgColumnBuilder { + static [entityKind] = "PgNumericBigIntBuilder"; + constructor(name, precision, scale) { + super(name, "bigint", "PgNumericBigInt"); + this.config.precision = precision; + this.config.scale = scale; + } + build(table) { + return new PgNumericBigInt(table, this.config); + } +} + +class PgNumericBigInt extends PgColumn { + static [entityKind] = "PgNumericBigInt"; + precision; + scale; + constructor(table, config) { + super(table, config); + this.precision = config.precision; + this.scale = config.scale; + } + mapFromDriverValue = BigInt; + mapToDriverValue = String; + getSQLType() { + if (this.precision !== undefined && this.scale !== undefined) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === undefined) { + return "numeric"; } else { - parsed = validateUrl(url2.parse(input)); - if (!isString2(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } + return `numeric(${this.precision})`; } - return parsed; } - function resolveUrl(relative, base) { - return useNativeURL ? new URL2(relative, base) : parseUrl4(url2.resolve(base, relative)); +} +function numeric(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + const mode = config?.mode; + return mode === "number" ? new PgNumericNumberBuilder(name, config?.precision, config?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder(name, config?.precision, config?.scale) : new PgNumericBuilder(name, config?.precision, config?.scale); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/point.js +class PgPointTupleBuilder extends PgColumnBuilder { + static [entityKind] = "PgPointTupleBuilder"; + constructor(name) { + super(name, "array", "PgPointTuple"); } - function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; + build(table) { + return new PgPointTuple(table, this.config); } - function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - if (spread.port !== "") { - spread.port = Number(spread.port); - } - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - return spread; +} + +class PgPointTuple extends PgColumn { + static [entityKind] = "PgPointTuple"; + getSQLType() { + return "point"; } - function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x, y] = value.slice(1, -1).split(","); + return [Number.parseFloat(x), Number.parseFloat(y)]; } - return lastValue === null || typeof lastValue === "undefined" ? undefined : String(lastValue).trim(); + return [value.x, value.y]; } - function createErrorType(code, message, baseClass) { - function CustomError(properties) { - if (isFunction2(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } - CustomError.prototype = new (baseClass || Error); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false - }, - name: { - value: "Error [" + code + "]", - enumerable: false - } - }); - return CustomError; + mapToDriverValue(value) { + return `(${value[0]},${value[1]})`; } - function destroyRequest(request2, error) { - for (var event of events) { - request2.removeListener(event, eventHandlers[event]); +} + +class PgPointObjectBuilder extends PgColumnBuilder { + static [entityKind] = "PgPointObjectBuilder"; + constructor(name) { + super(name, "json", "PgPointObject"); + } + build(table) { + return new PgPointObject(table, this.config); + } +} + +class PgPointObject extends PgColumn { + static [entityKind] = "PgPointObject"; + getSQLType() { + return "point"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x, y] = value.slice(1, -1).split(","); + return { x: Number.parseFloat(x), y: Number.parseFloat(y) }; } - request2.on("error", noop2); - request2.destroy(error); + return value; } - function isSubdomain(subdomain, domain) { - assert(isString2(subdomain) && isString2(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); + mapToDriverValue(value) { + return `(${value.x},${value.y})`; } - function isArray2(value) { - return value instanceof Array; +} +function point(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + if (!config?.mode || config.mode === "tuple") { + return new PgPointTupleBuilder(name); } - function isString2(value) { - return typeof value === "string" || value instanceof String; + return new PgPointObjectBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js +function hexToBytes(hex) { + const bytes = []; + for (let c = 0;c < hex.length; c += 2) { + bytes.push(Number.parseInt(hex.slice(c, c + 2), 16)); } - function isFunction2(value) { - return typeof value === "function"; + return new Uint8Array(bytes); +} +function bytesToFloat64(bytes, offset) { + const buffer = new ArrayBuffer(8); + const view = new DataView(buffer); + for (let i = 0;i < 8; i++) { + view.setUint8(i, bytes[offset + i]); } - function isBuffer2(value) { - return typeof value === "object" && "length" in value; + return view.getFloat64(0, true); +} +function parseEWKB(hex) { + const bytes = hexToBytes(hex); + let offset = 0; + const byteOrder = bytes[offset]; + offset += 1; + const view = new DataView(bytes.buffer); + const geomType = view.getUint32(offset, byteOrder === 1); + offset += 4; + let _srid; + if (geomType & 536870912) { + _srid = view.getUint32(offset, byteOrder === 1); + offset += 4; } - function isURL(value) { - return URL2 && value instanceof URL2; + if ((geomType & 65535) === 1) { + const x = bytesToFloat64(bytes, offset); + offset += 8; + const y = bytesToFloat64(bytes, offset); + offset += 8; + return [x, y]; } - function escapeRegex(regex) { - return regex.replace(/[\]\\/()*+?.$]/g, "\\$&"); + throw new Error("Unsupported geometry type"); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js +class PgGeometryBuilder extends PgColumnBuilder { + static [entityKind] = "PgGeometryBuilder"; + constructor(name) { + super(name, "array", "PgGeometry"); } - module.exports = wrap({ http, https }); - module.exports.wrap = wrap; -}); + build(table) { + return new PgGeometry(table, this.config); + } +} -// node_modules/.pnpm/cookie-signature@1.0.6/node_modules/cookie-signature/index.js -var require_cookie_signature2 = __commonJS((exports) => { - var crypto4 = __require("crypto"); - exports.sign = function(val, secret) { - if (typeof val != "string") - throw new TypeError("Cookie value must be provided as a string."); - if (typeof secret != "string") - throw new TypeError("Secret string must be provided."); - return val + "." + crypto4.createHmac("sha256", secret).update(val).digest("base64").replace(/\=+$/, ""); - }; - exports.unsign = function(val, secret) { - if (typeof val != "string") - throw new TypeError("Signed cookie string must be provided."); - if (typeof secret != "string") - throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf(".")), mac = exports.sign(str, secret); - return sha1(mac) == sha1(val) ? str : false; - }; - function sha1(str) { - return crypto4.createHash("sha1").update(str).digest("hex"); +class PgGeometry extends PgColumn { + static [entityKind] = "PgGeometry"; + getSQLType() { + return "geometry(point)"; } -}); + mapFromDriverValue(value) { + return parseEWKB(value); + } + mapToDriverValue(value) { + return `point(${value[0]} ${value[1]})`; + } +} -// node_modules/.pnpm/cookie-parser@1.4.7/node_modules/cookie-parser/index.js -var require_cookie_parser = __commonJS((exports, module) => { - /*! - * cookie-parser - * Copyright(c) 2014 TJ Holowaychuk - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - var cookie = require_cookie(); - var signature = require_cookie_signature2(); - module.exports = cookieParser; - module.exports.JSONCookie = JSONCookie; - module.exports.JSONCookies = JSONCookies; - module.exports.signedCookie = signedCookie; - module.exports.signedCookies = signedCookies; - function cookieParser(secret, options) { - var secrets = !secret || Array.isArray(secret) ? secret || [] : [secret]; - return function cookieParser2(req, res, next) { - if (req.cookies) { - return next(); - } - var cookies = req.headers.cookie; - req.secret = secrets[0]; - req.cookies = Object.create(null); - req.signedCookies = Object.create(null); - if (!cookies) { - return next(); - } - req.cookies = cookie.parse(cookies, options); - if (secrets.length !== 0) { - req.signedCookies = signedCookies(req.cookies, secrets); - req.signedCookies = JSONCookies(req.signedCookies); - } - req.cookies = JSONCookies(req.cookies); - next(); - }; +class PgGeometryObjectBuilder extends PgColumnBuilder { + static [entityKind] = "PgGeometryObjectBuilder"; + constructor(name) { + super(name, "json", "PgGeometryObject"); } - function JSONCookie(str) { - if (typeof str !== "string" || str.substr(0, 2) !== "j:") { - return; - } - try { - return JSON.parse(str.slice(2)); - } catch (err) { - return; - } + build(table) { + return new PgGeometryObject(table, this.config); } - function JSONCookies(obj) { - var cookies = Object.keys(obj); - var key; - var val; - for (var i2 = 0;i2 < cookies.length; i2++) { - key = cookies[i2]; - val = JSONCookie(obj[key]); - if (val) { - obj[key] = val; - } - } - return obj; +} + +class PgGeometryObject extends PgColumn { + static [entityKind] = "PgGeometryObject"; + getSQLType() { + return "geometry(point)"; } - function signedCookie(str, secret) { - if (typeof str !== "string") { - return; - } - if (str.substr(0, 2) !== "s:") { - return str; - } - var secrets = !secret || Array.isArray(secret) ? secret || [] : [secret]; - for (var i2 = 0;i2 < secrets.length; i2++) { - var val = signature.unsign(str.slice(2), secrets[i2]); - if (val !== false) { - return val; - } - } - return false; + mapFromDriverValue(value) { + const parsed = parseEWKB(value); + return { x: parsed[0], y: parsed[1] }; } - function signedCookies(obj, secret) { - var cookies = Object.keys(obj); - var dec; - var key; - var ret = Object.create(null); - var val; - for (var i2 = 0;i2 < cookies.length; i2++) { - key = cookies[i2]; - val = obj[key]; - dec = signedCookie(val, secret); - if (val !== dec) { - ret[key] = dec; - delete obj[key]; - } + mapToDriverValue(value) { + return `point(${value.x} ${value.y})`; + } +} +function geometry(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + if (!config?.mode || config.mode === "tuple") { + return new PgGeometryBuilder(name); + } + return new PgGeometryObjectBuilder(name); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/real.js +class PgRealBuilder extends PgColumnBuilder { + static [entityKind] = "PgRealBuilder"; + constructor(name, length) { + super(name, "number", "PgReal"); + this.config.length = length; + } + build(table) { + return new PgReal(table, this.config); + } +} + +class PgReal extends PgColumn { + static [entityKind] = "PgReal"; + constructor(table, config) { + super(table, config); + } + getSQLType() { + return "real"; + } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number.parseFloat(value); } - return ret; + return value; + }; +} +function real(name) { + return new PgRealBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/serial.js +class PgSerialBuilder extends PgColumnBuilder { + static [entityKind] = "PgSerialBuilder"; + constructor(name) { + super(name, "number", "PgSerial"); + this.config.hasDefault = true; + this.config.notNull = true; } -}); + build(table) { + return new PgSerial(table, this.config); + } +} -// src/index.ts -var import_express8 = __toESM(require_express(), 1); +class PgSerial extends PgColumn { + static [entityKind] = "PgSerial"; + getSQLType() { + return "serial"; + } +} +function serial(name) { + return new PgSerialBuilder(name ?? ""); +} -// src/loaders/express.ts -var import_cors = __toESM(require_lib3(), 1); -var import_express6 = __toESM(require_express(), 1); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallint.js +class PgSmallIntBuilder extends PgIntColumnBaseBuilder { + static [entityKind] = "PgSmallIntBuilder"; + constructor(name) { + super(name, "number", "PgSmallInt"); + } + build(table) { + return new PgSmallInt(table, this.config); + } +} -// src/api/auth/auth-route.ts -var import_express = __toESM(require_express(), 1); +class PgSmallInt extends PgColumn { + static [entityKind] = "PgSmallInt"; + getSQLType() { + return "smallint"; + } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number(value); + } + return value; + }; +} +function smallint(name) { + return new PgSmallIntBuilder(name ?? ""); +} -// node_modules/.pnpm/yup@1.7.1/node_modules/yup/index.esm.js -var import_property_expr = __toESM(require_property_expr(), 1); -var import_tiny_case = __toESM(require_tiny_case(), 1); -var import_toposort = __toESM(require_toposort(), 1); -var toString = Object.prototype.toString; -var errorToString = Error.prototype.toString; -var regExpToString = RegExp.prototype.toString; -var symbolToString = typeof Symbol !== "undefined" ? Symbol.prototype.toString : () => ""; -var SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/; -function printNumber(val) { - if (val != +val) - return "NaN"; - const isNegativeZero = val === 0 && 1 / val < 0; - return isNegativeZero ? "-0" : "" + val; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallserial.js +class PgSmallSerialBuilder extends PgColumnBuilder { + static [entityKind] = "PgSmallSerialBuilder"; + constructor(name) { + super(name, "number", "PgSmallSerial"); + this.config.hasDefault = true; + this.config.notNull = true; + } + build(table) { + return new PgSmallSerial(table, this.config); + } } -function printSimpleValue(val, quoteStrings = false) { - if (val == null || val === true || val === false) - return "" + val; - const typeOf = typeof val; - if (typeOf === "number") - return printNumber(val); - if (typeOf === "string") - return quoteStrings ? `"${val}"` : val; - if (typeOf === "function") - return "[Function " + (val.name || "anonymous") + "]"; - if (typeOf === "symbol") - return symbolToString.call(val).replace(SYMBOL_REGEXP, "Symbol($1)"); - const tag = toString.call(val).slice(8, -1); - if (tag === "Date") - return isNaN(val.getTime()) ? "" + val : val.toISOString(val); - if (tag === "Error" || val instanceof Error) - return "[" + errorToString.call(val) + "]"; - if (tag === "RegExp") - return regExpToString.call(val); - return null; + +class PgSmallSerial extends PgColumn { + static [entityKind] = "PgSmallSerial"; + getSQLType() { + return "smallserial"; + } } -function printValue(value, quoteStrings) { - let result = printSimpleValue(value, quoteStrings); - if (result !== null) - return result; - return JSON.stringify(value, function(key, value2) { - let result2 = printSimpleValue(this[key], quoteStrings); - if (result2 !== null) - return result2; - return value2; - }, 2); +function smallserial(name) { + return new PgSmallSerialBuilder(name ?? ""); } -function toArray(value) { - return value == null ? [] : [].concat(value); + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/text.js +class PgTextBuilder extends PgColumnBuilder { + static [entityKind] = "PgTextBuilder"; + constructor(name, config) { + super(name, "string", "PgText"); + this.config.enumValues = config.enum; + } + build(table) { + return new PgText(table, this.config); + } } -var _Symbol$toStringTag; -var _Symbol$hasInstance; -var _Symbol$toStringTag2; -var strReg = /\$\{\s*(\w+)\s*\}/g; -_Symbol$toStringTag = Symbol.toStringTag; -class ValidationErrorNoStack { - constructor(errorOrErrors, value, field, type) { - this.name = undefined; - this.message = undefined; - this.value = undefined; - this.path = undefined; - this.type = undefined; - this.params = undefined; - this.errors = undefined; - this.inner = undefined; - this[_Symbol$toStringTag] = "Error"; - this.name = "ValidationError"; - this.value = value; - this.path = field; - this.type = type; - this.errors = []; - this.inner = []; - toArray(errorOrErrors).forEach((err) => { - if (ValidationError.isError(err)) { - this.errors.push(...err.errors); - const innerErrors = err.inner.length ? err.inner : [err]; - this.inner.push(...innerErrors); - } else { - this.errors.push(err); - } - }); - this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0]; +class PgText extends PgColumn { + static [entityKind] = "PgText"; + enumValues = this.config.enumValues; + getSQLType() { + return "text"; } } -_Symbol$hasInstance = Symbol.hasInstance; -_Symbol$toStringTag2 = Symbol.toStringTag; +function text(a, b = {}) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgTextBuilder(name, config); +} -class ValidationError extends Error { - static formatError(message, params) { - const path = params.label || params.path || "this"; - params = Object.assign({}, params, { - path, - originalPath: params.path - }); - if (typeof message === "string") - return message.replace(strReg, (_, key) => printValue(params[key])); - if (typeof message === "function") - return message(params); - return message; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/time.js +class PgTimeBuilder extends PgDateColumnBaseBuilder { + constructor(name, withTimezone, precision) { + super(name, "string", "PgTime"); + this.withTimezone = withTimezone; + this.precision = precision; + this.config.withTimezone = withTimezone; + this.config.precision = precision; } - static isError(err) { - return err && err.name === "ValidationError"; + static [entityKind] = "PgTimeBuilder"; + build(table) { + return new PgTime(table, this.config); } - constructor(errorOrErrors, value, field, type, disableStack) { - const errorNoStack = new ValidationErrorNoStack(errorOrErrors, value, field, type); - if (disableStack) { - return errorNoStack; - } - super(); - this.value = undefined; - this.path = undefined; - this.type = undefined; - this.params = undefined; - this.errors = []; - this.inner = []; - this[_Symbol$toStringTag2] = "Error"; - this.name = errorNoStack.name; - this.message = errorNoStack.message; - this.type = errorNoStack.type; - this.value = errorNoStack.value; - this.path = errorNoStack.path; - this.errors = errorNoStack.errors; - this.inner = errorNoStack.inner; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, ValidationError); - } +} + +class PgTime extends PgColumn { + static [entityKind] = "PgTime"; + withTimezone; + precision; + constructor(table, config) { + super(table, config); + this.withTimezone = config.withTimezone; + this.precision = config.precision; } - static [_Symbol$hasInstance](inst) { - return ValidationErrorNoStack[Symbol.hasInstance](inst) || super[Symbol.hasInstance](inst); + getSQLType() { + const precision = this.precision === undefined ? "" : `(${this.precision})`; + return `time${precision}${this.withTimezone ? " with time zone" : ""}`; } } -var mixed = { - default: "${path} is invalid", - required: "${path} is a required field", - defined: "${path} must be defined", - notNull: "${path} cannot be null", - oneOf: "${path} must be one of the following values: ${values}", - notOneOf: "${path} must not be one of the following values: ${values}", - notType: ({ - path, - type, - value, - originalValue - }) => { - const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : "."; - return type !== "mixed" ? `${path} must be a \`${type}\` type, ` + `but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. ` + `The validated value was: \`${printValue(value, true)}\`` + castMsg; +function time(a, b = {}) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/timestamp.js +class PgTimestampBuilder extends PgDateColumnBaseBuilder { + static [entityKind] = "PgTimestampBuilder"; + constructor(name, withTimezone, precision) { + super(name, "date", "PgTimestamp"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; } -}; -var string = { - length: "${path} must be exactly ${length} characters", - min: "${path} must be at least ${min} characters", - max: "${path} must be at most ${max} characters", - matches: '${path} must match the following: "${regex}"', - email: "${path} must be a valid email", - url: "${path} must be a valid URL", - uuid: "${path} must be a valid UUID", - datetime: "${path} must be a valid ISO date-time", - datetime_precision: "${path} must be a valid ISO date-time with a sub-second precision of exactly ${precision} digits", - datetime_offset: '${path} must be a valid ISO date-time with UTC "Z" timezone', - trim: "${path} must be a trimmed string", - lowercase: "${path} must be a lowercase string", - uppercase: "${path} must be a upper case string" -}; -var number = { - min: "${path} must be greater than or equal to ${min}", - max: "${path} must be less than or equal to ${max}", - lessThan: "${path} must be less than ${less}", - moreThan: "${path} must be greater than ${more}", - positive: "${path} must be a positive number", - negative: "${path} must be a negative number", - integer: "${path} must be an integer" -}; -var date = { - min: "${path} field must be later than ${min}", - max: "${path} field must be at earlier than ${max}" -}; -var boolean = { - isValue: "${path} field must be ${value}" -}; -var object = { - noUnknown: "${path} field has unspecified keys: ${unknown}", - exact: "${path} object contains unknown properties: ${properties}" -}; -var array = { - min: "${path} field must have at least ${min} items", - max: "${path} field must have less than or equal to ${max} items", - length: "${path} must have ${length} items" -}; -var tuple = { - notType: (params) => { - const { - path, - value, - spec - } = params; - const typeLen = spec.types.length; - if (Array.isArray(value)) { - if (value.length < typeLen) - return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``; - if (value.length > typeLen) - return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``; - } - return ValidationError.formatError(mixed.notType, params); + build(table) { + return new PgTimestamp(table, this.config); } -}; -var locale = Object.assign(Object.create(null), { - mixed, - string, - number, - date, - object, - array, - boolean, - tuple -}); -var isSchema = (obj) => obj && obj.__isYupSchema__; +} -class Condition { - static fromOptions(refs, config) { - if (!config.then && !config.otherwise) - throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions"); - let { - is, - then, - otherwise - } = config; - let check = typeof is === "function" ? is : (...values) => values.every((value) => value === is); - return new Condition(refs, (values, schema) => { - var _branch; - let branch = check(...values) ? then : otherwise; - return (_branch = branch == null ? undefined : branch(schema)) != null ? _branch : schema; - }); +class PgTimestamp extends PgColumn { + static [entityKind] = "PgTimestamp"; + withTimezone; + precision; + constructor(table, config) { + super(table, config); + this.withTimezone = config.withTimezone; + this.precision = config.precision; } - constructor(refs, builder) { - this.fn = undefined; - this.refs = refs; - this.refs = refs; - this.fn = builder; + getSQLType() { + const precision = this.precision === undefined ? "" : ` (${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; } - resolve(base, options) { - let values = this.refs.map((ref) => ref.getValue(options == null ? undefined : options.value, options == null ? undefined : options.parent, options == null ? undefined : options.context)); - let schema = this.fn(values, base, options); - if (schema === undefined || schema === base) { - return base; - } - if (!isSchema(schema)) - throw new TypeError("conditions must return a schema object"); - return schema.resolve(options); + mapFromDriverValue = (value) => { + return new Date(this.withTimezone ? value : value + "+0000"); + }; + mapToDriverValue = (value) => { + return value.toISOString(); + }; +} + +class PgTimestampStringBuilder extends PgDateColumnBaseBuilder { + static [entityKind] = "PgTimestampStringBuilder"; + constructor(name, withTimezone, precision) { + super(name, "string", "PgTimestampString"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; + } + build(table) { + return new PgTimestampString(table, this.config); } } -var prefixes = { - context: "$", - value: "." -}; -class Reference { - constructor(key, options = {}) { - this.key = undefined; - this.isContext = undefined; - this.isValue = undefined; - this.isSibling = undefined; - this.path = undefined; - this.getter = undefined; - this.map = undefined; - if (typeof key !== "string") - throw new TypeError("ref must be a string, got: " + key); - this.key = key.trim(); - if (key === "") - throw new TypeError("ref must be a non-empty string"); - this.isContext = this.key[0] === prefixes.context; - this.isValue = this.key[0] === prefixes.value; - this.isSibling = !this.isContext && !this.isValue; - let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : ""; - this.path = this.key.slice(prefix.length); - this.getter = this.path && import_property_expr.getter(this.path, true); - this.map = options.map; + +class PgTimestampString extends PgColumn { + static [entityKind] = "PgTimestampString"; + withTimezone; + precision; + constructor(table, config) { + super(table, config); + this.withTimezone = config.withTimezone; + this.precision = config.precision; } - getValue(value, parent, context) { - let result = this.isContext ? context : this.isValue ? value : parent; - if (this.getter) - result = this.getter(result || {}); - if (this.map) - result = this.map(result); - return result; + getSQLType() { + const precision = this.precision === undefined ? "" : `(${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; } - cast(value, options) { - return this.getValue(value, options == null ? undefined : options.parent, options == null ? undefined : options.context); +} +function timestamp(a, b = {}) { + const { name, config } = getColumnNameAndConfig(a, b); + if (config?.mode === "string") { + return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision); } - resolve() { - return this; + return new PgTimestampBuilder(name, config?.withTimezone ?? false, config?.precision); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/uuid.js +class PgUUIDBuilder extends PgColumnBuilder { + static [entityKind] = "PgUUIDBuilder"; + constructor(name) { + super(name, "string", "PgUUID"); } - describe() { - return { - type: "ref", - key: this.key - }; + defaultRandom() { + return this.default(sql`gen_random_uuid()`); } - toString() { - return `Ref(${this.key})`; + build(table) { + return new PgUUID(table, this.config); } - static isRef(value) { - return value && value.__isYupRef; +} + +class PgUUID extends PgColumn { + static [entityKind] = "PgUUID"; + getSQLType() { + return "uuid"; } } -Reference.prototype.__isYupRef = true; -var isAbsent = (value) => value == null; -function createValidation(config) { - function validate({ - value, - path = "", - options, - originalValue, - schema - }, panic, next) { - const { - name, - test, - params, - message, - skipAbsent - } = config; - let { - parent, - context, - abortEarly = schema.spec.abortEarly, - disableStackTrace = schema.spec.disableStackTrace - } = options; - const resolveOptions = { - value, - parent, - context - }; - function createError(overrides = {}) { - const nextParams = resolveParams(Object.assign({ - value, - originalValue, - label: schema.spec.label, - path: overrides.path || path, - spec: schema.spec, - disableStackTrace: overrides.disableStackTrace || disableStackTrace - }, params, overrides.params), resolveOptions); - const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, nextParams.disableStackTrace); - error.params = nextParams; - return error; - } - const invalid = abortEarly ? panic : next; - let ctx = { - path, - parent, - type: name, - from: options.from, - createError, - resolve(item) { - return resolveMaybeRef(item, resolveOptions); - }, - options, - originalValue, - schema - }; - const handleResult = (validOrError) => { - if (ValidationError.isError(validOrError)) - invalid(validOrError); - else if (!validOrError) - invalid(createError()); - else - next(null); - }; - const handleError = (err) => { - if (ValidationError.isError(err)) - invalid(err); - else - panic(err); - }; - const shouldSkip = skipAbsent && isAbsent(value); - if (shouldSkip) { - return handleResult(true); - } - let result; - try { - var _result; - result = test.call(ctx, value, ctx); - if (typeof ((_result = result) == null ? undefined : _result.then) === "function") { - if (options.sync) { - throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. ` + `This test will finish after the validate call has returned`); - } - return Promise.resolve(result).then(handleResult, handleError); - } - } catch (err) { - handleError(err); - return; - } - handleResult(result); +function uuid(name) { + return new PgUUIDBuilder(name ?? ""); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/varchar.js +class PgVarcharBuilder extends PgColumnBuilder { + static [entityKind] = "PgVarcharBuilder"; + constructor(name, config) { + super(name, "string", "PgVarchar"); + this.config.length = config.length; + this.config.enumValues = config.enum; + } + build(table) { + return new PgVarchar(table, this.config); } - validate.OPTIONS = config; - return validate; } -function resolveParams(params, options) { - if (!params) - return params; - for (const key of Object.keys(params)) { - params[key] = resolveMaybeRef(params[key], options); + +class PgVarchar extends PgColumn { + static [entityKind] = "PgVarchar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === undefined ? `varchar` : `varchar(${this.length})`; } - return params; } -function resolveMaybeRef(item, options) { - return Reference.isRef(item) ? item.getValue(options.value, options.parent, options.context) : item; +function varchar(a, b = {}) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgVarcharBuilder(name, config); } -function getIn(schema, path, value, context = value) { - let parent, lastPart, lastPartDebug; - if (!path) - return { - parent, - parentPath: path, - schema - }; - import_property_expr.forEach(path, (_part, isBracket, isArray) => { - let part = isBracket ? _part.slice(1, _part.length - 1) : _part; - schema = schema.resolve({ - context, - parent, - value - }); - let isTuple = schema.type === "tuple"; - let idx = isArray ? parseInt(part, 10) : 0; - if (schema.innerType || isTuple) { - if (isTuple && !isArray) - throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`); - if (value && idx >= value.length) { - throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. ` + `because there is no value at that index. `); - } - parent = value; - value = value && value[idx]; - schema = isTuple ? schema.spec.types[idx] : schema.innerType; - } - if (!isArray) { - if (!schema.fields || !schema.fields[part]) - throw new Error(`The schema does not contain the path: ${path}. ` + `(failed at: ${lastPartDebug} which is a type: "${schema.type}")`); - parent = value; - value = value && value[part]; - schema = schema.fields[part]; - } - lastPart = part; - lastPartDebug = isBracket ? "[" + _part + "]" : "." + _part; - }); - return { - schema, - parent, - parentPath: lastPart - }; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js +class PgBinaryVectorBuilder extends PgColumnBuilder { + static [entityKind] = "PgBinaryVectorBuilder"; + constructor(name, config) { + super(name, "string", "PgBinaryVector"); + this.config.dimensions = config.dimensions; + } + build(table) { + return new PgBinaryVector(table, this.config); + } +} + +class PgBinaryVector extends PgColumn { + static [entityKind] = "PgBinaryVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `bit(${this.dimensions})`; + } +} +function bit(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgBinaryVectorBuilder(name, config); } -class ReferenceSet extends Set { - describe() { - const description = []; - for (const item of this.values()) { - description.push(Reference.isRef(item) ? item.describe() : item); - } - return description; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js +class PgHalfVectorBuilder extends PgColumnBuilder { + static [entityKind] = "PgHalfVectorBuilder"; + constructor(name, config) { + super(name, "array", "PgHalfVector"); + this.config.dimensions = config.dimensions; } - resolveAll(resolve) { - let result = []; - for (const item of this.values()) { - result.push(resolve(item)); - } - return result; + build(table) { + return new PgHalfVector(table, this.config); } - clone() { - return new ReferenceSet(this.values()); +} + +class PgHalfVector extends PgColumn { + static [entityKind] = "PgHalfVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `halfvec(${this.dimensions})`; } - merge(newItems, removeItems) { - const next = this.clone(); - newItems.forEach((value) => next.add(value)); - removeItems.forEach((value) => next.delete(value)); - return next; + mapToDriverValue(value) { + return JSON.stringify(value); } -} -function clone(src, seen = new Map) { - if (isSchema(src) || !src || typeof src !== "object") - return src; - if (seen.has(src)) - return seen.get(src); - let copy; - if (src instanceof Date) { - copy = new Date(src.getTime()); - seen.set(src, copy); - } else if (src instanceof RegExp) { - copy = new RegExp(src); - seen.set(src, copy); - } else if (Array.isArray(src)) { - copy = new Array(src.length); - seen.set(src, copy); - for (let i = 0;i < src.length; i++) - copy[i] = clone(src[i], seen); - } else if (src instanceof Map) { - copy = new Map; - seen.set(src, copy); - for (const [k, v] of src.entries()) - copy.set(k, clone(v, seen)); - } else if (src instanceof Set) { - copy = new Set; - seen.set(src, copy); - for (const v of src) - copy.add(clone(v, seen)); - } else if (src instanceof Object) { - copy = {}; - seen.set(src, copy); - for (const [k, v] of Object.entries(src)) - copy[k] = clone(v, seen); - } else { - throw Error(`Unable to clone ${src}`); + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); } - return copy; } -function createStandardPath(path) { - if (!(path != null && path.length)) { - return; +function halfvec(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgHalfVectorBuilder(name, config); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js +class PgSparseVectorBuilder extends PgColumnBuilder { + static [entityKind] = "PgSparseVectorBuilder"; + constructor(name, config) { + super(name, "string", "PgSparseVector"); + this.config.dimensions = config.dimensions; } - const segments = []; - let currentSegment = ""; - let inBrackets = false; - let inQuotes = false; - for (let i = 0;i < path.length; i++) { - const char = path[i]; - if (char === "[" && !inQuotes) { - if (currentSegment) { - segments.push(...currentSegment.split(".").filter(Boolean)); - currentSegment = ""; - } - inBrackets = true; - continue; - } - if (char === "]" && !inQuotes) { - if (currentSegment) { - if (/^\d+$/.test(currentSegment)) { - segments.push(currentSegment); - } else { - segments.push(currentSegment.replace(/^"|"$/g, "")); - } - currentSegment = ""; - } - inBrackets = false; - continue; - } - if (char === '"') { - inQuotes = !inQuotes; - continue; - } - if (char === "." && !inBrackets && !inQuotes) { - if (currentSegment) { - segments.push(currentSegment); - currentSegment = ""; - } - continue; - } - currentSegment += char; + build(table) { + return new PgSparseVector(table, this.config); } - if (currentSegment) { - segments.push(...currentSegment.split(".").filter(Boolean)); +} + +class PgSparseVector extends PgColumn { + static [entityKind] = "PgSparseVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `sparsevec(${this.dimensions})`; } - return segments; } -function createStandardIssues(error, parentPath) { - const path = parentPath ? `${parentPath}.${error.path}` : error.path; - return error.errors.map((err) => ({ - message: err, - path: createStandardPath(path) - })); +function sparsevec(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgSparseVectorBuilder(name, config); } -function issuesFromValidationError(error, parentPath) { - var _error$inner; - if (!((_error$inner = error.inner) != null && _error$inner.length) && error.errors.length) { - return createStandardIssues(error, parentPath); + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js +class PgVectorBuilder extends PgColumnBuilder { + static [entityKind] = "PgVectorBuilder"; + constructor(name, config) { + super(name, "array", "PgVector"); + this.config.dimensions = config.dimensions; + } + build(table) { + return new PgVector(table, this.config); } - const path = parentPath ? `${parentPath}.${error.path}` : error.path; - return error.inner.flatMap((err) => issuesFromValidationError(err, path)); } -class Schema { - constructor(options) { - this.type = undefined; - this.deps = []; - this.tests = undefined; - this.transforms = undefined; - this.conditions = []; - this._mutate = undefined; - this.internalTests = {}; - this._whitelist = new ReferenceSet; - this._blacklist = new ReferenceSet; - this.exclusiveTests = Object.create(null); - this._typeCheck = undefined; - this.spec = undefined; - this.tests = []; - this.transforms = []; - this.withMutation(() => { - this.typeError(mixed.notType); - }); - this.type = options.type; - this._typeCheck = options.check; - this.spec = Object.assign({ - strip: false, - strict: false, - abortEarly: true, - recursive: true, - disableStackTrace: false, - nullable: false, - optional: true, - coerce: true - }, options == null ? undefined : options.spec); - this.withMutation((s) => { - s.nonNullable(); - }); +class PgVector extends PgColumn { + static [entityKind] = "PgVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `vector(${this.dimensions})`; } - get _type() { - return this.type; + mapToDriverValue(value) { + return JSON.stringify(value); } - clone(spec) { - if (this._mutate) { - if (spec) - Object.assign(this.spec, spec); - return this; - } - const next = Object.create(Object.getPrototypeOf(this)); - next.type = this.type; - next._typeCheck = this._typeCheck; - next._whitelist = this._whitelist.clone(); - next._blacklist = this._blacklist.clone(); - next.internalTests = Object.assign({}, this.internalTests); - next.exclusiveTests = Object.assign({}, this.exclusiveTests); - next.deps = [...this.deps]; - next.conditions = [...this.conditions]; - next.tests = [...this.tests]; - next.transforms = [...this.transforms]; - next.spec = clone(Object.assign({}, this.spec, spec)); - return next; + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); } - label(label) { - let next = this.clone(); - next.spec.label = label; - return next; +} +function vector(a, b) { + const { name, config } = getColumnNameAndConfig(a, b); + return new PgVectorBuilder(name, config); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-promise.js +class QueryPromise { + static [entityKind] = "QueryPromise"; + [Symbol.toStringTag] = "QueryPromise"; + catch(onRejected) { + return this.then(undefined, onRejected); } - meta(...args) { - if (args.length === 0) - return this.spec.meta; - let next = this.clone(); - next.spec.meta = Object.assign(next.spec.meta || {}, args[0]); - return next; + finally(onFinally) { + return this.then((value) => { + onFinally?.(); + return value; + }, (reason) => { + onFinally?.(); + throw reason; + }); } - withMutation(fn) { - let before = this._mutate; - this._mutate = true; - let result = fn(this); - this._mutate = before; - return result; + then(onFulfilled, onRejected) { + return this.execute().then(onFulfilled, onRejected); } - concat(schema) { - if (!schema || schema === this) - return this; - if (schema.type !== this.type && this.type !== "mixed") - throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`); - let base = this; - let combined = schema.clone(); - const mergedSpec = Object.assign({}, base.spec, combined.spec); - combined.spec = mergedSpec; - combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests); - combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist); - combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist); - combined.tests = base.tests; - combined.exclusiveTests = base.exclusiveTests; - combined.withMutation((next) => { - schema.tests.forEach((fn) => { - next.test(fn.OPTIONS); - }); - }); - combined.transforms = [...base.transforms, ...combined.transforms]; - return combined; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/selection-proxy.js +class SelectionProxyHandler { + static [entityKind] = "SelectionProxyHandler"; + config; + constructor(config) { + this.config = { ...config }; } - isType(v) { - if (v == null) { - if (this.spec.nullable && v === null) - return true; - if (this.spec.optional && v === undefined) - return true; - return false; + get(subquery, prop) { + if (prop === "_") { + return { + ...subquery["_"], + selectedFields: new Proxy(subquery._.selectedFields, this) + }; } - return this._typeCheck(v); - } - resolve(options) { - let schema = this; - if (schema.conditions.length) { - let conditions = schema.conditions; - schema = schema.clone(); - schema.conditions = []; - schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema); - schema = schema.resolve(options); + if (prop === ViewBaseConfig) { + return { + ...subquery[ViewBaseConfig], + selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this) + }; } - return schema; - } - resolveOptions(options) { - var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack; - return Object.assign({}, options, { - from: options.from || [], - strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict, - abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly, - recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive, - disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace - }); - } - cast(value, options = {}) { - let resolvedSchema = this.resolve(Object.assign({}, options, { - value - })); - let allowOptionality = options.assert === "ignore-optionality"; - let result = resolvedSchema._cast(value, options); - if (options.assert !== false && !resolvedSchema.isType(result)) { - if (allowOptionality && isAbsent(result)) { - return result; + if (typeof prop === "symbol") { + return subquery[prop]; + } + const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; + const value = columns[prop]; + if (is(value, SQL.Aliased)) { + if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { + return value.sql; } - let formattedValue = printValue(value); - let formattedResult = printValue(result); - throw new TypeError(`The value of ${options.path || "field"} could not be cast to a value ` + `that satisfies the schema type: "${resolvedSchema.type}". - -` + `attempted value: ${formattedValue} -` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : "")); + const newValue = value.clone(); + newValue.isSelectionField = true; + return newValue; } - return result; - } - _cast(rawValue, options) { - let value = rawValue === undefined ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this, options), rawValue); - if (value === undefined) { - value = this.getDefault(options); + if (is(value, SQL)) { + if (this.config.sqlBehavior === "sql") { + return value; + } + throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`); } - return value; - } - _validate(_value, options = {}, panic, next) { - let { - path, - originalValue = _value, - strict = this.spec.strict - } = options; - let value = _value; - if (!strict) { - value = this._cast(value, Object.assign({ - assert: false - }, options)); + if (is(value, Column)) { + if (this.config.alias) { + return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)))); + } + return value; } - let initialTests = []; - for (let test of Object.values(this.internalTests)) { - if (test) - initialTests.push(test); + if (typeof value !== "object" || value === null) { + return value; } - this.runTests({ - path, - value, - originalValue, - options, - tests: initialTests - }, panic, (initialErrors) => { - if (initialErrors.length) { - return next(initialErrors, value); - } - this.runTests({ - path, - value, - originalValue, - options, - tests: this.tests - }, panic, next); - }); + return new Proxy(value, new SelectionProxyHandler(this.config)); } - runTests(runOptions, panic, next) { - let fired = false; - let { - tests, - value, - originalValue, - path, - options - } = runOptions; - let panicOnce = (arg) => { - if (fired) - return; - fired = true; - panic(arg, value); - }; - let nextOnce = (arg) => { - if (fired) - return; - fired = true; - next(arg, value); - }; - let count = tests.length; - let nestedErrors = []; - if (!count) - return nextOnce([]); - let args = { - value, - originalValue, - path, - options, - schema: this - }; - for (let i = 0;i < tests.length; i++) { - const test = tests[i]; - test(args, panicOnce, function finishTestRun(err) { - if (err) { - Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err); - } - if (--count <= 0) { - nextOnce(nestedErrors); - } - }); - } +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/all.js +function getPgColumnBuilders() { + return { + bigint, + bigserial, + boolean: boolean2, + char, + cidr, + customType, + date: date2, + doublePrecision, + inet, + integer, + interval, + json, + jsonb, + line, + macaddr, + macaddr8, + numeric, + point, + geometry, + real, + serial, + smallint, + smallserial, + text, + time, + timestamp, + uuid, + varchar, + bit, + halfvec, + sparsevec, + vector + }; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/table.js +var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys"); +var EnableRLS = Symbol.for("drizzle:EnableRLS"); + +class PgTable extends Table { + static [entityKind] = "PgTable"; + static Symbol = Object.assign({}, Table.Symbol, { + InlineForeignKeys, + EnableRLS + }); + [InlineForeignKeys] = []; + [EnableRLS] = false; + [Table.Symbol.ExtraConfigBuilder] = undefined; + [Table.Symbol.ExtraConfigColumns] = {}; +} +function pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) { + const rawTable = new PgTable(name, schema, baseName); + const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns; + const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.build(rawTable); + rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable)); + return [name2, column]; + })); + const builtColumnsForExtraConfig = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.buildExtraConfigColumn(rawTable); + return [name2, column]; + })); + const table = Object.assign(rawTable, builtColumns); + table[Table.Symbol.Columns] = builtColumns; + table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; + if (extraConfig) { + table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig; } - asNestedTest({ - key, - index, - parent, - parentPath, - originalParent, - options - }) { - const k = key != null ? key : index; - if (k == null) { - throw TypeError("Must include `key` or `index` for nested validations"); + return Object.assign(table, { + enableRLS: () => { + table[PgTable.Symbol.EnableRLS] = true; + return table; } - const isIndex = typeof k === "number"; - let value = parent[k]; - const testOptions = Object.assign({}, options, { - strict: true, - parent, - value, - originalValue: originalParent[k], - key: undefined, - [isIndex ? "index" : "key"]: k, - path: isIndex || k.includes(".") ? `${parentPath || ""}[${isIndex ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : "") + key - }); - return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next); - } - validate(value, options) { - var _options$disableStack2; - let schema = this.resolve(Object.assign({}, options, { - value - })); - let disableStackTrace = (_options$disableStack2 = options == null ? undefined : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace; - return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => { - if (ValidationError.isError(error)) - error.value = parsed; - reject(error); - }, (errors, validated) => { - if (errors.length) - reject(new ValidationError(errors, validated, undefined, undefined, disableStackTrace)); - else - resolve(validated); - })); + }); +} +var pgTable = (name, columns, extraConfig) => { + return pgTableWithSchema(name, columns, extraConfig, undefined); +}; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/indexes.js +class IndexBuilderOn { + constructor(unique, name) { + this.unique = unique; + this.name = name; } - validateSync(value, options) { - var _options$disableStack3; - let schema = this.resolve(Object.assign({}, options, { - value - })); - let result; - let disableStackTrace = (_options$disableStack3 = options == null ? undefined : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace; - schema._validate(value, Object.assign({}, options, { - sync: true - }), (error, parsed) => { - if (ValidationError.isError(error)) - error.value = parsed; - throw error; - }, (errors, validated) => { - if (errors.length) - throw new ValidationError(errors, value, undefined, undefined, disableStackTrace); - result = validated; - }); - return result; + static [entityKind] = "PgIndexBuilderOn"; + on(...columns) { + return new IndexBuilder(columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), this.unique, false, this.name); } - isValid(value, options) { - return this.validate(value, options).then(() => true, (err) => { - if (ValidationError.isError(err)) - return false; - throw err; - }); + onOnly(...columns) { + return new IndexBuilder(columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = it.defaultConfig; + return clonedIndexedColumn; + }), this.unique, true, this.name); } - isValidSync(value, options) { - try { - this.validateSync(value, options); - return true; - } catch (err) { - if (ValidationError.isError(err)) - return false; - throw err; - } + using(method, ...columns) { + return new IndexBuilder(columns.map((it) => { + if (is(it, SQL)) { + return it; + } + it = it; + const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), this.unique, true, this.name, method); } - _getDefault(options) { - let defaultValue = this.spec.default; - if (defaultValue == null) { - return defaultValue; - } - return typeof defaultValue === "function" ? defaultValue.call(this, options) : clone(defaultValue); +} + +class IndexBuilder { + static [entityKind] = "PgIndexBuilder"; + config; + constructor(columns, unique, only, name, method = "btree") { + this.config = { + name, + columns, + unique, + only, + method + }; } - getDefault(options) { - let schema = this.resolve(options || {}); - return schema._getDefault(options); + concurrently() { + this.config.concurrently = true; + return this; } - default(def) { - if (arguments.length === 0) { - return this._getDefault(); - } - let next = this.clone({ - default: def - }); - return next; + with(obj) { + this.config.with = obj; + return this; } - strict(isStrict = true) { - return this.clone({ - strict: isStrict - }); + where(condition) { + this.config.where = condition; + return this; } - nullability(nullable, message) { - const next = this.clone({ - nullable - }); - next.internalTests.nullable = createValidation({ - message, - name: "nullable", - test(value) { - return value === null ? this.schema.spec.nullable : true; - } - }); - return next; + build(table) { + return new Index(this.config, table); } - optionality(optional, message) { - const next = this.clone({ - optional - }); - next.internalTests.optionality = createValidation({ - message, - name: "optionality", - test(value) { - return value === undefined ? this.schema.spec.optional : true; - } - }); - return next; +} + +class Index { + static [entityKind] = "PgIndex"; + config; + constructor(config, table) { + this.config = { ...config, table }; } - optional() { - return this.optionality(true); +} +function index(name) { + return new IndexBuilderOn(false, name); +} +function uniqueIndex(name) { + return new IndexBuilderOn(true, name); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/primary-keys.js +function primaryKey(...config) { + if (config[0].columns) { + return new PrimaryKeyBuilder(config[0].columns, config[0].name); } - defined(message = mixed.defined) { - return this.optionality(false, message); + return new PrimaryKeyBuilder(config); +} + +class PrimaryKeyBuilder { + static [entityKind] = "PgPrimaryKeyBuilder"; + columns; + name; + constructor(columns, name) { + this.columns = columns; + this.name = name; } - nullable() { - return this.nullability(true); + build(table) { + return new PrimaryKey(table, this.columns, this.name); } - nonNullable(message = mixed.notNull) { - return this.nullability(false, message); +} + +class PrimaryKey { + constructor(table, columns, name) { + this.table = table; + this.columns = columns; + this.name = name; } - required(message = mixed.required) { - return this.clone().withMutation((next) => next.nonNullable(message).defined(message)); + static [entityKind] = "PgPrimaryKey"; + columns; + name; + getName() { + return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; } - notRequired() { - return this.clone().withMutation((next) => next.nullable().optional()); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/casing.js +function toSnakeCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.map((word) => word.toLowerCase()).join("_"); +} +function toCamelCase(input) { + const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; + return words.reduce((acc, word, i) => { + const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; + return acc + formattedWord; + }, ""); +} +function noopCase(input) { + return input; +} + +class CasingCache { + static [entityKind] = "CasingCache"; + cache = {}; + cachedTables = {}; + convert; + constructor(casing) { + this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; } - transform(fn) { - let next = this.clone(); - next.transforms.push(fn); - return next; + getColumnCasing(column) { + if (!column.keyAsName) + return column.name; + const schema = column.table[Table.Symbol.Schema] ?? "public"; + const tableName = column.table[Table.Symbol.OriginalName]; + const key = `${schema}.${tableName}.${column.name}`; + if (!this.cache[key]) { + this.cacheTable(column.table); + } + return this.cache[key]; } - test(...args) { - let opts; - if (args.length === 1) { - if (typeof args[0] === "function") { - opts = { - test: args[0] - }; - } else { - opts = args[0]; + cacheTable(table) { + const schema = table[Table.Symbol.Schema] ?? "public"; + const tableName = table[Table.Symbol.OriginalName]; + const tableKey = `${schema}.${tableName}`; + if (!this.cachedTables[tableKey]) { + for (const column of Object.values(table[Table.Symbol.Columns])) { + const columnKey = `${tableKey}.${column.name}`; + this.cache[columnKey] = this.convert(column.name); } - } else if (args.length === 2) { - opts = { - name: args[0], - test: args[1] - }; - } else { - opts = { - name: args[0], - message: args[1], - test: args[2] - }; - } - if (opts.message === undefined) - opts.message = mixed.default; - if (typeof opts.test !== "function") - throw new TypeError("`test` is a required parameters"); - let next = this.clone(); - let validate = createValidation(opts); - let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true; - if (opts.exclusive) { - if (!opts.name) - throw new TypeError("Exclusive tests must provide a unique `name` identifying the test"); + this.cachedTables[tableKey] = true; } - if (opts.name) - next.exclusiveTests[opts.name] = !!opts.exclusive; - next.tests = next.tests.filter((fn) => { - if (fn.OPTIONS.name === opts.name) { - if (isExclusive) - return false; - if (fn.OPTIONS.test === validate.OPTIONS.test) - return false; - } - return true; - }); - next.tests.push(validate); - return next; } - when(keys, options) { - if (!Array.isArray(keys) && typeof keys !== "string") { - options = keys; - keys = "."; - } - let next = this.clone(); - let deps = toArray(keys).map((key) => new Reference(key)); - deps.forEach((dep) => { - if (dep.isSibling) - next.deps.push(dep.key); - }); - next.conditions.push(typeof options === "function" ? new Condition(deps, options) : Condition.fromOptions(deps, options)); - return next; + clearCache() { + this.cache = {}; + this.cachedTables = {}; } - typeError(message) { - let next = this.clone(); - next.internalTests.typeError = createValidation({ - message, - name: "typeError", - skipAbsent: true, - test(value) { - if (!this.schema._typeCheck(value)) - return this.createError({ - params: { - type: this.schema.type - } - }); - return true; - } - }); - return next; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/errors.js +class DrizzleError extends Error { + static [entityKind] = "DrizzleError"; + constructor({ message, cause }) { + super(message); + this.name = "DrizzleError"; + this.cause = cause; } - oneOf(enums, message = mixed.oneOf) { - let next = this.clone(); - enums.forEach((val) => { - next._whitelist.add(val); - next._blacklist.delete(val); - }); - next.internalTests.whiteList = createValidation({ - message, - name: "oneOf", - skipAbsent: true, - test(value) { - let valids = this.schema._whitelist; - let resolved = valids.resolveAll(this.resolve); - return resolved.includes(value) ? true : this.createError({ - params: { - values: Array.from(valids).join(", "), - resolved - } - }); - } - }); - return next; +} + +class DrizzleQueryError extends Error { + constructor(query, params, cause) { + super(`Failed query: ${query} +params: ${params}`); + this.query = query; + this.params = params; + this.cause = cause; + Error.captureStackTrace(this, DrizzleQueryError); + if (cause) + this.cause = cause; } - notOneOf(enums, message = mixed.notOneOf) { - let next = this.clone(); - enums.forEach((val) => { - next._blacklist.add(val); - next._whitelist.delete(val); - }); - next.internalTests.blacklist = createValidation({ - message, - name: "notOneOf", - test(value) { - let invalids = this.schema._blacklist; - let resolved = invalids.resolveAll(this.resolve); - if (resolved.includes(value)) - return this.createError({ - params: { - values: Array.from(invalids).join(", "), - resolved - } - }); - return true; - } - }); - return next; +} + +class TransactionRollbackError extends DrizzleError { + static [entityKind] = "TransactionRollbackError"; + constructor() { + super({ message: "Rollback" }); } - strip(strip = true) { - let next = this.clone(); - next.spec.strip = strip; - return next; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/conditions.js +function bindIfParam(value, column) { + if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { + return new Param(value, column); } - describe(options) { - const next = (options ? this.resolve(options) : this).clone(); - const { - label, - meta, - optional, - nullable - } = next.spec; - const description = { - meta, - label, - optional, - nullable, - default: next.getDefault(options), - type: next.type, - oneOf: next._whitelist.describe(), - notOneOf: next._blacklist.describe(), - tests: next.tests.filter((n, idx, list) => list.findIndex((c) => c.OPTIONS.name === n.OPTIONS.name) === idx).map((fn) => { - const params = fn.OPTIONS.params && options ? resolveParams(Object.assign({}, fn.OPTIONS.params), options) : fn.OPTIONS.params; - return { - name: fn.OPTIONS.name, - params - }; - }) - }; - return description; + return value; +} +var eq = (left, right) => { + return sql`${left} = ${bindIfParam(right, left)}`; +}; +var ne = (left, right) => { + return sql`${left} <> ${bindIfParam(right, left)}`; +}; +function and(...unfilteredConditions) { + const conditions = unfilteredConditions.filter((c) => c !== undefined); + if (conditions.length === 0) { + return; } - get ["~standard"]() { - const schema = this; - const standard = { - version: 1, - vendor: "yup", - async validate(value) { - try { - const result = await schema.validate(value, { - abortEarly: false - }); - return { - value: result - }; - } catch (err) { - if (err instanceof ValidationError) { - return { - issues: issuesFromValidationError(err) - }; - } - throw err; - } - } - }; - return standard; + if (conditions.length === 1) { + return new SQL(conditions); } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" and ")), + new StringChunk(")") + ]); } -Schema.prototype.__isYupSchema__ = true; -for (const method of ["validate", "validateSync"]) - Schema.prototype[`${method}At`] = function(path, value, options = {}) { - const { - parent, - parentPath, - schema - } = getIn(this, path, value, options.context); - return schema[method](parent && parent[parentPath], Object.assign({}, options, { - parent, - path - })); - }; -for (const alias of ["equals", "is"]) - Schema.prototype[alias] = Schema.prototype.oneOf; -for (const alias of ["not", "nope"]) - Schema.prototype[alias] = Schema.prototype.notOneOf; -var returnsTrue = () => true; -function create$8(spec) { - return new MixedSchema(spec); +function or(...unfilteredConditions) { + const conditions = unfilteredConditions.filter((c) => c !== undefined); + if (conditions.length === 0) { + return; + } + if (conditions.length === 1) { + return new SQL(conditions); + } + return new SQL([ + new StringChunk("("), + sql.join(conditions, new StringChunk(" or ")), + new StringChunk(")") + ]); +} +function not(condition) { + return sql`not ${condition}`; +} +var gt = (left, right) => { + return sql`${left} > ${bindIfParam(right, left)}`; +}; +var gte = (left, right) => { + return sql`${left} >= ${bindIfParam(right, left)}`; +}; +var lt = (left, right) => { + return sql`${left} < ${bindIfParam(right, left)}`; +}; +var lte = (left, right) => { + return sql`${left} <= ${bindIfParam(right, left)}`; +}; +function inArray(column, values) { + if (Array.isArray(values)) { + if (values.length === 0) { + return sql`false`; + } + return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`; + } + return sql`${column} in ${bindIfParam(values, column)}`; +} +function notInArray(column, values) { + if (Array.isArray(values)) { + if (values.length === 0) { + return sql`true`; + } + return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`; + } + return sql`${column} not in ${bindIfParam(values, column)}`; +} +function isNull(value) { + return sql`${value} is null`; +} +function isNotNull(value) { + return sql`${value} is not null`; +} +function exists(subquery) { + return sql`exists ${subquery}`; +} +function notExists(subquery) { + return sql`not exists ${subquery}`; +} +function between(column, min, max) { + return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`; +} +function notBetween(column, min, max) { + return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`; +} +function like(column, value) { + return sql`${column} like ${value}`; +} +function notLike(column, value) { + return sql`${column} not like ${value}`; +} +function ilike(column, value) { + return sql`${column} ilike ${value}`; +} +function notIlike(column, value) { + return sql`${column} not ilike ${value}`; } -class MixedSchema extends Schema { - constructor(spec) { - super(typeof spec === "function" ? { - type: "mixed", - check: spec - } : Object.assign({ - type: "mixed", - check: returnsTrue - }, spec)); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/select.js +function asc(column) { + return sql`${column} asc`; +} +function desc(column) { + return sql`${column} desc`; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/relations.js +class Relation { + constructor(sourceTable, referencedTable, relationName) { + this.sourceTable = sourceTable; + this.referencedTable = referencedTable; + this.relationName = relationName; + this.referencedTableName = referencedTable[Table.Symbol.Name]; } + static [entityKind] = "Relation"; + referencedTableName; + fieldName; } -create$8.prototype = MixedSchema.prototype; -function create$7() { - return new BooleanSchema; + +class Relations { + constructor(table, config) { + this.table = table; + this.config = config; + } + static [entityKind] = "Relations"; } -class BooleanSchema extends Schema { - constructor() { - super({ - type: "boolean", - check(v) { - if (v instanceof Boolean) - v = v.valueOf(); - return typeof v === "boolean"; - } - }); - this.withMutation(() => { - this.transform((value, _raw) => { - if (this.spec.coerce && !this.isType(value)) { - if (/^(true|1)$/i.test(String(value))) - return true; - if (/^(false|0)$/i.test(String(value))) - return false; - } - return value; - }); - }); +class One extends Relation { + constructor(sourceTable, referencedTable, config, isNullable) { + super(sourceTable, referencedTable, config?.relationName); + this.config = config; + this.isNullable = isNullable; } - isTrue(message = boolean.isValue) { - return this.test({ - message, - name: "is-value", - exclusive: true, - params: { - value: "true" - }, - test(value) { - return isAbsent(value) || value === true; - } - }); + static [entityKind] = "One"; + withFieldName(fieldName) { + const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable); + relation.fieldName = fieldName; + return relation; } - isFalse(message = boolean.isValue) { - return this.test({ - message, - name: "is-value", - exclusive: true, - params: { - value: "false" - }, - test(value) { - return isAbsent(value) || value === false; - } - }); +} + +class Many extends Relation { + constructor(sourceTable, referencedTable, config) { + super(sourceTable, referencedTable, config?.relationName); + this.config = config; } - default(def) { - return super.default(def); + static [entityKind] = "Many"; + withFieldName(fieldName) { + const relation = new Many(this.sourceTable, this.referencedTable, this.config); + relation.fieldName = fieldName; + return relation; } - defined(msg) { - return super.defined(msg); +} +function getOperators() { + return { + and, + between, + eq, + exists, + gt, + gte, + ilike, + inArray, + isNull, + isNotNull, + like, + lt, + lte, + ne, + not, + notBetween, + notExists, + notLike, + notIlike, + notInArray, + or, + sql + }; +} +function getOrderByOperators() { + return { + sql, + asc, + desc + }; +} +function extractTablesRelationalConfig(schema, configHelpers) { + if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) { + schema = schema["default"]; } - optional() { - return super.optional(); + const tableNamesMap = {}; + const relationsBuffer = {}; + const tablesConfig = {}; + for (const [key, value] of Object.entries(schema)) { + if (is(value, Table)) { + const dbName = getTableUniqueName(value); + const bufferedRelations = relationsBuffer[dbName]; + tableNamesMap[dbName] = key; + tablesConfig[key] = { + tsName: key, + dbName: value[Table.Symbol.Name], + schema: value[Table.Symbol.Schema], + columns: value[Table.Symbol.Columns], + relations: bufferedRelations?.relations ?? {}, + primaryKey: bufferedRelations?.primaryKey ?? [] + }; + for (const column of Object.values(value[Table.Symbol.Columns])) { + if (column.primary) { + tablesConfig[key].primaryKey.push(column); + } + } + const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); + if (extraConfig) { + for (const configEntry of Object.values(extraConfig)) { + if (is(configEntry, PrimaryKeyBuilder)) { + tablesConfig[key].primaryKey.push(...configEntry.columns); + } + } + } + } else if (is(value, Relations)) { + const dbName = getTableUniqueName(value.table); + const tableName = tableNamesMap[dbName]; + const relations2 = value.config(configHelpers(value.table)); + let primaryKey2; + for (const [relationName, relation] of Object.entries(relations2)) { + if (tableName) { + const tableConfig = tablesConfig[tableName]; + tableConfig.relations[relationName] = relation; + if (primaryKey2) { + tableConfig.primaryKey.push(...primaryKey2); + } + } else { + if (!(dbName in relationsBuffer)) { + relationsBuffer[dbName] = { + relations: {}, + primaryKey: primaryKey2 + }; + } + relationsBuffer[dbName].relations[relationName] = relation; + } + } + } } - required(msg) { - return super.required(msg); + return { tables: tablesConfig, tableNamesMap }; +} +function createOne(sourceTable) { + return function one(table, config) { + return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false); + }; +} +function createMany(sourceTable) { + return function many(referencedTable, config) { + return new Many(sourceTable, referencedTable, config); + }; +} +function normalizeRelation(schema, tableNamesMap, relation) { + if (is(relation, One) && relation.config) { + return { + fields: relation.config.fields, + references: relation.config.references + }; } - notRequired() { - return super.notRequired(); + const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; + if (!referencedTableTsName) { + throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`); } - nullable() { - return super.nullable(); + const referencedTableConfig = schema[referencedTableTsName]; + if (!referencedTableConfig) { + throw new Error(`Table "${referencedTableTsName}" not found in schema`); } - nonNullable(msg) { - return super.nonNullable(msg); + const sourceTable = relation.sourceTable; + const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; + if (!sourceTableTsName) { + throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`); } - strip(v) { - return super.strip(v); + const reverseRelations = []; + for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) { + if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { + reverseRelations.push(referencedTableRelation); + } } -} -create$7.prototype = BooleanSchema.prototype; -var isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/; -function parseIsoDate(date2) { - const struct = parseDateStruct(date2); - if (!struct) - return Date.parse ? Date.parse(date2) : Number.NaN; - if (struct.z === undefined && struct.plusMinus === undefined) { - return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf(); + if (reverseRelations.length > 1) { + throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`); } - let totalMinutesOffset = 0; - if (struct.z !== "Z" && struct.plusMinus !== undefined) { - totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset; - if (struct.plusMinus === "+") - totalMinutesOffset = 0 - totalMinutesOffset; + if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { + return { + fields: reverseRelations[0].config.references, + references: reverseRelations[0].config.fields + }; } - return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond); + throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`); } -function parseDateStruct(date2) { - var _regexResult$7$length, _regexResult$; - const regexResult = isoReg.exec(date2); - if (!regexResult) - return null; +function createTableRelationsHelpers(sourceTable) { return { - year: toNumber(regexResult[1]), - month: toNumber(regexResult[2], 1) - 1, - day: toNumber(regexResult[3], 1), - hour: toNumber(regexResult[4]), - minute: toNumber(regexResult[5]), - second: toNumber(regexResult[6]), - millisecond: regexResult[7] ? toNumber(regexResult[7].substring(0, 3)) : 0, - precision: (_regexResult$7$length = (_regexResult$ = regexResult[7]) == null ? undefined : _regexResult$.length) != null ? _regexResult$7$length : undefined, - z: regexResult[8] || undefined, - plusMinus: regexResult[9] || undefined, - hourOffset: toNumber(regexResult[10]), - minuteOffset: toNumber(regexResult[11]) + one: createOne(sourceTable), + many: createMany(sourceTable) }; } -function toNumber(str, defaultValue = 0) { - return Number(str) || defaultValue; +function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { + const result = {}; + for (const [ + selectionItemIndex, + selectionItem + ] of buildQueryResultSelection.entries()) { + if (selectionItem.isJson) { + const relation = tableConfig.relations[selectionItem.tsKey]; + const rawSubRows = row[selectionItemIndex]; + const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; + result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue)); + } else { + const value = mapColumnValue(row[selectionItemIndex]); + const field = selectionItem.field; + let decoder; + if (is(field, Column)) { + decoder = field; + } else if (is(field, SQL)) { + decoder = field.decoder; + } else { + decoder = field.sql.decoder; + } + result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value); + } + } + return result; } -var rEmail = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -var rUrl = /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i; -var rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -var yearMonthDay = "^\\d{4}-\\d{2}-\\d{2}"; -var hourMinuteSecond = "\\d{2}:\\d{2}:\\d{2}"; -var zOrOffset = "(([+-]\\d{2}(:?\\d{2})?)|Z)"; -var rIsoDateTime = new RegExp(`${yearMonthDay}T${hourMinuteSecond}(\\.\\d+)?${zOrOffset}$`); -var isTrimmed = (value) => isAbsent(value) || value === value.trim(); -var objStringTag = {}.toString(); -function create$6() { - return new StringSchema; + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/functions/aggregate.js +function count(expression) { + return sql`count(${expression || sql.raw("*")})`.mapWith(Number); } -class StringSchema extends Schema { - constructor() { - super({ - type: "string", - check(value) { - if (value instanceof String) - value = value.valueOf(); - return typeof value === "string"; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view-base.js +class PgViewBase extends View { + static [entityKind] = "PgViewBase"; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/dialect.js +class PgDialect { + static [entityKind] = "PgDialect"; + casing; + constructor(config) { + this.casing = new CasingCache(config?.casing); + } + async migrate(migrations, session, config) { + const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations"; + const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle"; + const migrationTableCreate = sql` + CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ( + id SERIAL PRIMARY KEY, + hash text NOT NULL, + created_at bigint + ) + `; + await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`); + await session.execute(migrationTableCreate); + const dbMigrations = await session.all(sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`); + const lastDbMigration = dbMigrations[0]; + await session.transaction(async (tx) => { + for await (const migration of migrations) { + if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) { + for (const stmt of migration.sql) { + await tx.execute(sql.raw(stmt)); + } + await tx.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`); + } } }); - this.withMutation(() => { - this.transform((value, _raw) => { - if (!this.spec.coerce || this.isType(value)) - return value; - if (Array.isArray(value)) - return value; - const strValue = value != null && value.toString ? value.toString() : value; - if (strValue === objStringTag) - return value; - return strValue; - }); - }); } - required(message) { - return super.required(message).withMutation((schema) => schema.test({ - message: message || mixed.required, - name: "required", - skipAbsent: true, - test: (value) => !!value.length + escapeName(name) { + return `"${name}"`; + } + escapeParam(num) { + return `$${num + 1}`; + } + escapeString(str) { + return `'${str.replace(/'/g, "''")}'`; + } + buildWithCTE(queries) { + if (!queries?.length) + return; + const withSqlChunks = [sql`with `]; + for (const [i, w] of queries.entries()) { + withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`); + if (i < queries.length - 1) { + withSqlChunks.push(sql`, `); + } + } + withSqlChunks.push(sql` `); + return sql.join(withSqlChunks); + } + buildDeleteQuery({ table, where, returning, withList }) { + const withSql = this.buildWithCTE(withList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined; + const whereSql = where ? sql` where ${where}` : undefined; + return sql`${withSql}delete from ${table}${whereSql}${returningSql}`; + } + buildUpdateSet(table, set) { + const tableColumns = table[Table.Symbol.Columns]; + const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined); + const setSize = columnNames.length; + return sql.join(columnNames.flatMap((colName, i) => { + const col = tableColumns[colName]; + const value = set[colName] ?? sql.param(col.onUpdateFn(), col); + const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; + if (i < setSize - 1) { + return [res, sql.raw(", ")]; + } + return [res]; })); } - notRequired() { - return super.notRequired().withMutation((schema) => { - schema.tests = schema.tests.filter((t) => t.OPTIONS.name !== "required"); - return schema; - }); + buildUpdateQuery({ table, set, where, returning, withList, from, joins }) { + const withSql = this.buildWithCTE(withList); + const tableName = table[PgTable.Symbol.Name]; + const tableSchema = table[PgTable.Symbol.Schema]; + const origTableName = table[PgTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? undefined : tableName; + const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`; + const setSql = this.buildUpdateSet(table, set); + const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); + const joinsSql = this.buildJoins(joins); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : undefined; + const whereSql = where ? sql` where ${where}` : undefined; + return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`; } - length(length, message = string.length) { - return this.test({ - message, - name: "length", - exclusive: true, - params: { - length - }, - skipAbsent: true, - test(value) { - return value.length === this.resolve(length); + buildSelection(fields, { isSingleTable = false } = {}) { + const columnsLen = fields.length; + const chunks = fields.flatMap(({ field }, i) => { + const chunk = []; + if (is(field, SQL.Aliased) && field.isSelectionField) { + chunk.push(sql.identifier(field.fieldAlias)); + } else if (is(field, SQL.Aliased) || is(field, SQL)) { + const query = is(field, SQL.Aliased) ? field.sql : field; + if (isSingleTable) { + chunk.push(new SQL(query.queryChunks.map((c) => { + if (is(c, PgColumn)) { + return sql.identifier(this.casing.getColumnCasing(c)); + } + return c; + }))); + } else { + chunk.push(query); + } + if (is(field, SQL.Aliased)) { + chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); + } + } else if (is(field, Column)) { + if (isSingleTable) { + chunk.push(sql.identifier(this.casing.getColumnCasing(field))); + } else { + chunk.push(field); + } + } + if (i < columnsLen - 1) { + chunk.push(sql`, `); } + return chunk; }); + return sql.join(chunks); } - min(min, message = string.min) { - return this.test({ - message, - name: "min", - exclusive: true, - params: { - min - }, - skipAbsent: true, - test(value) { - return value.length >= this.resolve(min); + buildJoins(joins) { + if (!joins || joins.length === 0) { + return; + } + const joinsArray = []; + for (const [index2, joinMeta] of joins.entries()) { + if (index2 === 0) { + joinsArray.push(sql` `); } - }); + const table = joinMeta.table; + const lateralSql = joinMeta.lateral ? sql` lateral` : undefined; + const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : undefined; + if (is(table, PgTable)) { + const tableName = table[PgTable.Symbol.Name]; + const tableSchema = table[PgTable.Symbol.Schema]; + const origTableName = table[PgTable.Symbol.OriginalName]; + const alias = tableName === origTableName ? undefined : joinMeta.alias; + joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`); + } else if (is(table, View)) { + const viewName = table[ViewBaseConfig].name; + const viewSchema = table[ViewBaseConfig].schema; + const origViewName = table[ViewBaseConfig].originalName; + const alias = viewName === origViewName ? undefined : joinMeta.alias; + joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : undefined}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`); + } else { + joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`); + } + if (index2 < joins.length - 1) { + joinsArray.push(sql` `); + } + } + return sql.join(joinsArray); } - max(max, message = string.max) { - return this.test({ - name: "max", - exclusive: true, - message, - params: { - max - }, - skipAbsent: true, - test(value) { - return value.length <= this.resolve(max); + buildFromTable(table) { + if (is(table, Table) && table[Table.Symbol.IsAlias]) { + let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`; + if (table[Table.Symbol.Schema]) { + fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`; } - }); + return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`; + } + return table; } - matches(regex, options) { - let excludeEmptyString = false; - let message; - let name; - if (options) { - if (typeof options === "object") { - ({ - excludeEmptyString = false, - message, - name - } = options); + buildSelectQuery({ + withList, + fields, + fieldsFlat, + where, + having, + table, + joins, + orderBy, + groupBy, + limit, + offset, + lockingClause, + distinct, + setOperators + }) { + const fieldsList = fieldsFlat ?? orderSelectedFields(fields); + for (const f of fieldsList) { + if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) { + const tableName = getTableName(f.field.table); + throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`); + } + } + const isSingleTable = !joins || joins.length === 0; + const withSql = this.buildWithCTE(withList); + let distinctSql; + if (distinct) { + distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`; + } + const selection = this.buildSelection(fieldsList, { isSingleTable }); + const tableSql = this.buildFromTable(table); + const joinsSql = this.buildJoins(joins); + const whereSql = where ? sql` where ${where}` : undefined; + const havingSql = having ? sql` having ${having}` : undefined; + let orderBySql; + if (orderBy && orderBy.length > 0) { + orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`; + } + let groupBySql; + if (groupBy && groupBy.length > 0) { + groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined; + const offsetSql = offset ? sql` offset ${offset}` : undefined; + const lockingClauseSql = sql.empty(); + if (lockingClause) { + const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`; + if (lockingClause.config.of) { + clauseSql.append(sql` of ${sql.join(Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], sql`, `)}`); + } + if (lockingClause.config.noWait) { + clauseSql.append(sql` nowait`); + } else if (lockingClause.config.skipLocked) { + clauseSql.append(sql` skip locked`); + } + lockingClauseSql.append(clauseSql); + } + const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`; + if (setOperators.length > 0) { + return this.buildSetOperations(finalQuery, setOperators); + } + return finalQuery; + } + buildSetOperations(leftSelect, setOperators) { + const [setOperator, ...rest] = setOperators; + if (!setOperator) { + throw new Error("Cannot pass undefined values to any set operator"); + } + if (rest.length === 0) { + return this.buildSetOperationQuery({ leftSelect, setOperator }); + } + return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest); + } + buildSetOperationQuery({ + leftSelect, + setOperator: { type, isAll, rightSelect, limit, orderBy, offset } + }) { + const leftChunk = sql`(${leftSelect.getSQL()}) `; + const rightChunk = sql`(${rightSelect.getSQL()})`; + let orderBySql; + if (orderBy && orderBy.length > 0) { + const orderByValues = []; + for (const singleOrderBy of orderBy) { + if (is(singleOrderBy, PgColumn)) { + orderByValues.push(sql.identifier(singleOrderBy.name)); + } else if (is(singleOrderBy, SQL)) { + for (let i = 0;i < singleOrderBy.queryChunks.length; i++) { + const chunk = singleOrderBy.queryChunks[i]; + if (is(chunk, PgColumn)) { + singleOrderBy.queryChunks[i] = sql.identifier(chunk.name); + } + } + orderByValues.push(sql`${singleOrderBy}`); + } else { + orderByValues.push(sql`${singleOrderBy}`); + } + } + orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `; + } + const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined; + const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); + const offsetSql = offset ? sql` offset ${offset}` : undefined; + return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; + } + buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) { + const valuesSqlList = []; + const columns = table[Table.Symbol.Columns]; + const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert()); + const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column))); + if (select) { + const select2 = valuesOrSelect; + if (is(select2, SQL)) { + valuesSqlList.push(select2); } else { - message = options; + valuesSqlList.push(select2.getSQL()); + } + } else { + const values = valuesOrSelect; + valuesSqlList.push(sql.raw("values ")); + for (const [valueIndex, value] of values.entries()) { + const valueList = []; + for (const [fieldName, col] of colEntries) { + const colValue = value[fieldName]; + if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) { + if (col.defaultFn !== undefined) { + const defaultFnResult = col.defaultFn(); + const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); + valueList.push(defaultValue); + } else if (!col.default && col.onUpdateFn !== undefined) { + const onUpdateFnResult = col.onUpdateFn(); + const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); + valueList.push(newValue); + } else { + valueList.push(sql`default`); + } + } else { + valueList.push(colValue); + } + } + valuesSqlList.push(valueList); + if (valueIndex < values.length - 1) { + valuesSqlList.push(sql`, `); + } } } - return this.test({ - name: name || "matches", - message: message || string.matches, - params: { - regex - }, - skipAbsent: true, - test: (value) => value === "" && excludeEmptyString || value.search(regex) !== -1 - }); + const withSql = this.buildWithCTE(withList); + const valuesSql = sql.join(valuesSqlList); + const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined; + const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : undefined; + const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : undefined; + return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`; } - email(message = string.email) { - return this.matches(rEmail, { - name: "email", - message, - excludeEmptyString: true - }); + buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) { + const concurrentlySql = concurrently ? sql` concurrently` : undefined; + const withNoDataSql = withNoData ? sql` with no data` : undefined; + return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`; } - url(message = string.url) { - return this.matches(rUrl, { - name: "url", - message, - excludeEmptyString: true - }); + prepareTyping(encoder) { + if (is(encoder, PgJsonb) || is(encoder, PgJson)) { + return "json"; + } else if (is(encoder, PgNumeric)) { + return "decimal"; + } else if (is(encoder, PgTime)) { + return "time"; + } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) { + return "timestamp"; + } else if (is(encoder, PgDate) || is(encoder, PgDateString)) { + return "date"; + } else if (is(encoder, PgUUID)) { + return "uuid"; + } else { + return "none"; + } } - uuid(message = string.uuid) { - return this.matches(rUUID, { - name: "uuid", - message, - excludeEmptyString: false + sqlToQuery(sql2, invokeSource) { + return sql2.toQuery({ + casing: this.casing, + escapeName: this.escapeName, + escapeParam: this.escapeParam, + escapeString: this.escapeString, + prepareTyping: this.prepareTyping, + invokeSource }); } - datetime(options) { - let message = ""; - let allowOffset; - let precision; - if (options) { - if (typeof options === "object") { - ({ - message = "", - allowOffset = false, - precision = undefined - } = options); + buildRelationalQueryWithoutPK({ + fullSchema, + schema, + tableNamesMap, + table, + tableConfig, + queryConfig: config, + tableAlias, + nestedQueryRelation, + joinOn + }) { + let selection = []; + let limit, offset, orderBy = [], where; + const joins = []; + if (config === true) { + const selectionEntries = Object.entries(tableConfig.columns); + selection = selectionEntries.map(([key, value]) => ({ + dbKey: value.name, + tsKey: key, + field: aliasedTableColumn(value, tableAlias), + relationTableTsKey: undefined, + isJson: false, + selection: [] + })); + } else { + const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])); + if (config.where) { + const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where; + where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); + } + const fieldsSelection = []; + let selectedColumns = []; + if (config.columns) { + let isIncludeMode = false; + for (const [field, value] of Object.entries(config.columns)) { + if (value === undefined) { + continue; + } + if (field in tableConfig.columns) { + if (!isIncludeMode && value === true) { + isIncludeMode = true; + } + selectedColumns.push(field); + } + } + if (selectedColumns.length > 0) { + selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); + } } else { - message = options; + selectedColumns = Object.keys(tableConfig.columns); + } + for (const field of selectedColumns) { + const column = tableConfig.columns[field]; + fieldsSelection.push({ tsKey: field, value: column }); + } + let selectedRelations = []; + if (config.with) { + selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); + } + let extras; + if (config.extras) { + extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras; + for (const [tsKey, value] of Object.entries(extras)) { + fieldsSelection.push({ + tsKey, + value: mapColumnsInAliasedSQLToAlias(value, tableAlias) + }); + } + } + for (const { tsKey, value } of fieldsSelection) { + selection.push({ + dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, + tsKey, + field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, + relationTableTsKey: undefined, + isJson: false, + selection: [] + }); + } + let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? []; + if (!Array.isArray(orderByOrig)) { + orderByOrig = [orderByOrig]; + } + orderBy = orderByOrig.map((orderByValue) => { + if (is(orderByValue, Column)) { + return aliasedTableColumn(orderByValue, tableAlias); + } + return mapColumnsInSQLToAlias(orderByValue, tableAlias); + }); + limit = config.limit; + offset = config.offset; + for (const { + tsKey: selectedRelationTsKey, + queryConfig: selectedRelationConfigValue, + relation + } of selectedRelations) { + const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); + const relationTableName = getTableUniqueName(relation.referencedTable); + const relationTableTsName = tableNamesMap[relationTableName]; + const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; + const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias)))); + const builtRelation = this.buildRelationalQueryWithoutPK({ + fullSchema, + schema, + tableNamesMap, + table: fullSchema[relationTableTsName], + tableConfig: schema[relationTableTsName], + queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, + tableAlias: relationTableAlias, + joinOn: joinOn2, + nestedQueryRelation: relation + }); + const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey); + joins.push({ + on: sql`true`, + table: new Subquery(builtRelation.sql, {}, relationTableAlias), + alias: relationTableAlias, + joinType: "left", + lateral: true + }); + selection.push({ + dbKey: selectedRelationTsKey, + tsKey: selectedRelationTsKey, + field, + relationTableTsKey: relationTableTsName, + isJson: true, + selection: builtRelation.selection + }); } } - return this.matches(rIsoDateTime, { - name: "datetime", - message: message || string.datetime, - excludeEmptyString: true - }).test({ - name: "datetime_offset", - message: message || string.datetime_offset, - params: { - allowOffset - }, - skipAbsent: true, - test: (value) => { - if (!value || allowOffset) - return true; - const struct = parseDateStruct(value); - if (!struct) - return false; - return !!struct.z; + if (selection.length === 0) { + throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` }); + } + let result; + where = and(joinOn, where); + if (nestedQueryRelation) { + let field = sql`json_build_array(${sql.join(selection.map(({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`; + if (is(nestedQueryRelation, Many)) { + field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : undefined}), '[]'::json)`; } - }).test({ - name: "datetime_precision", - message: message || string.datetime_precision, - params: { - precision - }, - skipAbsent: true, - test: (value) => { - if (!value || precision == undefined) - return true; - const struct = parseDateStruct(value); - if (!struct) - return false; - return struct.precision === precision; + const nestedSelection = [{ + dbKey: "data", + tsKey: "data", + field: field.as("data"), + isJson: true, + relationTableTsKey: tableConfig.tsName, + selection + }]; + const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0; + if (needsSubquery) { + result = this.buildSelectQuery({ + table: aliasedTable(table, tableAlias), + fields: {}, + fieldsFlat: [{ + path: [], + field: sql.raw("*") + }], + where, + limit, + offset, + orderBy, + setOperators: [] + }); + where = undefined; + limit = undefined; + offset = undefined; + orderBy = []; + } else { + result = aliasedTable(table, tableAlias); } - }); + result = this.buildSelectQuery({ + table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias), + fields: {}, + fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ + path: [], + field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } else { + result = this.buildSelectQuery({ + table: aliasedTable(table, tableAlias), + fields: {}, + fieldsFlat: selection.map(({ field }) => ({ + path: [], + field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field + })), + joins, + where, + limit, + offset, + orderBy, + setOperators: [] + }); + } + return { + tableTsKey: tableConfig.tsName, + sql: result, + selection + }; } - ensure() { - return this.default("").transform((val) => val === null ? "" : val); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-builders/query-builder.js +class TypedQueryBuilder { + static [entityKind] = "TypedQueryBuilder"; + getSelectedFields() { + return this._.selectedFields; } - trim(message = string.trim) { - return this.transform((val) => val != null ? val.trim() : val).test({ - message, - name: "trim", - test: isTrimmed - }); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/select.js +class PgSelectBuilder { + static [entityKind] = "PgSelectBuilder"; + fields; + session; + dialect; + withList = []; + distinct; + constructor(config) { + this.fields = config.fields; + this.session = config.session; + this.dialect = config.dialect; + if (config.withList) { + this.withList = config.withList; + } + this.distinct = config.distinct; } - lowercase(message = string.lowercase) { - return this.transform((value) => !isAbsent(value) ? value.toLowerCase() : value).test({ - message, - name: "string_case", - exclusive: true, - skipAbsent: true, - test: (value) => isAbsent(value) || value === value.toLowerCase() - }); + authToken; + setToken(token) { + this.authToken = token; + return this; } - uppercase(message = string.uppercase) { - return this.transform((value) => !isAbsent(value) ? value.toUpperCase() : value).test({ - message, - name: "string_case", - exclusive: true, - skipAbsent: true, - test: (value) => isAbsent(value) || value === value.toUpperCase() - }); + from(source) { + const isPartialSelect = !!this.fields; + const src = source; + let fields; + if (this.fields) { + fields = this.fields; + } else if (is(src, Subquery)) { + fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [key, src[key]])); + } else if (is(src, PgViewBase)) { + fields = src[ViewBaseConfig].selectedFields; + } else if (is(src, SQL)) { + fields = {}; + } else { + fields = getTableColumns(src); + } + return new PgSelectBase({ + table: src, + fields, + isPartialSelect, + session: this.session, + dialect: this.dialect, + withList: this.withList, + distinct: this.distinct + }).setToken(this.authToken); } } -create$6.prototype = StringSchema.prototype; -var isNaN$1 = (value) => value != +value; -function create$5() { - return new NumberSchema; -} -class NumberSchema extends Schema { - constructor() { - super({ - type: "number", - check(value) { - if (value instanceof Number) - value = value.valueOf(); - return typeof value === "number" && !isNaN$1(value); +class PgSelectQueryBuilderBase extends TypedQueryBuilder { + static [entityKind] = "PgSelectQueryBuilder"; + _; + config; + joinsNotNullableMap; + tableName; + isPartialSelect; + session; + dialect; + cacheConfig = undefined; + usedTables = /* @__PURE__ */ new Set; + constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) { + super(); + this.config = { + withList, + table, + fields: { ...fields }, + distinct, + setOperators: [] + }; + this.isPartialSelect = isPartialSelect; + this.session = session; + this.dialect = dialect; + this._ = { + selectedFields: fields, + config: this.config + }; + this.tableName = getTableLikeName(table); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + for (const item of extractUsedTable(table)) + this.usedTables.add(item); + } + getUsedTables() { + return [...this.usedTables]; + } + createJoin(joinType, lateral) { + return (table, on) => { + const baseTableName = this.tableName; + const tableName = getTableLikeName(table); + for (const item of extractUsedTable(table)) + this.usedTables.add(item); + if (typeof tableName === "string" && this.config.joins?.some((join2) => join2.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); } - }); - this.withMutation(() => { - this.transform((value, _raw) => { - if (!this.spec.coerce) - return value; - let parsed = value; - if (typeof parsed === "string") { - parsed = parsed.replace(/\s/g, ""); - if (parsed === "") - return NaN; - parsed = +parsed; + if (!this.isPartialSelect) { + if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { + this.config.fields = { + [baseTableName]: this.config.fields + }; + } + if (typeof tableName === "string" && !is(table, SQL)) { + const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns]; + this.config.fields[tableName] = selection; } - if (this.isType(parsed) || parsed === null) - return parsed; - return parseFloat(parsed); - }); - }); - } - min(min, message = number.min) { - return this.test({ - message, - name: "min", - exclusive: true, - params: { - min - }, - skipAbsent: true, - test(value) { - return value >= this.resolve(min); } - }); - } - max(max, message = number.max) { - return this.test({ - message, - name: "max", - exclusive: true, - params: { - max - }, - skipAbsent: true, - test(value) { - return value <= this.resolve(max); + if (typeof on === "function") { + on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); } - }); - } - lessThan(less, message = number.lessThan) { - return this.test({ - message, - name: "max", - exclusive: true, - params: { - less - }, - skipAbsent: true, - test(value) { - return value < this.resolve(less); + if (!this.config.joins) { + this.config.joins = []; } - }); - } - moreThan(more, message = number.moreThan) { - return this.test({ - message, - name: "min", - exclusive: true, - params: { - more - }, - skipAbsent: true, - test(value) { - return value > this.resolve(more); + this.config.joins.push({ on, table, joinType, alias: tableName, lateral }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "cross": + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); + this.joinsNotNullableMap[tableName] = false; + break; + } + } } - }); + return this; + }; } - positive(msg = number.positive) { - return this.moreThan(0, msg); + leftJoin = this.createJoin("left", false); + leftJoinLateral = this.createJoin("left", true); + rightJoin = this.createJoin("right", false); + innerJoin = this.createJoin("inner", false); + innerJoinLateral = this.createJoin("inner", true); + fullJoin = this.createJoin("full", false); + crossJoin = this.createJoin("cross", false); + crossJoinLateral = this.createJoin("cross", true); + createSetOperator(type, isAll) { + return (rightSelection) => { + const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection; + if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { + throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order"); + } + this.config.setOperators.push({ type, isAll, rightSelect }); + return this; + }; } - negative(msg = number.negative) { - return this.lessThan(0, msg); + union = this.createSetOperator("union", false); + unionAll = this.createSetOperator("union", true); + intersect = this.createSetOperator("intersect", false); + intersectAll = this.createSetOperator("intersect", true); + except = this.createSetOperator("except", false); + exceptAll = this.createSetOperator("except", true); + addSetOperators(setOperators) { + this.config.setOperators.push(...setOperators); + return this; } - integer(message = number.integer) { - return this.test({ - name: "integer", - message, - skipAbsent: true, - test: (val) => Number.isInteger(val) - }); + where(where) { + if (typeof where === "function") { + where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); + } + this.config.where = where; + return this; } - truncate() { - return this.transform((value) => !isAbsent(value) ? value | 0 : value); + having(having) { + if (typeof having === "function") { + having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); + } + this.config.having = having; + return this; } - round(method) { - var _method; - let avail = ["ceil", "floor", "round", "trunc"]; - method = ((_method = method) == null ? undefined : _method.toLowerCase()) || "round"; - if (method === "trunc") - return this.truncate(); - if (avail.indexOf(method.toLowerCase()) === -1) - throw new TypeError("Only valid options for round() are: " + avail.join(", ")); - return this.transform((value) => !isAbsent(value) ? Math[method](value) : value); + groupBy(...columns) { + if (typeof columns[0] === "function") { + const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }))); + this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; + } else { + this.config.groupBy = columns; + } + return this; } -} -create$5.prototype = NumberSchema.prototype; -var invalidDate = new Date(""); -var isDate = (obj) => Object.prototype.toString.call(obj) === "[object Date]"; -function create$4() { - return new DateSchema; -} - -class DateSchema extends Schema { - constructor() { - super({ - type: "date", - check(v) { - return isDate(v) && !isNaN(v.getTime()); + orderBy(...columns) { + if (typeof columns[0] === "function") { + const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }))); + const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; } - }); - this.withMutation(() => { - this.transform((value, _raw) => { - if (!this.spec.coerce || this.isType(value) || value === null) - return value; - value = parseIsoDate(value); - return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE; - }); - }); - } - prepareParam(ref, name) { - let param; - if (!Reference.isRef(ref)) { - let cast = this.cast(ref); - if (!this._typeCheck(cast)) - throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`); - param = cast; } else { - param = ref; + const orderByArray = columns; + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).orderBy = orderByArray; + } else { + this.config.orderBy = orderByArray; + } } - return param; + return this; } - min(min, message = date.min) { - let limit = this.prepareParam(min, "min"); - return this.test({ - message, - name: "min", - exclusive: true, - params: { - min - }, - skipAbsent: true, - test(value) { - return value >= this.resolve(limit); - } - }); + limit(limit) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).limit = limit; + } else { + this.config.limit = limit; + } + return this; } - max(max, message = date.max) { - let limit = this.prepareParam(max, "max"); - return this.test({ - message, - name: "max", - exclusive: true, - params: { - max - }, - skipAbsent: true, - test(value) { - return value <= this.resolve(limit); - } - }); + offset(offset) { + if (this.config.setOperators.length > 0) { + this.config.setOperators.at(-1).offset = offset; + } else { + this.config.offset = offset; + } + return this; } -} -DateSchema.INVALID_DATE = invalidDate; -create$4.prototype = DateSchema.prototype; -create$4.INVALID_DATE = invalidDate; -function sortFields(fields, excludedEdges = []) { - let edges = []; - let nodes = new Set; - let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`)); - function addNode(depPath, key) { - let node = import_property_expr.split(depPath)[0]; - nodes.add(node); - if (!excludes.has(`${key}-${node}`)) - edges.push([key, node]); + for(strength, config = {}) { + this.config.lockingClause = { strength, config }; + return this; } - for (const key of Object.keys(fields)) { - let value = fields[key]; - nodes.add(key); - if (Reference.isRef(value) && value.isSibling) - addNode(value.path, key); - else if (isSchema(value) && "deps" in value) - value.deps.forEach((path) => addNode(path, key)); + getSQL() { + return this.dialect.buildSelectQuery(this.config); } - return import_toposort.default.array(Array.from(nodes), edges).reverse(); -} -function findIndex(arr, err) { - let idx = Infinity; - arr.some((key, ii) => { - var _err$path; - if ((_err$path = err.path) != null && _err$path.includes(key)) { - idx = ii; - return true; - } - }); - return idx; -} -function sortByKeyOrder(keys) { - return (a, b) => { - return findIndex(keys, a) - findIndex(keys, b); - }; -} -var parseJson = (value, _, schema) => { - if (typeof value !== "string") { - return value; + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; } - let parsed = value; - try { - parsed = JSON.parse(value); - } catch (err) {} - return schema.isType(parsed) ? parsed : value; -}; -function deepPartial(schema) { - if ("fields" in schema) { - const partial = {}; - for (const [key, fieldSchema] of Object.entries(schema.fields)) { - partial[key] = deepPartial(fieldSchema); + as(alias) { + const usedTables = []; + usedTables.push(...extractUsedTable(this.config.table)); + if (this.config.joins) { + for (const it of this.config.joins) + usedTables.push(...extractUsedTable(it.table)); } - return schema.setFields(partial); + return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); } - if (schema.type === "array") { - const nextArray = schema.optional(); - if (nextArray.innerType) - nextArray.innerType = deepPartial(nextArray.innerType); - return nextArray; + getSelectedFields() { + return new Proxy(this.config.fields, new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); } - if (schema.type === "tuple") { - return schema.optional().clone({ - types: schema.spec.types.map(deepPartial) - }); + $dynamic() { + return this; } - if ("optional" in schema) { - return schema.optional(); + $withCache(config) { + this.cacheConfig = config === undefined ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config }; + return this; } - return schema; -} -var deepHas = (obj, p) => { - const path = [...import_property_expr.normalizePath(p)]; - if (path.length === 1) - return path[0] in obj; - let last = path.pop(); - let parent = import_property_expr.getter(import_property_expr.join(path), true)(obj); - return !!(parent && (last in parent)); -}; -var isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]"; -function unknown(ctx, value) { - let known = Object.keys(ctx.fields); - return Object.keys(value).filter((key) => known.indexOf(key) === -1); -} -var defaultSort = sortByKeyOrder([]); -function create$3(spec) { - return new ObjectSchema(spec); } -class ObjectSchema extends Schema { - constructor(spec) { - super({ - type: "object", - check(value) { - return isObject(value) || typeof value === "function"; - } - }); - this.fields = Object.create(null); - this._sortErrors = defaultSort; - this._nodes = []; - this._excludedEdges = []; - this.withMutation(() => { - if (spec) { - this.shape(spec); - } +class PgSelectBase extends PgSelectQueryBuilderBase { + static [entityKind] = "PgSelect"; + _prepare(name) { + const { session, config, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this; + if (!session) { + throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); + } + const { fields } = config; + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + const fieldsList = orderSelectedFields(fields); + const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, undefined, { + type: "select", + tables: [...usedTables] + }, cacheConfig); + query.joinsNotNullableMap = joinsNotNullableMap; + return query.setToken(authToken); }); } - _cast(_value, options = {}) { - var _options$stripUnknown; - let value = super._cast(_value, options); - if (value === undefined) - return this.getDefault(options); - if (!this._typeCheck(value)) - return value; - let fields = this.fields; - let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown; - let props = [].concat(this._nodes, Object.keys(value).filter((v) => !this._nodes.includes(v))); - let intermediateValue = {}; - let innerOptions = Object.assign({}, options, { - parent: intermediateValue, - __validating: options.__validating || false + prepare(name) { + return this._prepare(name); + } + authToken; + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); }); - let isChanged = false; - for (const prop of props) { - let field = fields[prop]; - let exists = prop in value; - let inputValue = value[prop]; - if (field) { - let fieldValue; - innerOptions.path = (options.path ? `${options.path}.` : "") + prop; - field = field.resolve({ - value: inputValue, - context: options.context, - parent: intermediateValue - }); - let fieldSpec = field instanceof Schema ? field.spec : undefined; - let strict = fieldSpec == null ? undefined : fieldSpec.strict; - if (fieldSpec != null && fieldSpec.strip) { - isChanged = isChanged || prop in value; - continue; - } - fieldValue = !options.__validating || !strict ? field.cast(inputValue, innerOptions) : inputValue; - if (fieldValue !== undefined) { - intermediateValue[prop] = fieldValue; - } - } else if (exists && !strip) { - intermediateValue[prop] = inputValue; - } - if (exists !== prop in intermediateValue || intermediateValue[prop] !== inputValue) { - isChanged = true; + }; +} +applyMixins(PgSelectBase, [QueryPromise]); +function createSetOperator(type, isAll) { + return (leftSelect, rightSelect, ...restSelects) => { + const setOperators = [rightSelect, ...restSelects].map((select) => ({ + type, + isAll, + rightSelect: select + })); + for (const setOperator of setOperators) { + if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { + throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order"); } } - return isChanged ? intermediateValue : value; + return leftSelect.addSetOperators(setOperators); + }; +} +var getPgSetOperators = () => ({ + union, + unionAll, + intersect, + intersectAll, + except, + exceptAll +}); +var union = createSetOperator("union", false); +var unionAll = createSetOperator("union", true); +var intersect = createSetOperator("intersect", false); +var intersectAll = createSetOperator("intersect", true); +var except = createSetOperator("except", false); +var exceptAll = createSetOperator("except", true); + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js +class QueryBuilder { + static [entityKind] = "PgQueryBuilder"; + dialect; + dialectConfig; + constructor(dialect) { + this.dialect = is(dialect, PgDialect) ? dialect : undefined; + this.dialectConfig = is(dialect, PgDialect) ? undefined : dialect; } - _validate(_value, options = {}, panic, next) { - let { - from = [], - originalValue = _value, - recursive = this.spec.recursive - } = options; - options.from = [{ - schema: this, - value: originalValue - }, ...from]; - options.__validating = true; - options.originalValue = originalValue; - super._validate(_value, options, panic, (objectErrors, value) => { - if (!recursive || !isObject(value)) { - next(objectErrors, value); - return; - } - originalValue = originalValue || value; - let tests = []; - for (let key of this._nodes) { - let field = this.fields[key]; - if (!field || Reference.isRef(field)) { - continue; - } - tests.push(field.asNestedTest({ - options, - key, - parent: value, - parentPath: options.path, - originalParent: originalValue - })); + $with = (alias, selection) => { + const queryBuilder = this; + const as = (qb) => { + if (typeof qb === "function") { + qb = qb(queryBuilder); } - this.runTests({ - tests, - value, - originalValue, - options - }, panic, (fieldErrors) => { - next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value); + return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); + }; + return { as }; + }; + with(...queries) { + const self2 = this; + function select(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: undefined, + dialect: self2.getDialect(), + withList: queries }); - }); - } - clone(spec) { - const next = super.clone(spec); - next.fields = Object.assign({}, this.fields); - next._nodes = this._nodes; - next._excludedEdges = this._excludedEdges; - next._sortErrors = this._sortErrors; - return next; - } - concat(schema) { - let next = super.concat(schema); - let nextFields = next.fields; - for (let [field, schemaOrRef] of Object.entries(this.fields)) { - const target = nextFields[field]; - nextFields[field] = target === undefined ? schemaOrRef : target; } - return next.withMutation((s) => s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges])); - } - _getDefault(options) { - if ("default" in this.spec) { - return super._getDefault(options); + function selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: undefined, + dialect: self2.getDialect(), + distinct: true + }); } - if (!this._nodes.length) { - return; + function selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: undefined, + dialect: self2.getDialect(), + distinct: { on } + }); } - let dft = {}; - this._nodes.forEach((key) => { - var _innerOptions; - const field = this.fields[key]; - let innerOptions = options; - if ((_innerOptions = innerOptions) != null && _innerOptions.value) { - innerOptions = Object.assign({}, innerOptions, { - parent: innerOptions.value, - value: innerOptions.value[key] - }); - } - dft[key] = field && "getDefault" in field ? field.getDefault(innerOptions) : undefined; + return { select, selectDistinct, selectDistinctOn }; + } + select(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: undefined, + dialect: this.getDialect() }); - return dft; } - setFields(shape, excludedEdges) { - let next = this.clone(); - next.fields = shape; - next._nodes = sortFields(shape, excludedEdges); - next._sortErrors = sortByKeyOrder(Object.keys(shape)); - if (excludedEdges) - next._excludedEdges = excludedEdges; - return next; + selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: undefined, + dialect: this.getDialect(), + distinct: true + }); } - shape(additions, excludes = []) { - return this.clone().withMutation((next) => { - let edges = next._excludedEdges; - if (excludes.length) { - if (!Array.isArray(excludes[0])) - excludes = [excludes]; - edges = [...next._excludedEdges, ...excludes]; - } - return next.setFields(Object.assign(next.fields, additions), edges); + selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: undefined, + dialect: this.getDialect(), + distinct: { on } }); } - partial() { - const partial = {}; - for (const [key, schema] of Object.entries(this.fields)) { - partial[key] = "optional" in schema && schema.optional instanceof Function ? schema.optional() : schema; + getDialect() { + if (!this.dialect) { + this.dialect = new PgDialect(this.dialectConfig); } - return this.setFields(partial); + return this.dialect; } - deepPartial() { - const next = deepPartial(this); - return next; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils.js +function extractUsedTable(table) { + if (is(table, PgTable)) { + return [table[Schema2] ? `${table[Schema2]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]]; } - pick(keys) { - const picked = {}; - for (const key of keys) { - if (this.fields[key]) - picked[key] = this.fields[key]; - } - return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b))); + if (is(table, Subquery)) { + return table._.usedTables ?? []; } - omit(keys) { - const remaining = []; - for (const key of Object.keys(this.fields)) { - if (keys.includes(key)) - continue; - remaining.push(key); - } - return this.pick(remaining); + if (is(table, SQL)) { + return table.usedTables ?? []; } - from(from, to, alias) { - let fromGetter = import_property_expr.getter(from, true); - return this.transform((obj) => { - if (!obj) - return obj; - let newObj = obj; - if (deepHas(obj, from)) { - newObj = Object.assign({}, obj); - if (!alias) - delete newObj[from]; - newObj[to] = fromGetter(obj); - } - return newObj; - }); + return []; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/delete.js +class PgDeleteBase extends QueryPromise { + constructor(table, session, dialect, withList) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { table, withList }; } - json() { - return this.transform(parseJson); + static [entityKind] = "PgDelete"; + config; + cacheConfig; + where(where) { + this.config.where = where; + return this; } - exact(message) { - return this.test({ - name: "exact", - exclusive: true, - message: message || object.exact, - test(value) { - if (value == null) - return true; - const unknownKeys = unknown(this.schema, value); - return unknownKeys.length === 0 || this.createError({ - params: { - properties: unknownKeys.join(", ") - } - }); - } - }); + returning(fields = this.config.table[Table.Symbol.Columns]) { + this.config.returningFields = fields; + this.config.returning = orderSelectedFields(fields); + return this; } - stripUnknown() { - return this.clone({ - noUnknown: true - }); + getSQL() { + return this.dialect.buildDeleteQuery(this.config); } - noUnknown(noAllow = true, message = object.noUnknown) { - if (typeof noAllow !== "boolean") { - message = noAllow; - noAllow = true; - } - let next = this.test({ - name: "noUnknown", - exclusive: true, - message, - test(value) { - if (value == null) - return true; - const unknownKeys = unknown(this.schema, value); - return !noAllow || unknownKeys.length === 0 || this.createError({ - params: { - unknown: unknownKeys.join(", ") - } - }); - } + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; + } + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { + type: "delete", + tables: extractUsedTable(this.config.table) + }, this.cacheConfig); }); - next.spec.noUnknown = noAllow; - return next; } - unknown(allow = true, message = object.noUnknown) { - return this.noUnknown(!allow, message); + prepare(name) { + return this._prepare(name); } - transformKeys(fn) { - return this.transform((obj) => { - if (!obj) - return obj; - const result = {}; - for (const key of Object.keys(obj)) - result[fn(key)] = obj[key]; - return result; + authToken; + setToken(token) { + this.authToken = token; + return this; + } + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); }); + }; + getSelectedFields() { + return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({ + alias: getTableName(this.config.table), + sqlAliasedBehavior: "alias", + sqlBehavior: "error" + })) : undefined; } - camelCase() { - return this.transformKeys(import_tiny_case.camelCase); + $dynamic() { + return this; } - snakeCase() { - return this.transformKeys(import_tiny_case.snakeCase); +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/insert.js +class PgInsertBuilder { + constructor(table, session, dialect, withList, overridingSystemValue_) { + this.table = table; + this.session = session; + this.dialect = dialect; + this.withList = withList; + this.overridingSystemValue_ = overridingSystemValue_; } - constantCase() { - return this.transformKeys((key) => import_tiny_case.snakeCase(key).toUpperCase()); + static [entityKind] = "PgInsertBuilder"; + authToken; + setToken(token) { + this.authToken = token; + return this; } - describe(options) { - const next = (options ? this.resolve(options) : this).clone(); - const base = super.describe(options); - base.fields = {}; - for (const [key, value] of Object.entries(next.fields)) { - var _innerOptions2; - let innerOptions = options; - if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) { - innerOptions = Object.assign({}, innerOptions, { - parent: innerOptions.value, - value: innerOptions.value[key] - }); - } - base.fields[key] = value.describe(innerOptions); - } - return base; + overridingSystemValue() { + this.overridingSystemValue_ = true; + return this; } -} -create$3.prototype = ObjectSchema.prototype; -function create$2(type) { - return new ArraySchema(type); -} - -class ArraySchema extends Schema { - constructor(type) { - super({ - type: "array", - spec: { - types: type - }, - check(v) { - return Array.isArray(v); + values(values) { + values = Array.isArray(values) ? values : [values]; + if (values.length === 0) { + throw new Error("values() must be called with at least one value"); + } + const mappedValues = values.map((entry) => { + const result = {}; + const cols = this.table[Table.Symbol.Columns]; + for (const colKey of Object.keys(entry)) { + const colValue = entry[colKey]; + result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); } + return result; }); - this.innerType = undefined; - this.innerType = type; + return new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList, false, this.overridingSystemValue_).setToken(this.authToken); } - _cast(_value, _opts) { - const value = super._cast(_value, _opts); - if (!this._typeCheck(value) || !this.innerType) { - return value; + select(selectQuery) { + const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder) : selectQuery; + if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) { + throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition"); } - let isChanged = false; - const castArray = value.map((v, idx) => { - const castElement = this.innerType.cast(v, Object.assign({}, _opts, { - path: `${_opts.path || ""}[${idx}]`, - parent: value, - originalValue: v, - value: v, - index: idx - })); - if (castElement !== v) { - isChanged = true; - } - return castElement; - }); - return isChanged ? castArray : value; + return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true); } - _validate(_value, options = {}, panic, next) { - var _options$recursive; - let innerType = this.innerType; - let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive; - options.originalValue != null && options.originalValue; - super._validate(_value, options, panic, (arrayErrors, value) => { - var _options$originalValu2; - if (!recursive || !innerType || !this._typeCheck(value)) { - next(arrayErrors, value); - return; - } - let tests = new Array(value.length); - for (let index = 0;index < value.length; index++) { - var _options$originalValu; - tests[index] = innerType.asNestedTest({ - options, - index, - parent: value, - parentPath: options.path, - originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value - }); - } - this.runTests({ - value, - tests, - originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value, - options - }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(arrayErrors), value)); - }); +} + +class PgInsertBase extends QueryPromise { + constructor(table, values, session, dialect, withList, select, overridingSystemValue_) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { table, values, withList, select, overridingSystemValue_ }; } - clone(spec) { - const next = super.clone(spec); - next.innerType = this.innerType; - return next; + static [entityKind] = "PgInsert"; + config; + cacheConfig; + returning(fields = this.config.table[Table.Symbol.Columns]) { + this.config.returningFields = fields; + this.config.returning = orderSelectedFields(fields); + return this; } - json() { - return this.transform(parseJson); + onConflictDoNothing(config = {}) { + if (config.target === undefined) { + this.config.onConflict = sql`do nothing`; + } else { + let targetColumn = ""; + targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target)); + const whereSql = config.where ? sql` where ${config.where}` : undefined; + this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`; + } + return this; } - concat(schema) { - let next = super.concat(schema); - next.innerType = this.innerType; - if (schema.innerType) - next.innerType = next.innerType ? next.innerType.concat(schema.innerType) : schema.innerType; - return next; + onConflictDoUpdate(config) { + if (config.where && (config.targetWhere || config.setWhere)) { + throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'); + } + const whereSql = config.where ? sql` where ${config.where}` : undefined; + const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined; + const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined; + const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set)); + let targetColumn = ""; + targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target)); + this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`; + return this; } - of(schema) { - let next = this.clone(); - if (!isSchema(schema)) - throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: " + printValue(schema)); - next.innerType = schema; - next.spec = Object.assign({}, next.spec, { - types: schema - }); - return next; + getSQL() { + return this.dialect.buildInsertQuery(this.config); } - length(length, message = array.length) { - return this.test({ - message, - name: "length", - exclusive: true, - params: { - length - }, - skipAbsent: true, - test(value) { - return value.length === this.resolve(length); - } - }); + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; } - min(min, message) { - message = message || array.min; - return this.test({ - message, - name: "min", - exclusive: true, - params: { - min - }, - skipAbsent: true, - test(value) { - return value.length >= this.resolve(min); - } + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { + type: "insert", + tables: extractUsedTable(this.config.table) + }, this.cacheConfig); }); } - max(max, message) { - message = message || array.max; - return this.test({ - message, - name: "max", - exclusive: true, - params: { - max - }, - skipAbsent: true, - test(value) { - return value.length <= this.resolve(max); - } - }); + prepare(name) { + return this._prepare(name); } - ensure() { - return this.default(() => []).transform((val, original) => { - if (this._typeCheck(val)) - return val; - return original == null ? [] : [].concat(original); - }); + authToken; + setToken(token) { + this.authToken = token; + return this; } - compact(rejector) { - let reject = !rejector ? (v) => !!v : (v, i, a) => !rejector(v, i, a); - return this.transform((values) => values != null ? values.filter(reject) : values); + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; + getSelectedFields() { + return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({ + alias: getTableName(this.config.table), + sqlAliasedBehavior: "alias", + sqlBehavior: "error" + })) : undefined; } - describe(options) { - const next = (options ? this.resolve(options) : this).clone(); - const base = super.describe(options); - if (next.innerType) { - var _innerOptions; - let innerOptions = options; - if ((_innerOptions = innerOptions) != null && _innerOptions.value) { - innerOptions = Object.assign({}, innerOptions, { - parent: innerOptions.value, - value: innerOptions.value[0] - }); - } - base.innerType = next.innerType.describe(innerOptions); - } - return base; + $dynamic() { + return this; } } -create$2.prototype = ArraySchema.prototype; -function create$1(schemas) { - return new TupleSchema(schemas); -} -class TupleSchema extends Schema { - constructor(schemas) { - super({ - type: "tuple", - spec: { - types: schemas - }, - check(v) { - const types = this.spec.types; - return Array.isArray(v) && v.length === types.length; - } - }); - this.withMutation(() => { - this.typeError(tuple.notType); - }); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js +class PgRefreshMaterializedView extends QueryPromise { + constructor(view, session, dialect) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { view }; } - _cast(inputValue, options) { - const { - types - } = this.spec; - const value = super._cast(inputValue, options); - if (!this._typeCheck(value)) { - return value; + static [entityKind] = "PgRefreshMaterializedView"; + config; + concurrently() { + if (this.config.withNoData !== undefined) { + throw new Error("Cannot use concurrently and withNoData together"); } - let isChanged = false; - const castArray = types.map((type, idx) => { - const castElement = type.cast(value[idx], Object.assign({}, options, { - path: `${options.path || ""}[${idx}]`, - parent: value, - originalValue: value[idx], - value: value[idx], - index: idx - })); - if (castElement !== value[idx]) - isChanged = true; - return castElement; - }); - return isChanged ? castArray : value; + this.config.concurrently = true; + return this; } - _validate(_value, options = {}, panic, next) { - let itemTypes = this.spec.types; - super._validate(_value, options, panic, (tupleErrors, value) => { - var _options$originalValu2; - if (!this._typeCheck(value)) { - next(tupleErrors, value); - return; - } - let tests = []; - for (let [index, itemSchema] of itemTypes.entries()) { - var _options$originalValu; - tests[index] = itemSchema.asNestedTest({ - options, - index, - parent: value, - parentPath: options.path, - originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value - }); - } - this.runTests({ - value, - tests, - originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value, - options - }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(tupleErrors), value)); - }); + withNoData() { + if (this.config.concurrently !== undefined) { + throw new Error("Cannot use concurrently and withNoData together"); + } + this.config.withNoData = true; + return this; } - describe(options) { - const next = (options ? this.resolve(options) : this).clone(); - const base = super.describe(options); - base.innerType = next.spec.types.map((schema, index) => { - var _innerOptions; - let innerOptions = options; - if ((_innerOptions = innerOptions) != null && _innerOptions.value) { - innerOptions = Object.assign({}, innerOptions, { - parent: innerOptions.value, - value: innerOptions.value[index] - }); - } - return schema.describe(innerOptions); - }); - return base; + getSQL() { + return this.dialect.buildRefreshMaterializedViewQuery(this.config); } -} -create$1.prototype = TupleSchema.prototype; - -// src/utils/ApiError.ts -class ApiError extends Error { - statusCode; - success; - data; - isOperational; - constructor(message, statusCode, data) { - super(message); - this.statusCode = statusCode; - this.success = statusCode >= 200 && statusCode < 300; - this.isOperational = true; - this.data = data; - Error.captureStackTrace(this, this.constructor); + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; } -} -var ApiError_default = ApiError; - -// src/utils/asyncHandler.ts -var asyncHandler = (fn) => { - return (req, res, next) => { - fn(req, res, next).catch((err) => { - next(err); + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true); }); - }; -}; -var asyncHandler_default = asyncHandler; - -// src/shared/middleware.ts -var import_jsonwebtoken = __toESM(require_jsonwebtoken(), 1); - -// node_modules/.pnpm/http-status@2.1.0/node_modules/http-status/dist/chunk-CUNVWAK5.js -var e = { "1xx": "Informational", "1xx_NAME": "INFORMATIONAL", "1xx_MESSAGE": "Indicates an interim response for communicating connection status or request progress prior to completing the requested action and sending a final response.", INFORMATIONAL: "1xx", "2xx": "Successful", "2xx_NAME": "SUCCESSFUL", "2xx_MESSAGE": "Indicates that the client's request was successfully received, understood, and accepted.", SUCCESSFUL: "2xx", "3xx": "Redirection", "3xx_NAME": "REDIRECTION", "3xx_MESSAGE": "Indicates that further action needs to be taken by the user agent in order to fulfill the request.", REDIRECTION: "3xx", "4xx": "Client Error", "4xx_NAME": "CLIENT_ERROR", "4xx_MESSAGE": "Indicates that the client seems to have erred.", CLIENT_ERROR: "4xx", "5xx": "Server Error", "5xx_NAME": "SERVER_ERROR", "5xx_MESSAGE": "Indicates that the server is aware that it has erred or is incapable of performing the requested method.", SERVER_ERROR: "5xx" }; -var t = { classes: e, 100: "Continue", "100_NAME": "CONTINUE", "100_MESSAGE": "The server has received the request headers and the client should proceed to send the request body.", "100_CLASS": e.INFORMATIONAL, CONTINUE: 100, 101: "Switching Protocols", "101_NAME": "SWITCHING_PROTOCOLS", "101_MESSAGE": "The requester has asked the server to switch protocols and the server has agreed to do so.", "101_CLASS": e.INFORMATIONAL, SWITCHING_PROTOCOLS: 101, 102: "Processing", "102_NAME": "PROCESSING", "102_MESSAGE": "A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. This code indicates that the server has received and is processing the request, but no response is available yet.[7] This prevents the client from timing out and assuming the request was lost.", "102_CLASS": e.INFORMATIONAL, PROCESSING: 102, 103: "Early Hints", "103_NAME": "EARLY_HINTS", "103_MESSAGE": "Used to return some response headers before final HTTP message.", "103_CLASS": e.INFORMATIONAL, EARLY_HINTS: 103, 200: "OK", "200_NAME": "OK", "200_MESSAGE": "Standard response for successful HTTP requests.", "200_CLASS": e.SUCCESSFUL, OK: 200, 201: "Created", "201_NAME": "CREATED", "201_MESSAGE": "The request has been fulfilled, resulting in the creation of a new resource.", "201_CLASS": e.SUCCESSFUL, CREATED: 201, 202: "Accepted", "202_NAME": "ACCEPTED", "202_MESSAGE": "The request has been accepted for processing, but the processing has not been completed.", "202_CLASS": e.SUCCESSFUL, ACCEPTED: 202, 203: "Non-Authoritative Information", "203_NAME": "NON_AUTHORITATIVE_INFORMATION", "203_MESSAGE": "The server is a transforming proxy (e.g. a Web accelerator) that received a 200 OK from its origin, but is returning a modified version of the origin's response.", "203_CLASS": e.SUCCESSFUL, NON_AUTHORITATIVE_INFORMATION: 203, 204: "No Content", "204_NAME": "NO_CONTENT", "204_MESSAGE": "The server successfully processed the request and is not returning any content.", "204_CLASS": e.SUCCESSFUL, NO_CONTENT: 204, 205: "Reset Content", "205_NAME": "RESET_CONTENT", "205_MESSAGE": "The server successfully processed the request, but is not returning any content. Unlike a 204 response, this response requires that the requester reset the document view.", "205_CLASS": e.SUCCESSFUL, RESET_CONTENT: 205, 206: "Partial Content", "206_NAME": "PARTIAL_CONTENT", "206_MESSAGE": "The server is delivering only part of the resource (byte serving) due to a range header sent by the client.", "206_CLASS": e.SUCCESSFUL, PARTIAL_CONTENT: 206, 207: "Multi Status", "207_NAME": "MULTI_STATUS", "207_MESSAGE": "The message body that follows is by default an XML message and can contain a number of separate response codes, depending on how many sub-requests were made.", "207_CLASS": e.SUCCESSFUL, MULTI_STATUS: 207, 208: "Already Reported", "208_NAME": "ALREADY_REPORTED", "208_MESSAGE": "The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, and are not being included again.", "208_CLASS": e.SUCCESSFUL, ALREADY_REPORTED: 208, 226: "IM Used", "226_NAME": "IM_USED", "226_MESSAGE": "The server has fulfilled a request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance.", "226_CLASS": e.SUCCESSFUL, IM_USED: 226, 300: "Multiple Choices", "300_NAME": "MULTIPLE_CHOICES", "300_MESSAGE": "Indicates multiple options for the resource from which the client may choose.", "300_CLASS": e.REDIRECTION, MULTIPLE_CHOICES: 300, 301: "Moved Permanently", "301_NAME": "MOVED_PERMANENTLY", "301_MESSAGE": "This and all future requests should be directed to the given URI.", "301_CLASS": e.REDIRECTION, MOVED_PERMANENTLY: 301, 302: "Found", "302_NAME": "FOUND", "302_MESSAGE": 'This is an example of industry practice contradicting the standard. The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 to distinguish between the two behaviours.', "302_CLASS": e.REDIRECTION, FOUND: 302, 303: "See Other", "303_NAME": "SEE_OTHER", "303_MESSAGE": "The response to the request can be found under another URI using the GET method.", "303_CLASS": e.REDIRECTION, SEE_OTHER: 303, 304: "Not Modified", "304_NAME": "NOT_MODIFIED", "304_MESSAGE": "Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match.", "304_CLASS": e.REDIRECTION, NOT_MODIFIED: 304, 305: "Use Proxy", "305_NAME": "USE_PROXY", "305_MESSAGE": "The requested resource is available only through a proxy, the address for which is provided in the response.", "305_CLASS": e.REDIRECTION, USE_PROXY: 305, 306: "Switch Proxy", "306_NAME": "SWITCH_PROXY", "306_MESSAGE": 'No longer used. Originally meant "Subsequent requests should use the specified proxy.', "306_CLASS": e.REDIRECTION, SWITCH_PROXY: 306, 307: "Temporary Redirect", "307_NAME": "TEMPORARY_REDIRECT", "307_MESSAGE": "In this case, the request should be repeated with another URI; however, future requests should still use the original URI.", "307_CLASS": e.REDIRECTION, TEMPORARY_REDIRECT: 307, 308: "Permanent Redirect", "308_NAME": "PERMANENT_REDIRECT", "308_MESSAGE": "The request and all future requests should be repeated using another URI.", "308_CLASS": e.REDIRECTION, PERMANENT_REDIRECT: 308, 400: "Bad Request", "400_NAME": "BAD_REQUEST", "400_MESSAGE": "The server cannot or will not process the request due to an apparent client error.", "400_CLASS": e.CLIENT_ERROR, BAD_REQUEST: 400, 401: "Unauthorized", "401_NAME": "UNAUTHORIZED", "401_MESSAGE": "Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.", "401_CLASS": e.CLIENT_ERROR, UNAUTHORIZED: 401, 402: "Payment Required", "402_NAME": "PAYMENT_REQUIRED", "402_MESSAGE": "Reserved for future use. The original intention was that this code might be used as part of some form of digital cash or micropayment scheme, as proposed for example by GNU Taler, but that has not yet happened, and this code is not usually used.", "402_CLASS": e.CLIENT_ERROR, PAYMENT_REQUIRED: 402, 403: "Forbidden", "403_NAME": "FORBIDDEN", "403_MESSAGE": "The request was valid, but the server is refusing action.", "403_CLASS": e.CLIENT_ERROR, FORBIDDEN: 403, 404: "Not Found", "404_NAME": "NOT_FOUND", "404_MESSAGE": "The requested resource could not be found but may be available in the future. Subsequent requests by the client are permissible.", "404_CLASS": e.CLIENT_ERROR, NOT_FOUND: 404, 405: "Method Not Allowed", "405_NAME": "METHOD_NOT_ALLOWED", "405_MESSAGE": "A request method is not supported for the requested resource.", "405_CLASS": e.CLIENT_ERROR, METHOD_NOT_ALLOWED: 405, 406: "Not Acceptable", "406_NAME": "NOT_ACCEPTABLE", "406_MESSAGE": "The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request.", "406_CLASS": e.CLIENT_ERROR, NOT_ACCEPTABLE: 406, 407: "Proxy Authentication Required", "407_NAME": "PROXY_AUTHENTICATION_REQUIRED", "407_MESSAGE": "The client must first authenticate itself with the proxy.", "407_CLASS": e.CLIENT_ERROR, PROXY_AUTHENTICATION_REQUIRED: 407, 408: "Request Time-out", "408_NAME": "REQUEST_TIMEOUT", "408_MESSAGE": "The server timed out waiting for the request.", "408_CLASS": e.CLIENT_ERROR, REQUEST_TIMEOUT: 408, 409: "Conflict", "409_NAME": "CONFLICT", "409_MESSAGE": "Indicates that the request could not be processed because of conflict in the request, such as an edit conflict between multiple simultaneous updates.", "409_CLASS": e.CLIENT_ERROR, CONFLICT: 409, 410: "Gone", "410_NAME": "GONE", "410_MESSAGE": "Indicates that the resource requested is no longer available and will not be available again.", "410_CLASS": e.CLIENT_ERROR, GONE: 410, 411: "Length Required", "411_NAME": "LENGTH_REQUIRED", "411_MESSAGE": "The request did not specify the length of its content, which is required by the requested resource.", "411_CLASS": e.CLIENT_ERROR, LENGTH_REQUIRED: 411, 412: "Precondition Failed", "412_NAME": "PRECONDITION_FAILED", "412_MESSAGE": "The server does not meet one of the preconditions that the requester put on the request.", "412_CLASS": e.CLIENT_ERROR, PRECONDITION_FAILED: 412, 413: "Request Entity Too Large", "413_NAME": "REQUEST_ENTITY_TOO_LARGE", "413_MESSAGE": 'The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large".', "413_CLASS": e.CLIENT_ERROR, REQUEST_ENTITY_TOO_LARGE: 413, 414: "Request-URI Too Large", "414_NAME": "REQUEST_URI_TOO_LONG", "414_MESSAGE": "The URI provided was too long for the server to process.", "414_CLASS": e.CLIENT_ERROR, REQUEST_URI_TOO_LONG: 414, 415: "Unsupported Media Type", "415_NAME": "UNSUPPORTED_MEDIA_TYPE", "415_MESSAGE": "The request entity has a media type which the server or resource does not support.", "415_CLASS": e.CLIENT_ERROR, UNSUPPORTED_MEDIA_TYPE: 415, 416: "Requested Range not Satisfiable", "416_NAME": "REQUESTED_RANGE_NOT_SATISFIABLE", "416_MESSAGE": "The client has asked for a portion of the file (byte serving), but the server cannot supply that portion.", "416_CLASS": e.CLIENT_ERROR, REQUESTED_RANGE_NOT_SATISFIABLE: 416, 417: "Expectation Failed", "417_NAME": "EXPECTATION_FAILED", "417_MESSAGE": "The server cannot meet the requirements of the Expect request-header field.", "417_CLASS": e.CLIENT_ERROR, EXPECTATION_FAILED: 417, 418: "I'm a teapot", "418_NAME": "IM_A_TEAPOT", "418_MESSAGE": `Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout.`, "418_CLASS": e.CLIENT_ERROR, IM_A_TEAPOT: 418, 421: "Misdirected Request", "421_NAME": "MISDIRECTED_REQUEST", "421_MESSAGE": "The request was directed at a server that is not able to produce a response.", "421_CLASS": e.CLIENT_ERROR, MISDIRECTED_REQUEST: 421, 422: "Unprocessable Entity", "422_NAME": "UNPROCESSABLE_ENTITY", "422_MESSAGE": "The request was well-formed but was unable to be followed due to semantic errors.", "422_CLASS": e.CLIENT_ERROR, UNPROCESSABLE_ENTITY: 422, 423: "Locked", "423_NAME": "LOCKED", "423_MESSAGE": "The resource that is being accessed is locked.", "423_CLASS": e.CLIENT_ERROR, LOCKED: 423, 424: "Failed Dependency", "424_NAME": "FAILED_DEPENDENCY", "424_MESSAGE": "The request failed because it depended on another request and that request failed.", "424_CLASS": e.CLIENT_ERROR, FAILED_DEPENDENCY: 424, 425: "Too Early", "425_NAME": "TOO_EARLY", "425_MESSAGE": "The server is unwilling to risk processing a request that might be replayed.", "425_CLASS": e.CLIENT_ERROR, TOO_EARLY: 425, 426: "Upgrade Required", "426_NAME": "UPGRADE_REQUIRED", "426_MESSAGE": "The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field.", "426_CLASS": e.CLIENT_ERROR, UPGRADE_REQUIRED: 426, 428: "Precondition Required", "428_NAME": "PRECONDITION_REQUIRED", "428_MESSAGE": "The origin server requires the request to be conditional.", "428_CLASS": e.CLIENT_ERROR, PRECONDITION_REQUIRED: 428, 429: "Too Many Requests", "429_NAME": "TOO_MANY_REQUESTS", "429_MESSAGE": "The user has sent too many requests in a given amount of time.", "429_CLASS": e.CLIENT_ERROR, TOO_MANY_REQUESTS: 429, 431: "Request Header Fields Too Large", "431_NAME": "REQUEST_HEADER_FIELDS_TOO_LARGE", "431_MESSAGE": "The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.", "431_CLASS": e.CLIENT_ERROR, REQUEST_HEADER_FIELDS_TOO_LARGE: 431, 451: "Unavailable For Legal Reasons", "451_NAME": "UNAVAILABLE_FOR_LEGAL_REASONS", "451_MESSAGE": "A server operator has received a legal demand to deny access to a resource or to a set of resources that includes the requested resource.", "451_CLASS": e.CLIENT_ERROR, UNAVAILABLE_FOR_LEGAL_REASONS: 451, 500: "Internal Server Error", "500_NAME": "INTERNAL_SERVER_ERROR", "500_MESSAGE": "A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.", "500_CLASS": e.SERVER_ERROR, INTERNAL_SERVER_ERROR: 500, 501: "Not Implemented", "501_NAME": "NOT_IMPLEMENTED", "501_MESSAGE": "The server either does not recognize the request method, or it lacks the ability to fulfil the request. Usually this implies future availability.", "501_CLASS": e.SERVER_ERROR, NOT_IMPLEMENTED: 501, 502: "Bad Gateway", "502_NAME": "BAD_GATEWAY", "502_MESSAGE": "The server was acting as a gateway or proxy and received an invalid response from the upstream server.", "502_CLASS": e.SERVER_ERROR, BAD_GATEWAY: 502, 503: "Service Unavailable", "503_NAME": "SERVICE_UNAVAILABLE", "503_MESSAGE": "The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state.", "503_CLASS": e.SERVER_ERROR, SERVICE_UNAVAILABLE: 503, 504: "Gateway Time-out", "504_NAME": "GATEWAY_TIMEOUT", "504_MESSAGE": "The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.", "504_CLASS": e.SERVER_ERROR, GATEWAY_TIMEOUT: 504, 505: "HTTP Version not Supported", "505_NAME": "HTTP_VERSION_NOT_SUPPORTED", "505_MESSAGE": "The server does not support the HTTP protocol version used in the request.", "505_CLASS": e.SERVER_ERROR, HTTP_VERSION_NOT_SUPPORTED: 505, 506: "Variant Also Negotiates", "506_NAME": "VARIANT_ALSO_NEGOTIATES", "506_MESSAGE": "Transparent content negotiation for the request results in a circular reference.", "506_CLASS": e.SERVER_ERROR, VARIANT_ALSO_NEGOTIATES: 506, 507: "Insufficient Storage", "507_NAME": "INSUFFICIENT_STORAGE", "507_MESSAGE": "The server is unable to store the representation needed to complete the request.", "507_CLASS": e.SERVER_ERROR, INSUFFICIENT_STORAGE: 507, 508: "Loop Detected", "508_NAME": "LOOP_DETECTED", "508_MESSAGE": "The server detected an infinite loop while processing the request.", "508_CLASS": e.SERVER_ERROR, LOOP_DETECTED: 508, 510: "Not Extended", "510_NAME": "NOT_EXTENDED", "510_MESSAGE": "Further extensions to the request are required for the server to fulfil it.", "510_CLASS": e.SERVER_ERROR, NOT_EXTENDED: 510, 511: "Network Authentication Required", "511_NAME": "NETWORK_AUTHENTICATION_REQUIRED", "511_MESSAGE": "The client needs to authenticate to gain network access. Intended for use by intercepting proxies used to control access to the network.", "511_CLASS": e.SERVER_ERROR, NETWORK_AUTHENTICATION_REQUIRED: 511, extra: { unofficial: { 103: "Checkpoint", "103_NAME": "CHECKPOINT", "103_MESSAGE": "Used in the resumable requests proposal to resume aborted PUT or POST requests.", "103_CLASS": e.INFORMATIONAL, CHECKPOINT: 103, 419: "Page Expired", "419_NAME": "PAGE_EXPIRED", "419_MESSAGE": "Used by the Laravel Framework when a CSRF Token is missing or expired.", "419_CLASS": e.CLIENT_ERROR, PAGE_EXPIRED: 419, 218: "This is fine", "218_NAME": "THIS_IS_FINE", "218_MESSAGE": "Used as a catch-all error condition for allowing response bodies to flow through Apache when ProxyErrorOverride is enabled. When ProxyErrorOverride is enabled in Apache, response bodies that contain a status code of 4xx or 5xx are automatically discarded by Apache in favor of a generic response or a custom response specified by the ErrorDocument directive.", "218_CLASS": e.SUCCESSFUL, THIS_IS_FINE: 218, 420: "Enhance Your Calm", "420_NAME": "ENHANCE_YOUR_CALM", "420_MESSAGE": "Returned by version 1 of the Twitter Search and Trends API when the client is being rate limited; versions 1.1 and later use the 429 Too Many Requests response code instead.", "420_CLASS": e.CLIENT_ERROR, ENHANCE_YOUR_CALM: 420, 450: "Blocked by Windows Parental Controls", "450_NAME": "BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS", "450_MESSAGE": "The Microsoft extension code indicated when Windows Parental Controls are turned on and are blocking access to the requested webpage.", "450_CLASS": e.CLIENT_ERROR, BLOCKED_BY_WINDOWS_PARENTAL_CONTROLS: 450, 498: "Invalid Token", "498_NAME": "INVALID_TOKEN", "498_MESSAGE": "Returned by ArcGIS for Server. Code 498 indicates an expired or otherwise invalid token.", "498_CLASS": e.CLIENT_ERROR, INVALID_TOKEN: 498, 499: "Token Required", "499_NAME": "TOKEN_REQUIRED", "499_MESSAGE": "Returned by ArcGIS for Server. Code 499 indicates that a token is required but was not submitted.", "499_CLASS": e.CLIENT_ERROR, TOKEN_REQUIRED: 499, 509: "Bandwidth Limit Exceeded", "509_NAME": "BANDWIDTH_LIMIT_EXCEEDED", "509_MESSAGE": "The server has exceeded the bandwidth specified by the server administrator.", "509_CLASS": e.SERVER_ERROR, BANDWIDTH_LIMIT_EXCEEDED: 509, 530: "Site is frozen", "530_NAME": "SITE_IS_FROZEN", "530_MESSAGE": "Used by the Pantheon web platform to indicate a site that has been frozen due to inactivity.", "530_CLASS": e.SERVER_ERROR, SITE_IS_FROZEN: 530, 598: "Network read timeout error", "598_NAME": "NETWORK_READ_TIMEOUT_ERROR", "598_MESSAGE": "Used by some HTTP proxies to signal a network read timeout behind the proxy to a client in front of the proxy.", "598_CLASS": e.SERVER_ERROR, NETWORK_READ_TIMEOUT_ERROR: 598 }, iis: { 440: "Login Time-out", "440_NAME": "LOGIN_TIME_OUT", "440_MESSAGE": "The client's session has expired and must log in again.", "440_CLASS": e.CLIENT_ERROR, LOGIN_TIME_OUT: 440, 449: "Retry With", "449_NAME": "RETRY_WITH", "449_MESSAGE": "The server cannot honour the request because the user has not provided the required information.", "449_CLASS": e.CLIENT_ERROR, RETRY_WITH: 449, 451: "Redirect", "451_NAME": "REDIRECT", "451_MESSAGE": "Used in Exchange ActiveSync when either a more efficient server is available or the server cannot access the users' mailbox.", "451_CLASS": e.CLIENT_ERROR, REDIRECT: 451 }, nginx: { 444: "No Response", "444_NAME": "NO_RESPONSE", "444_MESSAGE": "Used internally to instruct the server to return no information to the client and close the connection immediately.", "444_CLASS": e.CLIENT_ERROR, NO_RESPONSE: 444, 494: "Request header too large", "494_NAME": "REQUEST_HEADER_TOO_LARGE", "494_MESSAGE": "Client sent too large request or too long header line.", "494_CLASS": e.CLIENT_ERROR, REQUEST_HEADER_TOO_LARGE: 494, 495: "SSL Certificate Error", "495_NAME": "SSL_CERTIFICATE_ERROR", "495_MESSAGE": "An expansion of the 400 Bad Request response code, used when the client has provided an invalid client certificate.", "495_CLASS": e.CLIENT_ERROR, SSL_CERTIFICATE_ERROR: 495, 496: "SSL Certificate Required", "496_NAME": "SSL_CERTIFICATE_REQUIRED", "496_MESSAGE": "An expansion of the 400 Bad Request response code, used when a client certificate is required but not provided.", "496_CLASS": e.CLIENT_ERROR, SSL_CERTIFICATE_REQUIRED: 496, 497: "HTTP Request Sent to HTTPS Port", "497_NAME": "HTTP_REQUEST_SENT_TO_HTTPS_PORT", "497_MESSAGE": "An expansion of the 400 Bad Request response code, used when the client has made a HTTP request to a port listening for HTTPS requests.", "497_CLASS": e.CLIENT_ERROR, HTTP_REQUEST_SENT_TO_HTTPS_PORT: 497, 499: "Client Closed Request", "499_NAME": "CLIENT_CLOSED_REQUEST", "499_MESSAGE": "Used when the client has closed the request before the server could send a response.", "499_CLASS": e.CLIENT_ERROR, CLIENT_CLOSED_REQUEST: 499 }, cloudflare: { 520: "Unknown Error", "520_NAME": "UNKNOWN_ERROR", "520_MESSAGE": 'The 520 error is used as a "catch-all response for when the origin server returns something unexpected", listing connection resets, large headers, and empty or invalid responses as common triggers.', "520_CLASS": e.SERVER_ERROR, UNKNOWN_ERROR: 520, 521: "Web Server Is Down", "521_NAME": "WEB_SERVER_IS_DOWN", "521_MESSAGE": "The origin server has refused the connection from Cloudflare.", "521_CLASS": e.SERVER_ERROR, WEB_SERVER_IS_DOWN: 521, 522: "Connection Timed Out", "522_NAME": "CONNECTION_TIMED_OUT", "522_MESSAGE": "Cloudflare could not negotiate a TCP handshake with the origin server.", "522_CLASS": e.SERVER_ERROR, CONNECTION_TIMED_OUT: 522, 523: "Origin Is Unreachable", "523_NAME": "ORIGIN_IS_UNREACHABLE", "523_MESSAGE": "Cloudflare could not reach the origin server.", "523_CLASS": e.SERVER_ERROR, ORIGIN_IS_UNREACHABLE: 523, 524: "A Timeout Occurred", "524_NAME": "A_TIMEOUT_OCCURRED", "524_MESSAGE": "Cloudflare was able to complete a TCP connection to the origin server, but did not receive a timely HTTP response.", "524_CLASS": e.SERVER_ERROR, A_TIMEOUT_OCCURRED: 524, 525: "SSL Handshake Failed", "525_NAME": "SSL_HANDSHAKE_FAILED", "525_MESSAGE": "Cloudflare could not negotiate a SSL/TLS handshake with the origin server.", "525_CLASS": e.SERVER_ERROR, SSL_HANDSHAKE_FAILED: 525, 526: "Invalid SSL Certificate", "526_NAME": "INVALID_SSL_CERTIFICATE", "526_MESSAGE": "Cloudflare could not validate the SSL/TLS certificate that the origin server presented.", "526_CLASS": e.SERVER_ERROR, INVALID_SSL_CERTIFICATE: 526, 527: "Railgun Error", "527_NAME": "RAILGUN_ERROR", "527_MESSAGE": "Error 527 indicates that the request timed out or failed after the WAN connection had been established.", "527_CLASS": e.SERVER_ERROR, RAILGUN_ERROR: 527 } } }; -var E = t; - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/entity.js -var entityKind = Symbol.for("drizzle:entityKind"); -var hasOwnEntityKind = Symbol.for("drizzle:hasOwnEntityKind"); -function is(value, type) { - if (!value || typeof value !== "object") { - return false; - } - if (value instanceof type) { - return true; } - if (!Object.prototype.hasOwnProperty.call(type, entityKind)) { - throw new Error(`Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`); + prepare(name) { + return this._prepare(name); } - let cls = Object.getPrototypeOf(value).constructor; - if (cls) { - while (cls) { - if (entityKind in cls && cls[entityKind] === type[entityKind]) { - return true; - } - cls = Object.getPrototypeOf(cls); - } + authToken; + setToken(token) { + this.authToken = token; + return this; } - return false; + execute = (placeholderValues) => { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(placeholderValues, this.authToken); + }); + }; } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column.js -class Column { - constructor(table, config) { +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/update.js +class PgUpdateBuilder { + constructor(table, session, dialect, withList) { this.table = table; - this.config = config; - this.name = config.name; - this.keyAsName = config.keyAsName; - this.notNull = config.notNull; - this.default = config.default; - this.defaultFn = config.defaultFn; - this.onUpdateFn = config.onUpdateFn; - this.hasDefault = config.hasDefault; - this.primary = config.primaryKey; - this.isUnique = config.isUnique; - this.uniqueName = config.uniqueName; - this.uniqueType = config.uniqueType; - this.dataType = config.dataType; - this.columnType = config.columnType; - this.generated = config.generated; - this.generatedIdentity = config.generatedIdentity; - } - static [entityKind] = "Column"; - name; - keyAsName; - primary; - notNull; - default; - defaultFn; - onUpdateFn; - hasDefault; - isUnique; - uniqueName; - uniqueType; - dataType; - columnType; - enumValues = undefined; - generated = undefined; - generatedIdentity = undefined; - config; - mapFromDriverValue(value) { - return value; + this.session = session; + this.dialect = dialect; + this.withList = withList; } - mapToDriverValue(value) { - return value; + static [entityKind] = "PgUpdateBuilder"; + authToken; + setToken(token) { + this.authToken = token; + return this; } - shouldDisableInsert() { - return this.config.generated !== undefined && this.config.generated.type !== "byDefault"; + set(values) { + return new PgUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList).setToken(this.authToken); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/column-builder.js -class ColumnBuilder { - static [entityKind] = "ColumnBuilder"; +class PgUpdateBase extends QueryPromise { + constructor(table, set, session, dialect, withList) { + super(); + this.session = session; + this.dialect = dialect; + this.config = { set, table, withList, joins: [] }; + this.tableName = getTableLikeName(table); + this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; + } + static [entityKind] = "PgUpdate"; config; - constructor(name, dataType, columnType) { - this.config = { - name, - keyAsName: name === "", - notNull: false, - default: undefined, - hasDefault: false, - primaryKey: false, - isUnique: false, - uniqueName: undefined, - uniqueType: undefined, - dataType, - columnType, - generated: undefined + tableName; + joinsNotNullableMap; + cacheConfig; + from(source) { + const src = source; + const tableName = getTableLikeName(src); + if (typeof tableName === "string") { + this.joinsNotNullableMap[tableName] = true; + } + this.config.from = src; + return this; + } + getTableLikeFields(table) { + if (is(table, PgTable)) { + return table[Table.Symbol.Columns]; + } else if (is(table, Subquery)) { + return table._.selectedFields; + } + return table[ViewBaseConfig].selectedFields; + } + createJoin(joinType) { + return (table, on) => { + const tableName = getTableLikeName(table); + if (typeof tableName === "string" && this.config.joins.some((join2) => join2.alias === tableName)) { + throw new Error(`Alias "${tableName}" is already used in this query`); + } + if (typeof on === "function") { + const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : undefined; + on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); + } + this.config.joins.push({ on, table, joinType, alias: tableName }); + if (typeof tableName === "string") { + switch (joinType) { + case "left": { + this.joinsNotNullableMap[tableName] = false; + break; + } + case "right": { + this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); + this.joinsNotNullableMap[tableName] = true; + break; + } + case "inner": { + this.joinsNotNullableMap[tableName] = true; + break; + } + case "full": { + this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); + this.joinsNotNullableMap[tableName] = false; + break; + } + } + } + return this; }; } - $type() { + leftJoin = this.createJoin("left"); + rightJoin = this.createJoin("right"); + innerJoin = this.createJoin("inner"); + fullJoin = this.createJoin("full"); + where(where) { + this.config.where = where; return this; } - notNull() { - this.config.notNull = true; + returning(fields) { + if (!fields) { + fields = Object.assign({}, this.config.table[Table.Symbol.Columns]); + if (this.config.from) { + const tableName = getTableLikeName(this.config.from); + if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) { + const fromFields = this.getTableLikeFields(this.config.from); + fields[tableName] = fromFields; + } + for (const join2 of this.config.joins) { + const tableName2 = getTableLikeName(join2.table); + if (typeof tableName2 === "string" && !is(join2.table, SQL)) { + const fromFields = this.getTableLikeFields(join2.table); + fields[tableName2] = fromFields; + } + } + } + } + this.config.returningFields = fields; + this.config.returning = orderSelectedFields(fields); return this; } - default(value) { - this.config.default = value; - this.config.hasDefault = true; - return this; + getSQL() { + return this.dialect.buildUpdateQuery(this.config); } - $defaultFn(fn) { - this.config.defaultFn = fn; - this.config.hasDefault = true; - return this; + toSQL() { + const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); + return rest; } - $default = this.$defaultFn; - $onUpdateFn(fn) { - this.config.onUpdateFn = fn; - this.config.hasDefault = true; - return this; + _prepare(name) { + const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { + type: "insert", + tables: extractUsedTable(this.config.table) + }, this.cacheConfig); + query.joinsNotNullableMap = this.joinsNotNullableMap; + return query; } - $onUpdate = this.$onUpdateFn; - primaryKey() { - this.config.primaryKey = true; - this.config.notNull = true; + prepare(name) { + return this._prepare(name); + } + authToken; + setToken(token) { + this.authToken = token; return this; } - setName(name) { - if (this.config.name !== "") - return; - this.config.name = name; + execute = (placeholderValues) => { + return this._prepare().execute(placeholderValues, this.authToken); + }; + getSelectedFields() { + return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({ + alias: getTableName(this.config.table), + sqlAliasedBehavior: "alias", + sqlBehavior: "error" + })) : undefined; + } + $dynamic() { + return this; } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.utils.js -var TableName = Symbol.for("drizzle:Name"); - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/foreign-keys.js -class ForeignKeyBuilder { - static [entityKind] = "PgForeignKeyBuilder"; - reference; - _onUpdate = "no action"; - _onDelete = "no action"; - constructor(config, actions) { - this.reference = () => { - const { name, columns, foreignColumns } = config(); - return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; - }; - if (actions) { - this._onUpdate = actions.onUpdate; - this._onDelete = actions.onDelete; - } +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/count.js +class PgCountBuilder extends SQL { + constructor(params) { + super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); + this.params = params; + this.mapWith(Number); + this.session = params.session; + this.sql = PgCountBuilder.buildCount(params.source, params.filters); } - onUpdate(action) { - this._onUpdate = action === undefined ? "no action" : action; - return this; + sql; + token; + static [entityKind] = "PgCountBuilder"; + [Symbol.toStringTag] = "PgCountBuilder"; + session; + static buildEmbeddedCount(source, filters) { + return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; } - onDelete(action) { - this._onDelete = action === undefined ? "no action" : action; + static buildCount(source, filters) { + return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`; + } + setToken(token) { + this.token = token; return this; } - build(table) { - return new ForeignKey(table, this); + then(onfulfilled, onrejected) { + return Promise.resolve(this.session.count(this.sql, this.token)).then(onfulfilled, onrejected); + } + catch(onRejected) { + return this.then(undefined, onRejected); + } + finally(onFinally) { + return this.then((value) => { + onFinally?.(); + return value; + }, (reason) => { + onFinally?.(); + throw reason; + }); } } -class ForeignKey { - constructor(table, builder) { +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query.js +class RelationalQueryBuilder { + constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) { + this.fullSchema = fullSchema; + this.schema = schema; + this.tableNamesMap = tableNamesMap; this.table = table; - this.reference = builder.reference; - this.onUpdate = builder._onUpdate; - this.onDelete = builder._onDelete; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session; } - static [entityKind] = "PgForeignKey"; - reference; - onUpdate; - onDelete; - getName() { - const { name, columns, foreignColumns } = this.reference(); - const columnNames = columns.map((column) => column.name); - const foreignColumnNames = foreignColumns.map((column) => column.name); - const chunks = [ - this.table[TableName], - ...columnNames, - foreignColumns[0].table[TableName], - ...foreignColumnNames - ]; - return name ?? `${chunks.join("_")}_fk`; + static [entityKind] = "PgRelationalQueryBuilder"; + findMany(config) { + return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many"); } -} -function foreignKey(config) { - function mappedConfig() { - const { name, columns, foreignColumns } = config; - return { - name, - columns, - foreignColumns - }; + findFirst(config) { + return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first"); } - return new ForeignKeyBuilder(mappedConfig); } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing-utils.js -function iife(fn, ...args) { - return fn(...args); +class PgRelationalQuery extends QueryPromise { + constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) { + super(); + this.fullSchema = fullSchema; + this.schema = schema; + this.tableNamesMap = tableNamesMap; + this.table = table; + this.tableConfig = tableConfig; + this.dialect = dialect; + this.session = session; + this.config = config; + this.mode = mode; + } + static [entityKind] = "PgRelationalQuery"; + _prepare(name) { + return tracer.startActiveSpan("drizzle.prepareQuery", () => { + const { query, builtQuery } = this._toSQL(); + return this.session.prepareQuery(builtQuery, undefined, name, true, (rawRows, mapColumnValue) => { + const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)); + if (this.mode === "first") { + return rows[0]; + } + return rows; + }); + }); + } + prepare(name) { + return this._prepare(name); + } + _getQuery() { + return this.dialect.buildRelationalQueryWithoutPK({ + fullSchema: this.fullSchema, + schema: this.schema, + tableNamesMap: this.tableNamesMap, + table: this.table, + tableConfig: this.tableConfig, + queryConfig: this.config, + tableAlias: this.tableConfig.tsName + }); + } + getSQL() { + return this._getQuery().sql; + } + _toSQL() { + const query = this._getQuery(); + const builtQuery = this.dialect.sqlToQuery(query.sql); + return { query, builtQuery }; + } + toSQL() { + return this._toSQL().builtQuery; + } + authToken; + setToken(token) { + this.authToken = token; + return this; + } + execute() { + return tracer.startActiveSpan("drizzle.operation", () => { + return this._prepare().execute(undefined, this.authToken); + }); + } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/unique-constraint.js -function uniqueKeyName(table, columns) { - return `${table[TableName]}_${columns.join("_")}_unique`; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/raw.js +class PgRaw extends QueryPromise { + constructor(execute, sql2, query, mapBatchResult) { + super(); + this.execute = execute; + this.sql = sql2; + this.query = query; + this.mapBatchResult = mapBatchResult; + } + static [entityKind] = "PgRaw"; + getSQL() { + return this.sql; + } + getQuery() { + return this.query; + } + mapResult(result, isFromBatch) { + return isFromBatch ? this.mapBatchResult(result) : result; + } + _prepare() { + return this; + } + isResponseInArrayMode() { + return false; + } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils/array.js -function parsePgArrayValue(arrayString, startFrom, inQuotes) { - for (let i = startFrom;i < arrayString.length; i++) { - const char = arrayString[i]; - if (char === "\\") { - i++; - continue; - } - if (char === '"') { - return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; - } - if (inQuotes) { - continue; - } - if (char === "," || char === "}") { - return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/db.js +class PgDatabase { + constructor(dialect, session, schema) { + this.dialect = dialect; + this.session = session; + this._ = schema ? { + schema: schema.schema, + fullSchema: schema.fullSchema, + tableNamesMap: schema.tableNamesMap, + session + } : { + schema: undefined, + fullSchema: {}, + tableNamesMap: {}, + session + }; + this.query = {}; + if (this._.schema) { + for (const [tableName, columns] of Object.entries(this._.schema)) { + this.query[tableName] = new RelationalQueryBuilder(schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session); + } } + this.$cache = { invalidate: async (_params) => {} }; } - return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; -} -function parsePgNestedArray(arrayString, startFrom = 0) { - const result = []; - let i = startFrom; - let lastCharIsComma = false; - while (i < arrayString.length) { - const char = arrayString[i]; - if (char === ",") { - if (lastCharIsComma || i === startFrom) { - result.push(""); + static [entityKind] = "PgDatabase"; + query; + $with = (alias, selection) => { + const self2 = this; + const as = (qb) => { + if (typeof qb === "function") { + qb = qb(new QueryBuilder(self2.dialect)); } - lastCharIsComma = true; - i++; - continue; - } - lastCharIsComma = false; - if (char === "\\") { - i += 2; - continue; + return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); + }; + return { as }; + }; + $count(source, filters) { + return new PgCountBuilder({ source, filters, session: this.session }); + } + $cache; + with(...queries) { + const self2 = this; + function select(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: self2.session, + dialect: self2.dialect, + withList: queries + }); } - if (char === '"') { - const [value2, startFrom2] = parsePgArrayValue(arrayString, i + 1, true); - result.push(value2); - i = startFrom2; - continue; + function selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: true + }); } - if (char === "}") { - return [result, i + 1]; + function selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: self2.session, + dialect: self2.dialect, + withList: queries, + distinct: { on } + }); } - if (char === "{") { - const [value2, startFrom2] = parsePgNestedArray(arrayString, i + 1); - result.push(value2); - i = startFrom2; - continue; + function update(table) { + return new PgUpdateBuilder(table, self2.session, self2.dialect, queries); } - const [value, newStartFrom] = parsePgArrayValue(arrayString, i, false); - result.push(value); - i = newStartFrom; - } - return [result, i]; -} -function parsePgArray(arrayString) { - const [result] = parsePgNestedArray(arrayString, 1); - return result; -} -function makePgArray(array2) { - return `{${array2.map((item) => { - if (Array.isArray(item)) { - return makePgArray(item); + function insert(table) { + return new PgInsertBuilder(table, self2.session, self2.dialect, queries); } - if (typeof item === "string") { - return `"${item.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`; + function delete_(table) { + return new PgDeleteBase(table, self2.session, self2.dialect, queries); } - return `${item}`; - }).join(",")}}`; -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/common.js -class PgColumnBuilder extends ColumnBuilder { - foreignKeyConfigs = []; - static [entityKind] = "PgColumnBuilder"; - array(size) { - return new PgArrayBuilder(this.config.name, this, size); + return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ }; + } + select(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: this.session, + dialect: this.dialect + }); + } + selectDistinct(fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: this.session, + dialect: this.dialect, + distinct: true + }); } - references(ref, actions = {}) { - this.foreignKeyConfigs.push({ ref, actions }); - return this; + selectDistinctOn(on, fields) { + return new PgSelectBuilder({ + fields: fields ?? undefined, + session: this.session, + dialect: this.dialect, + distinct: { on } + }); } - unique(name, config) { - this.config.isUnique = true; - this.config.uniqueName = name; - this.config.uniqueType = config?.nulls; - return this; + update(table) { + return new PgUpdateBuilder(table, this.session, this.dialect); } - generatedAlwaysAs(as) { - this.config.generated = { - as, - type: "always", - mode: "stored" - }; - return this; + insert(table) { + return new PgInsertBuilder(table, this.session, this.dialect); } - buildForeignKeys(column, table) { - return this.foreignKeyConfigs.map(({ ref, actions }) => { - return iife((ref2, actions2) => { - const builder = new ForeignKeyBuilder(() => { - const foreignColumn = ref2(); - return { columns: [column], foreignColumns: [foreignColumn] }; - }); - if (actions2.onUpdate) { - builder.onUpdate(actions2.onUpdate); - } - if (actions2.onDelete) { - builder.onDelete(actions2.onDelete); - } - return builder.build(table); - }, ref, actions); - }); + delete(table) { + return new PgDeleteBase(table, this.session, this.dialect); } - buildExtraConfigColumn(table) { - return new ExtraConfigColumn(table, this.config); + refreshMaterializedView(view) { + return new PgRefreshMaterializedView(view, this.session, this.dialect); + } + authToken; + execute(query) { + const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); + const builtQuery = this.dialect.sqlToQuery(sequel); + const prepared = this.session.prepareQuery(builtQuery, undefined, undefined, false); + return new PgRaw(() => prepared.execute(undefined, this.authToken), sequel, builtQuery, (result) => prepared.mapResult(result, true)); + } + transaction(transaction, config) { + return this.session.transaction(transaction, config); } } -class PgColumn extends Column { - constructor(table, config) { - if (!config.uniqueName) { - config.uniqueName = uniqueKeyName(table, [config.name]); - } - super(table, config); - this.table = table; - } - static [entityKind] = "PgColumn"; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/cache/core/cache.js +class Cache { + static [entityKind] = "Cache"; } -class ExtraConfigColumn extends PgColumn { - static [entityKind] = "ExtraConfigColumn"; - getSQLType() { - return this.getSQLType(); +class NoopCache extends Cache { + strategy() { + return "all"; } - indexConfig = { - order: this.config.order ?? "asc", - nulls: this.config.nulls ?? "last", - opClass: this.config.opClass - }; - defaultConfig = { - order: "asc", - nulls: "last", - opClass: undefined - }; - asc() { - this.indexConfig.order = "asc"; - return this; + static [entityKind] = "NoopCache"; + async get(_key) { + return; } - desc() { - this.indexConfig.order = "desc"; - return this; + async put(_hashedQuery, _response, _tables, _config) {} + async onMutate(_params) {} +} +async function hashQuery(sql2, params) { + const dataToHash = `${sql2}-${JSON.stringify(params)}`; + const encoder = new TextEncoder; + const data = encoder.encode(dataToHash); + const hashBuffer = await crypto.subtle.digest("SHA-256", data); + const hashArray = [...new Uint8Array(hashBuffer)]; + const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); + return hashHex; +} + +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/session.js +class PgPreparedQuery { + constructor(query, cache, queryMetadata, cacheConfig) { + this.query = query; + this.cache = cache; + this.queryMetadata = queryMetadata; + this.cacheConfig = cacheConfig; + if (cache && cache.strategy() === "all" && cacheConfig === undefined) { + this.cacheConfig = { enable: true, autoInvalidate: true }; + } + if (!this.cacheConfig?.enable) { + this.cacheConfig = undefined; + } } - nullsFirst() { - this.indexConfig.nulls = "first"; - return this; + authToken; + getQuery() { + return this.query; } - nullsLast() { - this.indexConfig.nulls = "last"; - return this; + mapResult(response, _isFromBatch) { + return response; } - op(opClass) { - this.indexConfig.opClass = opClass; + setToken(token) { + this.authToken = token; return this; } -} - -class IndexedColumn { - static [entityKind] = "IndexedColumn"; - constructor(name, keyAsName, type, indexConfig) { - this.name = name; - this.keyAsName = keyAsName; - this.type = type; - this.indexConfig = indexConfig; + static [entityKind] = "PgPreparedQuery"; + joinsNotNullableMap; + async queryWithCache(queryString, params, query) { + if (this.cache === undefined || is(this.cache, NoopCache) || this.queryMetadata === undefined) { + try { + return await query(); + } catch (e2) { + throw new DrizzleQueryError(queryString, params, e2); + } + } + if (this.cacheConfig && !this.cacheConfig.enable) { + try { + return await query(); + } catch (e2) { + throw new DrizzleQueryError(queryString, params, e2); + } + } + if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) { + try { + const [res] = await Promise.all([ + query(), + this.cache.onMutate({ tables: this.queryMetadata.tables }) + ]); + return res; + } catch (e2) { + throw new DrizzleQueryError(queryString, params, e2); + } + } + if (!this.cacheConfig) { + try { + return await query(); + } catch (e2) { + throw new DrizzleQueryError(queryString, params, e2); + } + } + if (this.queryMetadata.type === "select") { + const fromCache = await this.cache.get(this.cacheConfig.tag ?? await hashQuery(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== undefined, this.cacheConfig.autoInvalidate); + if (fromCache === undefined) { + let result; + try { + result = await query(); + } catch (e2) { + throw new DrizzleQueryError(queryString, params, e2); + } + await this.cache.put(this.cacheConfig.tag ?? await hashQuery(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== undefined, this.cacheConfig.config); + return result; + } + return fromCache; + } + try { + return await query(); + } catch (e2) { + throw new DrizzleQueryError(queryString, params, e2); + } } - name; - keyAsName; - type; - indexConfig; } -class PgArrayBuilder extends PgColumnBuilder { - static [entityKind] = "PgArrayBuilder"; - constructor(name, baseBuilder, size) { - super(name, "array", "PgArray"); - this.config.baseBuilder = baseBuilder; - this.config.size = size; +class PgSession { + constructor(dialect) { + this.dialect = dialect; } - build(table) { - const baseColumn = this.config.baseBuilder.build(table); - return new PgArray(table, this.config, baseColumn); + static [entityKind] = "PgSession"; + execute(query, token) { + return tracer.startActiveSpan("drizzle.operation", () => { + const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => { + return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false); + }); + return prepared.setToken(token).execute(undefined, token); + }); + } + all(query) { + return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false).all(); + } + async count(sql2, token) { + const res = await this.execute(sql2, token); + return Number(res[0]["count"]); } } -class PgArray extends PgColumn { - constructor(table, config, baseColumn, range) { - super(table, config); - this.baseColumn = baseColumn; - this.range = range; - this.size = config.size; +class PgTransaction extends PgDatabase { + constructor(dialect, session, schema, nestedIndex = 0) { + super(dialect, session, schema); + this.schema = schema; + this.nestedIndex = nestedIndex; } - size; - static [entityKind] = "PgArray"; - getSQLType() { - return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; + static [entityKind] = "PgTransaction"; + rollback() { + throw new TransactionRollbackError; } - mapFromDriverValue(value) { - if (typeof value === "string") { - value = parsePgArray(value); + getTransactionConfigSQL(config) { + const chunks = []; + if (config.isolationLevel) { + chunks.push(`isolation level ${config.isolationLevel}`); } - return value.map((v) => this.baseColumn.mapFromDriverValue(v)); + if (config.accessMode) { + chunks.push(config.accessMode); + } + if (typeof config.deferrable === "boolean") { + chunks.push(config.deferrable ? "deferrable" : "not deferrable"); + } + return sql.raw(chunks.join(" ")); } - mapToDriverValue(value, isNestedArray = false) { - const a = value.map((v) => v === null ? null : is(this.baseColumn, PgArray) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)); - if (isNestedArray) - return a; - return makePgArray(a); + setTransaction(config) { + return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/enum.js -class PgEnumObjectColumnBuilder extends PgColumnBuilder { - static [entityKind] = "PgEnumObjectColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumObjectColumn"); - this.config.enum = enumInstance; - } - build(table) { - return new PgEnumObjectColumn(table, this.config); +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/logger.js +class ConsoleLogWriter { + static [entityKind] = "ConsoleLogWriter"; + write(message) { + console.log(message); } } -class PgEnumObjectColumn extends PgColumn { - static [entityKind] = "PgEnumObjectColumn"; - enum; - enumValues = this.config.enum.enumValues; - constructor(table, config) { - super(table, config); - this.enum = config.enum; +class DefaultLogger { + static [entityKind] = "DefaultLogger"; + writer; + constructor(config) { + this.writer = config?.writer ?? new ConsoleLogWriter; } - getSQLType() { - return this.enum.enumName; + logQuery(query, params) { + const stringifiedParams = params.map((p) => { + try { + return JSON.stringify(p); + } catch { + return String(p); + } + }); + const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; + this.writer.write(`Query: ${query}${paramsStr}`); } } -var isPgEnumSym = Symbol.for("drizzle:isPgEnum"); -function isPgEnum(obj) { - return !!obj && typeof obj === "function" && isPgEnumSym in obj && obj[isPgEnumSym] === true; + +class NoopLogger { + static [entityKind] = "NoopLogger"; + logQuery() {} } -class PgEnumColumnBuilder extends PgColumnBuilder { - static [entityKind] = "PgEnumColumnBuilder"; - constructor(name, enumInstance) { - super(name, "string", "PgEnumColumn"); - this.config.enum = enumInstance; - } - build(table) { - return new PgEnumColumn(table, this.config); +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js +var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +var _32n = /* @__PURE__ */ BigInt(32); +function fromBig(n, le = false) { + if (le) + return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; + return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; +} +function split2(lst, le = false) { + const len = lst.length; + let Ah = new Uint32Array(len); + let Al = new Uint32Array(len); + for (let i = 0;i < len; i++) { + const { h, l } = fromBig(lst[i], le); + [Ah[i], Al[i]] = [h, l]; } + return [Ah, Al]; } +var rotlSH = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; -class PgEnumColumn extends PgColumn { - static [entityKind] = "PgEnumColumn"; - enum = this.config.enum; - enumValues = this.config.enum.enumValues; - constructor(table, config) { - super(table, config); - this.enum = config.enum; +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js +function isBytes(a) { + return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; +} +function anumber(n, title = "") { + if (typeof n !== "number") { + const prefix = title && `"${title}" `; + throw new TypeError(`${prefix}expected number, got ${typeof n}`); } - getSQLType() { - return this.enum.enumName; + if (!Number.isSafeInteger(n) || n < 0) { + const prefix = title && `"${title}" `; + throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); } } -function pgEnum(enumName, input) { - return Array.isArray(input) ? pgEnumWithSchema(enumName, [...input], undefined) : pgEnumObjectWithSchema(enumName, input, undefined); -} -function pgEnumWithSchema(enumName, values, schema) { - const enumInstance = Object.assign((name) => new PgEnumColumnBuilder(name ?? "", enumInstance), { - enumName, - enumValues: values, - schema, - [isPgEnumSym]: true - }); - return enumInstance; +function abytes(value, length, title = "") { + const bytes = isBytes(value); + const len = value?.length; + const needsLen = length !== undefined; + if (!bytes || needsLen && len !== length) { + const prefix = title && `"${title}" `; + const ofLen = needsLen ? ` of length ${length}` : ""; + const got = bytes ? `length=${len}` : `type=${typeof value}`; + const message = prefix + "expected Uint8Array" + ofLen + ", got " + got; + if (!bytes) + throw new TypeError(message); + throw new RangeError(message); + } + return value; } -function pgEnumObjectWithSchema(enumName, values, schema) { - const enumInstance = Object.assign((name) => new PgEnumObjectColumnBuilder(name ?? "", enumInstance), { - enumName, - enumValues: Object.values(values), - schema, - [isPgEnumSym]: true - }); - return enumInstance; +function aexists(instance, checkFinished = true) { + if (instance.destroyed) + throw new Error("Hash instance has been destroyed"); + if (checkFinished && instance.finished) + throw new Error("Hash#digest() has already been called"); } - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/subquery.js -class Subquery { - static [entityKind] = "Subquery"; - constructor(sql, fields, alias, isWith = false, usedTables = []) { - this._ = { - brand: "Subquery", - sql, - selectedFields: fields, - alias, - isWith, - usedTables - }; +function aoutput(out, instance) { + abytes(out, undefined, "digestInto() output"); + const min = instance.outputLen; + if (out.length < min) { + throw new RangeError('"digestInto() output" expected to be of length >=' + min); } } - -class WithSubquery extends Subquery { - static [entityKind] = "WithSubquery"; +function u32(arr) { + return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/version.js -var version = "0.44.7"; - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/tracing.js -var otel; -var rawTracer; -var tracer = { - startActiveSpan(name, fn) { - if (!otel) { - return fn(); - } - if (!rawTracer) { - rawTracer = otel.trace.getTracer("drizzle-orm", version); - } - return iife((otel2, rawTracer2) => rawTracer2.startActiveSpan(name, (span) => { - try { - return fn(span); - } catch (e2) { - span.setStatus({ - code: otel2.SpanStatusCode.ERROR, - message: e2 instanceof Error ? e2.message : "Unknown error" - }); - throw e2; - } finally { - span.end(); - } - }), otel, rawTracer); - } -}; - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/view-common.js -var ViewBaseConfig = Symbol.for("drizzle:ViewBaseConfig"); - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/table.js -var Schema2 = Symbol.for("drizzle:Schema"); -var Columns = Symbol.for("drizzle:Columns"); -var ExtraConfigColumns = Symbol.for("drizzle:ExtraConfigColumns"); -var OriginalName = Symbol.for("drizzle:OriginalName"); -var BaseName = Symbol.for("drizzle:BaseName"); -var IsAlias = Symbol.for("drizzle:IsAlias"); -var ExtraConfigBuilder = Symbol.for("drizzle:ExtraConfigBuilder"); -var IsDrizzleTable = Symbol.for("drizzle:IsDrizzleTable"); - -class Table { - static [entityKind] = "Table"; - static Symbol = { - Name: TableName, - Schema: Schema2, - OriginalName, - Columns, - ExtraConfigColumns, - BaseName, - IsAlias, - ExtraConfigBuilder - }; - [TableName]; - [OriginalName]; - [Schema2]; - [Columns]; - [ExtraConfigColumns]; - [BaseName]; - [IsAlias] = false; - [IsDrizzleTable] = true; - [ExtraConfigBuilder] = undefined; - constructor(name, schema, baseName) { - this[TableName] = this[OriginalName] = name; - this[Schema2] = schema; - this[BaseName] = baseName; +function clean(...arrays) { + for (let i = 0;i < arrays.length; i++) { + arrays[i].fill(0); } } -function getTableName(table) { - return table[TableName]; +var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +function byteSwap(word) { + return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; } -function getTableUniqueName(table) { - return `${table[Schema2] ?? "public"}.${table[TableName]}`; +function byteSwap32(arr) { + for (let i = 0;i < arr.length; i++) { + arr[i] = byteSwap(arr[i]); + } + return arr; +} +var swap32IfBE = isLE ? (u) => u : byteSwap32; +function createHasher(hashCons, info = {}) { + const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); + const tmp = hashCons(undefined); + hashC.outputLen = tmp.outputLen; + hashC.blockLen = tmp.blockLen; + hashC.canXOF = tmp.canXOF; + hashC.create = (opts) => hashCons(opts); + Object.assign(hashC, info); + return Object.freeze(hashC); } +var oidNist = (suffix) => ({ + oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) +}); -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/sql.js -function isSQLWrapper(value) { - return value !== null && value !== undefined && typeof value.getSQL === "function"; +// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha3.js +var _0n = BigInt(0); +var _1n = BigInt(1); +var _2n = BigInt(2); +var _7n = BigInt(7); +var _256n = BigInt(256); +var _0x71n = BigInt(113); +var SHA3_PI = []; +var SHA3_ROTL = []; +var _SHA3_IOTA = []; +for (let round = 0, R = _1n, x = 1, y = 0;round < 24; round++) { + [x, y] = [y, (2 * x + 3 * y) % 5]; + SHA3_PI.push(2 * (5 * y + x)); + SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); + let t2 = _0n; + for (let j = 0;j < 7; j++) { + R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n; + if (R & _2n) + t2 ^= _1n << (_1n << BigInt(j)) - _1n; + } + _SHA3_IOTA.push(t2); } -function mergeQueries(queries) { - const result = { sql: "", params: [] }; - for (const query of queries) { - result.sql += query.sql; - result.params.push(...query.params); - if (query.typings?.length) { - if (!result.typings) { - result.typings = []; +var IOTAS = split2(_SHA3_IOTA, true); +var SHA3_IOTA_H = IOTAS[0]; +var SHA3_IOTA_L = IOTAS[1]; +var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); +var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); +function keccakP(s, rounds = 24) { + anumber(rounds, "rounds"); + if (rounds < 1 || rounds > 24) + throw new Error('"rounds" expected integer 1..24'); + const B = new Uint32Array(5 * 2); + for (let round = 24 - rounds;round < 24; round++) { + for (let x = 0;x < 10; x++) + B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40]; + for (let x = 0;x < 10; x += 2) { + const idx1 = (x + 8) % 10; + const idx0 = (x + 2) % 10; + const B0 = B[idx0]; + const B1 = B[idx0 + 1]; + const Th = rotlH(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + for (let y = 0;y < 50; y += 10) { + s[x + y] ^= Th; + s[x + y + 1] ^= Tl; } - result.typings.push(...query.typings); } + let curH = s[2]; + let curL = s[3]; + for (let t2 = 0;t2 < 24; t2++) { + const shift = SHA3_ROTL[t2]; + const Th = rotlH(curH, curL, shift); + const Tl = rotlL(curH, curL, shift); + const PI = SHA3_PI[t2]; + curH = s[PI]; + curL = s[PI + 1]; + s[PI] = Th; + s[PI + 1] = Tl; + } + for (let y = 0;y < 50; y += 10) { + const b0 = s[y], b1 = s[y + 1], b2 = s[y + 2], b3 = s[y + 3]; + s[y] ^= ~s[y + 2] & s[y + 4]; + s[y + 1] ^= ~s[y + 3] & s[y + 5]; + s[y + 2] ^= ~s[y + 4] & s[y + 6]; + s[y + 3] ^= ~s[y + 5] & s[y + 7]; + s[y + 4] ^= ~s[y + 6] & s[y + 8]; + s[y + 5] ^= ~s[y + 7] & s[y + 9]; + s[y + 6] ^= ~s[y + 8] & b0; + s[y + 7] ^= ~s[y + 9] & b1; + s[y + 8] ^= ~b0 & b2; + s[y + 9] ^= ~b1 & b3; + } + s[0] ^= SHA3_IOTA_H[round]; + s[1] ^= SHA3_IOTA_L[round]; } - return result; + clean(B); } -class StringChunk { - static [entityKind] = "StringChunk"; - value; - constructor(value) { - this.value = Array.isArray(value) ? value : [value]; +class Keccak { + state; + pos = 0; + posOut = 0; + finished = false; + state32; + destroyed = false; + blockLen; + suffix; + outputLen; + canXOF; + enableXOF = false; + rounds; + constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) { + this.blockLen = blockLen; + this.suffix = suffix; + this.outputLen = outputLen; + this.enableXOF = enableXOF; + this.canXOF = enableXOF; + this.rounds = rounds; + anumber(outputLen, "outputLen"); + if (!(0 < blockLen && blockLen < 200)) + throw new Error("only keccak-f1600 function is supported"); + this.state = new Uint8Array(200); + this.state32 = u32(this.state); } - getSQL() { - return new SQL([this]); + clone() { + return this._cloneInto(); + } + keccak() { + swap32IfBE(this.state32); + keccakP(this.state32, this.rounds); + swap32IfBE(this.state32); + this.posOut = 0; + this.pos = 0; + } + update(data) { + aexists(this); + abytes(data); + const { blockLen, state } = this; + const len = data.length; + for (let pos = 0;pos < len; ) { + const take = Math.min(blockLen - this.pos, len - pos); + for (let i = 0;i < take; i++) + state[this.pos++] ^= data[pos++]; + if (this.pos === blockLen) + this.keccak(); + } + return this; + } + finish() { + if (this.finished) + return; + this.finished = true; + const { state, suffix, pos, blockLen } = this; + state[pos] ^= suffix; + if ((suffix & 128) !== 0 && pos === blockLen - 1) + this.keccak(); + state[blockLen - 1] ^= 128; + this.keccak(); + } + writeInto(out) { + aexists(this, false); + abytes(out); + this.finish(); + const bufferOut = this.state; + const { blockLen } = this; + for (let pos = 0, len = out.length;pos < len; ) { + if (this.posOut >= blockLen) + this.keccak(); + const take = Math.min(blockLen - this.posOut, len - pos); + out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos); + this.posOut += take; + pos += take; + } + return out; + } + xofInto(out) { + if (!this.enableXOF) + throw new Error("XOF is not possible for this instance"); + return this.writeInto(out); + } + xof(bytes) { + anumber(bytes); + return this.xofInto(new Uint8Array(bytes)); + } + digestInto(out) { + aoutput(out, this); + if (this.finished) + throw new Error("digest() was already called"); + this.writeInto(out.subarray(0, this.outputLen)); + this.destroy(); + } + digest() { + const out = new Uint8Array(this.outputLen); + this.digestInto(out); + return out; + } + destroy() { + this.destroyed = true; + clean(this.state); + } + _cloneInto(to) { + const { blockLen, suffix, outputLen, rounds, enableXOF } = this; + to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to.blockLen = blockLen; + to.state32.set(this.state32); + to.pos = this.pos; + to.posOut = this.posOut; + to.finished = this.finished; + to.rounds = rounds; + to.suffix = suffix; + to.outputLen = outputLen; + to.enableXOF = enableXOF; + to.canXOF = this.canXOF; + to.destroyed = this.destroyed; + return to; } } +var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info); +var sha3_512 = /* @__PURE__ */ genKeccak(6, 72, 64, /* @__PURE__ */ oidNist(10)); -class SQL { - constructor(queryChunks) { - this.queryChunks = queryChunks; - for (const chunk of queryChunks) { - if (is(chunk, Table)) { - const schemaName = chunk[Table.Symbol.Schema]; - this.usedTables.push(schemaName === undefined ? chunk[Table.Symbol.Name] : schemaName + "." + chunk[Table.Symbol.Name]); +// node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.mjs +var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; +var mathceil = Math.ceil; +var mathfloor = Math.floor; +var bignumberError = "[BigNumber Error] "; +var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; +var BASE = 100000000000000; +var LOG_BASE = 14; +var MAX_SAFE_INTEGER = 9007199254740991; +var POWS_TEN = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000]; +var SQRT_BASE = 1e7; +var MAX = 1e9; +function clone2(configObject) { + var div, convertBase, parseNumeric, P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, ONE = new BigNumber(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + prefix: "", + groupSize: 3, + secondaryGroupSize: 0, + groupSeparator: ",", + decimalSeparator: ".", + fractionGroupSize: 0, + fractionGroupSeparator: "\xA0", + suffix: "" + }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; + function BigNumber(v, b) { + var alphabet, c, caseChanged, e2, i, isNum, len, str, x = this; + if (!(x instanceof BigNumber)) + return new BigNumber(v, b); + if (b == null) { + if (v && v._isBigNumber === true) { + x.s = v.s; + if (!v.c || v.e > MAX_EXP) { + x.c = x.e = null; + } else if (v.e < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = v.e; + x.c = v.c.slice(); + } + return; + } + if ((isNum = typeof v == "number") && v * 0 == 0) { + x.s = 1 / v < 0 ? (v = -v, -1) : 1; + if (v === ~~v) { + for (e2 = 0, i = v;i >= 10; i /= 10, e2++) + ; + if (e2 > MAX_EXP) { + x.c = x.e = null; + } else { + x.e = e2; + x.c = [v]; + } + return; + } + str = String(v); + } else { + if (!isNumeric.test(str = String(v))) + return parseNumeric(x, str, isNum); + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + if ((i = str.search(/e/i)) > 0) { + if (e2 < 0) + e2 = i; + e2 += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e2 < 0) { + e2 = str.length; + } + } else { + intCheck(b, 2, ALPHABET.length, "Base"); + if (b == 10 && alphabetHasNormalDecimalDigits) { + x = new BigNumber(v); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + str = String(v); + if (isNum = typeof v == "number") { + if (v * 0 != 0) + return parseNumeric(x, str, isNum, b); + x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits + v); + } + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + alphabet = ALPHABET.slice(0, b); + e2 = i = 0; + for (len = str.length;i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == ".") { + if (i > e2) { + e2 = len; + continue; + } + } else if (!caseChanged) { + if (str == str.toUpperCase() && (str = str.toLowerCase()) || str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e2 = 0; + continue; + } + } + return parseNumeric(x, String(v), isNum, b); + } + } + isNum = false; + str = convertBase(str, b, 10, x.s); + if ((e2 = str.indexOf(".")) > -1) + str = str.replace(".", ""); + else + e2 = str.length; + } + for (i = 0;str.charCodeAt(i) === 48; i++) + ; + for (len = str.length;str.charCodeAt(--len) === 48; ) + ; + if (str = str.slice(i, ++len)) { + len -= i; + if (isNum && BigNumber.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { + throw Error(tooManyDigits + x.s * v); + } + if ((e2 = e2 - i - 1) > MAX_EXP) { + x.c = x.e = null; + } else if (e2 < MIN_EXP) { + x.c = [x.e = 0]; + } else { + x.e = e2; + x.c = []; + i = (e2 + 1) % LOG_BASE; + if (e2 < 0) + i += LOG_BASE; + if (i < len) { + if (i) + x.c.push(+str.slice(0, i)); + for (len -= LOG_BASE;i < len; ) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + i = LOG_BASE - (str = str.slice(i)).length; + } else { + i -= len; + } + for (;i--; str += "0") + ; + x.c.push(+str); + } + } else { + x.c = [x.e = 0]; + } + } + BigNumber.clone = clone2; + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + BigNumber.config = BigNumber.set = function(obj) { + var p, v; + if (obj != null) { + if (typeof obj == "object") { + if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + if (obj.hasOwnProperty(p = "ROUNDING_MODE")) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + if (obj.hasOwnProperty(p = "RANGE")) { + v = obj[p]; + if (v && v.pop) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error(bignumberError + p + " cannot be zero: " + v); + } + } + } + if (obj.hasOwnProperty(p = "CRYPTO")) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != "undefined" && crypto && (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error(bignumberError + "crypto unavailable"); + } + } else { + CRYPTO = v; + } + } else { + throw Error(bignumberError + p + " not true or false: " + v); + } + } + if (obj.hasOwnProperty(p = "MODULO_MODE")) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + if (obj.hasOwnProperty(p = "POW_PRECISION")) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + if (obj.hasOwnProperty(p = "FORMAT")) { + v = obj[p]; + if (typeof v == "object") + FORMAT = v; + else + throw Error(bignumberError + p + " not an object: " + v); + } + if (obj.hasOwnProperty(p = "ALPHABET")) { + v = obj[p]; + if (typeof v == "string" && !/^.?$|[+\-.\s]|(.).*\1/.test(v)) { + alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; + ALPHABET = v; + } else { + throw Error(bignumberError + p + " invalid: " + v); + } + } + } else { + throw Error(bignumberError + "Object expected: " + obj); + } + } + return { + DECIMAL_PLACES, + ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO, + MODULO_MODE, + POW_PRECISION, + FORMAT, + ALPHABET + }; + }; + BigNumber.isBigNumber = function(v) { + if (!v || v._isBigNumber !== true) + return false; + if (!BigNumber.DEBUG) + return true; + var i, n, c = v.c, e2 = v.e, s = v.s; + out: + if ({}.toString.call(c) == "[object Array]") { + if ((s === 1 || s === -1) && e2 >= -MAX && e2 <= MAX && e2 === mathfloor(e2)) { + if (c[0] === 0) { + if (e2 === 0 && c.length === 1) + return true; + break out; + } + i = (e2 + 1) % LOG_BASE; + if (i < 1) + i += LOG_BASE; + if (String(c[0]).length == i) { + for (i = 0;i < c.length; i++) { + n = c[i]; + if (n < 0 || n >= BASE || n !== mathfloor(n)) + break out; + } + if (n !== 0) + return true; + } + } + } else if (c === null && e2 === null && (s === null || s === 1 || s === -1)) { + return true; } - } - } - static [entityKind] = "SQL"; - decoder = noopDecoder; - shouldInlineParams = false; - usedTables = []; - append(query) { - this.queryChunks.push(...query.queryChunks); - return this; - } - toQuery(config) { - return tracer.startActiveSpan("drizzle.buildSQL", (span) => { - const query = this.buildQueryFromSourceParams(this.queryChunks, config); - span?.setAttributes({ - "drizzle.query.text": query.sql, - "drizzle.query.params": JSON.stringify(query.params) - }); - return query; - }); - } - buildQueryFromSourceParams(chunks, _config) { - const config = Object.assign({}, _config, { - inlineParams: _config.inlineParams || this.shouldInlineParams, - paramStartIndex: _config.paramStartIndex || { value: 0 } - }); - const { - casing, - escapeName, - escapeParam, - prepareTyping, - inlineParams, - paramStartIndex - } = config; - return mergeQueries(chunks.map((chunk) => { - if (is(chunk, StringChunk)) { - return { sql: chunk.value.join(""), params: [] }; + throw Error(bignumberError + "Invalid BigNumber: " + v); + }; + BigNumber.maximum = BigNumber.max = function() { + return maxOrMin(arguments, -1); + }; + BigNumber.minimum = BigNumber.min = function() { + return maxOrMin(arguments, 1); + }; + BigNumber.random = function() { + var pow2_53 = 9007199254740992; + var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { + return mathfloor(Math.random() * pow2_53); + } : function() { + return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); + }; + return function(dp) { + var a, b, e2, k, v, i = 0, c = [], rand = new BigNumber(ONE); + if (dp == null) + dp = DECIMAL_PLACES; + else + intCheck(dp, 0, MAX); + k = mathceil(dp / LOG_BASE); + if (CRYPTO) { + if (crypto.getRandomValues) { + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + for (;i < k; ) { + v = a[i] * 131072 + (a[i + 1] >>> 11); + if (v >= 9000000000000000) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + c.push(v % 100000000000000); + i += 2; + } + } + i = k / 2; + } else if (crypto.randomBytes) { + a = crypto.randomBytes(k *= 7); + for (;i < k; ) { + v = (a[i] & 31) * 281474976710656 + a[i + 1] * 1099511627776 + a[i + 2] * 4294967296 + a[i + 3] * 16777216 + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + if (v >= 9000000000000000) { + crypto.randomBytes(7).copy(a, i); + } else { + c.push(v % 100000000000000); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error(bignumberError + "crypto unavailable"); + } } - if (is(chunk, Name)) { - return { sql: escapeName(chunk.value), params: [] }; + if (!CRYPTO) { + for (;i < k; ) { + v = random53bitInt(); + if (v < 9000000000000000) + c[i++] = v % 100000000000000; + } } - if (chunk === undefined) { - return { sql: "", params: [] }; + k = c[--i]; + dp %= LOG_BASE; + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; } - if (Array.isArray(chunk)) { - const result = [new StringChunk("(")]; - for (const [i, p] of chunk.entries()) { - result.push(p); - if (i < chunk.length - 1) { - result.push(new StringChunk(", ")); + for (;c[i] === 0; c.pop(), i--) + ; + if (i < 0) { + c = [e2 = 0]; + } else { + for (e2 = -1;c[0] === 0; c.splice(0, 1), e2 -= LOG_BASE) + ; + for (i = 1, v = c[0];v >= 10; v /= 10, i++) + ; + if (i < LOG_BASE) + e2 -= LOG_BASE - i; + } + rand.e = e2; + rand.c = c; + return rand; + }; + }(); + BigNumber.sum = function() { + var i = 1, args = arguments, sum = new BigNumber(args[0]); + for (;i < args.length; ) + sum = sum.plus(args[i++]); + return sum; + }; + convertBase = function() { + var decimal = "0123456789"; + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, arr = [0], arrL, i = 0, len = str.length; + for (;i < len; ) { + for (arrL = arr.length;arrL--; arr[arrL] *= baseIn) + ; + arr[0] += alphabet.indexOf(str.charAt(i++)); + for (j = 0;j < arr.length; j++) { + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) + arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; } } - result.push(new StringChunk(")")); - return this.buildQueryFromSourceParams(result, config); } - if (is(chunk, SQL)) { - return this.buildQueryFromSourceParams(chunk.queryChunks, { - ...config, - inlineParams: inlineParams || chunk.shouldInlineParams - }); + return arr.reverse(); + } + return function(str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e2, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + if (i >= 0) { + k = POW_PRECISION; + POW_PRECISION = 0; + str = str.replace(".", ""); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, "0"), 10, baseOut, decimal); + y.e = y.c.length; } - if (is(chunk, Table)) { - const schemaName = chunk[Table.Symbol.Schema]; - const tableName = chunk[Table.Symbol.Name]; - return { - sql: schemaName === undefined || chunk[IsAlias] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), - params: [] - }; + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); + e2 = k = xc.length; + for (;xc[--k] == 0; xc.pop()) + ; + if (!xc[0]) + return alphabet.charAt(0); + if (i < 0) { + --e2; + } else { + x.c = xc; + x.e = e2; + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e2 = x.e; } - if (is(chunk, Column)) { - const columnName = casing.getColumnCasing(chunk); - if (_config.invokeSource === "indexes") { - return { sql: escapeName(columnName), params: [] }; + d = e2 + dp + 1; + i = xc[d]; + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); + if (d < 1 || !xc[0]) { + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + } else { + xc.length = d; + if (r) { + for (--baseOut;++xc[--d] > baseOut; ) { + xc[d] = 0; + if (!d) { + ++e2; + xc = [1].concat(xc); + } + } } - const schemaName = chunk.table[Table.Symbol.Schema]; - return { - sql: chunk.table[IsAlias] || schemaName === undefined ? escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table.Symbol.Name]) + "." + escapeName(columnName), - params: [] - }; + for (k = xc.length;!xc[--k]; ) + ; + for (i = 0, str = "";i <= k; str += alphabet.charAt(xc[i++])) + ; + str = toFixedPoint(str, e2, alphabet.charAt(0)); } - if (is(chunk, View)) { - const schemaName = chunk[ViewBaseConfig].schema; - const viewName = chunk[ViewBaseConfig].name; - return { - sql: schemaName === undefined || chunk[ViewBaseConfig].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), - params: [] - }; + return str; + }; + }(); + div = function() { + function multiply(x, k, base) { + var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; + for (x = x.slice();i--; ) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; } - if (is(chunk, Param)) { - if (is(chunk.value, Placeholder)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - } - const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); - if (is(mappedValue, SQL)) { - return this.buildQueryFromSourceParams([mappedValue], config); - } - if (inlineParams) { - return { sql: this.mapInlineParam(mappedValue, config), params: [] }; - } - let typings = ["none"]; - if (prepareTyping) { - typings = [prepareTyping(chunk.encoder)]; + if (carry) + x = [carry].concat(x); + return x; + } + function compare(a, b, aL, bL) { + var i, cmp; + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + for (i = cmp = 0;i < aL; i++) { + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } } - return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; } - if (is(chunk, Placeholder)) { - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + return cmp; + } + function subtract(a, b, aL, base) { + var i = 0; + for (;aL--; ) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; } - if (is(chunk, SQL.Aliased) && chunk.fieldAlias !== undefined) { - return { sql: escapeName(chunk.fieldAlias), params: [] }; + for (;!a[0] && a.length > 1; a.splice(0, 1)) + ; + } + return function(x, y, dp, rm, base) { + var cmp, e2, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; + if (!xc || !xc[0] || !yc || !yc[0]) { + return new BigNumber(!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s * 0 : s / 0); } - if (is(chunk, Subquery)) { - if (chunk._.isWith) { - return { sql: escapeName(chunk._.alias), params: [] }; - } - return this.buildQueryFromSourceParams([ - new StringChunk("("), - chunk._.sql, - new StringChunk(") "), - new Name(chunk._.alias) - ], config); + q = new BigNumber(s); + qc = q.c = []; + e2 = x.e - y.e; + s = dp + e2 + 1; + if (!base) { + base = BASE; + e2 = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; } - if (isPgEnum(chunk)) { - if (chunk.schema) { - return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; + for (i = 0;yc[i] == (xc[i] || 0); i++) + ; + if (yc[i] > (xc[i] || 0)) + e2--; + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + n = mathfloor(base / (yc[0] + 1)); + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; } - return { sql: escapeName(chunk.enumName), params: [] }; + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + for (;remL < yL; rem[remL++] = 0) + ; + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) + yc0++; + do { + n = 0; + cmp = compare(yc, rem, yL, remL); + if (cmp < 0) { + rem0 = rem[0]; + if (yL != remL) + rem0 = rem0 * base + (rem[1] || 0); + n = mathfloor(rem0 / yc0); + if (n > 1) { + if (n >= base) + n = base - 1; + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + while (compare(prod, rem, prodL, remL) == 1) { + n--; + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + if (n == 0) { + cmp = n = 1; + } + prod = yc.slice(); + prodL = prod.length; + } + if (prodL < remL) + prod = [0].concat(prod); + subtract(rem, prod, remL, base); + remL = rem.length; + if (cmp == -1) { + while (compare(yc, rem, yL, remL) < 1) { + n++; + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } + qc[i++] = n; + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + more = rem[0] != null; + if (!qc[0]) + qc.splice(0, 1); } - if (isSQLWrapper(chunk)) { - if (chunk.shouldOmitSQLParens?.()) { - return this.buildQueryFromSourceParams([chunk.getSQL()], config); - } - return this.buildQueryFromSourceParams([ - new StringChunk("("), - chunk.getSQL(), - new StringChunk(")") - ], config); + if (base == BASE) { + for (i = 1, s = qc[0];s >= 10; s /= 10, i++) + ; + round(q, dp + (q.e = i + e2 * LOG_BASE - 1) + 1, rm, more); + } else { + q.e = e2; + q.r = +more; } - if (inlineParams) { - return { sql: this.mapInlineParam(chunk, config), params: [] }; + return q; + }; + }(); + function format(n, i, rm, id) { + var c0, e2, ne2, len, str; + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + if (!n.c) + return n.toString(); + c0 = n.c[0]; + ne2 = n.e; + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential(str, ne2) : toFixedPoint(str, ne2, "0"); + } else { + n = round(new BigNumber(n), i, rm); + e2 = n.e; + str = coeffToString(n.c); + len = str.length; + if (id == 1 || id == 2 && (i <= e2 || e2 <= TO_EXP_NEG)) { + for (;len < i; str += "0", len++) + ; + str = toExponential(str, e2); + } else { + i -= ne2 + (id === 2 && e2 > ne2); + str = toFixedPoint(str, e2, "0"); + if (e2 + 1 > len) { + if (--i > 0) + for (str += ".";i--; str += "0") + ; + } else { + i += e2 - len; + if (i > 0) { + if (e2 + 1 == len) + str += "."; + for (;i--; str += "0") + ; + } + } } - return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; - })); - } - mapInlineParam(chunk, { escapeString }) { - if (chunk === null) { - return "null"; - } - if (typeof chunk === "number" || typeof chunk === "boolean") { - return chunk.toString(); - } - if (typeof chunk === "string") { - return escapeString(chunk); } - if (typeof chunk === "object") { - const mappedValueAsString = chunk.toString(); - if (mappedValueAsString === "[object Object]") { - return escapeString(JSON.stringify(chunk)); + return n.s < 0 && c0 ? "-" + str : str; + } + function maxOrMin(args, n) { + var k, y, i = 1, x = new BigNumber(args[0]); + for (;i < args.length; i++) { + y = new BigNumber(args[i]); + if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + x = y; } - return escapeString(mappedValueAsString); } - throw new Error("Unexpected param value: " + chunk); - } - getSQL() { - return this; + return x; } - as(alias) { - if (alias === undefined) { - return this; + function normalise(n, c, e2) { + var i = 1, j = c.length; + for (;!c[--j]; c.pop()) + ; + for (j = c[0];j >= 10; j /= 10, i++) + ; + if ((e2 = i + e2 * LOG_BASE - 1) > MAX_EXP) { + n.c = n.e = null; + } else if (e2 < MIN_EXP) { + n.c = [n.e = 0]; + } else { + n.e = e2; + n.c = c; } - return new SQL.Aliased(this, alias); - } - mapWith(decoder) { - this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder; - return this; - } - inlineParams() { - this.shouldInlineParams = true; - return this; - } - if(condition) { - return condition ? this : undefined; - } -} - -class Name { - constructor(value) { - this.value = value; - } - static [entityKind] = "Name"; - brand; - getSQL() { - return new SQL([this]); - } -} -function isDriverValueEncoder(value) { - return typeof value === "object" && value !== null && "mapToDriverValue" in value && typeof value.mapToDriverValue === "function"; -} -var noopDecoder = { - mapFromDriverValue: (value) => value -}; -var noopEncoder = { - mapToDriverValue: (value) => value -}; -var noopMapper = { - ...noopDecoder, - ...noopEncoder -}; - -class Param { - constructor(value, encoder = noopEncoder) { - this.value = value; - this.encoder = encoder; - } - static [entityKind] = "Param"; - brand; - getSQL() { - return new SQL([this]); - } -} -function sql(strings, ...params) { - const queryChunks = []; - if (params.length > 0 || strings.length > 0 && strings[0] !== "") { - queryChunks.push(new StringChunk(strings[0])); - } - for (const [paramIndex, param2] of params.entries()) { - queryChunks.push(param2, new StringChunk(strings[paramIndex + 1])); - } - return new SQL(queryChunks); -} -((sql2) => { - function empty() { - return new SQL([]); - } - sql2.empty = empty; - function fromList(list) { - return new SQL(list); - } - sql2.fromList = fromList; - function raw(str) { - return new SQL([new StringChunk(str)]); + return n; } - sql2.raw = raw; - function join2(chunks, separator) { - const result = []; - for (const [i, chunk] of chunks.entries()) { - if (i > 0 && separator !== undefined) { - result.push(separator); + parseNumeric = function() { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, dotAfter = /^([^.]+)\.$/, dotBefore = /^\.([^.]+)$/, isInfinityOrNaN = /^-?(Infinity|NaN)$/, whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + return function(x, str, isNum, b) { + var base, s = isNum ? str : str.replace(whitespaceOrPlus, ""); + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + } else { + if (!isNum) { + s = s.replace(basePrefix, function(m, p1, p2) { + base = (p2 = p2.toLowerCase()) == "x" ? 16 : p2 == "b" ? 2 : 8; + return !b || b == base ? p1 : m; + }); + if (b) { + base = b; + s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); + } + if (str != s) + return new BigNumber(s, base); + } + if (BigNumber.DEBUG) { + throw Error(bignumberError + "Not a" + (b ? " base " + b : "") + " number: " + str); + } + x.s = null; + } + x.c = x.e = null; + }; + }(); + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN; + if (xc) { + out: { + for (d = 1, k = xc[0];k >= 10; k /= 10, d++) + ; + i = sd - d; + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + rd = mathfloor(n / pows10[d - j - 1] % 10); + } else { + ni = mathceil((i + 1) / LOG_BASE); + if (ni >= xc.length) { + if (r) { + for (;xc.length <= ni; xc.push(0)) + ; + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + for (d = 1;k >= 10; k /= 10, d++) + ; + i %= LOG_BASE; + j = i - LOG_BASE + d; + rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + } + } + r = r || sd < 0 || xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + r = rm < 4 ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && (i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10 & 1 || rm == (x.s < 0 ? 8 : 7)); + if (sd < 1 || !xc[0]) { + xc.length = 0; + if (r) { + sd -= x.e + 1; + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + xc[0] = x.e = 0; + } + return x; + } + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + if (r) { + for (;; ) { + if (ni == 0) { + for (i = 1, j = xc[0];j >= 10; j /= 10, i++) + ; + j = xc[0] += k; + for (k = 1;j >= 10; j /= 10, k++) + ; + if (i != k) { + x.e++; + if (xc[0] == BASE) + xc[0] = 1; + } + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) + break; + xc[ni--] = 0; + k = 1; + } + } + } + for (i = xc.length;xc[--i] === 0; xc.pop()) + ; + } + if (x.e > MAX_EXP) { + x.c = x.e = null; + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; } - result.push(chunk); } - return new SQL(result); - } - sql2.join = join2; - function identifier(value) { - return new Name(value); - } - sql2.identifier = identifier; - function placeholder2(name2) { - return new Placeholder(name2); + return x; } - sql2.placeholder = placeholder2; - function param2(value, encoder) { - return new Param(value, encoder); + function valueOf(n) { + var str, e2 = n.e; + if (e2 === null) + return n.toString(); + str = coeffToString(n.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); + return n.s < 0 ? "-" + str : str; } - sql2.param = param2; -})(sql || (sql = {})); -((SQL2) => { - - class Aliased { - constructor(sql2, fieldAlias) { - this.sql = sql2; - this.fieldAlias = fieldAlias; - } - static [entityKind] = "SQL.Aliased"; - isSelectionField = false; - getSQL() { - return this.sql; - } - clone() { - return new Aliased(this.sql, this.fieldAlias); + P.absoluteValue = P.abs = function() { + var x = new BigNumber(this); + if (x.s < 0) + x.s = 1; + return x; + }; + P.comparedTo = function(y, b) { + return compare(this, new BigNumber(y, b)); + }; + P.decimalPlaces = P.dp = function(dp, rm) { + var c, n, v, x = this; + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber(x), dp + x.e + 1, rm); } - } - SQL2.Aliased = Aliased; -})(SQL || (SQL = {})); - -class Placeholder { - constructor(name2) { - this.name = name2; - } - static [entityKind] = "Placeholder"; - getSQL() { - return new SQL([this]); - } -} -function fillPlaceholders(params, values) { - return params.map((p) => { - if (is(p, Placeholder)) { - if (!(p.name in values)) { - throw new Error(`No value for placeholder "${p.name}" was provided`); - } - return values[p.name]; + if (!(c = x.c)) + return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + if (v = c[v]) + for (;v % 10 == 0; v /= 10, n--) + ; + if (n < 0) + n = 0; + return n; + }; + P.dividedBy = P.div = function(y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + P.dividedToIntegerBy = P.idiv = function(y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + P.exponentiatedBy = P.pow = function(n, m) { + var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; + n = new BigNumber(n); + if (n.c && !n.isInteger()) { + throw Error(bignumberError + "Exponent not an integer: " + valueOf(n)); } - if (is(p, Param) && is(p.value, Placeholder)) { - if (!(p.value.name in values)) { - throw new Error(`No value for placeholder "${p.value.name}" was provided`); - } - return p.encoder.mapToDriverValue(values[p.value.name]); + if (m != null) + m = new BigNumber(m); + nIsBig = n.e > 14; + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + return m ? y.mod(m) : y; } - return p; - }); -} -var IsDrizzleView = Symbol.for("drizzle:IsDrizzleView"); - -class View { - static [entityKind] = "View"; - [ViewBaseConfig]; - [IsDrizzleView] = true; - constructor({ name: name2, schema, selectedFields, query }) { - this[ViewBaseConfig] = { - name: name2, - originalName: name2, - schema, - selectedFields, - query, - isExisting: !query, - isAlias: false - }; - } - getSQL() { - return new SQL([this]); - } -} -Column.prototype.getSQL = function() { - return new SQL([this]); -}; -Table.prototype.getSQL = function() { - return new SQL([this]); -}; -Subquery.prototype.getSQL = function() { - return new SQL([this]); -}; - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/alias.js -class ColumnAliasProxyHandler { - constructor(table) { - this.table = table; - } - static [entityKind] = "ColumnAliasProxyHandler"; - get(columnObj, prop) { - if (prop === "table") { - return this.table; + nIsNeg = n.s < 0; + if (m) { + if (m.c ? !m.c[0] : !m.s) + return new BigNumber(NaN); + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + if (isModExp) + x = x.mod(m); + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 240000000 : x.c[0] < 80000000000000 || nIsBig && x.c[0] <= 99999750000000))) { + k = x.s < 0 && isOdd(n) ? -0 : 0; + if (x.e > -1) + k = 1 / k; + return new BigNumber(nIsNeg ? 1 / k : k); + } else if (POW_PRECISION) { + k = mathceil(POW_PRECISION / LOG_BASE + 2); } - return columnObj[prop]; - } -} - -class TableAliasProxyHandler { - constructor(alias, replaceOriginalName) { - this.alias = alias; - this.replaceOriginalName = replaceOriginalName; - } - static [entityKind] = "TableAliasProxyHandler"; - get(target, prop) { - if (prop === Table.Symbol.IsAlias) { - return true; + if (nIsBig) { + half = new BigNumber(0.5); + if (nIsNeg) + n.s = 1; + nIsOdd = isOdd(n); + } else { + i = Math.abs(+valueOf(n)); + nIsOdd = i % 2; } - if (prop === Table.Symbol.Name) { - return this.alias; + y = new BigNumber(ONE); + for (;; ) { + if (nIsOdd) { + y = y.times(x); + if (!y.c) + break; + if (k) { + if (y.c.length > k) + y.c.length = k; + } else if (isModExp) { + y = y.mod(m); + } + } + if (i) { + i = mathfloor(i / 2); + if (i === 0) + break; + nIsOdd = i % 2; + } else { + n = n.times(half); + round(n, n.e + 1, 1); + if (n.e > 14) { + nIsOdd = isOdd(n); + } else { + i = +valueOf(n); + if (i === 0) + break; + nIsOdd = i % 2; + } + } + x = x.times(x); + if (k) { + if (x.c && x.c.length > k) + x.c.length = k; + } else if (isModExp) { + x = x.mod(m); + } } - if (this.replaceOriginalName && prop === Table.Symbol.OriginalName) { - return this.alias; + if (isModExp) + return y; + if (nIsNeg) + y = ONE.div(y); + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + P.integerValue = function(rm) { + var n = new BigNumber(this); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + P.isEqualTo = P.eq = function(y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + P.isFinite = function() { + return !!this.c; + }; + P.isGreaterThan = P.gt = function(y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + P.isGreaterThanOrEqualTo = P.gte = function(y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + }; + P.isInteger = function() { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + P.isLessThan = P.lt = function(y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + P.isLessThanOrEqualTo = P.lte = function(y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + P.isNaN = function() { + return !this.s; + }; + P.isNegative = function() { + return this.s < 0; + }; + P.isPositive = function() { + return this.s > 0; + }; + P.isZero = function() { + return !!this.c && this.c[0] == 0; + }; + P.minus = function(y, b) { + var i, j, t2, xLTy, x = this, a = x.s; + y = new BigNumber(y, b); + b = y.s; + if (!a || !b) + return new BigNumber(NaN); + if (a != b) { + y.s = -b; + return x.plus(y); } - if (prop === ViewBaseConfig) { - return { - ...target[ViewBaseConfig], - name: this.alias, - isAlias: true - }; + var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; + if (!xe || !ye) { + if (!xc || !yc) + return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + if (!xc[0] || !yc[0]) { + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : ROUNDING_MODE == 3 ? -0 : 0); + } } - if (prop === Table.Symbol.Columns) { - const columns = target[Table.Symbol.Columns]; - if (!columns) { - return columns; + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a = xe - ye) { + if (xLTy = a < 0) { + a = -a; + t2 = xc; + } else { + ye = xe; + t2 = yc; + } + t2.reverse(); + for (b = a;b--; t2.push(0)) + ; + t2.reverse(); + } else { + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + for (a = b = 0;b < j; b++) { + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } } - const proxiedColumns = {}; - Object.keys(columns).map((key) => { - proxiedColumns[key] = new Proxy(columns[key], new ColumnAliasProxyHandler(new Proxy(target, this))); - }); - return proxiedColumns; } - const value = target[prop]; - if (is(value, Column)) { - return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(target, this))); + if (xLTy) { + t2 = xc; + xc = yc; + yc = t2; + y.s = -y.s; } - return value; - } -} -function aliasedTable(table, tableAlias) { - return new Proxy(table, new TableAliasProxyHandler(tableAlias, false)); -} -function aliasedTableColumn(column, tableAlias) { - return new Proxy(column, new ColumnAliasProxyHandler(new Proxy(column.table, new TableAliasProxyHandler(tableAlias, false)))); -} -function mapColumnsInAliasedSQLToAlias(query, alias) { - return new SQL.Aliased(mapColumnsInSQLToAlias(query.sql, alias), query.fieldAlias); -} -function mapColumnsInSQLToAlias(query, alias) { - return sql.join(query.queryChunks.map((c) => { - if (is(c, Column)) { - return aliasedTableColumn(c, alias); + b = (j = yc.length) - (i = xc.length); + if (b > 0) + for (;b--; xc[i++] = 0) + ; + b = BASE - 1; + for (;j > a; ) { + if (xc[--j] < yc[j]) { + for (i = j;i && !xc[--i]; xc[i] = b) + ; + --xc[i]; + xc[j] += BASE; + } + xc[j] -= yc[j]; } - if (is(c, SQL)) { - return mapColumnsInSQLToAlias(c, alias); + for (;xc[0] == 0; xc.splice(0, 1), --ye) + ; + if (!xc[0]) { + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; } - if (is(c, SQL.Aliased)) { - return mapColumnsInAliasedSQLToAlias(c, alias); + return normalise(y, xc, ye); + }; + P.modulo = P.mod = function(y, b) { + var q, s, x = this; + y = new BigNumber(y, b); + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); } - return c; - })); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/utils.js -function mapResultRow(columns, row, joinsNotNullableMap) { - const nullifyMap = {}; - const result = columns.reduce((result2, { path, field }, columnIndex) => { - let decoder; - if (is(field, Column)) { - decoder = field; - } else if (is(field, SQL)) { - decoder = field.decoder; + if (MODULO_MODE == 9) { + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; } else { - decoder = field.sql.decoder; + q = div(x, y, 0, MODULO_MODE); } - let node = result2; - for (const [pathChunkIndex, pathChunk] of path.entries()) { - if (pathChunkIndex < path.length - 1) { - if (!(pathChunk in node)) { - node[pathChunk] = {}; - } - node = node[pathChunk]; + y = x.minus(q.times(y)); + if (!y.c[0] && MODULO_MODE == 1) + y.s = x.s; + return y; + }; + P.multipliedBy = P.times = function(y, b) { + var c, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber(y, b)).c; + if (!xc || !yc || !xc[0] || !yc[0]) { + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; } else { - const rawValue = row[columnIndex]; - const value = node[pathChunk] = rawValue === null ? null : decoder.mapFromDriverValue(rawValue); - if (joinsNotNullableMap && is(field, Column) && path.length === 2) { - const objectName = path[0]; - if (!(objectName in nullifyMap)) { - nullifyMap[objectName] = value === null ? getTableName(field.table) : false; - } else if (typeof nullifyMap[objectName] === "string" && nullifyMap[objectName] !== getTableName(field.table)) { - nullifyMap[objectName] = false; - } + y.s *= x.s; + if (!xc || !yc) { + y.c = y.e = null; + } else { + y.c = [0]; + y.e = 0; } } + return y; } - return result2; - }, {}); - if (joinsNotNullableMap && Object.keys(nullifyMap).length > 0) { - for (const [objectName, tableName] of Object.entries(nullifyMap)) { - if (typeof tableName === "string" && !joinsNotNullableMap[tableName]) { - result[objectName] = null; - } - } - } - return result; -} -function orderSelectedFields(fields, pathPrefix) { - return Object.entries(fields).reduce((result, [name, field]) => { - if (typeof name !== "string") { - return result; - } - const newPath = pathPrefix ? [...pathPrefix, name] : [name]; - if (is(field, Column) || is(field, SQL) || is(field, SQL.Aliased)) { - result.push({ path: newPath, field }); - } else if (is(field, Table)) { - result.push(...orderSelectedFields(field[Table.Symbol.Columns], newPath)); - } else { - result.push(...orderSelectedFields(field, newPath)); + e2 = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + if (xcL < ycL) { + zc = xc; + xc = yc; + yc = zc; + i = xcL; + xcL = ycL; + ycL = i; } - return result; - }, []); -} -function haveSameKeys(left, right) { - const leftKeys = Object.keys(left); - const rightKeys = Object.keys(right); - if (leftKeys.length !== rightKeys.length) { - return false; - } - for (const [index, key] of leftKeys.entries()) { - if (key !== rightKeys[index]) { - return false; + for (i = xcL + ycL, zc = [];i--; zc.push(0)) + ; + base = BASE; + sqrtBase = SQRT_BASE; + for (i = ycL;--i >= 0; ) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + for (k = xcL, j = i + k;j > i; ) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + m % sqrtBase * sqrtBase + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + zc[j] = c; } - } - return true; -} -function mapUpdateSet(table, values) { - const entries = Object.entries(values).filter(([, value]) => value !== undefined).map(([key, value]) => { - if (is(value, SQL) || is(value, Column)) { - return [key, value]; + if (c) { + ++e2; } else { - return [key, new Param(value, table[Table.Symbol.Columns][key])]; - } - }); - if (entries.length === 0) { - throw new Error("No values to set"); - } - return Object.fromEntries(entries); -} -function applyMixins(baseClass, extendedClasses) { - for (const extendedClass of extendedClasses) { - for (const name of Object.getOwnPropertyNames(extendedClass.prototype)) { - if (name === "constructor") - continue; - Object.defineProperty(baseClass.prototype, name, Object.getOwnPropertyDescriptor(extendedClass.prototype, name) || /* @__PURE__ */ Object.create(null)); + zc.splice(0, 1); } - } -} -function getTableColumns(table) { - return table[Table.Symbol.Columns]; -} -function getTableLikeName(table) { - return is(table, Subquery) ? table._.alias : is(table, View) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : table[Table.Symbol.IsAlias] ? table[Table.Symbol.Name] : table[Table.Symbol.BaseName]; -} -function getColumnNameAndConfig(a, b) { - return { - name: typeof a === "string" && a.length > 0 ? a : "", - config: typeof a === "object" ? a : b + return normalise(y, zc, e2); }; -} -function isConfig(data) { - if (typeof data !== "object" || data === null) - return false; - if (data.constructor.name !== "Object") - return false; - if ("logger" in data) { - const type = typeof data["logger"]; - if (type !== "boolean" && (type !== "object" || typeof data["logger"]["logQuery"] !== "function") && type !== "undefined") - return false; - return true; - } - if ("schema" in data) { - const type = typeof data["schema"]; - if (type !== "object" && type !== "undefined") - return false; - return true; - } - if ("casing" in data) { - const type = typeof data["casing"]; - if (type !== "string" && type !== "undefined") - return false; - return true; - } - if ("mode" in data) { - if (data["mode"] !== "default" || data["mode"] !== "planetscale" || data["mode"] !== undefined) - return false; - return true; - } - if ("connection" in data) { - const type = typeof data["connection"]; - if (type !== "string" && type !== "object" && type !== "undefined") - return false; - return true; - } - if ("client" in data) { - const type = typeof data["client"]; - if (type !== "object" && type !== "function" && type !== "undefined") - return false; - return true; - } - if (Object.keys(data).length === 0) - return true; - return false; -} -var textDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder; - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/int.common.js -class PgIntColumnBaseBuilder extends PgColumnBuilder { - static [entityKind] = "PgIntColumnBaseBuilder"; - generatedAlwaysAsIdentity(sequence) { - if (sequence) { - const { name, ...options } = sequence; - this.config.generatedIdentity = { - type: "always", - sequenceName: name, - sequenceOptions: options - }; - } else { - this.config.generatedIdentity = { - type: "always" - }; - } - this.config.hasDefault = true; - this.config.notNull = true; - return this; - } - generatedByDefaultAsIdentity(sequence) { - if (sequence) { - const { name, ...options } = sequence; - this.config.generatedIdentity = { - type: "byDefault", - sequenceName: name, - sequenceOptions: options - }; - } else { - this.config.generatedIdentity = { - type: "byDefault" - }; + P.negated = function() { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + P.plus = function(y, b) { + var t2, x = this, a = x.s; + y = new BigNumber(y, b); + b = y.s; + if (!a || !b) + return new BigNumber(NaN); + if (a != b) { + y.s = -b; + return x.minus(y); } - this.config.hasDefault = true; - this.config.notNull = true; - return this; - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigint.js -class PgBigInt53Builder extends PgIntColumnBaseBuilder { - static [entityKind] = "PgBigInt53Builder"; - constructor(name) { - super(name, "number", "PgBigInt53"); - } - build(table) { - return new PgBigInt53(table, this.config); - } -} - -class PgBigInt53 extends PgColumn { - static [entityKind] = "PgBigInt53"; - getSQLType() { - return "bigint"; - } - mapFromDriverValue(value) { - if (typeof value === "number") { - return value; + var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; + if (!xe || !ye) { + if (!xc || !yc) + return new BigNumber(a / 0); + if (!xc[0] || !yc[0]) + return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); } - return Number(value); - } -} - -class PgBigInt64Builder extends PgIntColumnBaseBuilder { - static [entityKind] = "PgBigInt64Builder"; - constructor(name) { - super(name, "bigint", "PgBigInt64"); - } - build(table) { - return new PgBigInt64(table, this.config); - } -} - -class PgBigInt64 extends PgColumn { - static [entityKind] = "PgBigInt64"; - getSQLType() { - return "bigint"; - } - mapFromDriverValue(value) { - return BigInt(value); - } -} -function bigint(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - if (config.mode === "number") { - return new PgBigInt53Builder(name); - } - return new PgBigInt64Builder(name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/bigserial.js -class PgBigSerial53Builder extends PgColumnBuilder { - static [entityKind] = "PgBigSerial53Builder"; - constructor(name) { - super(name, "number", "PgBigSerial53"); - this.config.hasDefault = true; - this.config.notNull = true; - } - build(table) { - return new PgBigSerial53(table, this.config); - } -} - -class PgBigSerial53 extends PgColumn { - static [entityKind] = "PgBigSerial53"; - getSQLType() { - return "bigserial"; - } - mapFromDriverValue(value) { - if (typeof value === "number") { - return value; + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t2 = yc; + } else { + a = -a; + t2 = xc; + } + t2.reverse(); + for (;a--; t2.push(0)) + ; + t2.reverse(); } - return Number(value); - } -} - -class PgBigSerial64Builder extends PgColumnBuilder { - static [entityKind] = "PgBigSerial64Builder"; - constructor(name) { - super(name, "bigint", "PgBigSerial64"); - this.config.hasDefault = true; - } - build(table) { - return new PgBigSerial64(table, this.config); - } -} - -class PgBigSerial64 extends PgColumn { - static [entityKind] = "PgBigSerial64"; - getSQLType() { - return "bigserial"; - } - mapFromDriverValue(value) { - return BigInt(value); - } -} -function bigserial(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - if (config.mode === "number") { - return new PgBigSerial53Builder(name); - } - return new PgBigSerial64Builder(name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/boolean.js -class PgBooleanBuilder extends PgColumnBuilder { - static [entityKind] = "PgBooleanBuilder"; - constructor(name) { - super(name, "boolean", "PgBoolean"); - } - build(table) { - return new PgBoolean(table, this.config); - } -} - -class PgBoolean extends PgColumn { - static [entityKind] = "PgBoolean"; - getSQLType() { - return "boolean"; - } -} -function boolean2(name) { - return new PgBooleanBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/char.js -class PgCharBuilder extends PgColumnBuilder { - static [entityKind] = "PgCharBuilder"; - constructor(name, config) { - super(name, "string", "PgChar"); - this.config.length = config.length; - this.config.enumValues = config.enum; - } - build(table) { - return new PgChar(table, this.config); - } -} - -class PgChar extends PgColumn { - static [entityKind] = "PgChar"; - length = this.config.length; - enumValues = this.config.enumValues; - getSQLType() { - return this.length === undefined ? `char` : `char(${this.length})`; - } -} -function char(a, b = {}) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgCharBuilder(name, config); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/cidr.js -class PgCidrBuilder extends PgColumnBuilder { - static [entityKind] = "PgCidrBuilder"; - constructor(name) { - super(name, "string", "PgCidr"); - } - build(table) { - return new PgCidr(table, this.config); - } -} - -class PgCidr extends PgColumn { - static [entityKind] = "PgCidr"; - getSQLType() { - return "cidr"; - } -} -function cidr(name) { - return new PgCidrBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/custom.js -class PgCustomColumnBuilder extends PgColumnBuilder { - static [entityKind] = "PgCustomColumnBuilder"; - constructor(name, fieldConfig, customTypeParams) { - super(name, "custom", "PgCustomColumn"); - this.config.fieldConfig = fieldConfig; - this.config.customTypeParams = customTypeParams; - } - build(table) { - return new PgCustomColumn(table, this.config); - } -} - -class PgCustomColumn extends PgColumn { - static [entityKind] = "PgCustomColumn"; - sqlName; - mapTo; - mapFrom; - constructor(table, config) { - super(table, config); - this.sqlName = config.customTypeParams.dataType(config.fieldConfig); - this.mapTo = config.customTypeParams.toDriver; - this.mapFrom = config.customTypeParams.fromDriver; - } - getSQLType() { - return this.sqlName; - } - mapFromDriverValue(value) { - return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; - } - mapToDriverValue(value) { - return typeof this.mapTo === "function" ? this.mapTo(value) : value; - } -} -function customType(customTypeParams) { - return (a, b) => { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgCustomColumnBuilder(name, config, customTypeParams); - }; -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.common.js -class PgDateColumnBaseBuilder extends PgColumnBuilder { - static [entityKind] = "PgDateColumnBaseBuilder"; - defaultNow() { - return this.default(sql`now()`); - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/date.js -class PgDateBuilder extends PgDateColumnBaseBuilder { - static [entityKind] = "PgDateBuilder"; - constructor(name) { - super(name, "date", "PgDate"); - } - build(table) { - return new PgDate(table, this.config); - } -} - -class PgDate extends PgColumn { - static [entityKind] = "PgDate"; - getSQLType() { - return "date"; - } - mapFromDriverValue(value) { - return new Date(value); - } - mapToDriverValue(value) { - return value.toISOString(); - } -} - -class PgDateStringBuilder extends PgDateColumnBaseBuilder { - static [entityKind] = "PgDateStringBuilder"; - constructor(name) { - super(name, "string", "PgDateString"); - } - build(table) { - return new PgDateString(table, this.config); - } -} - -class PgDateString extends PgColumn { - static [entityKind] = "PgDateString"; - getSQLType() { - return "date"; - } -} -function date2(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - if (config?.mode === "date") { - return new PgDateBuilder(name); - } - return new PgDateStringBuilder(name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/double-precision.js -class PgDoublePrecisionBuilder extends PgColumnBuilder { - static [entityKind] = "PgDoublePrecisionBuilder"; - constructor(name) { - super(name, "number", "PgDoublePrecision"); - } - build(table) { - return new PgDoublePrecision(table, this.config); - } -} - -class PgDoublePrecision extends PgColumn { - static [entityKind] = "PgDoublePrecision"; - getSQLType() { - return "double precision"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - return Number.parseFloat(value); + a = xc.length; + b = yc.length; + if (a - b < 0) { + t2 = yc; + yc = xc; + xc = t2; + b = a; } - return value; - } -} -function doublePrecision(name) { - return new PgDoublePrecisionBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/inet.js -class PgInetBuilder extends PgColumnBuilder { - static [entityKind] = "PgInetBuilder"; - constructor(name) { - super(name, "string", "PgInet"); - } - build(table) { - return new PgInet(table, this.config); - } -} - -class PgInet extends PgColumn { - static [entityKind] = "PgInet"; - getSQLType() { - return "inet"; - } -} -function inet(name) { - return new PgInetBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/integer.js -class PgIntegerBuilder extends PgIntColumnBaseBuilder { - static [entityKind] = "PgIntegerBuilder"; - constructor(name) { - super(name, "number", "PgInteger"); - } - build(table) { - return new PgInteger(table, this.config); - } -} - -class PgInteger extends PgColumn { - static [entityKind] = "PgInteger"; - getSQLType() { - return "integer"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - return Number.parseInt(value); + for (a = 0;b; ) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; } - return value; - } -} -function integer(name) { - return new PgIntegerBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/interval.js -class PgIntervalBuilder extends PgColumnBuilder { - static [entityKind] = "PgIntervalBuilder"; - constructor(name, intervalConfig) { - super(name, "string", "PgInterval"); - this.config.intervalConfig = intervalConfig; - } - build(table) { - return new PgInterval(table, this.config); - } -} - -class PgInterval extends PgColumn { - static [entityKind] = "PgInterval"; - fields = this.config.intervalConfig.fields; - precision = this.config.intervalConfig.precision; - getSQLType() { - const fields = this.fields ? ` ${this.fields}` : ""; - const precision = this.precision ? `(${this.precision})` : ""; - return `interval${fields}${precision}`; - } -} -function interval(a, b = {}) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgIntervalBuilder(name, config); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/json.js -class PgJsonBuilder extends PgColumnBuilder { - static [entityKind] = "PgJsonBuilder"; - constructor(name) { - super(name, "json", "PgJson"); - } - build(table) { - return new PgJson(table, this.config); - } -} - -class PgJson extends PgColumn { - static [entityKind] = "PgJson"; - constructor(table, config) { - super(table, config); - } - getSQLType() { - return "json"; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return value; - } + if (a) { + xc = [a].concat(xc); + ++ye; } - return value; - } -} -function json(name) { - return new PgJsonBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/jsonb.js -class PgJsonbBuilder extends PgColumnBuilder { - static [entityKind] = "PgJsonbBuilder"; - constructor(name) { - super(name, "json", "PgJsonb"); - } - build(table) { - return new PgJsonb(table, this.config); - } -} - -class PgJsonb extends PgColumn { - static [entityKind] = "PgJsonb"; - constructor(table, config) { - super(table, config); - } - getSQLType() { - return "jsonb"; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - if (typeof value === "string") { - try { - return JSON.parse(value); - } catch { - return value; - } + return normalise(y, xc, ye); + }; + P.precision = P.sd = function(sd, rm) { + var c, n, v, x = this; + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) + rm = ROUNDING_MODE; + else + intCheck(rm, 0, 8); + return round(new BigNumber(x), sd, rm); } - return value; - } -} -function jsonb(name) { - return new PgJsonbBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/line.js -class PgLineBuilder extends PgColumnBuilder { - static [entityKind] = "PgLineBuilder"; - constructor(name) { - super(name, "array", "PgLine"); - } - build(table) { - return new PgLineTuple(table, this.config); - } -} - -class PgLineTuple extends PgColumn { - static [entityKind] = "PgLine"; - getSQLType() { - return "line"; - } - mapFromDriverValue(value) { - const [a, b, c] = value.slice(1, -1).split(","); - return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)]; - } - mapToDriverValue(value) { - return `{${value[0]},${value[1]},${value[2]}}`; - } -} - -class PgLineABCBuilder extends PgColumnBuilder { - static [entityKind] = "PgLineABCBuilder"; - constructor(name) { - super(name, "json", "PgLineABC"); - } - build(table) { - return new PgLineABC(table, this.config); - } -} - -class PgLineABC extends PgColumn { - static [entityKind] = "PgLineABC"; - getSQLType() { - return "line"; - } - mapFromDriverValue(value) { - const [a, b, c] = value.slice(1, -1).split(","); - return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) }; - } - mapToDriverValue(value) { - return `{${value.a},${value.b},${value.c}}`; - } -} -function line(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - if (!config?.mode || config.mode === "tuple") { - return new PgLineBuilder(name); - } - return new PgLineABCBuilder(name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr.js -class PgMacaddrBuilder extends PgColumnBuilder { - static [entityKind] = "PgMacaddrBuilder"; - constructor(name) { - super(name, "string", "PgMacaddr"); - } - build(table) { - return new PgMacaddr(table, this.config); - } -} - -class PgMacaddr extends PgColumn { - static [entityKind] = "PgMacaddr"; - getSQLType() { - return "macaddr"; - } -} -function macaddr(name) { - return new PgMacaddrBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/macaddr8.js -class PgMacaddr8Builder extends PgColumnBuilder { - static [entityKind] = "PgMacaddr8Builder"; - constructor(name) { - super(name, "string", "PgMacaddr8"); - } - build(table) { - return new PgMacaddr8(table, this.config); - } -} - -class PgMacaddr8 extends PgColumn { - static [entityKind] = "PgMacaddr8"; - getSQLType() { - return "macaddr8"; - } -} -function macaddr8(name) { - return new PgMacaddr8Builder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/numeric.js -class PgNumericBuilder extends PgColumnBuilder { - static [entityKind] = "PgNumericBuilder"; - constructor(name, precision, scale) { - super(name, "string", "PgNumeric"); - this.config.precision = precision; - this.config.scale = scale; - } - build(table) { - return new PgNumeric(table, this.config); - } -} - -class PgNumeric extends PgColumn { - static [entityKind] = "PgNumeric"; - precision; - scale; - constructor(table, config) { - super(table, config); - this.precision = config.precision; - this.scale = config.scale; - } - mapFromDriverValue(value) { - if (typeof value === "string") - return value; - return String(value); - } - getSQLType() { - if (this.precision !== undefined && this.scale !== undefined) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === undefined) { - return "numeric"; - } else { - return `numeric(${this.precision})`; + if (!(c = x.c)) + return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + if (v = c[v]) { + for (;v % 10 == 0; v /= 10, n--) + ; + for (v = c[0];v >= 10; v /= 10, n++) + ; } - } -} - -class PgNumericNumberBuilder extends PgColumnBuilder { - static [entityKind] = "PgNumericNumberBuilder"; - constructor(name, precision, scale) { - super(name, "number", "PgNumericNumber"); - this.config.precision = precision; - this.config.scale = scale; - } - build(table) { - return new PgNumericNumber(table, this.config); - } -} - -class PgNumericNumber extends PgColumn { - static [entityKind] = "PgNumericNumber"; - precision; - scale; - constructor(table, config) { - super(table, config); - this.precision = config.precision; - this.scale = config.scale; - } - mapFromDriverValue(value) { - if (typeof value === "number") - return value; - return Number(value); - } - mapToDriverValue = String; - getSQLType() { - if (this.precision !== undefined && this.scale !== undefined) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === undefined) { - return "numeric"; - } else { - return `numeric(${this.precision})`; + if (sd && x.e + 1 > n) + n = x.e + 1; + return n; + }; + P.shiftedBy = function(k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times("1e" + k); + }; + P.squareRoot = P.sqrt = function() { + var m, n, r, rep, t2, x = this, c = x.c, s = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber("0.5"); + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); } - } -} - -class PgNumericBigIntBuilder extends PgColumnBuilder { - static [entityKind] = "PgNumericBigIntBuilder"; - constructor(name, precision, scale) { - super(name, "bigint", "PgNumericBigInt"); - this.config.precision = precision; - this.config.scale = scale; - } - build(table) { - return new PgNumericBigInt(table, this.config); - } -} - -class PgNumericBigInt extends PgColumn { - static [entityKind] = "PgNumericBigInt"; - precision; - scale; - constructor(table, config) { - super(table, config); - this.precision = config.precision; - this.scale = config.scale; - } - mapFromDriverValue = BigInt; - mapToDriverValue = String; - getSQLType() { - if (this.precision !== undefined && this.scale !== undefined) { - return `numeric(${this.precision}, ${this.scale})`; - } else if (this.precision === undefined) { - return "numeric"; + s = Math.sqrt(+valueOf(x)); + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e2) % 2 == 0) + n += "0"; + s = Math.sqrt(+n); + e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + if (s == 1 / 0) { + n = "5e" + e2; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf("e") + 1) + e2; + } + r = new BigNumber(n); } else { - return `numeric(${this.precision})`; + r = new BigNumber(s + ""); } - } -} -function numeric(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - const mode = config?.mode; - return mode === "number" ? new PgNumericNumberBuilder(name, config?.precision, config?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder(name, config?.precision, config?.scale) : new PgNumericBuilder(name, config?.precision, config?.scale); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/point.js -class PgPointTupleBuilder extends PgColumnBuilder { - static [entityKind] = "PgPointTupleBuilder"; - constructor(name) { - super(name, "array", "PgPointTuple"); - } - build(table) { - return new PgPointTuple(table, this.config); - } -} - -class PgPointTuple extends PgColumn { - static [entityKind] = "PgPointTuple"; - getSQLType() { - return "point"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - const [x, y] = value.slice(1, -1).split(","); - return [Number.parseFloat(x), Number.parseFloat(y)]; + if (r.c[0]) { + e2 = r.e; + s = e2 + dp; + if (s < 3) + s = 0; + for (;; ) { + t2 = r; + r = half.times(t2.plus(div(x, t2, dp, 1))); + if (coeffToString(t2.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + if (r.e < e2) + --s; + n = n.slice(s - 3, s + 1); + if (n == "9999" || !rep && n == "4999") { + if (!rep) { + round(t2, t2.e + DECIMAL_PLACES + 2, 0); + if (t2.times(t2).eq(x)) { + r = t2; + break; + } + } + dp += 4; + s += 4; + rep = 1; + } else { + if (!+n || !+n.slice(1) && n.charAt(0) == "5") { + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + break; + } + } + } } - return [value.x, value.y]; - } - mapToDriverValue(value) { - return `(${value[0]},${value[1]})`; - } -} - -class PgPointObjectBuilder extends PgColumnBuilder { - static [entityKind] = "PgPointObjectBuilder"; - constructor(name) { - super(name, "json", "PgPointObject"); - } - build(table) { - return new PgPointObject(table, this.config); - } -} - -class PgPointObject extends PgColumn { - static [entityKind] = "PgPointObject"; - getSQLType() { - return "point"; - } - mapFromDriverValue(value) { - if (typeof value === "string") { - const [x, y] = value.slice(1, -1).split(","); - return { x: Number.parseFloat(x), y: Number.parseFloat(y) }; + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + P.toExponential = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; } - return value; - } - mapToDriverValue(value) { - return `(${value.x},${value.y})`; - } -} -function point(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - if (!config?.mode || config.mode === "tuple") { - return new PgPointTupleBuilder(name); - } - return new PgPointObjectBuilder(name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js -function hexToBytes(hex) { - const bytes = []; - for (let c = 0;c < hex.length; c += 2) { - bytes.push(Number.parseInt(hex.slice(c, c + 2), 16)); - } - return new Uint8Array(bytes); -} -function bytesToFloat64(bytes, offset) { - const buffer = new ArrayBuffer(8); - const view = new DataView(buffer); - for (let i = 0;i < 8; i++) { - view.setUint8(i, bytes[offset + i]); - } - return view.getFloat64(0, true); -} -function parseEWKB(hex) { - const bytes = hexToBytes(hex); - let offset = 0; - const byteOrder = bytes[offset]; - offset += 1; - const view = new DataView(bytes.buffer); - const geomType = view.getUint32(offset, byteOrder === 1); - offset += 4; - let _srid; - if (geomType & 536870912) { - _srid = view.getUint32(offset, byteOrder === 1); - offset += 4; - } - if ((geomType & 65535) === 1) { - const x = bytesToFloat64(bytes, offset); - offset += 8; - const y = bytesToFloat64(bytes, offset); - offset += 8; - return [x, y]; - } - throw new Error("Unsupported geometry type"); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js -class PgGeometryBuilder extends PgColumnBuilder { - static [entityKind] = "PgGeometryBuilder"; - constructor(name) { - super(name, "array", "PgGeometry"); - } - build(table) { - return new PgGeometry(table, this.config); - } -} - -class PgGeometry extends PgColumn { - static [entityKind] = "PgGeometry"; - getSQLType() { - return "geometry(point)"; - } - mapFromDriverValue(value) { - return parseEWKB(value); - } - mapToDriverValue(value) { - return `point(${value[0]} ${value[1]})`; - } -} - -class PgGeometryObjectBuilder extends PgColumnBuilder { - static [entityKind] = "PgGeometryObjectBuilder"; - constructor(name) { - super(name, "json", "PgGeometryObject"); - } - build(table) { - return new PgGeometryObject(table, this.config); - } -} - -class PgGeometryObject extends PgColumn { - static [entityKind] = "PgGeometryObject"; - getSQLType() { - return "geometry(point)"; - } - mapFromDriverValue(value) { - const parsed = parseEWKB(value); - return { x: parsed[0], y: parsed[1] }; - } - mapToDriverValue(value) { - return `point(${value.x} ${value.y})`; - } -} -function geometry(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - if (!config?.mode || config.mode === "tuple") { - return new PgGeometryBuilder(name); - } - return new PgGeometryObjectBuilder(name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/real.js -class PgRealBuilder extends PgColumnBuilder { - static [entityKind] = "PgRealBuilder"; - constructor(name, length) { - super(name, "number", "PgReal"); - this.config.length = length; - } - build(table) { - return new PgReal(table, this.config); - } -} - -class PgReal extends PgColumn { - static [entityKind] = "PgReal"; - constructor(table, config) { - super(table, config); - } - getSQLType() { - return "real"; - } - mapFromDriverValue = (value) => { - if (typeof value === "string") { - return Number.parseFloat(value); + return format(this, dp, rm, 1); + }; + P.toFixed = function(dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; } - return value; + return format(this, dp, rm); }; -} -function real(name) { - return new PgRealBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/serial.js -class PgSerialBuilder extends PgColumnBuilder { - static [entityKind] = "PgSerialBuilder"; - constructor(name) { - super(name, "number", "PgSerial"); - this.config.hasDefault = true; - this.config.notNull = true; - } - build(table) { - return new PgSerial(table, this.config); - } -} - -class PgSerial extends PgColumn { - static [entityKind] = "PgSerial"; - getSQLType() { - return "serial"; - } -} -function serial(name) { - return new PgSerialBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallint.js -class PgSmallIntBuilder extends PgIntColumnBaseBuilder { - static [entityKind] = "PgSmallIntBuilder"; - constructor(name) { - super(name, "number", "PgSmallInt"); - } - build(table) { - return new PgSmallInt(table, this.config); - } -} - -class PgSmallInt extends PgColumn { - static [entityKind] = "PgSmallInt"; - getSQLType() { - return "smallint"; - } - mapFromDriverValue = (value) => { - if (typeof value === "string") { - return Number(value); + P.toFormat = function(dp, rm, format2) { + var str, x = this; + if (format2 == null) { + if (dp != null && rm && typeof rm == "object") { + format2 = rm; + rm = null; + } else if (dp && typeof dp == "object") { + format2 = dp; + dp = rm = null; + } else { + format2 = FORMAT; + } + } else if (typeof format2 != "object") { + throw Error(bignumberError + "Argument not an object: " + format2); } - return value; + str = x.toFixed(dp, rm); + if (x.c) { + var i, arr = str.split("."), g1 = +format2.groupSize, g2 = +format2.secondaryGroupSize, groupSeparator = format2.groupSeparator || "", intPart = arr[0], fractionPart = arr[1], isNeg = x.s < 0, intDigits = isNeg ? intPart.slice(1) : intPart, len = intDigits.length; + if (g2) { + i = g1; + g1 = g2; + g2 = i; + len -= i; + } + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + for (;i < len; i += g1) + intPart += groupSeparator + intDigits.substr(i, g1); + if (g2 > 0) + intPart += groupSeparator + intDigits.slice(i); + if (isNeg) + intPart = "-" + intPart; + } + str = fractionPart ? intPart + (format2.decimalSeparator || "") + ((g2 = +format2.fractionGroupSize) ? fractionPart.replace(new RegExp("\\d{" + g2 + "}\\B", "g"), "$&" + (format2.fractionGroupSeparator || "")) : fractionPart) : intPart; + } + return (format2.prefix || "") + str + (format2.suffix || ""); }; + P.toFraction = function(md) { + var d, d0, d1, d2, e2, exp, n, n0, n1, q, r, s, x = this, xc = x.c; + if (md != null) { + n = new BigNumber(md); + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error(bignumberError + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); + } + } + if (!xc) + return new BigNumber(x); + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + e2 = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n; + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + n0.c[0] = 0; + for (;; ) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) + break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e2 = e2 * 2; + r = div(n1, d1, e2, ROUNDING_MODE).minus(x).abs().comparedTo(div(n0, d0, e2, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; + MAX_EXP = exp; + return r; + }; + P.toNumber = function() { + return +valueOf(this); + }; + P.toPrecision = function(sd, rm) { + if (sd != null) + intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + P.toString = function(b) { + var str, n = this, s = n.s, e2 = n.e; + if (e2 === null) { + if (s) { + str = "Infinity"; + if (s < 0) + str = "-" + str; + } else { + str = "NaN"; + } + } else { + if (b == null) { + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n.c), e2) : toFixedPoint(coeffToString(n.c), e2, "0"); + } else if (b === 10 && alphabetHasNormalDecimalDigits) { + n = round(new BigNumber(n), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint(coeffToString(n.c), n.e, "0"); + } else { + intCheck(b, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint(coeffToString(n.c), e2, "0"), 10, b, s, true); + } + if (s < 0 && n.c[0]) + str = "-" + str; + } + return str; + }; + P.valueOf = P.toJSON = function() { + return valueOf(this); + }; + P._isBigNumber = true; + P[Symbol.toStringTag] = "BigNumber"; + P[Symbol.for("nodejs.util.inspect.custom")] = P.valueOf; + if (configObject != null) + BigNumber.set(configObject); + return BigNumber; } -function smallint(name) { - return new PgSmallIntBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/smallserial.js -class PgSmallSerialBuilder extends PgColumnBuilder { - static [entityKind] = "PgSmallSerialBuilder"; - constructor(name) { - super(name, "number", "PgSmallSerial"); - this.config.hasDefault = true; - this.config.notNull = true; - } - build(table) { - return new PgSmallSerial(table, this.config); - } +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; } - -class PgSmallSerial extends PgColumn { - static [entityKind] = "PgSmallSerial"; - getSQLType() { - return "smallserial"; +function coeffToString(a) { + var s, z, i = 1, j = a.length, r = a[0] + ""; + for (;i < j; ) { + s = a[i++] + ""; + z = LOG_BASE - s.length; + for (;z--; s = "0" + s) + ; + r += s; } + for (j = r.length;r.charCodeAt(--j) === 48; ) + ; + return r.slice(0, j + 1 || 1); } -function smallserial(name) { - return new PgSmallSerialBuilder(name ?? ""); +function compare(x, y) { + var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; + if (!i || !j) + return null; + a = xc && !xc[0]; + b = yc && !yc[0]; + if (a || b) + return a ? b ? 0 : -j : i; + if (i != j) + return i; + a = i < 0; + b = k == l; + if (!xc || !yc) + return b ? 0 : !xc ^ a ? 1 : -1; + if (!b) + return k > l ^ a ? 1 : -1; + j = (k = xc.length) < (l = yc.length) ? k : l; + for (i = 0;i < j; i++) + if (xc[i] != yc[i]) + return xc[i] > yc[i] ^ a ? 1 : -1; + return k == l ? 0 : k > l ^ a ? 1 : -1; } - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/text.js -class PgTextBuilder extends PgColumnBuilder { - static [entityKind] = "PgTextBuilder"; - constructor(name, config) { - super(name, "string", "PgText"); - this.config.enumValues = config.enum; - } - build(table) { - return new PgText(table, this.config); +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== mathfloor(n)) { + throw Error(bignumberError + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); } } - -class PgText extends PgColumn { - static [entityKind] = "PgText"; - enumValues = this.config.enumValues; - getSQLType() { - return "text"; - } +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; } -function text(a, b = {}) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgTextBuilder(name, config); +function toExponential(str, e2) { + return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; } - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/time.js -class PgTimeBuilder extends PgDateColumnBaseBuilder { - constructor(name, withTimezone, precision) { - super(name, "string", "PgTime"); - this.withTimezone = withTimezone; - this.precision = precision; - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - static [entityKind] = "PgTimeBuilder"; - build(table) { - return new PgTime(table, this.config); +function toFixedPoint(str, e2, z) { + var len, zs; + if (e2 < 0) { + for (zs = z + ".";++e2; zs += z) + ; + str = zs + str; + } else { + len = str.length; + if (++e2 > len) { + for (zs = z, e2 -= len;--e2; zs += z) + ; + str += zs; + } else if (e2 < len) { + str = str.slice(0, e2) + "." + str.slice(e2); + } } + return str; } +var BigNumber = clone2(); +var bignumber_default = BigNumber; -class PgTime extends PgColumn { - static [entityKind] = "PgTime"; - withTimezone; - precision; - constructor(table, config) { - super(table, config); - this.withTimezone = config.withTimezone; - this.precision = config.precision; - } - getSQLType() { - const precision = this.precision === undefined ? "" : `(${this.precision})`; - return `time${precision}${this.withTimezone ? " with time zone" : ""}`; +// node_modules/.pnpm/@paralleldrive+cuid2@3.3.0/node_modules/@paralleldrive/cuid2/src/index.js +var defaultLength = 24; +var bigLength = 32; +var createRandom = () => { + if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") { + return () => { + const buffer = new Uint32Array(1); + globalThis.crypto.getRandomValues(buffer); + return buffer[0] / 4294967296; + }; } -} -function time(a, b = {}) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgTimeBuilder(name, config.withTimezone ?? false, config.precision); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/timestamp.js -class PgTimestampBuilder extends PgDateColumnBaseBuilder { - static [entityKind] = "PgTimestampBuilder"; - constructor(name, withTimezone, precision) { - super(name, "date", "PgTimestamp"); - this.config.withTimezone = withTimezone; - this.config.precision = precision; + return Math.random; +}; +var random = createRandom(); +var createEntropy = (length = 4, rand = random) => { + let entropy = ""; + while (entropy.length < length) { + entropy = entropy + Math.floor(rand() * 36).toString(36); } - build(table) { - return new PgTimestamp(table, this.config); + return entropy; +}; +function bufToBigInt(buf) { + let value = new bignumber_default(0); + for (const i of buf.values()) { + value = value.multipliedBy(256).plus(i); } + return value; } - -class PgTimestamp extends PgColumn { - static [entityKind] = "PgTimestamp"; - withTimezone; - precision; - constructor(table, config) { - super(table, config); - this.withTimezone = config.withTimezone; - this.precision = config.precision; - } - getSQLType() { - const precision = this.precision === undefined ? "" : ` (${this.precision})`; - return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; +var hash = (input = "") => { + const encoder = new TextEncoder; + return bufToBigInt(sha3_512(encoder.encode(input))).toString(36).slice(1); +}; +var alphabet = Array.from({ length: 26 }, (x, i) => String.fromCharCode(i + 97)); +var randomLetter = (rand) => alphabet[Math.floor(rand() * alphabet.length)]; +var createFingerprint = ({ + globalObj = typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {}, + random: rand = random +} = {}) => { + const globals = Object.keys(globalObj).toString(); + const sourceString = globals.length ? globals + createEntropy(bigLength, rand) : createEntropy(bigLength, rand); + return hash(sourceString).substring(0, bigLength); +}; +var createCounter = (count2) => () => { + return count2++; +}; +var initialCountMax = 476782367; +var init = ({ + random: rand = random, + counter = createCounter(Math.floor(rand() * initialCountMax)), + length = defaultLength, + fingerprint = createFingerprint({ random: rand }) +} = {}) => { + if (length > bigLength) { + throw new Error(`Length must be between 2 and ${bigLength}. Received: ${length}`); } - mapFromDriverValue = (value) => { - return new Date(this.withTimezone ? value : value + "+0000"); + return function cuid2() { + const firstLetter = randomLetter(rand); + const time2 = Date.now().toString(36); + const count2 = counter().toString(36); + const salt = createEntropy(length, rand); + const hashInput = `${time2 + salt + count2 + fingerprint}`; + return `${firstLetter + hash(hashInput).substring(1, length)}`; }; - mapToDriverValue = (value) => { - return value.toISOString(); +}; +var createId = lazy(init); +function lazy(fn) { + let initialized; + return () => { + if (!initialized) { + initialized = fn(); + } + return initialized(); }; } -class PgTimestampStringBuilder extends PgDateColumnBaseBuilder { - static [entityKind] = "PgTimestampStringBuilder"; - constructor(name, withTimezone, precision) { - super(name, "string", "PgTimestampString"); - this.config.withTimezone = withTimezone; - this.config.precision = precision; - } - build(table) { - return new PgTimestampString(table, this.config); - } -} +// src/db/schema.ts +var roleEnum = pgEnum("role", ["ADMIN", "AUTHOR", "USER"]); +var authProvider = pgEnum("AuthProvider", [ + "GOOGLE_OAUTH", + "EMAIL_PASSWORD" +]); +var languageEnum = pgEnum("Language", [ + "CPP", + "JAVA", + "PYTHON", + "JAVASCRIPT", + "C", + "CSHARP" +]); +var jobStatusEnum = pgEnum("JobStatus", [ + "PENDING", + "RUNNING", + "FAILED", + "COMPLETED" +]); +var verdictEnum = pgEnum("Verdict", [ + "PENDING", + "ACCEPTED", + "WRONG_ANSWER", + "TIME_LIMIT_EXCEEDED", + "MEMORY_LIMIT_EXCEEDED", + "RUNTIME_ERROR", + "COMPILE_ERROR" +]); +var difficultyEnum = pgEnum("Difficulty", [ + "EASY", + "MEDIUM", + "HARD", + "EXPERT" +]); +var problemStatusEnum = pgEnum("ProblemStatus", [ + "DRAFT", + "DONE", + "PENDING", + "APPROVED", + "REJECTED" +]); +var submissionModeEnum = pgEnum("SubmissionMode", [ + "SUBMIT", + "RUN" +]); +var user = pgTable("user", { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + email: text("email"), + displayName: text("display_name"), + avatarUrl: text("avatar_url"), + username: text("username").notNull(), + role: roleEnum("role").notNull().default("USER"), + is2FaAuthEnabled: boolean2("is2fa_auth_enabled").default(false).notNull(), + isBanned: boolean2("is_banned").default(false).notNull(), + isEmailVerified: boolean2("is_email_verified").default(false).notNull(), + verificationToken: text("verification_token"), + createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +}, (table) => [ + uniqueIndex("user_email_key").using("btree", table.email.asc().nullsLast()), + uniqueIndex("user_username_key").using("btree", table.username.asc().nullsLast()) +]); +var authMethodColumns = { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + userId: text("user_id").notNull(), + provider: authProvider("provider").notNull(), + googleSub: text("google_sub"), + googleEmail: text("google_email"), + email: text("email"), + passwordHash: text("password_hash"), + createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +}; +var authMethod = pgTable("auth_method", authMethodColumns, (table) => [ + uniqueIndex("auth_method_google_email_key").using("btree", table.googleEmail.asc().nullsLast()), + uniqueIndex("auth_method_google_sub_key").using("btree", table.googleSub.asc().nullsLast()), + index("auth_method_provider_idx").using("btree", table.provider.asc().nullsLast()), + uniqueIndex("auth_method_user_id_key").using("btree", table.userId.asc().nullsLast()), + foreignKey({ + columns: [table.userId], + foreignColumns: [user.id], + name: "auth_method_user_id_fkey" + }).onUpdate("cascade").onDelete("cascade") +]); +var session = pgTable("session", { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade", onUpdate: "cascade" }), + sessionToken: text("session_token").notNull(), + expires: timestamp("expires", { precision: 3, mode: "string" }).notNull() +}, (table) => [ + index("session_user_id_idx").using("btree", table.userId.asc().nullsLast()) +]); +var problem = pgTable("problem", { + id: text("id").primaryKey().$defaultFn(() => createId()), + title: text("title").notNull(), + description: text("description").notNull(), + slug: text("slug").notNull(), + difficulty: difficultyEnum("difficulty").notNull(), + authorId: text("author_id").notNull().references(() => user.id, { onDelete: "restrict" }), + inputFormat: text("input_format").notNull(), + outputFormat: text("output_format").notNull(), + constraints: text("constraints").notNull(), + status: problemStatusEnum("status").notNull().default("DRAFT"), + timeLimit: integer("time_limit").notNull(), + memoryLimit: integer("memory_limit").notNull(), + createdAt: timestamp("created_at").default(sql`now()`).notNull(), + updatedAt: timestamp("updated_at").default(sql`now()`).notNull() +}, (t2) => [ + index("problem_author_idx").on(t2.authorId), + index("problem_difficulty_idx").on(t2.difficulty) +]); +var tagColumns = { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + name: text("name").notNull() +}; +var tag = pgTable("tag", tagColumns, (table) => [ + uniqueIndex("tag_name_key").using("btree", table.name.asc().nullsLast()) +]); +var problemTag = pgTable("problem_tag", { + problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), + tagId: text("tag_id").notNull().references(() => tag.id, { onDelete: "cascade", onUpdate: "cascade" }) +}, (table) => [ + primaryKey({ columns: [table.problemId, table.tagId] }) +]); +var testcase = pgTable("testcase", { + id: text("id").primaryKey().$defaultFn(() => createId()), + problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade" }), + s3Key: text("s3_key").notNull(), + isSample: boolean2("is_sample").default(false).notNull(), + isHidden: boolean2("is_hidden").default(true).notNull(), + order: smallint("order").default(0).notNull(), + batch: smallint("batch").default(0).notNull(), + createdAt: timestamp("created_at").default(sql`now()`).notNull() +}, (t2) => [ + index("testcase_problem_idx").on(t2.problemId), + index("testcase_sample_idx").on(t2.isSample) +]); +var hint = pgTable("hint", { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), + order: smallint("order").notNull().default(0), + title: text("title").notNull(), + content: text("content").notNull(), + createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +}, (table) => [ + index("hints_problem_id_idx").using("btree", table.problemId.asc().nullsLast()) +]); +var editorial = pgTable("editorial", { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), + contentS3Key: text("content_s3_key").notNull(), + editorialLink: text("editorial_link"), + solutionS3Key: text("solution_s3_key").notNull(), + createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +}, (table) => [ + uniqueIndex("editorial_problem_id_key").using("btree", table.problemId.asc().nullsLast()) +]); +var submission = pgTable("submission", { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), + userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade", onUpdate: "cascade" }), + mode: submissionModeEnum("mode").notNull(), + code: text("code").notNull(), + language: languageEnum("language").notNull().default("CPP"), + status: jobStatusEnum("status").notNull().default("PENDING"), + totalTestcases: integer("total_testcases").notNull().default(0), + passedTestcases: integer("passed_testcases").notNull().default(0), + failedTestcases: integer("failed_testcases").notNull().default(0), + timeTaken: integer("time_taken").notNull().default(0), + memoryTaken: integer("memory_taken").notNull().default(0), + createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +}, (table) => [ + index("submission_user_problem_idx").using("btree", table.userId.asc(), table.problemId.asc()), + index("submission_problem_id_idx").using("btree", table.problemId.asc().nullsLast()), + index("submission_user_id_idx").using("btree", table.userId.asc().nullsLast()), + index("submission_status_idx").using("btree", table.status.asc().nullsLast()), + index("submission_created_at_idx").using("btree", table.createdAt.asc().nullsLast()) +]); +var executionResult = pgTable("execution_result", { + id: text("id").primaryKey().notNull().$defaultFn(() => createId()), + submissionId: text("submission_id").notNull().references(() => submission.id, { onDelete: "cascade", onUpdate: "cascade" }), + verdict: verdictEnum("verdict").notNull().default("PENDING"), + stdout: text("stdout"), + stderr: text("stderr"), + createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +}, (table) => [ + index("execution_result_submission_verdict_idx").using("btree", table.submissionId.asc(), table.verdict.asc()), + index("execution_result_submission_id_idx").using("btree", table.submissionId.asc().nullsLast()) +]); -class PgTimestampString extends PgColumn { - static [entityKind] = "PgTimestampString"; - withTimezone; - precision; - constructor(table, config) { - super(table, config); - this.withTimezone = config.withTimezone; - this.precision = config.precision; - } - getSQLType() { - const precision = this.precision === undefined ? "" : `(${this.precision})`; - return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; - } -} -function timestamp(a, b = {}) { - const { name, config } = getColumnNameAndConfig(a, b); - if (config?.mode === "string") { - return new PgTimestampStringBuilder(name, config.withTimezone ?? false, config.precision); - } - return new PgTimestampBuilder(name, config?.withTimezone ?? false, config?.precision); -} +// node_modules/.pnpm/pg@8.20.0/node_modules/pg/esm/index.mjs +var import_lib = __toESM(require_lib5(), 1); +var Client = import_lib.default.Client; +var Pool = import_lib.default.Pool; +var Connection = import_lib.default.Connection; +var types = import_lib.default.types; +var Query = import_lib.default.Query; +var DatabaseError = import_lib.default.DatabaseError; +var escapeIdentifier = import_lib.default.escapeIdentifier; +var escapeLiteral = import_lib.default.escapeLiteral; +var Result = import_lib.default.Result; +var TypeOverrides = import_lib.default.TypeOverrides; +var defaults = import_lib.default.defaults; +var esm_default = import_lib.default; -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/uuid.js -class PgUUIDBuilder extends PgColumnBuilder { - static [entityKind] = "PgUUIDBuilder"; - constructor(name) { - super(name, "string", "PgUUID"); - } - defaultRandom() { - return this.default(sql`gen_random_uuid()`); - } - build(table) { - return new PgUUID(table, this.config); - } -} +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/session.js +var { Pool: Pool2, types: types2 } = esm_default; -class PgUUID extends PgColumn { - static [entityKind] = "PgUUID"; - getSQLType() { - return "uuid"; +class NodePgPreparedQuery extends PgPreparedQuery { + constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, name, _isResponseInArrayMode, customResultMapper) { + super({ sql: queryString, params }, cache, queryMetadata, cacheConfig); + this.client = client; + this.queryString = queryString; + this.params = params; + this.logger = logger; + this.fields = fields; + this._isResponseInArrayMode = _isResponseInArrayMode; + this.customResultMapper = customResultMapper; + this.rawQueryConfig = { + name, + text: queryString, + types: { + getTypeParser: (typeId, format) => { + if (typeId === types2.builtins.TIMESTAMPTZ) { + return (val) => val; + } + if (typeId === types2.builtins.TIMESTAMP) { + return (val) => val; + } + if (typeId === types2.builtins.DATE) { + return (val) => val; + } + if (typeId === types2.builtins.INTERVAL) { + return (val) => val; + } + if (typeId === 1231) { + return (val) => val; + } + if (typeId === 1115) { + return (val) => val; + } + if (typeId === 1185) { + return (val) => val; + } + if (typeId === 1187) { + return (val) => val; + } + if (typeId === 1182) { + return (val) => val; + } + return types2.getTypeParser(typeId, format); + } + } + }; + this.queryConfig = { + name, + text: queryString, + rowMode: "array", + types: { + getTypeParser: (typeId, format) => { + if (typeId === types2.builtins.TIMESTAMPTZ) { + return (val) => val; + } + if (typeId === types2.builtins.TIMESTAMP) { + return (val) => val; + } + if (typeId === types2.builtins.DATE) { + return (val) => val; + } + if (typeId === types2.builtins.INTERVAL) { + return (val) => val; + } + if (typeId === 1231) { + return (val) => val; + } + if (typeId === 1115) { + return (val) => val; + } + if (typeId === 1185) { + return (val) => val; + } + if (typeId === 1187) { + return (val) => val; + } + if (typeId === 1182) { + return (val) => val; + } + return types2.getTypeParser(typeId, format); + } + } + }; } -} -function uuid(name) { - return new PgUUIDBuilder(name ?? ""); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/varchar.js -class PgVarcharBuilder extends PgColumnBuilder { - static [entityKind] = "PgVarcharBuilder"; - constructor(name, config) { - super(name, "string", "PgVarchar"); - this.config.length = config.length; - this.config.enumValues = config.enum; + static [entityKind] = "NodePgPreparedQuery"; + rawQueryConfig; + queryConfig; + async execute(placeholderValues = {}) { + return tracer.startActiveSpan("drizzle.execute", async () => { + const params = fillPlaceholders(this.params, placeholderValues); + this.logger.logQuery(this.rawQueryConfig.text, params); + const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } = this; + if (!fields && !customResultMapper) { + return tracer.startActiveSpan("drizzle.driver.execute", async (span) => { + span?.setAttributes({ + "drizzle.query.name": rawQuery.name, + "drizzle.query.text": rawQuery.text, + "drizzle.query.params": JSON.stringify(params) + }); + return this.queryWithCache(rawQuery.text, params, async () => { + return await client.query(rawQuery, params); + }); + }); + } + const result = await tracer.startActiveSpan("drizzle.driver.execute", (span) => { + span?.setAttributes({ + "drizzle.query.name": query.name, + "drizzle.query.text": query.text, + "drizzle.query.params": JSON.stringify(params) + }); + return this.queryWithCache(query.text, params, async () => { + return await client.query(query, params); + }); + }); + return tracer.startActiveSpan("drizzle.mapResponse", () => { + return customResultMapper ? customResultMapper(result.rows) : result.rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap)); + }); + }); + } + all(placeholderValues = {}) { + return tracer.startActiveSpan("drizzle.execute", () => { + const params = fillPlaceholders(this.params, placeholderValues); + this.logger.logQuery(this.rawQueryConfig.text, params); + return tracer.startActiveSpan("drizzle.driver.execute", (span) => { + span?.setAttributes({ + "drizzle.query.name": this.rawQueryConfig.name, + "drizzle.query.text": this.rawQueryConfig.text, + "drizzle.query.params": JSON.stringify(params) + }); + return this.queryWithCache(this.rawQueryConfig.text, params, async () => { + return this.client.query(this.rawQueryConfig, params); + }).then((result) => result.rows); + }); + }); } - build(table) { - return new PgVarchar(table, this.config); + isResponseInArrayMode() { + return this._isResponseInArrayMode; } } -class PgVarchar extends PgColumn { - static [entityKind] = "PgVarchar"; - length = this.config.length; - enumValues = this.config.enumValues; - getSQLType() { - return this.length === undefined ? `varchar` : `varchar(${this.length})`; +class NodePgSession extends PgSession { + constructor(client, dialect, schema, options = {}) { + super(dialect); + this.client = client; + this.schema = schema; + this.options = options; + this.logger = options.logger ?? new NoopLogger; + this.cache = options.cache ?? new NoopCache; } -} -function varchar(a, b = {}) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgVarcharBuilder(name, config); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js -class PgBinaryVectorBuilder extends PgColumnBuilder { - static [entityKind] = "PgBinaryVectorBuilder"; - constructor(name, config) { - super(name, "string", "PgBinaryVector"); - this.config.dimensions = config.dimensions; + static [entityKind] = "NodePgSession"; + logger; + cache; + prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { + return new NodePgPreparedQuery(this.client, query.sql, query.params, this.logger, this.cache, queryMetadata, cacheConfig, fields, name, isResponseInArrayMode, customResultMapper); } - build(table) { - return new PgBinaryVector(table, this.config); + async transaction(transaction, config) { + const session2 = this.client instanceof Pool2 ? new NodePgSession(await this.client.connect(), this.dialect, this.schema, this.options) : this; + const tx = new NodePgTransaction(this.dialect, session2, this.schema); + await tx.execute(sql`begin${config ? sql` ${tx.getTransactionConfigSQL(config)}` : undefined}`); + try { + const result = await transaction(tx); + await tx.execute(sql`commit`); + return result; + } catch (error) { + await tx.execute(sql`rollback`); + throw error; + } finally { + if (this.client instanceof Pool2) { + session2.client.release(); + } + } + } + async count(sql2) { + const res = await this.execute(sql2); + return Number(res["rows"][0]["count"]); } } -class PgBinaryVector extends PgColumn { - static [entityKind] = "PgBinaryVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `bit(${this.dimensions})`; +class NodePgTransaction extends PgTransaction { + static [entityKind] = "NodePgTransaction"; + async transaction(transaction) { + const savepointName = `sp${this.nestedIndex + 1}`; + const tx = new NodePgTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1); + await tx.execute(sql.raw(`savepoint ${savepointName}`)); + try { + const result = await transaction(tx); + await tx.execute(sql.raw(`release savepoint ${savepointName}`)); + return result; + } catch (err) { + await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`)); + throw err; + } } } -function bit(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgBinaryVectorBuilder(name, config); -} -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js -class PgHalfVectorBuilder extends PgColumnBuilder { - static [entityKind] = "PgHalfVectorBuilder"; - constructor(name, config) { - super(name, "array", "PgHalfVector"); - this.config.dimensions = config.dimensions; +// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/driver.js +class NodePgDriver { + constructor(client, dialect, options = {}) { + this.client = client; + this.dialect = dialect; + this.options = options; } - build(table) { - return new PgHalfVector(table, this.config); + static [entityKind] = "NodePgDriver"; + createSession(schema) { + return new NodePgSession(this.client, this.dialect, schema, { + logger: this.options.logger, + cache: this.options.cache + }); } } -class PgHalfVector extends PgColumn { - static [entityKind] = "PgHalfVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `halfvec(${this.dimensions})`; +class NodePgDatabase extends PgDatabase { + static [entityKind] = "NodePgDatabase"; +} +function construct(client, config = {}) { + const dialect = new PgDialect({ casing: config.casing }); + let logger; + if (config.logger === true) { + logger = new DefaultLogger; + } else if (config.logger !== false) { + logger = config.logger; } - mapToDriverValue(value) { - return JSON.stringify(value); + let schema; + if (config.schema) { + const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers); + schema = { + fullSchema: config.schema, + schema: tablesConfig.tables, + tableNamesMap: tablesConfig.tableNamesMap + }; } - mapFromDriverValue(value) { - return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); + const driver = new NodePgDriver(client, dialect, { logger, cache: config.cache }); + const session2 = driver.createSession(schema); + const db = new NodePgDatabase(dialect, session2, schema); + db.$client = client; + db.$cache = config.cache; + if (db.$cache) { + db.$cache["invalidate"] = config.cache?.onMutate; } + return db; } -function halfvec(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgHalfVectorBuilder(name, config); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js -class PgSparseVectorBuilder extends PgColumnBuilder { - static [entityKind] = "PgSparseVectorBuilder"; - constructor(name, config) { - super(name, "string", "PgSparseVector"); - this.config.dimensions = config.dimensions; +function drizzle(...params) { + if (typeof params[0] === "string") { + const instance = new esm_default.Pool({ + connectionString: params[0] + }); + return construct(instance, params[1]); } - build(table) { - return new PgSparseVector(table, this.config); + if (isConfig(params[0])) { + const { connection, client, ...drizzleConfig } = params[0]; + if (client) + return construct(client, drizzleConfig); + const instance = typeof connection === "string" ? new esm_default.Pool({ + connectionString: connection + }) : new esm_default.Pool(connection); + return construct(instance, drizzleConfig); } + return construct(params[0], params[1]); } - -class PgSparseVector extends PgColumn { - static [entityKind] = "PgSparseVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `sparsevec(${this.dimensions})`; +((drizzle2) => { + function mock(config) { + return construct({}, config); } -} -function sparsevec(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgSparseVectorBuilder(name, config); -} + drizzle2.mock = mock; +})(drizzle || (drizzle = {})); -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js -class PgVectorBuilder extends PgColumnBuilder { - static [entityKind] = "PgVectorBuilder"; - constructor(name, config) { - super(name, "array", "PgVector"); - this.config.dimensions = config.dimensions; - } - build(table) { - return new PgVector(table, this.config); - } -} +// src/loaders/logger.ts +var import_winston = __toESM(require_winston(), 1); +var import_winston_daily_rotate_file = __toESM(require_winston_daily_rotate_file(), 1); -class PgVector extends PgColumn { - static [entityKind] = "PgVector"; - dimensions = this.config.dimensions; - getSQLType() { - return `vector(${this.dimensions})`; - } - mapToDriverValue(value) { - return JSON.stringify(value); - } - mapFromDriverValue(value) { - return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); - } -} -function vector(a, b) { - const { name, config } = getColumnNameAndConfig(a, b); - return new PgVectorBuilder(name, config); -} +// src/utils/constants.ts +var import_unique_username_generator = __toESM(require_dist3(), 1); -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-promise.js -class QueryPromise { - static [entityKind] = "QueryPromise"; - [Symbol.toStringTag] = "QueryPromise"; - catch(onRejected) { - return this.then(undefined, onRejected); - } - finally(onFinally) { - return this.then((value) => { - onFinally?.(); - return value; - }, (reason) => { - onFinally?.(); - throw reason; - }); +// src/config/index.ts +var import_dotenv = __toESM(require_main(), 1); +import path from "path"; +var __dirname = "/home/kmadhav824/Desktop/CodeSM/backend/src/config"; +import_dotenv.default.config({ path: path.join(__dirname, "../../.env") }); +var envSchema = create$3().shape({ + NODE_ENV: create$6().oneOf(["dev", "production"]).default("dev"), + DATABASE_URL: create$6().required("Database URL is Required"), + PORT: create$6().default("8000"), + ALLOWED_ORIGINS: create$6(), + GOOGLE_CLIENT_ID: create$6().required(), + GOOGLE_CLIENT_SECRET: create$6().required(), + GOOGLE_CALLBACK_URL: create$6().required(), + GEMINI_API_KEY: create$6().optional(), + LOG_LEVEL: create$6().oneOf(["error", "warn", "info", "http", "verbose", "debug", "silly"]).default("info"), + API_VERSION: create$6().default("v1"), + MAX_API_REQUEST_RETRIES: create$5().integer().default(3), + CLIENT_URL: create$6().default("https://code-sm.vercel.app"), + MURF_API_KEY: create$6().optional(), + REDIS_HOST: create$6().required(), + REDIS_PASSWORD: create$6().required(), + REDIS_PORT: create$6().required(), + REDIS_USER: create$6().required(), + REDIS_URL: create$6().required(), + REFRESH_TOKEN_EXPIRY: create$6().required(), + REFRESH_TOKEN_SECRET: create$6().required(), + MONGO_URI: create$6().required(), + ACCESS_TOKEN_EXPIRY: create$6().required(), + ACCESS_TOKEN_SECRET: create$6().required(), + AWS_ACCESS_KEY_ID: create$6().required(), + AWS_BUCKET_NAME: create$6().required(), + AWS_REGION: create$6().required(), + VITE_API_URL: create$6().required(), + EMAIL_FROM: create$6().required(), + EMAIL_HOST: create$6().required(), + EMAIL_PASS: create$6().required(), + EMAIL_PORT: create$5().required(), + EMAIL_USER: create$6().required(), + SMTP_VERIFY_URL: create$6().required(), + GOOGLE_REDIRECT_URI: create$6().required(), + JWT_SECRET: create$6().required() +}); +var parsedEnv = envSchema.validateSync(process.env, { + abortEarly: false, + stripUnknown: true +}); +var env = parsedEnv; +var config_default = env; + +// src/utils/constants.ts +var loggerConfig = { + level: config_default.LOG_LEVEL || "info" +}; +var apiPrefix = "/api" + `/${config_default.API_VERSION}`; +var usernameGeneratorConfig = { + dictionaries: [import_unique_username_generator.adjectives, import_unique_username_generator.nouns] +}; + +// src/loaders/logger.ts +var transports = []; +if (true) { + transports.push(new import_winston.default.transports.Console); + const extraTransports = [ + new import_winston_daily_rotate_file.default({ + filename: "./logs/error/error-%DATE%.log", + datePattern: "YYYY-MM-DD", + level: "error", + zippedArchive: true, + format: import_winston.default.format.combine(import_winston.default.format.timestamp({ + format: "YYYY-MM-DD HH:mm:ss" + }), import_winston.default.format.errors({ stack: true }), import_winston.default.format.splat(), import_winston.default.format.json()) + }), + new import_winston_daily_rotate_file.default({ + filename: "./logs/combined/combined-%DATE%.log", + datePattern: "YYYY-MM-DD", + zippedArchive: true, + maxSize: "20m", + maxFiles: "14d", + format: import_winston.default.format.combine(import_winston.default.format.timestamp({ + format: "YYYY-MM-DD HH:mm:ss" + }), import_winston.default.format.errors({ stack: true }), import_winston.default.format.splat(), import_winston.default.format.json()) + }) + ]; + transports.push(...extraTransports); +} else {} +var LoggerInstance = import_winston.default.createLogger({ + level: loggerConfig.level, + levels: import_winston.default.config.npm.levels, + format: import_winston.default.format.combine(import_winston.default.format.timestamp({ + format: "YYYY-MM-DD HH:mm:ss" + }), import_winston.default.format.errors({ stack: true }), import_winston.default.format.splat(), import_winston.default.format.json()), + transports +}); +var logger_default = LoggerInstance; + +// ../db-schema/src/db/schema.ts +var exports_schema = {}; +__export(exports_schema, { + verdictEnum: () => verdictEnum2, + user: () => user2, + testcase: () => testcase2, + tag: () => tag2, + submissionModeEnum: () => submissionModeEnum2, + submission: () => submission2, + session: () => session2, + roleEnum: () => roleEnum2, + problemTag: () => problemTag2, + problemStatusEnum: () => problemStatusEnum2, + problem: () => problem2, + languageEnum: () => languageEnum2, + jobStatusEnum: () => jobStatusEnum2, + hint: () => hint2, + executionResult: () => executionResult2, + editorial: () => editorial2, + difficultyEnum: () => difficultyEnum2, + authProvider: () => authProvider2, + authMethod: () => authMethod2 +}); + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/entity.js +var entityKind2 = Symbol.for("drizzle:entityKind"); +var hasOwnEntityKind2 = Symbol.for("drizzle:hasOwnEntityKind"); +function is2(value, type) { + if (!value || typeof value !== "object") { + return false; } - then(onFulfilled, onRejected) { - return this.execute().then(onFulfilled, onRejected); + if (value instanceof type) { + return true; } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/selection-proxy.js -class SelectionProxyHandler { - static [entityKind] = "SelectionProxyHandler"; - config; - constructor(config) { - this.config = { ...config }; + if (!Object.prototype.hasOwnProperty.call(type, entityKind2)) { + throw new Error(`Class "${type.name ?? ""}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`); } - get(subquery, prop) { - if (prop === "_") { - return { - ...subquery["_"], - selectedFields: new Proxy(subquery._.selectedFields, this) - }; - } - if (prop === ViewBaseConfig) { - return { - ...subquery[ViewBaseConfig], - selectedFields: new Proxy(subquery[ViewBaseConfig].selectedFields, this) - }; - } - if (typeof prop === "symbol") { - return subquery[prop]; - } - const columns = is(subquery, Subquery) ? subquery._.selectedFields : is(subquery, View) ? subquery[ViewBaseConfig].selectedFields : subquery; - const value = columns[prop]; - if (is(value, SQL.Aliased)) { - if (this.config.sqlAliasedBehavior === "sql" && !value.isSelectionField) { - return value.sql; - } - const newValue = value.clone(); - newValue.isSelectionField = true; - return newValue; - } - if (is(value, SQL)) { - if (this.config.sqlBehavior === "sql") { - return value; - } - throw new Error(`You tried to reference "${prop}" field from a subquery, which is a raw SQL field, but it doesn't have an alias declared. Please add an alias to the field using ".as('alias')" method.`); - } - if (is(value, Column)) { - if (this.config.alias) { - return new Proxy(value, new ColumnAliasProxyHandler(new Proxy(value.table, new TableAliasProxyHandler(this.config.alias, this.config.replaceOriginalName ?? false)))); + let cls = Object.getPrototypeOf(value).constructor; + if (cls) { + while (cls) { + if (entityKind2 in cls && cls[entityKind2] === type[entityKind2]) { + return true; } - return value; - } - if (typeof value !== "object" || value === null) { - return value; + cls = Object.getPrototypeOf(cls); } - return new Proxy(value, new SelectionProxyHandler(this.config)); - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/columns/all.js -function getPgColumnBuilders() { - return { - bigint, - bigserial, - boolean: boolean2, - char, - cidr, - customType, - date: date2, - doublePrecision, - inet, - integer, - interval, - json, - jsonb, - line, - macaddr, - macaddr8, - numeric, - point, - geometry, - real, - serial, - smallint, - smallserial, - text, - time, - timestamp, - uuid, - varchar, - bit, - halfvec, - sparsevec, - vector - }; -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/table.js -var InlineForeignKeys = Symbol.for("drizzle:PgInlineForeignKeys"); -var EnableRLS = Symbol.for("drizzle:EnableRLS"); - -class PgTable extends Table { - static [entityKind] = "PgTable"; - static Symbol = Object.assign({}, Table.Symbol, { - InlineForeignKeys, - EnableRLS - }); - [InlineForeignKeys] = []; - [EnableRLS] = false; - [Table.Symbol.ExtraConfigBuilder] = undefined; - [Table.Symbol.ExtraConfigColumns] = {}; -} -function pgTableWithSchema(name, columns, extraConfig, schema, baseName = name) { - const rawTable = new PgTable(name, schema, baseName); - const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders()) : columns; - const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.build(rawTable); - rawTable[InlineForeignKeys].push(...colBuilder.buildForeignKeys(column, rawTable)); - return [name2, column]; - })); - const builtColumnsForExtraConfig = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { - const colBuilder = colBuilderBase; - colBuilder.setName(name2); - const column = colBuilder.buildExtraConfigColumn(rawTable); - return [name2, column]; - })); - const table = Object.assign(rawTable, builtColumns); - table[Table.Symbol.Columns] = builtColumns; - table[Table.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; - if (extraConfig) { - table[PgTable.Symbol.ExtraConfigBuilder] = extraConfig; } - return Object.assign(table, { - enableRLS: () => { - table[PgTable.Symbol.EnableRLS] = true; - return table; - } - }); + return false; } -var pgTable = (name, columns, extraConfig) => { - return pgTableWithSchema(name, columns, extraConfig, undefined); -}; -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/indexes.js -class IndexBuilderOn { - constructor(unique, name) { - this.unique = unique; - this.name = name; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/column.js +class Column2 { + constructor(table, config) { + this.table = table; + this.config = config; + this.name = config.name; + this.keyAsName = config.keyAsName; + this.notNull = config.notNull; + this.default = config.default; + this.defaultFn = config.defaultFn; + this.onUpdateFn = config.onUpdateFn; + this.hasDefault = config.hasDefault; + this.primary = config.primaryKey; + this.isUnique = config.isUnique; + this.uniqueName = config.uniqueName; + this.uniqueType = config.uniqueType; + this.dataType = config.dataType; + this.columnType = config.columnType; + this.generated = config.generated; + this.generatedIdentity = config.generatedIdentity; } - static [entityKind] = "PgIndexBuilderOn"; - on(...columns) { - return new IndexBuilder(columns.map((it) => { - if (is(it, SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); - return clonedIndexedColumn; - }), this.unique, false, this.name); + static [entityKind2] = "Column"; + name; + keyAsName; + primary; + notNull; + default; + defaultFn; + onUpdateFn; + hasDefault; + isUnique; + uniqueName; + uniqueType; + dataType; + columnType; + enumValues = undefined; + generated = undefined; + generatedIdentity = undefined; + config; + mapFromDriverValue(value) { + return value; } - onOnly(...columns) { - return new IndexBuilder(columns.map((it) => { - if (is(it, SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = it.defaultConfig; - return clonedIndexedColumn; - }), this.unique, true, this.name); + mapToDriverValue(value) { + return value; } - using(method, ...columns) { - return new IndexBuilder(columns.map((it) => { - if (is(it, SQL)) { - return it; - } - it = it; - const clonedIndexedColumn = new IndexedColumn(it.name, !!it.keyAsName, it.columnType, it.indexConfig); - it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); - return clonedIndexedColumn; - }), this.unique, true, this.name, method); + shouldDisableInsert() { + return this.config.generated !== undefined && this.config.generated.type !== "byDefault"; } } -class IndexBuilder { - static [entityKind] = "PgIndexBuilder"; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/column-builder.js +class ColumnBuilder2 { + static [entityKind2] = "ColumnBuilder"; config; - constructor(columns, unique, only, name, method = "btree") { + constructor(name, dataType, columnType) { this.config = { name, - columns, - unique, - only, - method + keyAsName: name === "", + notNull: false, + default: undefined, + hasDefault: false, + primaryKey: false, + isUnique: false, + uniqueName: undefined, + uniqueType: undefined, + dataType, + columnType, + generated: undefined }; } - concurrently() { - this.config.concurrently = true; + $type() { return this; } - with(obj) { - this.config.with = obj; + notNull() { + this.config.notNull = true; return this; } - where(condition) { - this.config.where = condition; + default(value) { + this.config.default = value; + this.config.hasDefault = true; return this; } - build(table) { - return new Index(this.config, table); - } -} - -class Index { - static [entityKind] = "PgIndex"; - config; - constructor(config, table) { - this.config = { ...config, table }; - } -} -function index(name) { - return new IndexBuilderOn(false, name); -} -function uniqueIndex(name) { - return new IndexBuilderOn(true, name); -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/primary-keys.js -function primaryKey(...config) { - if (config[0].columns) { - return new PrimaryKeyBuilder(config[0].columns, config[0].name); - } - return new PrimaryKeyBuilder(config); -} - -class PrimaryKeyBuilder { - static [entityKind] = "PgPrimaryKeyBuilder"; - columns; - name; - constructor(columns, name) { - this.columns = columns; - this.name = name; + $defaultFn(fn) { + this.config.defaultFn = fn; + this.config.hasDefault = true; + return this; } - build(table) { - return new PrimaryKey(table, this.columns, this.name); + $default = this.$defaultFn; + $onUpdateFn(fn) { + this.config.onUpdateFn = fn; + this.config.hasDefault = true; + return this; } -} - -class PrimaryKey { - constructor(table, columns, name) { - this.table = table; - this.columns = columns; - this.name = name; + $onUpdate = this.$onUpdateFn; + primaryKey() { + this.config.primaryKey = true; + this.config.notNull = true; + return this; } - static [entityKind] = "PgPrimaryKey"; - columns; - name; - getName() { - return this.name ?? `${this.table[PgTable.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; + setName(name) { + if (this.config.name !== "") + return; + this.config.name = name; } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/casing.js -function toSnakeCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.map((word) => word.toLowerCase()).join("_"); -} -function toCamelCase(input) { - const words = input.replace(/['\u2019]/g, "").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g) ?? []; - return words.reduce((acc, word, i) => { - const formattedWord = i === 0 ? word.toLowerCase() : `${word[0].toUpperCase()}${word.slice(1)}`; - return acc + formattedWord; - }, ""); -} -function noopCase(input) { - return input; -} +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/table.utils.js +var TableName2 = Symbol.for("drizzle:Name"); -class CasingCache { - static [entityKind] = "CasingCache"; - cache = {}; - cachedTables = {}; - convert; - constructor(casing) { - this.convert = casing === "snake_case" ? toSnakeCase : casing === "camelCase" ? toCamelCase : noopCase; - } - getColumnCasing(column) { - if (!column.keyAsName) - return column.name; - const schema = column.table[Table.Symbol.Schema] ?? "public"; - const tableName = column.table[Table.Symbol.OriginalName]; - const key = `${schema}.${tableName}.${column.name}`; - if (!this.cache[key]) { - this.cacheTable(column.table); - } - return this.cache[key]; - } - cacheTable(table) { - const schema = table[Table.Symbol.Schema] ?? "public"; - const tableName = table[Table.Symbol.OriginalName]; - const tableKey = `${schema}.${tableName}`; - if (!this.cachedTables[tableKey]) { - for (const column of Object.values(table[Table.Symbol.Columns])) { - const columnKey = `${tableKey}.${column.name}`; - this.cache[columnKey] = this.convert(column.name); - } - this.cachedTables[tableKey] = true; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/foreign-keys.js +class ForeignKeyBuilder2 { + static [entityKind2] = "PgForeignKeyBuilder"; + reference; + _onUpdate = "no action"; + _onDelete = "no action"; + constructor(config, actions) { + this.reference = () => { + const { name, columns, foreignColumns } = config(); + return { name, columns, foreignTable: foreignColumns[0].table, foreignColumns }; + }; + if (actions) { + this._onUpdate = actions.onUpdate; + this._onDelete = actions.onDelete; } } - clearCache() { - this.cache = {}; - this.cachedTables = {}; - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/errors.js -class DrizzleError extends Error { - static [entityKind] = "DrizzleError"; - constructor({ message, cause }) { - super(message); - this.name = "DrizzleError"; - this.cause = cause; + onUpdate(action) { + this._onUpdate = action === undefined ? "no action" : action; + return this; } -} - -class DrizzleQueryError extends Error { - constructor(query, params, cause) { - super(`Failed query: ${query} -params: ${params}`); - this.query = query; - this.params = params; - this.cause = cause; - Error.captureStackTrace(this, DrizzleQueryError); - if (cause) - this.cause = cause; + onDelete(action) { + this._onDelete = action === undefined ? "no action" : action; + return this; } -} - -class TransactionRollbackError extends DrizzleError { - static [entityKind] = "TransactionRollbackError"; - constructor() { - super({ message: "Rollback" }); + build(table) { + return new ForeignKey2(table, this); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/conditions.js -function bindIfParam(value, column) { - if (isDriverValueEncoder(column) && !isSQLWrapper(value) && !is(value, Param) && !is(value, Placeholder) && !is(value, Column) && !is(value, Table) && !is(value, View)) { - return new Param(value, column); - } - return value; -} -var eq = (left, right) => { - return sql`${left} = ${bindIfParam(right, left)}`; -}; -var ne = (left, right) => { - return sql`${left} <> ${bindIfParam(right, left)}`; -}; -function and(...unfilteredConditions) { - const conditions = unfilteredConditions.filter((c) => c !== undefined); - if (conditions.length === 0) { - return; - } - if (conditions.length === 1) { - return new SQL(conditions); - } - return new SQL([ - new StringChunk("("), - sql.join(conditions, new StringChunk(" and ")), - new StringChunk(")") - ]); -} -function or(...unfilteredConditions) { - const conditions = unfilteredConditions.filter((c) => c !== undefined); - if (conditions.length === 0) { - return; - } - if (conditions.length === 1) { - return new SQL(conditions); - } - return new SQL([ - new StringChunk("("), - sql.join(conditions, new StringChunk(" or ")), - new StringChunk(")") - ]); -} -function not(condition) { - return sql`not ${condition}`; -} -var gt = (left, right) => { - return sql`${left} > ${bindIfParam(right, left)}`; -}; -var gte = (left, right) => { - return sql`${left} >= ${bindIfParam(right, left)}`; -}; -var lt = (left, right) => { - return sql`${left} < ${bindIfParam(right, left)}`; -}; -var lte = (left, right) => { - return sql`${left} <= ${bindIfParam(right, left)}`; -}; -function inArray(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - return sql`false`; - } - return sql`${column} in ${values.map((v) => bindIfParam(v, column))}`; +class ForeignKey2 { + constructor(table, builder) { + this.table = table; + this.reference = builder.reference; + this.onUpdate = builder._onUpdate; + this.onDelete = builder._onDelete; } - return sql`${column} in ${bindIfParam(values, column)}`; -} -function notInArray(column, values) { - if (Array.isArray(values)) { - if (values.length === 0) { - return sql`true`; - } - return sql`${column} not in ${values.map((v) => bindIfParam(v, column))}`; + static [entityKind2] = "PgForeignKey"; + reference; + onUpdate; + onDelete; + getName() { + const { name, columns, foreignColumns } = this.reference(); + const columnNames = columns.map((column) => column.name); + const foreignColumnNames = foreignColumns.map((column) => column.name); + const chunks = [ + this.table[TableName2], + ...columnNames, + foreignColumns[0].table[TableName2], + ...foreignColumnNames + ]; + return name ?? `${chunks.join("_")}_fk`; } - return sql`${column} not in ${bindIfParam(values, column)}`; -} -function isNull(value) { - return sql`${value} is null`; -} -function isNotNull(value) { - return sql`${value} is not null`; -} -function exists(subquery) { - return sql`exists ${subquery}`; -} -function notExists(subquery) { - return sql`not exists ${subquery}`; -} -function between(column, min, max) { - return sql`${column} between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`; -} -function notBetween(column, min, max) { - return sql`${column} not between ${bindIfParam(min, column)} and ${bindIfParam(max, column)}`; -} -function like(column, value) { - return sql`${column} like ${value}`; -} -function notLike(column, value) { - return sql`${column} not like ${value}`; -} -function ilike(column, value) { - return sql`${column} ilike ${value}`; -} -function notIlike(column, value) { - return sql`${column} not ilike ${value}`; } - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/sql/expressions/select.js -function asc(column) { - return sql`${column} asc`; -} -function desc(column) { - return sql`${column} desc`; -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/relations.js -class Relation { - constructor(sourceTable, referencedTable, relationName) { - this.sourceTable = sourceTable; - this.referencedTable = referencedTable; - this.relationName = relationName; - this.referencedTableName = referencedTable[Table.Symbol.Name]; +function foreignKey2(config) { + function mappedConfig() { + const { name, columns, foreignColumns } = config; + return { + name, + columns, + foreignColumns + }; } - static [entityKind] = "Relation"; - referencedTableName; - fieldName; + return new ForeignKeyBuilder2(mappedConfig); } -class Relations { - constructor(table, config) { - this.table = table; - this.config = config; - } - static [entityKind] = "Relations"; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/tracing-utils.js +function iife2(fn, ...args) { + return fn(...args); } -class One extends Relation { - constructor(sourceTable, referencedTable, config, isNullable) { - super(sourceTable, referencedTable, config?.relationName); - this.config = config; - this.isNullable = isNullable; - } - static [entityKind] = "One"; - withFieldName(fieldName) { - const relation = new One(this.sourceTable, this.referencedTable, this.config, this.isNullable); - relation.fieldName = fieldName; - return relation; - } +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/unique-constraint.js +function uniqueKeyName2(table, columns) { + return `${table[TableName2]}_${columns.join("_")}_unique`; } -class Many extends Relation { - constructor(sourceTable, referencedTable, config) { - super(sourceTable, referencedTable, config?.relationName); - this.config = config; - } - static [entityKind] = "Many"; - withFieldName(fieldName) { - const relation = new Many(this.sourceTable, this.referencedTable, this.config); - relation.fieldName = fieldName; - return relation; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/utils/array.js +function parsePgArrayValue2(arrayString, startFrom, inQuotes) { + for (let i = startFrom;i < arrayString.length; i++) { + const char2 = arrayString[i]; + if (char2 === "\\") { + i++; + continue; + } + if (char2 === '"') { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i + 1]; + } + if (inQuotes) { + continue; + } + if (char2 === "," || char2 === "}") { + return [arrayString.slice(startFrom, i).replace(/\\/g, ""), i]; + } } + return [arrayString.slice(startFrom).replace(/\\/g, ""), arrayString.length]; } -function getOperators() { - return { - and, - between, - eq, - exists, - gt, - gte, - ilike, - inArray, - isNull, - isNotNull, - like, - lt, - lte, - ne, - not, - notBetween, - notExists, - notLike, - notIlike, - notInArray, - or, - sql - }; -} -function getOrderByOperators() { - return { - sql, - asc, - desc - }; -} -function extractTablesRelationalConfig(schema, configHelpers) { - if (Object.keys(schema).length === 1 && "default" in schema && !is(schema["default"], Table)) { - schema = schema["default"]; - } - const tableNamesMap = {}; - const relationsBuffer = {}; - const tablesConfig = {}; - for (const [key, value] of Object.entries(schema)) { - if (is(value, Table)) { - const dbName = getTableUniqueName(value); - const bufferedRelations = relationsBuffer[dbName]; - tableNamesMap[dbName] = key; - tablesConfig[key] = { - tsName: key, - dbName: value[Table.Symbol.Name], - schema: value[Table.Symbol.Schema], - columns: value[Table.Symbol.Columns], - relations: bufferedRelations?.relations ?? {}, - primaryKey: bufferedRelations?.primaryKey ?? [] - }; - for (const column of Object.values(value[Table.Symbol.Columns])) { - if (column.primary) { - tablesConfig[key].primaryKey.push(column); - } - } - const extraConfig = value[Table.Symbol.ExtraConfigBuilder]?.(value[Table.Symbol.ExtraConfigColumns]); - if (extraConfig) { - for (const configEntry of Object.values(extraConfig)) { - if (is(configEntry, PrimaryKeyBuilder)) { - tablesConfig[key].primaryKey.push(...configEntry.columns); - } - } - } - } else if (is(value, Relations)) { - const dbName = getTableUniqueName(value.table); - const tableName = tableNamesMap[dbName]; - const relations2 = value.config(configHelpers(value.table)); - let primaryKey2; - for (const [relationName, relation] of Object.entries(relations2)) { - if (tableName) { - const tableConfig = tablesConfig[tableName]; - tableConfig.relations[relationName] = relation; - if (primaryKey2) { - tableConfig.primaryKey.push(...primaryKey2); - } - } else { - if (!(dbName in relationsBuffer)) { - relationsBuffer[dbName] = { - relations: {}, - primaryKey: primaryKey2 - }; - } - relationsBuffer[dbName].relations[relationName] = relation; - } +function parsePgNestedArray2(arrayString, startFrom = 0) { + const result = []; + let i = startFrom; + let lastCharIsComma = false; + while (i < arrayString.length) { + const char2 = arrayString[i]; + if (char2 === ",") { + if (lastCharIsComma || i === startFrom) { + result.push(""); } + lastCharIsComma = true; + i++; + continue; + } + lastCharIsComma = false; + if (char2 === "\\") { + i += 2; + continue; + } + if (char2 === '"') { + const [value2, startFrom2] = parsePgArrayValue2(arrayString, i + 1, true); + result.push(value2); + i = startFrom2; + continue; + } + if (char2 === "}") { + return [result, i + 1]; + } + if (char2 === "{") { + const [value2, startFrom2] = parsePgNestedArray2(arrayString, i + 1); + result.push(value2); + i = startFrom2; + continue; } + const [value, newStartFrom] = parsePgArrayValue2(arrayString, i, false); + result.push(value); + i = newStartFrom; } - return { tables: tablesConfig, tableNamesMap }; + return [result, i]; } -function createOne(sourceTable) { - return function one(table, config) { - return new One(sourceTable, table, config, config?.fields.reduce((res, f) => res && f.notNull, true) ?? false); - }; +function parsePgArray2(arrayString) { + const [result] = parsePgNestedArray2(arrayString, 1); + return result; } -function createMany(sourceTable) { - return function many(referencedTable, config) { - return new Many(sourceTable, referencedTable, config); - }; +function makePgArray2(array2) { + return `{${array2.map((item) => { + if (Array.isArray(item)) { + return makePgArray2(item); + } + if (typeof item === "string") { + return `"${item.replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}"`; + } + return `${item}`; + }).join(",")}}`; } -function normalizeRelation(schema, tableNamesMap, relation) { - if (is(relation, One) && relation.config) { - return { - fields: relation.config.fields, - references: relation.config.references - }; + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/common.js +class PgColumnBuilder2 extends ColumnBuilder2 { + foreignKeyConfigs = []; + static [entityKind2] = "PgColumnBuilder"; + array(size) { + return new PgArrayBuilder2(this.config.name, this, size); } - const referencedTableTsName = tableNamesMap[getTableUniqueName(relation.referencedTable)]; - if (!referencedTableTsName) { - throw new Error(`Table "${relation.referencedTable[Table.Symbol.Name]}" not found in schema`); + references(ref, actions = {}) { + this.foreignKeyConfigs.push({ ref, actions }); + return this; } - const referencedTableConfig = schema[referencedTableTsName]; - if (!referencedTableConfig) { - throw new Error(`Table "${referencedTableTsName}" not found in schema`); + unique(name, config) { + this.config.isUnique = true; + this.config.uniqueName = name; + this.config.uniqueType = config?.nulls; + return this; } - const sourceTable = relation.sourceTable; - const sourceTableTsName = tableNamesMap[getTableUniqueName(sourceTable)]; - if (!sourceTableTsName) { - throw new Error(`Table "${sourceTable[Table.Symbol.Name]}" not found in schema`); + generatedAlwaysAs(as) { + this.config.generated = { + as, + type: "always", + mode: "stored" + }; + return this; } - const reverseRelations = []; - for (const referencedTableRelation of Object.values(referencedTableConfig.relations)) { - if (relation.relationName && relation !== referencedTableRelation && referencedTableRelation.relationName === relation.relationName || !relation.relationName && referencedTableRelation.referencedTable === relation.sourceTable) { - reverseRelations.push(referencedTableRelation); - } + buildForeignKeys(column, table) { + return this.foreignKeyConfigs.map(({ ref, actions }) => { + return iife2((ref2, actions2) => { + const builder = new ForeignKeyBuilder2(() => { + const foreignColumn = ref2(); + return { columns: [column], foreignColumns: [foreignColumn] }; + }); + if (actions2.onUpdate) { + builder.onUpdate(actions2.onUpdate); + } + if (actions2.onDelete) { + builder.onDelete(actions2.onDelete); + } + return builder.build(table); + }, ref, actions); + }); } - if (reverseRelations.length > 1) { - throw relation.relationName ? new Error(`There are multiple relations with name "${relation.relationName}" in table "${referencedTableTsName}"`) : new Error(`There are multiple relations between "${referencedTableTsName}" and "${relation.sourceTable[Table.Symbol.Name]}". Please specify relation name`); + buildExtraConfigColumn(table) { + return new ExtraConfigColumn2(table, this.config); } - if (reverseRelations[0] && is(reverseRelations[0], One) && reverseRelations[0].config) { - return { - fields: reverseRelations[0].config.references, - references: reverseRelations[0].config.fields - }; +} + +class PgColumn2 extends Column2 { + constructor(table, config) { + if (!config.uniqueName) { + config.uniqueName = uniqueKeyName2(table, [config.name]); + } + super(table, config); + this.table = table; } - throw new Error(`There is not enough information to infer relation "${sourceTableTsName}.${relation.fieldName}"`); + static [entityKind2] = "PgColumn"; } -function createTableRelationsHelpers(sourceTable) { - return { - one: createOne(sourceTable), - many: createMany(sourceTable) + +class ExtraConfigColumn2 extends PgColumn2 { + static [entityKind2] = "ExtraConfigColumn"; + getSQLType() { + return this.getSQLType(); + } + indexConfig = { + order: this.config.order ?? "asc", + nulls: this.config.nulls ?? "last", + opClass: this.config.opClass + }; + defaultConfig = { + order: "asc", + nulls: "last", + opClass: undefined }; + asc() { + this.indexConfig.order = "asc"; + return this; + } + desc() { + this.indexConfig.order = "desc"; + return this; + } + nullsFirst() { + this.indexConfig.nulls = "first"; + return this; + } + nullsLast() { + this.indexConfig.nulls = "last"; + return this; + } + op(opClass) { + this.indexConfig.opClass = opClass; + return this; + } } -function mapRelationalRow(tablesConfig, tableConfig, row, buildQueryResultSelection, mapColumnValue = (value) => value) { - const result = {}; - for (const [ - selectionItemIndex, - selectionItem - ] of buildQueryResultSelection.entries()) { - if (selectionItem.isJson) { - const relation = tableConfig.relations[selectionItem.tsKey]; - const rawSubRows = row[selectionItemIndex]; - const subRows = typeof rawSubRows === "string" ? JSON.parse(rawSubRows) : rawSubRows; - result[selectionItem.tsKey] = is(relation, One) ? subRows && mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRows, selectionItem.selection, mapColumnValue) : subRows.map((subRow) => mapRelationalRow(tablesConfig, tablesConfig[selectionItem.relationTableTsKey], subRow, selectionItem.selection, mapColumnValue)); - } else { - const value = mapColumnValue(row[selectionItemIndex]); - const field = selectionItem.field; - let decoder; - if (is(field, Column)) { - decoder = field; - } else if (is(field, SQL)) { - decoder = field.decoder; - } else { - decoder = field.sql.decoder; - } - result[selectionItem.tsKey] = value === null ? null : decoder.mapFromDriverValue(value); - } + +class IndexedColumn2 { + static [entityKind2] = "IndexedColumn"; + constructor(name, keyAsName, type, indexConfig) { + this.name = name; + this.keyAsName = keyAsName; + this.type = type; + this.indexConfig = indexConfig; } - return result; + name; + keyAsName; + type; + indexConfig; } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/view-base.js -class PgViewBase extends View { - static [entityKind] = "PgViewBase"; +class PgArrayBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgArrayBuilder"; + constructor(name, baseBuilder, size) { + super(name, "array", "PgArray"); + this.config.baseBuilder = baseBuilder; + this.config.size = size; + } + build(table) { + const baseColumn = this.config.baseBuilder.build(table); + return new PgArray2(table, this.config, baseColumn); + } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/dialect.js -class PgDialect { - static [entityKind] = "PgDialect"; - casing; - constructor(config) { - this.casing = new CasingCache(config?.casing); +class PgArray2 extends PgColumn2 { + constructor(table, config, baseColumn, range) { + super(table, config); + this.baseColumn = baseColumn; + this.range = range; + this.size = config.size; } - async migrate(migrations, session, config) { - const migrationsTable = typeof config === "string" ? "__drizzle_migrations" : config.migrationsTable ?? "__drizzle_migrations"; - const migrationsSchema = typeof config === "string" ? "drizzle" : config.migrationsSchema ?? "drizzle"; - const migrationTableCreate = sql` - CREATE TABLE IF NOT EXISTS ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ( - id SERIAL PRIMARY KEY, - hash text NOT NULL, - created_at bigint - ) - `; - await session.execute(sql`CREATE SCHEMA IF NOT EXISTS ${sql.identifier(migrationsSchema)}`); - await session.execute(migrationTableCreate); - const dbMigrations = await session.all(sql`select id, hash, created_at from ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} order by created_at desc limit 1`); - const lastDbMigration = dbMigrations[0]; - await session.transaction(async (tx) => { - for await (const migration of migrations) { - if (!lastDbMigration || Number(lastDbMigration.created_at) < migration.folderMillis) { - for (const stmt of migration.sql) { - await tx.execute(sql.raw(stmt)); - } - await tx.execute(sql`insert into ${sql.identifier(migrationsSchema)}.${sql.identifier(migrationsTable)} ("hash", "created_at") values(${migration.hash}, ${migration.folderMillis})`); - } - } - }); + size; + static [entityKind2] = "PgArray"; + getSQLType() { + return `${this.baseColumn.getSQLType()}[${typeof this.size === "number" ? this.size : ""}]`; } - escapeName(name) { - return `"${name}"`; + mapFromDriverValue(value) { + if (typeof value === "string") { + value = parsePgArray2(value); + } + return value.map((v) => this.baseColumn.mapFromDriverValue(v)); } - escapeParam(num) { - return `$${num + 1}`; + mapToDriverValue(value, isNestedArray = false) { + const a = value.map((v) => v === null ? null : is2(this.baseColumn, PgArray2) ? this.baseColumn.mapToDriverValue(v, true) : this.baseColumn.mapToDriverValue(v)); + if (isNestedArray) + return a; + return makePgArray2(a); } - escapeString(str) { - return `'${str.replace(/'/g, "''")}'`; +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/enum.js +class PgEnumObjectColumnBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgEnumObjectColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumObjectColumn"); + this.config.enum = enumInstance; } - buildWithCTE(queries) { - if (!queries?.length) - return; - const withSqlChunks = [sql`with `]; - for (const [i, w] of queries.entries()) { - withSqlChunks.push(sql`${sql.identifier(w._.alias)} as (${w._.sql})`); - if (i < queries.length - 1) { - withSqlChunks.push(sql`, `); - } - } - withSqlChunks.push(sql` `); - return sql.join(withSqlChunks); + build(table) { + return new PgEnumObjectColumn2(table, this.config); } - buildDeleteQuery({ table, where, returning, withList }) { - const withSql = this.buildWithCTE(withList); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined; - const whereSql = where ? sql` where ${where}` : undefined; - return sql`${withSql}delete from ${table}${whereSql}${returningSql}`; +} + +class PgEnumObjectColumn2 extends PgColumn2 { + static [entityKind2] = "PgEnumObjectColumn"; + enum; + enumValues = this.config.enum.enumValues; + constructor(table, config) { + super(table, config); + this.enum = config.enum; } - buildUpdateSet(table, set) { - const tableColumns = table[Table.Symbol.Columns]; - const columnNames = Object.keys(tableColumns).filter((colName) => set[colName] !== undefined || tableColumns[colName]?.onUpdateFn !== undefined); - const setSize = columnNames.length; - return sql.join(columnNames.flatMap((colName, i) => { - const col = tableColumns[colName]; - const value = set[colName] ?? sql.param(col.onUpdateFn(), col); - const res = sql`${sql.identifier(this.casing.getColumnCasing(col))} = ${value}`; - if (i < setSize - 1) { - return [res, sql.raw(", ")]; - } - return [res]; - })); + getSQLType() { + return this.enum.enumName; } - buildUpdateQuery({ table, set, where, returning, withList, from, joins }) { - const withSql = this.buildWithCTE(withList); - const tableName = table[PgTable.Symbol.Name]; - const tableSchema = table[PgTable.Symbol.Schema]; - const origTableName = table[PgTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? undefined : tableName; - const tableSql = sql`${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}`; - const setSql = this.buildUpdateSet(table, set); - const fromSql = from && sql.join([sql.raw(" from "), this.buildFromTable(from)]); - const joinsSql = this.buildJoins(joins); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: !from })}` : undefined; - const whereSql = where ? sql` where ${where}` : undefined; - return sql`${withSql}update ${tableSql} set ${setSql}${fromSql}${joinsSql}${whereSql}${returningSql}`; +} +var isPgEnumSym2 = Symbol.for("drizzle:isPgEnum"); +function isPgEnum2(obj) { + return !!obj && typeof obj === "function" && isPgEnumSym2 in obj && obj[isPgEnumSym2] === true; +} + +class PgEnumColumnBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgEnumColumnBuilder"; + constructor(name, enumInstance) { + super(name, "string", "PgEnumColumn"); + this.config.enum = enumInstance; } - buildSelection(fields, { isSingleTable = false } = {}) { - const columnsLen = fields.length; - const chunks = fields.flatMap(({ field }, i) => { - const chunk = []; - if (is(field, SQL.Aliased) && field.isSelectionField) { - chunk.push(sql.identifier(field.fieldAlias)); - } else if (is(field, SQL.Aliased) || is(field, SQL)) { - const query = is(field, SQL.Aliased) ? field.sql : field; - if (isSingleTable) { - chunk.push(new SQL(query.queryChunks.map((c) => { - if (is(c, PgColumn)) { - return sql.identifier(this.casing.getColumnCasing(c)); - } - return c; - }))); - } else { - chunk.push(query); - } - if (is(field, SQL.Aliased)) { - chunk.push(sql` as ${sql.identifier(field.fieldAlias)}`); - } - } else if (is(field, Column)) { - if (isSingleTable) { - chunk.push(sql.identifier(this.casing.getColumnCasing(field))); - } else { - chunk.push(field); - } - } - if (i < columnsLen - 1) { - chunk.push(sql`, `); - } - return chunk; - }); - return sql.join(chunks); + build(table) { + return new PgEnumColumn2(table, this.config); } - buildJoins(joins) { - if (!joins || joins.length === 0) { - return; - } - const joinsArray = []; - for (const [index2, joinMeta] of joins.entries()) { - if (index2 === 0) { - joinsArray.push(sql` `); - } - const table = joinMeta.table; - const lateralSql = joinMeta.lateral ? sql` lateral` : undefined; - const onSql = joinMeta.on ? sql` on ${joinMeta.on}` : undefined; - if (is(table, PgTable)) { - const tableName = table[PgTable.Symbol.Name]; - const tableSchema = table[PgTable.Symbol.Schema]; - const origTableName = table[PgTable.Symbol.OriginalName]; - const alias = tableName === origTableName ? undefined : joinMeta.alias; - joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${tableSchema ? sql`${sql.identifier(tableSchema)}.` : undefined}${sql.identifier(origTableName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`); - } else if (is(table, View)) { - const viewName = table[ViewBaseConfig].name; - const viewSchema = table[ViewBaseConfig].schema; - const origViewName = table[ViewBaseConfig].originalName; - const alias = viewName === origViewName ? undefined : joinMeta.alias; - joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${viewSchema ? sql`${sql.identifier(viewSchema)}.` : undefined}${sql.identifier(origViewName)}${alias && sql` ${sql.identifier(alias)}`}${onSql}`); - } else { - joinsArray.push(sql`${sql.raw(joinMeta.joinType)} join${lateralSql} ${table}${onSql}`); - } - if (index2 < joins.length - 1) { - joinsArray.push(sql` `); - } - } - return sql.join(joinsArray); +} + +class PgEnumColumn2 extends PgColumn2 { + static [entityKind2] = "PgEnumColumn"; + enum = this.config.enum; + enumValues = this.config.enum.enumValues; + constructor(table, config) { + super(table, config); + this.enum = config.enum; } - buildFromTable(table) { - if (is(table, Table) && table[Table.Symbol.IsAlias]) { - let fullName = sql`${sql.identifier(table[Table.Symbol.OriginalName])}`; - if (table[Table.Symbol.Schema]) { - fullName = sql`${sql.identifier(table[Table.Symbol.Schema])}.${fullName}`; - } - return sql`${fullName} ${sql.identifier(table[Table.Symbol.Name])}`; - } - return table; + getSQLType() { + return this.enum.enumName; } - buildSelectQuery({ - withList, - fields, - fieldsFlat, - where, - having, - table, - joins, - orderBy, - groupBy, - limit, - offset, - lockingClause, - distinct, - setOperators - }) { - const fieldsList = fieldsFlat ?? orderSelectedFields(fields); - for (const f of fieldsList) { - if (is(f.field, Column) && getTableName(f.field.table) !== (is(table, Subquery) ? table._.alias : is(table, PgViewBase) ? table[ViewBaseConfig].name : is(table, SQL) ? undefined : getTableName(table)) && !((table2) => joins?.some(({ alias }) => alias === (table2[Table.Symbol.IsAlias] ? getTableName(table2) : table2[Table.Symbol.BaseName])))(f.field.table)) { - const tableName = getTableName(f.field.table); - throw new Error(`Your "${f.path.join("->")}" field references a column "${tableName}"."${f.field.name}", but the table "${tableName}" is not part of the query! Did you forget to join it?`); - } - } - const isSingleTable = !joins || joins.length === 0; - const withSql = this.buildWithCTE(withList); - let distinctSql; - if (distinct) { - distinctSql = distinct === true ? sql` distinct` : sql` distinct on (${sql.join(distinct.on, sql`, `)})`; - } - const selection = this.buildSelection(fieldsList, { isSingleTable }); - const tableSql = this.buildFromTable(table); - const joinsSql = this.buildJoins(joins); - const whereSql = where ? sql` where ${where}` : undefined; - const havingSql = having ? sql` having ${having}` : undefined; - let orderBySql; - if (orderBy && orderBy.length > 0) { - orderBySql = sql` order by ${sql.join(orderBy, sql`, `)}`; +} +function pgEnum2(enumName, input) { + return Array.isArray(input) ? pgEnumWithSchema2(enumName, [...input], undefined) : pgEnumObjectWithSchema2(enumName, input, undefined); +} +function pgEnumWithSchema2(enumName, values, schema) { + const enumInstance = Object.assign((name) => new PgEnumColumnBuilder2(name ?? "", enumInstance), { + enumName, + enumValues: values, + schema, + [isPgEnumSym2]: true + }); + return enumInstance; +} +function pgEnumObjectWithSchema2(enumName, values, schema) { + const enumInstance = Object.assign((name) => new PgEnumObjectColumnBuilder2(name ?? "", enumInstance), { + enumName, + enumValues: Object.values(values), + schema, + [isPgEnumSym2]: true + }); + return enumInstance; +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/subquery.js +class Subquery2 { + static [entityKind2] = "Subquery"; + constructor(sql2, fields, alias, isWith = false, usedTables = []) { + this._ = { + brand: "Subquery", + sql: sql2, + selectedFields: fields, + alias, + isWith, + usedTables + }; + } +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/version.js +var version2 = "0.44.0"; + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/tracing.js +var otel2; +var rawTracer2; +var tracer2 = { + startActiveSpan(name, fn) { + if (!otel2) { + return fn(); } - let groupBySql; - if (groupBy && groupBy.length > 0) { - groupBySql = sql` group by ${sql.join(groupBy, sql`, `)}`; + if (!rawTracer2) { + rawTracer2 = otel2.trace.getTracer("drizzle-orm", version2); } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined; - const offsetSql = offset ? sql` offset ${offset}` : undefined; - const lockingClauseSql = sql.empty(); - if (lockingClause) { - const clauseSql = sql` for ${sql.raw(lockingClause.strength)}`; - if (lockingClause.config.of) { - clauseSql.append(sql` of ${sql.join(Array.isArray(lockingClause.config.of) ? lockingClause.config.of : [lockingClause.config.of], sql`, `)}`); - } - if (lockingClause.config.noWait) { - clauseSql.append(sql` nowait`); - } else if (lockingClause.config.skipLocked) { - clauseSql.append(sql` skip locked`); + return iife2((otel22, rawTracer22) => rawTracer22.startActiveSpan(name, (span) => { + try { + return fn(span); + } catch (e2) { + span.setStatus({ + code: otel22.SpanStatusCode.ERROR, + message: e2 instanceof Error ? e2.message : "Unknown error" + }); + throw e2; + } finally { + span.end(); } - lockingClauseSql.append(clauseSql); - } - const finalQuery = sql`${withSql}select${distinctSql} ${selection} from ${tableSql}${joinsSql}${whereSql}${groupBySql}${havingSql}${orderBySql}${limitSql}${offsetSql}${lockingClauseSql}`; - if (setOperators.length > 0) { - return this.buildSetOperations(finalQuery, setOperators); - } - return finalQuery; + }), otel2, rawTracer2); } - buildSetOperations(leftSelect, setOperators) { - const [setOperator, ...rest] = setOperators; - if (!setOperator) { - throw new Error("Cannot pass undefined values to any set operator"); - } - if (rest.length === 0) { - return this.buildSetOperationQuery({ leftSelect, setOperator }); - } - return this.buildSetOperations(this.buildSetOperationQuery({ leftSelect, setOperator }), rest); +}; + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/view-common.js +var ViewBaseConfig2 = Symbol.for("drizzle:ViewBaseConfig"); + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/table.js +var Schema3 = Symbol.for("drizzle:Schema"); +var Columns2 = Symbol.for("drizzle:Columns"); +var ExtraConfigColumns2 = Symbol.for("drizzle:ExtraConfigColumns"); +var OriginalName2 = Symbol.for("drizzle:OriginalName"); +var BaseName2 = Symbol.for("drizzle:BaseName"); +var IsAlias2 = Symbol.for("drizzle:IsAlias"); +var ExtraConfigBuilder2 = Symbol.for("drizzle:ExtraConfigBuilder"); +var IsDrizzleTable2 = Symbol.for("drizzle:IsDrizzleTable"); + +class Table2 { + static [entityKind2] = "Table"; + static Symbol = { + Name: TableName2, + Schema: Schema3, + OriginalName: OriginalName2, + Columns: Columns2, + ExtraConfigColumns: ExtraConfigColumns2, + BaseName: BaseName2, + IsAlias: IsAlias2, + ExtraConfigBuilder: ExtraConfigBuilder2 + }; + [TableName2]; + [OriginalName2]; + [Schema3]; + [Columns2]; + [ExtraConfigColumns2]; + [BaseName2]; + [IsAlias2] = false; + [IsDrizzleTable2] = true; + [ExtraConfigBuilder2] = undefined; + constructor(name, schema, baseName) { + this[TableName2] = this[OriginalName2] = name; + this[Schema3] = schema; + this[BaseName2] = baseName; } - buildSetOperationQuery({ - leftSelect, - setOperator: { type, isAll, rightSelect, limit, orderBy, offset } - }) { - const leftChunk = sql`(${leftSelect.getSQL()}) `; - const rightChunk = sql`(${rightSelect.getSQL()})`; - let orderBySql; - if (orderBy && orderBy.length > 0) { - const orderByValues = []; - for (const singleOrderBy of orderBy) { - if (is(singleOrderBy, PgColumn)) { - orderByValues.push(sql.identifier(singleOrderBy.name)); - } else if (is(singleOrderBy, SQL)) { - for (let i = 0;i < singleOrderBy.queryChunks.length; i++) { - const chunk = singleOrderBy.queryChunks[i]; - if (is(chunk, PgColumn)) { - singleOrderBy.queryChunks[i] = sql.identifier(chunk.name); - } - } - orderByValues.push(sql`${singleOrderBy}`); - } else { - orderByValues.push(sql`${singleOrderBy}`); - } +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/sql/sql.js +function isSQLWrapper2(value) { + return value !== null && value !== undefined && typeof value.getSQL === "function"; +} +function mergeQueries2(queries) { + const result = { sql: "", params: [] }; + for (const query of queries) { + result.sql += query.sql; + result.params.push(...query.params); + if (query.typings?.length) { + if (!result.typings) { + result.typings = []; } - orderBySql = sql` order by ${sql.join(orderByValues, sql`, `)} `; + result.typings.push(...query.typings); } - const limitSql = typeof limit === "object" || typeof limit === "number" && limit >= 0 ? sql` limit ${limit}` : undefined; - const operatorChunk = sql.raw(`${type} ${isAll ? "all " : ""}`); - const offsetSql = offset ? sql` offset ${offset}` : undefined; - return sql`${leftChunk}${operatorChunk}${rightChunk}${orderBySql}${limitSql}${offsetSql}`; } - buildInsertQuery({ table, values: valuesOrSelect, onConflict, returning, withList, select, overridingSystemValue_ }) { - const valuesSqlList = []; - const columns = table[Table.Symbol.Columns]; - const colEntries = Object.entries(columns).filter(([_, col]) => !col.shouldDisableInsert()); - const insertOrder = colEntries.map(([, column]) => sql.identifier(this.casing.getColumnCasing(column))); - if (select) { - const select2 = valuesOrSelect; - if (is(select2, SQL)) { - valuesSqlList.push(select2); - } else { - valuesSqlList.push(select2.getSQL()); - } - } else { - const values = valuesOrSelect; - valuesSqlList.push(sql.raw("values ")); - for (const [valueIndex, value] of values.entries()) { - const valueList = []; - for (const [fieldName, col] of colEntries) { - const colValue = value[fieldName]; - if (colValue === undefined || is(colValue, Param) && colValue.value === undefined) { - if (col.defaultFn !== undefined) { - const defaultFnResult = col.defaultFn(); - const defaultValue = is(defaultFnResult, SQL) ? defaultFnResult : sql.param(defaultFnResult, col); - valueList.push(defaultValue); - } else if (!col.default && col.onUpdateFn !== undefined) { - const onUpdateFnResult = col.onUpdateFn(); - const newValue = is(onUpdateFnResult, SQL) ? onUpdateFnResult : sql.param(onUpdateFnResult, col); - valueList.push(newValue); - } else { - valueList.push(sql`default`); - } - } else { - valueList.push(colValue); - } - } - valuesSqlList.push(valueList); - if (valueIndex < values.length - 1) { - valuesSqlList.push(sql`, `); - } - } - } - const withSql = this.buildWithCTE(withList); - const valuesSql = sql.join(valuesSqlList); - const returningSql = returning ? sql` returning ${this.buildSelection(returning, { isSingleTable: true })}` : undefined; - const onConflictSql = onConflict ? sql` on conflict ${onConflict}` : undefined; - const overridingSql = overridingSystemValue_ === true ? sql`overriding system value ` : undefined; - return sql`${withSql}insert into ${table} ${insertOrder} ${overridingSql}${valuesSql}${onConflictSql}${returningSql}`; + return result; +} + +class StringChunk2 { + static [entityKind2] = "StringChunk"; + value; + constructor(value) { + this.value = Array.isArray(value) ? value : [value]; } - buildRefreshMaterializedViewQuery({ view, concurrently, withNoData }) { - const concurrentlySql = concurrently ? sql` concurrently` : undefined; - const withNoDataSql = withNoData ? sql` with no data` : undefined; - return sql`refresh materialized view${concurrentlySql} ${view}${withNoDataSql}`; + getSQL() { + return new SQL2([this]); } - prepareTyping(encoder) { - if (is(encoder, PgJsonb) || is(encoder, PgJson)) { - return "json"; - } else if (is(encoder, PgNumeric)) { - return "decimal"; - } else if (is(encoder, PgTime)) { - return "time"; - } else if (is(encoder, PgTimestamp) || is(encoder, PgTimestampString)) { - return "timestamp"; - } else if (is(encoder, PgDate) || is(encoder, PgDateString)) { - return "date"; - } else if (is(encoder, PgUUID)) { - return "uuid"; - } else { - return "none"; +} + +class SQL2 { + constructor(queryChunks) { + this.queryChunks = queryChunks; + for (const chunk of queryChunks) { + if (is2(chunk, Table2)) { + const schemaName = chunk[Table2.Symbol.Schema]; + this.usedTables.push(schemaName === undefined ? chunk[Table2.Symbol.Name] : schemaName + "." + chunk[Table2.Symbol.Name]); + } } } - sqlToQuery(sql2, invokeSource) { - return sql2.toQuery({ - casing: this.casing, - escapeName: this.escapeName, - escapeParam: this.escapeParam, - escapeString: this.escapeString, - prepareTyping: this.prepareTyping, - invokeSource + static [entityKind2] = "SQL"; + decoder = noopDecoder2; + shouldInlineParams = false; + usedTables = []; + append(query) { + this.queryChunks.push(...query.queryChunks); + return this; + } + toQuery(config) { + return tracer2.startActiveSpan("drizzle.buildSQL", (span) => { + const query = this.buildQueryFromSourceParams(this.queryChunks, config); + span?.setAttributes({ + "drizzle.query.text": query.sql, + "drizzle.query.params": JSON.stringify(query.params) + }); + return query; }); } - buildRelationalQueryWithoutPK({ - fullSchema, - schema, - tableNamesMap, - table, - tableConfig, - queryConfig: config, - tableAlias, - nestedQueryRelation, - joinOn - }) { - let selection = []; - let limit, offset, orderBy = [], where; - const joins = []; - if (config === true) { - const selectionEntries = Object.entries(tableConfig.columns); - selection = selectionEntries.map(([key, value]) => ({ - dbKey: value.name, - tsKey: key, - field: aliasedTableColumn(value, tableAlias), - relationTableTsKey: undefined, - isJson: false, - selection: [] - })); - } else { - const aliasedColumns = Object.fromEntries(Object.entries(tableConfig.columns).map(([key, value]) => [key, aliasedTableColumn(value, tableAlias)])); - if (config.where) { - const whereSql = typeof config.where === "function" ? config.where(aliasedColumns, getOperators()) : config.where; - where = whereSql && mapColumnsInSQLToAlias(whereSql, tableAlias); - } - const fieldsSelection = []; - let selectedColumns = []; - if (config.columns) { - let isIncludeMode = false; - for (const [field, value] of Object.entries(config.columns)) { - if (value === undefined) { - continue; - } - if (field in tableConfig.columns) { - if (!isIncludeMode && value === true) { - isIncludeMode = true; - } - selectedColumns.push(field); - } - } - if (selectedColumns.length > 0) { - selectedColumns = isIncludeMode ? selectedColumns.filter((c) => config.columns?.[c] === true) : Object.keys(tableConfig.columns).filter((key) => !selectedColumns.includes(key)); - } - } else { - selectedColumns = Object.keys(tableConfig.columns); + buildQueryFromSourceParams(chunks, _config) { + const config = Object.assign({}, _config, { + inlineParams: _config.inlineParams || this.shouldInlineParams, + paramStartIndex: _config.paramStartIndex || { value: 0 } + }); + const { + casing, + escapeName, + escapeParam, + prepareTyping, + inlineParams, + paramStartIndex + } = config; + return mergeQueries2(chunks.map((chunk) => { + if (is2(chunk, StringChunk2)) { + return { sql: chunk.value.join(""), params: [] }; } - for (const field of selectedColumns) { - const column = tableConfig.columns[field]; - fieldsSelection.push({ tsKey: field, value: column }); + if (is2(chunk, Name2)) { + return { sql: escapeName(chunk.value), params: [] }; } - let selectedRelations = []; - if (config.with) { - selectedRelations = Object.entries(config.with).filter((entry) => !!entry[1]).map(([tsKey, queryConfig]) => ({ tsKey, queryConfig, relation: tableConfig.relations[tsKey] })); + if (chunk === undefined) { + return { sql: "", params: [] }; } - let extras; - if (config.extras) { - extras = typeof config.extras === "function" ? config.extras(aliasedColumns, { sql }) : config.extras; - for (const [tsKey, value] of Object.entries(extras)) { - fieldsSelection.push({ - tsKey, - value: mapColumnsInAliasedSQLToAlias(value, tableAlias) - }); + if (Array.isArray(chunk)) { + const result = [new StringChunk2("(")]; + for (const [i, p] of chunk.entries()) { + result.push(p); + if (i < chunk.length - 1) { + result.push(new StringChunk2(", ")); + } } + result.push(new StringChunk2(")")); + return this.buildQueryFromSourceParams(result, config); } - for (const { tsKey, value } of fieldsSelection) { - selection.push({ - dbKey: is(value, SQL.Aliased) ? value.fieldAlias : tableConfig.columns[tsKey].name, - tsKey, - field: is(value, Column) ? aliasedTableColumn(value, tableAlias) : value, - relationTableTsKey: undefined, - isJson: false, - selection: [] + if (is2(chunk, SQL2)) { + return this.buildQueryFromSourceParams(chunk.queryChunks, { + ...config, + inlineParams: inlineParams || chunk.shouldInlineParams }); } - let orderByOrig = typeof config.orderBy === "function" ? config.orderBy(aliasedColumns, getOrderByOperators()) : config.orderBy ?? []; - if (!Array.isArray(orderByOrig)) { - orderByOrig = [orderByOrig]; + if (is2(chunk, Table2)) { + const schemaName = chunk[Table2.Symbol.Schema]; + const tableName = chunk[Table2.Symbol.Name]; + return { + sql: schemaName === undefined || chunk[IsAlias2] ? escapeName(tableName) : escapeName(schemaName) + "." + escapeName(tableName), + params: [] + }; } - orderBy = orderByOrig.map((orderByValue) => { - if (is(orderByValue, Column)) { - return aliasedTableColumn(orderByValue, tableAlias); + if (is2(chunk, Column2)) { + const columnName = casing.getColumnCasing(chunk); + if (_config.invokeSource === "indexes") { + return { sql: escapeName(columnName), params: [] }; } - return mapColumnsInSQLToAlias(orderByValue, tableAlias); - }); - limit = config.limit; - offset = config.offset; - for (const { - tsKey: selectedRelationTsKey, - queryConfig: selectedRelationConfigValue, - relation - } of selectedRelations) { - const normalizedRelation = normalizeRelation(schema, tableNamesMap, relation); - const relationTableName = getTableUniqueName(relation.referencedTable); - const relationTableTsName = tableNamesMap[relationTableName]; - const relationTableAlias = `${tableAlias}_${selectedRelationTsKey}`; - const joinOn2 = and(...normalizedRelation.fields.map((field2, i) => eq(aliasedTableColumn(normalizedRelation.references[i], relationTableAlias), aliasedTableColumn(field2, tableAlias)))); - const builtRelation = this.buildRelationalQueryWithoutPK({ - fullSchema, - schema, - tableNamesMap, - table: fullSchema[relationTableTsName], - tableConfig: schema[relationTableTsName], - queryConfig: is(relation, One) ? selectedRelationConfigValue === true ? { limit: 1 } : { ...selectedRelationConfigValue, limit: 1 } : selectedRelationConfigValue, - tableAlias: relationTableAlias, - joinOn: joinOn2, - nestedQueryRelation: relation - }); - const field = sql`${sql.identifier(relationTableAlias)}.${sql.identifier("data")}`.as(selectedRelationTsKey); - joins.push({ - on: sql`true`, - table: new Subquery(builtRelation.sql, {}, relationTableAlias), - alias: relationTableAlias, - joinType: "left", - lateral: true - }); - selection.push({ - dbKey: selectedRelationTsKey, - tsKey: selectedRelationTsKey, - field, - relationTableTsKey: relationTableTsName, - isJson: true, - selection: builtRelation.selection - }); - } - } - if (selection.length === 0) { - throw new DrizzleError({ message: `No fields selected for table "${tableConfig.tsName}" ("${tableAlias}")` }); - } - let result; - where = and(joinOn, where); - if (nestedQueryRelation) { - let field = sql`json_build_array(${sql.join(selection.map(({ field: field2, tsKey, isJson }) => isJson ? sql`${sql.identifier(`${tableAlias}_${tsKey}`)}.${sql.identifier("data")}` : is(field2, SQL.Aliased) ? field2.sql : field2), sql`, `)})`; - if (is(nestedQueryRelation, Many)) { - field = sql`coalesce(json_agg(${field}${orderBy.length > 0 ? sql` order by ${sql.join(orderBy, sql`, `)}` : undefined}), '[]'::json)`; - } - const nestedSelection = [{ - dbKey: "data", - tsKey: "data", - field: field.as("data"), - isJson: true, - relationTableTsKey: tableConfig.tsName, - selection - }]; - const needsSubquery = limit !== undefined || offset !== undefined || orderBy.length > 0; - if (needsSubquery) { - result = this.buildSelectQuery({ - table: aliasedTable(table, tableAlias), - fields: {}, - fieldsFlat: [{ - path: [], - field: sql.raw("*") - }], - where, - limit, - offset, - orderBy, - setOperators: [] - }); - where = undefined; - limit = undefined; - offset = undefined; - orderBy = []; - } else { - result = aliasedTable(table, tableAlias); + const schemaName = chunk.table[Table2.Symbol.Schema]; + return { + sql: chunk.table[IsAlias2] || schemaName === undefined ? escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName) : escapeName(schemaName) + "." + escapeName(chunk.table[Table2.Symbol.Name]) + "." + escapeName(columnName), + params: [] + }; } - result = this.buildSelectQuery({ - table: is(result, PgTable) ? result : new Subquery(result, {}, tableAlias), - fields: {}, - fieldsFlat: nestedSelection.map(({ field: field2 }) => ({ - path: [], - field: is(field2, Column) ? aliasedTableColumn(field2, tableAlias) : field2 - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } else { - result = this.buildSelectQuery({ - table: aliasedTable(table, tableAlias), - fields: {}, - fieldsFlat: selection.map(({ field }) => ({ - path: [], - field: is(field, Column) ? aliasedTableColumn(field, tableAlias) : field - })), - joins, - where, - limit, - offset, - orderBy, - setOperators: [] - }); - } - return { - tableTsKey: tableConfig.tsName, - sql: result, - selection - }; - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/query-builders/query-builder.js -class TypedQueryBuilder { - static [entityKind] = "TypedQueryBuilder"; - getSelectedFields() { - return this._.selectedFields; - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/select.js -class PgSelectBuilder { - static [entityKind] = "PgSelectBuilder"; - fields; - session; - dialect; - withList = []; - distinct; - constructor(config) { - this.fields = config.fields; - this.session = config.session; - this.dialect = config.dialect; - if (config.withList) { - this.withList = config.withList; - } - this.distinct = config.distinct; - } - authToken; - setToken(token) { - this.authToken = token; - return this; - } - from(source) { - const isPartialSelect = !!this.fields; - const src = source; - let fields; - if (this.fields) { - fields = this.fields; - } else if (is(src, Subquery)) { - fields = Object.fromEntries(Object.keys(src._.selectedFields).map((key) => [key, src[key]])); - } else if (is(src, PgViewBase)) { - fields = src[ViewBaseConfig].selectedFields; - } else if (is(src, SQL)) { - fields = {}; - } else { - fields = getTableColumns(src); - } - return new PgSelectBase({ - table: src, - fields, - isPartialSelect, - session: this.session, - dialect: this.dialect, - withList: this.withList, - distinct: this.distinct - }).setToken(this.authToken); - } -} - -class PgSelectQueryBuilderBase extends TypedQueryBuilder { - static [entityKind] = "PgSelectQueryBuilder"; - _; - config; - joinsNotNullableMap; - tableName; - isPartialSelect; - session; - dialect; - cacheConfig = undefined; - usedTables = /* @__PURE__ */ new Set; - constructor({ table, fields, isPartialSelect, session, dialect, withList, distinct }) { - super(); - this.config = { - withList, - table, - fields: { ...fields }, - distinct, - setOperators: [] - }; - this.isPartialSelect = isPartialSelect; - this.session = session; - this.dialect = dialect; - this._ = { - selectedFields: fields, - config: this.config - }; - this.tableName = getTableLikeName(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; - for (const item of extractUsedTable(table)) - this.usedTables.add(item); - } - getUsedTables() { - return [...this.usedTables]; - } - createJoin(joinType, lateral) { - return (table, on) => { - const baseTableName = this.tableName; - const tableName = getTableLikeName(table); - for (const item of extractUsedTable(table)) - this.usedTables.add(item); - if (typeof tableName === "string" && this.config.joins?.some((join2) => join2.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); + if (is2(chunk, View2)) { + const schemaName = chunk[ViewBaseConfig2].schema; + const viewName = chunk[ViewBaseConfig2].name; + return { + sql: schemaName === undefined || chunk[ViewBaseConfig2].isAlias ? escapeName(viewName) : escapeName(schemaName) + "." + escapeName(viewName), + params: [] + }; } - if (!this.isPartialSelect) { - if (Object.keys(this.joinsNotNullableMap).length === 1 && typeof baseTableName === "string") { - this.config.fields = { - [baseTableName]: this.config.fields - }; + if (is2(chunk, Param2)) { + if (is2(chunk.value, Placeholder2)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; } - if (typeof tableName === "string" && !is(table, SQL)) { - const selection = is(table, Subquery) ? table._.selectedFields : is(table, View) ? table[ViewBaseConfig].selectedFields : table[Table.Symbol.Columns]; - this.config.fields[tableName] = selection; + const mappedValue = chunk.value === null ? null : chunk.encoder.mapToDriverValue(chunk.value); + if (is2(mappedValue, SQL2)) { + return this.buildQueryFromSourceParams([mappedValue], config); + } + if (inlineParams) { + return { sql: this.mapInlineParam(mappedValue, config), params: [] }; + } + let typings = ["none"]; + if (prepareTyping) { + typings = [prepareTyping(chunk.encoder)]; } + return { sql: escapeParam(paramStartIndex.value++, mappedValue), params: [mappedValue], typings }; } - if (typeof on === "function") { - on = on(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); + if (is2(chunk, Placeholder2)) { + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; } - if (!this.config.joins) { - this.config.joins = []; + if (is2(chunk, SQL2.Aliased) && chunk.fieldAlias !== undefined) { + return { sql: escapeName(chunk.fieldAlias), params: [] }; } - this.config.joins.push({ on, table, joinType, alias: tableName, lateral }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; - } - case "right": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = true; - break; - } - case "cross": - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; - } - case "full": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = false; - break; - } + if (is2(chunk, Subquery2)) { + if (chunk._.isWith) { + return { sql: escapeName(chunk._.alias), params: [] }; } + return this.buildQueryFromSourceParams([ + new StringChunk2("("), + chunk._.sql, + new StringChunk2(") "), + new Name2(chunk._.alias) + ], config); } - return this; - }; + if (isPgEnum2(chunk)) { + if (chunk.schema) { + return { sql: escapeName(chunk.schema) + "." + escapeName(chunk.enumName), params: [] }; + } + return { sql: escapeName(chunk.enumName), params: [] }; + } + if (isSQLWrapper2(chunk)) { + if (chunk.shouldOmitSQLParens?.()) { + return this.buildQueryFromSourceParams([chunk.getSQL()], config); + } + return this.buildQueryFromSourceParams([ + new StringChunk2("("), + chunk.getSQL(), + new StringChunk2(")") + ], config); + } + if (inlineParams) { + return { sql: this.mapInlineParam(chunk, config), params: [] }; + } + return { sql: escapeParam(paramStartIndex.value++, chunk), params: [chunk], typings: ["none"] }; + })); } - leftJoin = this.createJoin("left", false); - leftJoinLateral = this.createJoin("left", true); - rightJoin = this.createJoin("right", false); - innerJoin = this.createJoin("inner", false); - innerJoinLateral = this.createJoin("inner", true); - fullJoin = this.createJoin("full", false); - crossJoin = this.createJoin("cross", false); - crossJoinLateral = this.createJoin("cross", true); - createSetOperator(type, isAll) { - return (rightSelection) => { - const rightSelect = typeof rightSelection === "function" ? rightSelection(getPgSetOperators()) : rightSelection; - if (!haveSameKeys(this.getSelectedFields(), rightSelect.getSelectedFields())) { - throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order"); + mapInlineParam(chunk, { escapeString }) { + if (chunk === null) { + return "null"; + } + if (typeof chunk === "number" || typeof chunk === "boolean") { + return chunk.toString(); + } + if (typeof chunk === "string") { + return escapeString(chunk); + } + if (typeof chunk === "object") { + const mappedValueAsString = chunk.toString(); + if (mappedValueAsString === "[object Object]") { + return escapeString(JSON.stringify(chunk)); } - this.config.setOperators.push({ type, isAll, rightSelect }); - return this; - }; + return escapeString(mappedValueAsString); + } + throw new Error("Unexpected param value: " + chunk); } - union = this.createSetOperator("union", false); - unionAll = this.createSetOperator("union", true); - intersect = this.createSetOperator("intersect", false); - intersectAll = this.createSetOperator("intersect", true); - except = this.createSetOperator("except", false); - exceptAll = this.createSetOperator("except", true); - addSetOperators(setOperators) { - this.config.setOperators.push(...setOperators); + getSQL() { return this; } - where(where) { - if (typeof where === "function") { - where = where(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); + as(alias) { + if (alias === undefined) { + return this; } - this.config.where = where; - return this; + return new SQL2.Aliased(this, alias); } - having(having) { - if (typeof having === "function") { - having = having(new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); - } - this.config.having = having; + mapWith(decoder) { + this.decoder = typeof decoder === "function" ? { mapFromDriverValue: decoder } : decoder; return this; } - groupBy(...columns) { - if (typeof columns[0] === "function") { - const groupBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }))); - this.config.groupBy = Array.isArray(groupBy) ? groupBy : [groupBy]; - } else { - this.config.groupBy = columns; - } + inlineParams() { + this.shouldInlineParams = true; return this; } - orderBy(...columns) { - if (typeof columns[0] === "function") { - const orderBy = columns[0](new Proxy(this.config.fields, new SelectionProxyHandler({ sqlAliasedBehavior: "alias", sqlBehavior: "sql" }))); - const orderByArray = Array.isArray(orderBy) ? orderBy : [orderBy]; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; - } - } else { - const orderByArray = columns; - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).orderBy = orderByArray; - } else { - this.config.orderBy = orderByArray; + if(condition) { + return condition ? this : undefined; + } +} + +class Name2 { + constructor(value) { + this.value = value; + } + static [entityKind2] = "Name"; + brand; + getSQL() { + return new SQL2([this]); + } +} +var noopDecoder2 = { + mapFromDriverValue: (value) => value +}; +var noopEncoder2 = { + mapToDriverValue: (value) => value +}; +var noopMapper2 = { + ...noopDecoder2, + ...noopEncoder2 +}; + +class Param2 { + constructor(value, encoder = noopEncoder2) { + this.value = value; + this.encoder = encoder; + } + static [entityKind2] = "Param"; + brand; + getSQL() { + return new SQL2([this]); + } +} +function sql2(strings, ...params) { + const queryChunks = []; + if (params.length > 0 || strings.length > 0 && strings[0] !== "") { + queryChunks.push(new StringChunk2(strings[0])); + } + for (const [paramIndex, param2] of params.entries()) { + queryChunks.push(param2, new StringChunk2(strings[paramIndex + 1])); + } + return new SQL2(queryChunks); +} +((sql22) => { + function empty() { + return new SQL2([]); + } + sql22.empty = empty; + function fromList(list) { + return new SQL2(list); + } + sql22.fromList = fromList; + function raw(str) { + return new SQL2([new StringChunk2(str)]); + } + sql22.raw = raw; + function join2(chunks, separator) { + const result = []; + for (const [i, chunk] of chunks.entries()) { + if (i > 0 && separator !== undefined) { + result.push(separator); } + result.push(chunk); } - return this; + return new SQL2(result); } - limit(limit) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).limit = limit; + sql22.join = join2; + function identifier(value) { + return new Name2(value); + } + sql22.identifier = identifier; + function placeholder2(name2) { + return new Placeholder2(name2); + } + sql22.placeholder = placeholder2; + function param2(value, encoder) { + return new Param2(value, encoder); + } + sql22.param = param2; +})(sql2 || (sql2 = {})); +((SQL22) => { + + class Aliased { + constructor(sql22, fieldAlias) { + this.sql = sql22; + this.fieldAlias = fieldAlias; + } + static [entityKind2] = "SQL.Aliased"; + isSelectionField = false; + getSQL() { + return this.sql; + } + clone() { + return new Aliased(this.sql, this.fieldAlias); + } + } + SQL22.Aliased = Aliased; +})(SQL2 || (SQL2 = {})); + +class Placeholder2 { + constructor(name2) { + this.name = name2; + } + static [entityKind2] = "Placeholder"; + getSQL() { + return new SQL2([this]); + } +} +var IsDrizzleView2 = Symbol.for("drizzle:IsDrizzleView"); + +class View2 { + static [entityKind2] = "View"; + [ViewBaseConfig2]; + [IsDrizzleView2] = true; + constructor({ name: name2, schema, selectedFields, query }) { + this[ViewBaseConfig2] = { + name: name2, + originalName: name2, + schema, + selectedFields, + query, + isExisting: !query, + isAlias: false + }; + } + getSQL() { + return new SQL2([this]); + } +} +Column2.prototype.getSQL = function() { + return new SQL2([this]); +}; +Table2.prototype.getSQL = function() { + return new SQL2([this]); +}; +Subquery2.prototype.getSQL = function() { + return new SQL2([this]); +}; + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/utils.js +function getColumnNameAndConfig2(a, b) { + return { + name: typeof a === "string" && a.length > 0 ? a : "", + config: typeof a === "object" ? a : b + }; +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/int.common.js +class PgIntColumnBaseBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgIntColumnBaseBuilder"; + generatedAlwaysAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "always", + sequenceName: name, + sequenceOptions: options + }; } else { - this.config.limit = limit; + this.config.generatedIdentity = { + type: "always" + }; } + this.config.hasDefault = true; + this.config.notNull = true; return this; } - offset(offset) { - if (this.config.setOperators.length > 0) { - this.config.setOperators.at(-1).offset = offset; + generatedByDefaultAsIdentity(sequence) { + if (sequence) { + const { name, ...options } = sequence; + this.config.generatedIdentity = { + type: "byDefault", + sequenceName: name, + sequenceOptions: options + }; } else { - this.config.offset = offset; + this.config.generatedIdentity = { + type: "byDefault" + }; } + this.config.hasDefault = true; + this.config.notNull = true; return this; } - for(strength, config = {}) { - this.config.lockingClause = { strength, config }; - return this; +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/bigint.js +class PgBigInt53Builder2 extends PgIntColumnBaseBuilder2 { + static [entityKind2] = "PgBigInt53Builder"; + constructor(name) { + super(name, "number", "PgBigInt53"); } - getSQL() { - return this.dialect.buildSelectQuery(this.config); + build(table) { + return new PgBigInt532(table, this.config); } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; +} + +class PgBigInt532 extends PgColumn2 { + static [entityKind2] = "PgBigInt53"; + getSQLType() { + return "bigint"; } - as(alias) { - const usedTables = []; - usedTables.push(...extractUsedTable(this.config.table)); - if (this.config.joins) { - for (const it of this.config.joins) - usedTables.push(...extractUsedTable(it.table)); + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; } - return new Proxy(new Subquery(this.getSQL(), this.config.fields, alias, false, [...new Set(usedTables)]), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); + return Number(value); } - getSelectedFields() { - return new Proxy(this.config.fields, new SelectionProxyHandler({ alias: this.tableName, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); +} + +class PgBigInt64Builder2 extends PgIntColumnBaseBuilder2 { + static [entityKind2] = "PgBigInt64Builder"; + constructor(name) { + super(name, "bigint", "PgBigInt64"); } - $dynamic() { - return this; + build(table) { + return new PgBigInt642(table, this.config); } - $withCache(config) { - this.cacheConfig = config === undefined ? { config: {}, enable: true, autoInvalidate: true } : config === false ? { enable: false } : { enable: true, autoInvalidate: true, ...config }; - return this; +} + +class PgBigInt642 extends PgColumn2 { + static [entityKind2] = "PgBigInt64"; + getSQLType() { + return "bigint"; + } + mapFromDriverValue(value) { + return BigInt(value); + } +} +function bigint2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (config.mode === "number") { + return new PgBigInt53Builder2(name); } + return new PgBigInt64Builder2(name); } -class PgSelectBase extends PgSelectQueryBuilderBase { - static [entityKind] = "PgSelect"; - _prepare(name) { - const { session, config, dialect, joinsNotNullableMap, authToken, cacheConfig, usedTables } = this; - if (!session) { - throw new Error("Cannot execute a query on a query builder. Please use a database instance instead."); +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/bigserial.js +class PgBigSerial53Builder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgBigSerial53Builder"; + constructor(name) { + super(name, "number", "PgBigSerial53"); + this.config.hasDefault = true; + this.config.notNull = true; + } + build(table) { + return new PgBigSerial532(table, this.config); + } +} + +class PgBigSerial532 extends PgColumn2 { + static [entityKind2] = "PgBigSerial53"; + getSQLType() { + return "bigserial"; + } + mapFromDriverValue(value) { + if (typeof value === "number") { + return value; } - const { fields } = config; - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - const fieldsList = orderSelectedFields(fields); - const query = session.prepareQuery(dialect.sqlToQuery(this.getSQL()), fieldsList, name, true, undefined, { - type: "select", - tables: [...usedTables] - }, cacheConfig); - query.joinsNotNullableMap = joinsNotNullableMap; - return query.setToken(authToken); - }); + return Number(value); } - prepare(name) { - return this._prepare(name); +} + +class PgBigSerial64Builder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgBigSerial64Builder"; + constructor(name) { + super(name, "bigint", "PgBigSerial64"); + this.config.hasDefault = true; } - authToken; - setToken(token) { - this.authToken = token; - return this; + build(table) { + return new PgBigSerial642(table, this.config); } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; } -applyMixins(PgSelectBase, [QueryPromise]); -function createSetOperator(type, isAll) { - return (leftSelect, rightSelect, ...restSelects) => { - const setOperators = [rightSelect, ...restSelects].map((select) => ({ - type, - isAll, - rightSelect: select - })); - for (const setOperator of setOperators) { - if (!haveSameKeys(leftSelect.getSelectedFields(), setOperator.rightSelect.getSelectedFields())) { - throw new Error("Set operator error (union / intersect / except): selected fields are not the same or are in a different order"); - } - } - return leftSelect.addSetOperators(setOperators); - }; + +class PgBigSerial642 extends PgColumn2 { + static [entityKind2] = "PgBigSerial64"; + getSQLType() { + return "bigserial"; + } + mapFromDriverValue(value) { + return BigInt(value); + } +} +function bigserial2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (config.mode === "number") { + return new PgBigSerial53Builder2(name); + } + return new PgBigSerial64Builder2(name); } -var getPgSetOperators = () => ({ - union, - unionAll, - intersect, - intersectAll, - except, - exceptAll -}); -var union = createSetOperator("union", false); -var unionAll = createSetOperator("union", true); -var intersect = createSetOperator("intersect", false); -var intersectAll = createSetOperator("intersect", true); -var except = createSetOperator("except", false); -var exceptAll = createSetOperator("except", true); -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query-builder.js -class QueryBuilder { - static [entityKind] = "PgQueryBuilder"; - dialect; - dialectConfig; - constructor(dialect) { - this.dialect = is(dialect, PgDialect) ? dialect : undefined; - this.dialectConfig = is(dialect, PgDialect) ? undefined : dialect; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/boolean.js +class PgBooleanBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgBooleanBuilder"; + constructor(name) { + super(name, "boolean", "PgBoolean"); } - $with = (alias, selection) => { - const queryBuilder = this; - const as = (qb) => { - if (typeof qb === "function") { - qb = qb(queryBuilder); - } - return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); - }; - return { as }; + build(table) { + return new PgBoolean2(table, this.config); + } +} + +class PgBoolean2 extends PgColumn2 { + static [entityKind2] = "PgBoolean"; + getSQLType() { + return "boolean"; + } +} +function boolean3(name) { + return new PgBooleanBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/char.js +class PgCharBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgCharBuilder"; + constructor(name, config) { + super(name, "string", "PgChar"); + this.config.length = config.length; + this.config.enumValues = config.enum; + } + build(table) { + return new PgChar2(table, this.config); + } +} + +class PgChar2 extends PgColumn2 { + static [entityKind2] = "PgChar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === undefined ? `char` : `char(${this.length})`; + } +} +function char2(a, b = {}) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgCharBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/cidr.js +class PgCidrBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgCidrBuilder"; + constructor(name) { + super(name, "string", "PgCidr"); + } + build(table) { + return new PgCidr2(table, this.config); + } +} + +class PgCidr2 extends PgColumn2 { + static [entityKind2] = "PgCidr"; + getSQLType() { + return "cidr"; + } +} +function cidr2(name) { + return new PgCidrBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/custom.js +class PgCustomColumnBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgCustomColumnBuilder"; + constructor(name, fieldConfig, customTypeParams) { + super(name, "custom", "PgCustomColumn"); + this.config.fieldConfig = fieldConfig; + this.config.customTypeParams = customTypeParams; + } + build(table) { + return new PgCustomColumn2(table, this.config); + } +} + +class PgCustomColumn2 extends PgColumn2 { + static [entityKind2] = "PgCustomColumn"; + sqlName; + mapTo; + mapFrom; + constructor(table, config) { + super(table, config); + this.sqlName = config.customTypeParams.dataType(config.fieldConfig); + this.mapTo = config.customTypeParams.toDriver; + this.mapFrom = config.customTypeParams.fromDriver; + } + getSQLType() { + return this.sqlName; + } + mapFromDriverValue(value) { + return typeof this.mapFrom === "function" ? this.mapFrom(value) : value; + } + mapToDriverValue(value) { + return typeof this.mapTo === "function" ? this.mapTo(value) : value; + } +} +function customType2(customTypeParams) { + return (a, b) => { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgCustomColumnBuilder2(name, config, customTypeParams); }; - with(...queries) { - const self2 = this; - function select(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: self2.getDialect(), - withList: queries - }); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/date.common.js +class PgDateColumnBaseBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgDateColumnBaseBuilder"; + defaultNow() { + return this.default(sql2`now()`); + } +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/date.js +class PgDateBuilder2 extends PgDateColumnBaseBuilder2 { + static [entityKind2] = "PgDateBuilder"; + constructor(name) { + super(name, "date", "PgDate"); + } + build(table) { + return new PgDate2(table, this.config); + } +} + +class PgDate2 extends PgColumn2 { + static [entityKind2] = "PgDate"; + getSQLType() { + return "date"; + } + mapFromDriverValue(value) { + return new Date(value); + } + mapToDriverValue(value) { + return value.toISOString(); + } +} + +class PgDateStringBuilder2 extends PgDateColumnBaseBuilder2 { + static [entityKind2] = "PgDateStringBuilder"; + constructor(name) { + super(name, "string", "PgDateString"); + } + build(table) { + return new PgDateString2(table, this.config); + } +} + +class PgDateString2 extends PgColumn2 { + static [entityKind2] = "PgDateString"; + getSQLType() { + return "date"; + } +} +function date3(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (config?.mode === "date") { + return new PgDateBuilder2(name); + } + return new PgDateStringBuilder2(name); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/double-precision.js +class PgDoublePrecisionBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgDoublePrecisionBuilder"; + constructor(name) { + super(name, "number", "PgDoublePrecision"); + } + build(table) { + return new PgDoublePrecision2(table, this.config); + } +} + +class PgDoublePrecision2 extends PgColumn2 { + static [entityKind2] = "PgDoublePrecision"; + getSQLType() { + return "double precision"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseFloat(value); } - function selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: self2.getDialect(), - distinct: true - }); + return value; + } +} +function doublePrecision2(name) { + return new PgDoublePrecisionBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/inet.js +class PgInetBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgInetBuilder"; + constructor(name) { + super(name, "string", "PgInet"); + } + build(table) { + return new PgInet2(table, this.config); + } +} + +class PgInet2 extends PgColumn2 { + static [entityKind2] = "PgInet"; + getSQLType() { + return "inet"; + } +} +function inet2(name) { + return new PgInetBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/integer.js +class PgIntegerBuilder2 extends PgIntColumnBaseBuilder2 { + static [entityKind2] = "PgIntegerBuilder"; + constructor(name) { + super(name, "number", "PgInteger"); + } + build(table) { + return new PgInteger2(table, this.config); + } +} + +class PgInteger2 extends PgColumn2 { + static [entityKind2] = "PgInteger"; + getSQLType() { + return "integer"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + return Number.parseInt(value); } - function selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: self2.getDialect(), - distinct: { on } - }); + return value; + } +} +function integer2(name) { + return new PgIntegerBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/interval.js +class PgIntervalBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgIntervalBuilder"; + constructor(name, intervalConfig) { + super(name, "string", "PgInterval"); + this.config.intervalConfig = intervalConfig; + } + build(table) { + return new PgInterval2(table, this.config); + } +} + +class PgInterval2 extends PgColumn2 { + static [entityKind2] = "PgInterval"; + fields = this.config.intervalConfig.fields; + precision = this.config.intervalConfig.precision; + getSQLType() { + const fields = this.fields ? ` ${this.fields}` : ""; + const precision = this.precision ? `(${this.precision})` : ""; + return `interval${fields}${precision}`; + } +} +function interval2(a, b = {}) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgIntervalBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/json.js +class PgJsonBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgJsonBuilder"; + constructor(name) { + super(name, "json", "PgJson"); + } + build(table) { + return new PgJson2(table, this.config); + } +} + +class PgJson2 extends PgColumn2 { + static [entityKind2] = "PgJson"; + constructor(table, config) { + super(table, config); + } + getSQLType() { + return "json"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; + } } - return { select, selectDistinct, selectDistinctOn }; + return value; } - select(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: this.getDialect() - }); +} +function json2(name) { + return new PgJsonBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/jsonb.js +class PgJsonbBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgJsonbBuilder"; + constructor(name) { + super(name, "json", "PgJsonb"); } - selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: this.getDialect(), - distinct: true - }); + build(table) { + return new PgJsonb2(table, this.config); } - selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: undefined, - dialect: this.getDialect(), - distinct: { on } - }); +} + +class PgJsonb2 extends PgColumn2 { + static [entityKind2] = "PgJsonb"; + constructor(table, config) { + super(table, config); } - getDialect() { - if (!this.dialect) { - this.dialect = new PgDialect(this.dialectConfig); + getSQLType() { + return "jsonb"; + } + mapToDriverValue(value) { + return JSON.stringify(value); + } + mapFromDriverValue(value) { + if (typeof value === "string") { + try { + return JSON.parse(value); + } catch { + return value; + } } - return this.dialect; + return value; } } +function jsonb2(name) { + return new PgJsonbBuilder2(name ?? ""); +} -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/utils.js -function extractUsedTable(table) { - if (is(table, PgTable)) { - return [table[Schema2] ? `${table[Schema2]}.${table[Table.Symbol.BaseName]}` : table[Table.Symbol.BaseName]]; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/line.js +class PgLineBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgLineBuilder"; + constructor(name) { + super(name, "array", "PgLine"); } - if (is(table, Subquery)) { - return table._.usedTables ?? []; + build(table) { + return new PgLineTuple2(table, this.config); } - if (is(table, SQL)) { - return table.usedTables ?? []; +} + +class PgLineTuple2 extends PgColumn2 { + static [entityKind2] = "PgLine"; + getSQLType() { + return "line"; + } + mapFromDriverValue(value) { + const [a, b, c] = value.slice(1, -1).split(","); + return [Number.parseFloat(a), Number.parseFloat(b), Number.parseFloat(c)]; + } + mapToDriverValue(value) { + return `{${value[0]},${value[1]},${value[2]}}`; } - return []; } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/delete.js -class PgDeleteBase extends QueryPromise { - constructor(table, session, dialect, withList) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { table, withList }; +class PgLineABCBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgLineABCBuilder"; + constructor(name) { + super(name, "json", "PgLineABC"); } - static [entityKind] = "PgDelete"; - config; - cacheConfig; - where(where) { - this.config.where = where; - return this; + build(table) { + return new PgLineABC2(table, this.config); } - returning(fields = this.config.table[Table.Symbol.Columns]) { - this.config.returningFields = fields; - this.config.returning = orderSelectedFields(fields); - return this; +} + +class PgLineABC2 extends PgColumn2 { + static [entityKind2] = "PgLineABC"; + getSQLType() { + return "line"; } - getSQL() { - return this.dialect.buildDeleteQuery(this.config); + mapFromDriverValue(value) { + const [a, b, c] = value.slice(1, -1).split(","); + return { a: Number.parseFloat(a), b: Number.parseFloat(b), c: Number.parseFloat(c) }; } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; + mapToDriverValue(value) { + return `{${value.a},${value.b},${value.c}}`; } - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { - type: "delete", - tables: extractUsedTable(this.config.table) - }, this.cacheConfig); - }); +} +function line2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (!config?.mode || config.mode === "tuple") { + return new PgLineBuilder2(name); } - prepare(name) { - return this._prepare(name); + return new PgLineABCBuilder2(name); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/macaddr.js +class PgMacaddrBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgMacaddrBuilder"; + constructor(name) { + super(name, "string", "PgMacaddr"); } - authToken; - setToken(token) { - this.authToken = token; - return this; + build(table) { + return new PgMacaddr2(table, this.config); } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - getSelectedFields() { - return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({ - alias: getTableName(this.config.table), - sqlAliasedBehavior: "alias", - sqlBehavior: "error" - })) : undefined; +} + +class PgMacaddr2 extends PgColumn2 { + static [entityKind2] = "PgMacaddr"; + getSQLType() { + return "macaddr"; } - $dynamic() { - return this; +} +function macaddr2(name) { + return new PgMacaddrBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/macaddr8.js +class PgMacaddr8Builder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgMacaddr8Builder"; + constructor(name) { + super(name, "string", "PgMacaddr8"); + } + build(table) { + return new PgMacaddr82(table, this.config); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/insert.js -class PgInsertBuilder { - constructor(table, session, dialect, withList, overridingSystemValue_) { - this.table = table; - this.session = session; - this.dialect = dialect; - this.withList = withList; - this.overridingSystemValue_ = overridingSystemValue_; +class PgMacaddr82 extends PgColumn2 { + static [entityKind2] = "PgMacaddr8"; + getSQLType() { + return "macaddr8"; } - static [entityKind] = "PgInsertBuilder"; - authToken; - setToken(token) { - this.authToken = token; - return this; +} +function macaddr82(name) { + return new PgMacaddr8Builder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/numeric.js +class PgNumericBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgNumericBuilder"; + constructor(name, precision, scale) { + super(name, "string", "PgNumeric"); + this.config.precision = precision; + this.config.scale = scale; } - overridingSystemValue() { - this.overridingSystemValue_ = true; - return this; + build(table) { + return new PgNumeric2(table, this.config); } - values(values) { - values = Array.isArray(values) ? values : [values]; - if (values.length === 0) { - throw new Error("values() must be called with at least one value"); +} + +class PgNumeric2 extends PgColumn2 { + static [entityKind2] = "PgNumeric"; + precision; + scale; + constructor(table, config) { + super(table, config); + this.precision = config.precision; + this.scale = config.scale; + } + mapFromDriverValue(value) { + if (typeof value === "string") + return value; + return String(value); + } + getSQLType() { + if (this.precision !== undefined && this.scale !== undefined) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === undefined) { + return "numeric"; + } else { + return `numeric(${this.precision})`; } - const mappedValues = values.map((entry) => { - const result = {}; - const cols = this.table[Table.Symbol.Columns]; - for (const colKey of Object.keys(entry)) { - const colValue = entry[colKey]; - result[colKey] = is(colValue, SQL) ? colValue : new Param(colValue, cols[colKey]); - } - return result; - }); - return new PgInsertBase(this.table, mappedValues, this.session, this.dialect, this.withList, false, this.overridingSystemValue_).setToken(this.authToken); } - select(selectQuery) { - const select = typeof selectQuery === "function" ? selectQuery(new QueryBuilder) : selectQuery; - if (!is(select, SQL) && !haveSameKeys(this.table[Columns], select._.selectedFields)) { - throw new Error("Insert select error: selected fields are not the same or are in a different order compared to the table definition"); +} + +class PgNumericNumberBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgNumericNumberBuilder"; + constructor(name, precision, scale) { + super(name, "number", "PgNumericNumber"); + this.config.precision = precision; + this.config.scale = scale; + } + build(table) { + return new PgNumericNumber2(table, this.config); + } +} + +class PgNumericNumber2 extends PgColumn2 { + static [entityKind2] = "PgNumericNumber"; + precision; + scale; + constructor(table, config) { + super(table, config); + this.precision = config.precision; + this.scale = config.scale; + } + mapFromDriverValue(value) { + if (typeof value === "number") + return value; + return Number(value); + } + mapToDriverValue = String; + getSQLType() { + if (this.precision !== undefined && this.scale !== undefined) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === undefined) { + return "numeric"; + } else { + return `numeric(${this.precision})`; } - return new PgInsertBase(this.table, select, this.session, this.dialect, this.withList, true); } } -class PgInsertBase extends QueryPromise { - constructor(table, values, session, dialect, withList, select, overridingSystemValue_) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { table, values, withList, select, overridingSystemValue_ }; +class PgNumericBigIntBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgNumericBigIntBuilder"; + constructor(name, precision, scale) { + super(name, "bigint", "PgNumericBigInt"); + this.config.precision = precision; + this.config.scale = scale; } - static [entityKind] = "PgInsert"; - config; - cacheConfig; - returning(fields = this.config.table[Table.Symbol.Columns]) { - this.config.returningFields = fields; - this.config.returning = orderSelectedFields(fields); - return this; + build(table) { + return new PgNumericBigInt2(table, this.config); } - onConflictDoNothing(config = {}) { - if (config.target === undefined) { - this.config.onConflict = sql`do nothing`; +} + +class PgNumericBigInt2 extends PgColumn2 { + static [entityKind2] = "PgNumericBigInt"; + precision; + scale; + constructor(table, config) { + super(table, config); + this.precision = config.precision; + this.scale = config.scale; + } + mapFromDriverValue = BigInt; + mapToDriverValue = String; + getSQLType() { + if (this.precision !== undefined && this.scale !== undefined) { + return `numeric(${this.precision}, ${this.scale})`; + } else if (this.precision === undefined) { + return "numeric"; } else { - let targetColumn = ""; - targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target)); - const whereSql = config.where ? sql` where ${config.where}` : undefined; - this.config.onConflict = sql`(${sql.raw(targetColumn)})${whereSql} do nothing`; + return `numeric(${this.precision})`; } - return this; } - onConflictDoUpdate(config) { - if (config.where && (config.targetWhere || config.setWhere)) { - throw new Error('You cannot use both "where" and "targetWhere"/"setWhere" at the same time - "where" is deprecated, use "targetWhere" or "setWhere" instead.'); +} +function numeric2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + const mode = config?.mode; + return mode === "number" ? new PgNumericNumberBuilder2(name, config?.precision, config?.scale) : mode === "bigint" ? new PgNumericBigIntBuilder2(name, config?.precision, config?.scale) : new PgNumericBuilder2(name, config?.precision, config?.scale); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/point.js +class PgPointTupleBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgPointTupleBuilder"; + constructor(name) { + super(name, "array", "PgPointTuple"); + } + build(table) { + return new PgPointTuple2(table, this.config); + } +} + +class PgPointTuple2 extends PgColumn2 { + static [entityKind2] = "PgPointTuple"; + getSQLType() { + return "point"; + } + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x, y] = value.slice(1, -1).split(","); + return [Number.parseFloat(x), Number.parseFloat(y)]; } - const whereSql = config.where ? sql` where ${config.where}` : undefined; - const targetWhereSql = config.targetWhere ? sql` where ${config.targetWhere}` : undefined; - const setWhereSql = config.setWhere ? sql` where ${config.setWhere}` : undefined; - const setSql = this.dialect.buildUpdateSet(this.config.table, mapUpdateSet(this.config.table, config.set)); - let targetColumn = ""; - targetColumn = Array.isArray(config.target) ? config.target.map((it) => this.dialect.escapeName(this.dialect.casing.getColumnCasing(it))).join(",") : this.dialect.escapeName(this.dialect.casing.getColumnCasing(config.target)); - this.config.onConflict = sql`(${sql.raw(targetColumn)})${targetWhereSql} do update set ${setSql}${whereSql}${setWhereSql}`; - return this; + return [value.x, value.y]; } - getSQL() { - return this.dialect.buildInsertQuery(this.config); + mapToDriverValue(value) { + return `(${value[0]},${value[1]})`; } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; +} + +class PgPointObjectBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgPointObjectBuilder"; + constructor(name) { + super(name, "json", "PgPointObject"); } - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { - type: "insert", - tables: extractUsedTable(this.config.table) - }, this.cacheConfig); - }); + build(table) { + return new PgPointObject2(table, this.config); } - prepare(name) { - return this._prepare(name); +} + +class PgPointObject2 extends PgColumn2 { + static [entityKind2] = "PgPointObject"; + getSQLType() { + return "point"; } - authToken; - setToken(token) { - this.authToken = token; - return this; + mapFromDriverValue(value) { + if (typeof value === "string") { + const [x, y] = value.slice(1, -1).split(","); + return { x: Number.parseFloat(x), y: Number.parseFloat(y) }; + } + return value; } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; - getSelectedFields() { - return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({ - alias: getTableName(this.config.table), - sqlAliasedBehavior: "alias", - sqlBehavior: "error" - })) : undefined; + mapToDriverValue(value) { + return `(${value.x},${value.y})`; } - $dynamic() { - return this; +} +function point2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (!config?.mode || config.mode === "tuple") { + return new PgPointTupleBuilder2(name); } + return new PgPointObjectBuilder2(name); } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/refresh-materialized-view.js -class PgRefreshMaterializedView extends QueryPromise { - constructor(view, session, dialect) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { view }; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/utils.js +function hexToBytes2(hex) { + const bytes = []; + for (let c = 0;c < hex.length; c += 2) { + bytes.push(Number.parseInt(hex.slice(c, c + 2), 16)); + } + return new Uint8Array(bytes); +} +function bytesToFloat642(bytes, offset) { + const buffer = new ArrayBuffer(8); + const view = new DataView(buffer); + for (let i = 0;i < 8; i++) { + view.setUint8(i, bytes[offset + i]); + } + return view.getFloat64(0, true); +} +function parseEWKB2(hex) { + const bytes = hexToBytes2(hex); + let offset = 0; + const byteOrder = bytes[offset]; + offset += 1; + const view = new DataView(bytes.buffer); + const geomType = view.getUint32(offset, byteOrder === 1); + offset += 4; + let _srid; + if (geomType & 536870912) { + _srid = view.getUint32(offset, byteOrder === 1); + offset += 4; + } + if ((geomType & 65535) === 1) { + const x = bytesToFloat642(bytes, offset); + offset += 8; + const y = bytesToFloat642(bytes, offset); + offset += 8; + return [x, y]; } - static [entityKind] = "PgRefreshMaterializedView"; - config; - concurrently() { - if (this.config.withNoData !== undefined) { - throw new Error("Cannot use concurrently and withNoData together"); - } - this.config.concurrently = true; - return this; + throw new Error("Unsupported geometry type"); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/postgis_extension/geometry.js +class PgGeometryBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgGeometryBuilder"; + constructor(name) { + super(name, "array", "PgGeometry"); } - withNoData() { - if (this.config.concurrently !== undefined) { - throw new Error("Cannot use concurrently and withNoData together"); - } - this.config.withNoData = true; - return this; + build(table) { + return new PgGeometry2(table, this.config); } - getSQL() { - return this.dialect.buildRefreshMaterializedViewQuery(this.config); +} + +class PgGeometry2 extends PgColumn2 { + static [entityKind2] = "PgGeometry"; + getSQLType() { + return "geometry(point)"; } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; + mapFromDriverValue(value) { + return parseEWKB2(value); } - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), undefined, name, true); - }); + mapToDriverValue(value) { + return `point(${value[0]} ${value[1]})`; } - prepare(name) { - return this._prepare(name); +} + +class PgGeometryObjectBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgGeometryObjectBuilder"; + constructor(name) { + super(name, "json", "PgGeometryObject"); } - authToken; - setToken(token) { - this.authToken = token; - return this; + build(table) { + return new PgGeometryObject2(table, this.config); } - execute = (placeholderValues) => { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(placeholderValues, this.authToken); - }); - }; } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/update.js -class PgUpdateBuilder { - constructor(table, session, dialect, withList) { - this.table = table; - this.session = session; - this.dialect = dialect; - this.withList = withList; +class PgGeometryObject2 extends PgColumn2 { + static [entityKind2] = "PgGeometryObject"; + getSQLType() { + return "geometry(point)"; } - static [entityKind] = "PgUpdateBuilder"; - authToken; - setToken(token) { - this.authToken = token; - return this; + mapFromDriverValue(value) { + const parsed = parseEWKB2(value); + return { x: parsed[0], y: parsed[1] }; } - set(values) { - return new PgUpdateBase(this.table, mapUpdateSet(this.table, values), this.session, this.dialect, this.withList).setToken(this.authToken); + mapToDriverValue(value) { + return `point(${value.x} ${value.y})`; } } - -class PgUpdateBase extends QueryPromise { - constructor(table, set, session, dialect, withList) { - super(); - this.session = session; - this.dialect = dialect; - this.config = { set, table, withList, joins: [] }; - this.tableName = getTableLikeName(table); - this.joinsNotNullableMap = typeof this.tableName === "string" ? { [this.tableName]: true } : {}; +function geometry2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (!config?.mode || config.mode === "tuple") { + return new PgGeometryBuilder2(name); } - static [entityKind] = "PgUpdate"; - config; - tableName; - joinsNotNullableMap; - cacheConfig; - from(source) { - const src = source; - const tableName = getTableLikeName(src); - if (typeof tableName === "string") { - this.joinsNotNullableMap[tableName] = true; - } - this.config.from = src; - return this; + return new PgGeometryObjectBuilder2(name); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/real.js +class PgRealBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgRealBuilder"; + constructor(name, length) { + super(name, "number", "PgReal"); + this.config.length = length; } - getTableLikeFields(table) { - if (is(table, PgTable)) { - return table[Table.Symbol.Columns]; - } else if (is(table, Subquery)) { - return table._.selectedFields; - } - return table[ViewBaseConfig].selectedFields; + build(table) { + return new PgReal2(table, this.config); } - createJoin(joinType) { - return (table, on) => { - const tableName = getTableLikeName(table); - if (typeof tableName === "string" && this.config.joins.some((join2) => join2.alias === tableName)) { - throw new Error(`Alias "${tableName}" is already used in this query`); - } - if (typeof on === "function") { - const from = this.config.from && !is(this.config.from, SQL) ? this.getTableLikeFields(this.config.from) : undefined; - on = on(new Proxy(this.config.table[Table.Symbol.Columns], new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" })), from && new Proxy(from, new SelectionProxyHandler({ sqlAliasedBehavior: "sql", sqlBehavior: "sql" }))); - } - this.config.joins.push({ on, table, joinType, alias: tableName }); - if (typeof tableName === "string") { - switch (joinType) { - case "left": { - this.joinsNotNullableMap[tableName] = false; - break; - } - case "right": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = true; - break; - } - case "inner": { - this.joinsNotNullableMap[tableName] = true; - break; - } - case "full": { - this.joinsNotNullableMap = Object.fromEntries(Object.entries(this.joinsNotNullableMap).map(([key]) => [key, false])); - this.joinsNotNullableMap[tableName] = false; - break; - } - } - } - return this; - }; +} + +class PgReal2 extends PgColumn2 { + static [entityKind2] = "PgReal"; + constructor(table, config) { + super(table, config); } - leftJoin = this.createJoin("left"); - rightJoin = this.createJoin("right"); - innerJoin = this.createJoin("inner"); - fullJoin = this.createJoin("full"); - where(where) { - this.config.where = where; - return this; + getSQLType() { + return "real"; } - returning(fields) { - if (!fields) { - fields = Object.assign({}, this.config.table[Table.Symbol.Columns]); - if (this.config.from) { - const tableName = getTableLikeName(this.config.from); - if (typeof tableName === "string" && this.config.from && !is(this.config.from, SQL)) { - const fromFields = this.getTableLikeFields(this.config.from); - fields[tableName] = fromFields; - } - for (const join2 of this.config.joins) { - const tableName2 = getTableLikeName(join2.table); - if (typeof tableName2 === "string" && !is(join2.table, SQL)) { - const fromFields = this.getTableLikeFields(join2.table); - fields[tableName2] = fromFields; - } - } - } + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number.parseFloat(value); } - this.config.returningFields = fields; - this.config.returning = orderSelectedFields(fields); - return this; + return value; + }; +} +function real2(name) { + return new PgRealBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/serial.js +class PgSerialBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgSerialBuilder"; + constructor(name) { + super(name, "number", "PgSerial"); + this.config.hasDefault = true; + this.config.notNull = true; } - getSQL() { - return this.dialect.buildUpdateQuery(this.config); + build(table) { + return new PgSerial2(table, this.config); } - toSQL() { - const { typings: _typings, ...rest } = this.dialect.sqlToQuery(this.getSQL()); - return rest; +} + +class PgSerial2 extends PgColumn2 { + static [entityKind2] = "PgSerial"; + getSQLType() { + return "serial"; } - _prepare(name) { - const query = this.session.prepareQuery(this.dialect.sqlToQuery(this.getSQL()), this.config.returning, name, true, undefined, { - type: "insert", - tables: extractUsedTable(this.config.table) - }, this.cacheConfig); - query.joinsNotNullableMap = this.joinsNotNullableMap; - return query; +} +function serial2(name) { + return new PgSerialBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/smallint.js +class PgSmallIntBuilder2 extends PgIntColumnBaseBuilder2 { + static [entityKind2] = "PgSmallIntBuilder"; + constructor(name) { + super(name, "number", "PgSmallInt"); } - prepare(name) { - return this._prepare(name); + build(table) { + return new PgSmallInt2(table, this.config); } - authToken; - setToken(token) { - this.authToken = token; - return this; +} + +class PgSmallInt2 extends PgColumn2 { + static [entityKind2] = "PgSmallInt"; + getSQLType() { + return "smallint"; } - execute = (placeholderValues) => { - return this._prepare().execute(placeholderValues, this.authToken); + mapFromDriverValue = (value) => { + if (typeof value === "string") { + return Number(value); + } + return value; }; - getSelectedFields() { - return this.config.returningFields ? new Proxy(this.config.returningFields, new SelectionProxyHandler({ - alias: getTableName(this.config.table), - sqlAliasedBehavior: "alias", - sqlBehavior: "error" - })) : undefined; +} +function smallint2(name) { + return new PgSmallIntBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/smallserial.js +class PgSmallSerialBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgSmallSerialBuilder"; + constructor(name) { + super(name, "number", "PgSmallSerial"); + this.config.hasDefault = true; + this.config.notNull = true; } - $dynamic() { - return this; + build(table) { + return new PgSmallSerial2(table, this.config); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/count.js -class PgCountBuilder extends SQL { - constructor(params) { - super(PgCountBuilder.buildEmbeddedCount(params.source, params.filters).queryChunks); - this.params = params; - this.mapWith(Number); - this.session = params.session; - this.sql = PgCountBuilder.buildCount(params.source, params.filters); - } - sql; - token; - static [entityKind] = "PgCountBuilder"; - [Symbol.toStringTag] = "PgCountBuilder"; - session; - static buildEmbeddedCount(source, filters) { - return sql`(select count(*) from ${source}${sql.raw(" where ").if(filters)}${filters})`; +class PgSmallSerial2 extends PgColumn2 { + static [entityKind2] = "PgSmallSerial"; + getSQLType() { + return "smallserial"; } - static buildCount(source, filters) { - return sql`select count(*) as count from ${source}${sql.raw(" where ").if(filters)}${filters};`; +} +function smallserial2(name) { + return new PgSmallSerialBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/text.js +class PgTextBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgTextBuilder"; + constructor(name, config) { + super(name, "string", "PgText"); + this.config.enumValues = config.enum; } - setToken(token) { - this.token = token; - return this; + build(table) { + return new PgText2(table, this.config); } - then(onfulfilled, onrejected) { - return Promise.resolve(this.session.count(this.sql, this.token)).then(onfulfilled, onrejected); +} + +class PgText2 extends PgColumn2 { + static [entityKind2] = "PgText"; + enumValues = this.config.enumValues; + getSQLType() { + return "text"; } - catch(onRejected) { - return this.then(undefined, onRejected); +} +function text2(a, b = {}) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgTextBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/time.js +class PgTimeBuilder2 extends PgDateColumnBaseBuilder2 { + constructor(name, withTimezone, precision) { + super(name, "string", "PgTime"); + this.withTimezone = withTimezone; + this.precision = precision; + this.config.withTimezone = withTimezone; + this.config.precision = precision; } - finally(onFinally) { - return this.then((value) => { - onFinally?.(); - return value; - }, (reason) => { - onFinally?.(); - throw reason; - }); + static [entityKind2] = "PgTimeBuilder"; + build(table) { + return new PgTime2(table, this.config); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/query.js -class RelationalQueryBuilder { - constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session) { - this.fullSchema = fullSchema; - this.schema = schema; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session; - } - static [entityKind] = "PgRelationalQueryBuilder"; - findMany(config) { - return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? config : {}, "many"); +class PgTime2 extends PgColumn2 { + static [entityKind2] = "PgTime"; + withTimezone; + precision; + constructor(table, config) { + super(table, config); + this.withTimezone = config.withTimezone; + this.precision = config.precision; } - findFirst(config) { - return new PgRelationalQuery(this.fullSchema, this.schema, this.tableNamesMap, this.table, this.tableConfig, this.dialect, this.session, config ? { ...config, limit: 1 } : { limit: 1 }, "first"); + getSQLType() { + const precision = this.precision === undefined ? "" : `(${this.precision})`; + return `time${precision}${this.withTimezone ? " with time zone" : ""}`; } } +function time2(a, b = {}) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgTimeBuilder2(name, config.withTimezone ?? false, config.precision); +} -class PgRelationalQuery extends QueryPromise { - constructor(fullSchema, schema, tableNamesMap, table, tableConfig, dialect, session, config, mode) { - super(); - this.fullSchema = fullSchema; - this.schema = schema; - this.tableNamesMap = tableNamesMap; - this.table = table; - this.tableConfig = tableConfig; - this.dialect = dialect; - this.session = session; - this.config = config; - this.mode = mode; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/timestamp.js +class PgTimestampBuilder2 extends PgDateColumnBaseBuilder2 { + static [entityKind2] = "PgTimestampBuilder"; + constructor(name, withTimezone, precision) { + super(name, "date", "PgTimestamp"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; } - static [entityKind] = "PgRelationalQuery"; - _prepare(name) { - return tracer.startActiveSpan("drizzle.prepareQuery", () => { - const { query, builtQuery } = this._toSQL(); - return this.session.prepareQuery(builtQuery, undefined, name, true, (rawRows, mapColumnValue) => { - const rows = rawRows.map((row) => mapRelationalRow(this.schema, this.tableConfig, row, query.selection, mapColumnValue)); - if (this.mode === "first") { - return rows[0]; - } - return rows; - }); - }); + build(table) { + return new PgTimestamp2(table, this.config); } - prepare(name) { - return this._prepare(name); +} + +class PgTimestamp2 extends PgColumn2 { + static [entityKind2] = "PgTimestamp"; + withTimezone; + precision; + constructor(table, config) { + super(table, config); + this.withTimezone = config.withTimezone; + this.precision = config.precision; } - _getQuery() { - return this.dialect.buildRelationalQueryWithoutPK({ - fullSchema: this.fullSchema, - schema: this.schema, - tableNamesMap: this.tableNamesMap, - table: this.table, - tableConfig: this.tableConfig, - queryConfig: this.config, - tableAlias: this.tableConfig.tsName - }); + getSQLType() { + const precision = this.precision === undefined ? "" : ` (${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; } - getSQL() { - return this._getQuery().sql; + mapFromDriverValue = (value) => { + return new Date(this.withTimezone ? value : value + "+0000"); + }; + mapToDriverValue = (value) => { + return value.toISOString(); + }; +} + +class PgTimestampStringBuilder2 extends PgDateColumnBaseBuilder2 { + static [entityKind2] = "PgTimestampStringBuilder"; + constructor(name, withTimezone, precision) { + super(name, "string", "PgTimestampString"); + this.config.withTimezone = withTimezone; + this.config.precision = precision; } - _toSQL() { - const query = this._getQuery(); - const builtQuery = this.dialect.sqlToQuery(query.sql); - return { query, builtQuery }; + build(table) { + return new PgTimestampString2(table, this.config); } - toSQL() { - return this._toSQL().builtQuery; +} + +class PgTimestampString2 extends PgColumn2 { + static [entityKind2] = "PgTimestampString"; + withTimezone; + precision; + constructor(table, config) { + super(table, config); + this.withTimezone = config.withTimezone; + this.precision = config.precision; } - authToken; - setToken(token) { - this.authToken = token; - return this; + getSQLType() { + const precision = this.precision === undefined ? "" : `(${this.precision})`; + return `timestamp${precision}${this.withTimezone ? " with time zone" : ""}`; } - execute() { - return tracer.startActiveSpan("drizzle.operation", () => { - return this._prepare().execute(undefined, this.authToken); - }); +} +function timestamp2(a, b = {}) { + const { name, config } = getColumnNameAndConfig2(a, b); + if (config?.mode === "string") { + return new PgTimestampStringBuilder2(name, config.withTimezone ?? false, config.precision); } + return new PgTimestampBuilder2(name, config?.withTimezone ?? false, config?.precision); } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/query-builders/raw.js -class PgRaw extends QueryPromise { - constructor(execute, sql2, query, mapBatchResult) { - super(); - this.execute = execute; - this.sql = sql2; - this.query = query; - this.mapBatchResult = mapBatchResult; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/uuid.js +class PgUUIDBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgUUIDBuilder"; + constructor(name) { + super(name, "string", "PgUUID"); } - static [entityKind] = "PgRaw"; - getSQL() { - return this.sql; + defaultRandom() { + return this.default(sql2`gen_random_uuid()`); } - getQuery() { - return this.query; + build(table) { + return new PgUUID2(table, this.config); } - mapResult(result, isFromBatch) { - return isFromBatch ? this.mapBatchResult(result) : result; +} + +class PgUUID2 extends PgColumn2 { + static [entityKind2] = "PgUUID"; + getSQLType() { + return "uuid"; } - _prepare() { - return this; +} +function uuid2(name) { + return new PgUUIDBuilder2(name ?? ""); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/varchar.js +class PgVarcharBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgVarcharBuilder"; + constructor(name, config) { + super(name, "string", "PgVarchar"); + this.config.length = config.length; + this.config.enumValues = config.enum; } - isResponseInArrayMode() { - return false; + build(table) { + return new PgVarchar2(table, this.config); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/db.js -class PgDatabase { - constructor(dialect, session, schema) { - this.dialect = dialect; - this.session = session; - this._ = schema ? { - schema: schema.schema, - fullSchema: schema.fullSchema, - tableNamesMap: schema.tableNamesMap, - session - } : { - schema: undefined, - fullSchema: {}, - tableNamesMap: {}, - session - }; - this.query = {}; - if (this._.schema) { - for (const [tableName, columns] of Object.entries(this._.schema)) { - this.query[tableName] = new RelationalQueryBuilder(schema.fullSchema, this._.schema, this._.tableNamesMap, schema.fullSchema[tableName], columns, dialect, session); - } - } - this.$cache = { invalidate: async (_params) => {} }; - } - static [entityKind] = "PgDatabase"; - query; - $with = (alias, selection) => { - const self2 = this; - const as = (qb) => { - if (typeof qb === "function") { - qb = qb(new QueryBuilder(self2.dialect)); - } - return new Proxy(new WithSubquery(qb.getSQL(), selection ?? ("getSelectedFields" in qb ? qb.getSelectedFields() ?? {} : {}), alias, true), new SelectionProxyHandler({ alias, sqlAliasedBehavior: "alias", sqlBehavior: "error" })); - }; - return { as }; - }; - $count(source, filters) { - return new PgCountBuilder({ source, filters, session: this.session }); +class PgVarchar2 extends PgColumn2 { + static [entityKind2] = "PgVarchar"; + length = this.config.length; + enumValues = this.config.enumValues; + getSQLType() { + return this.length === undefined ? `varchar` : `varchar(${this.length})`; } - $cache; - with(...queries) { - const self2 = this; - function select(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: self2.session, - dialect: self2.dialect, - withList: queries - }); - } - function selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: true - }); - } - function selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: self2.session, - dialect: self2.dialect, - withList: queries, - distinct: { on } - }); - } - function update(table) { - return new PgUpdateBuilder(table, self2.session, self2.dialect, queries); - } - function insert(table) { - return new PgInsertBuilder(table, self2.session, self2.dialect, queries); - } - function delete_(table) { - return new PgDeleteBase(table, self2.session, self2.dialect, queries); - } - return { select, selectDistinct, selectDistinctOn, update, insert, delete: delete_ }; +} +function varchar2(a, b = {}) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgVarcharBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/bit.js +class PgBinaryVectorBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgBinaryVectorBuilder"; + constructor(name, config) { + super(name, "string", "PgBinaryVector"); + this.config.dimensions = config.dimensions; } - select(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: this.session, - dialect: this.dialect - }); + build(table) { + return new PgBinaryVector2(table, this.config); } - selectDistinct(fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: this.session, - dialect: this.dialect, - distinct: true - }); +} + +class PgBinaryVector2 extends PgColumn2 { + static [entityKind2] = "PgBinaryVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `bit(${this.dimensions})`; } - selectDistinctOn(on, fields) { - return new PgSelectBuilder({ - fields: fields ?? undefined, - session: this.session, - dialect: this.dialect, - distinct: { on } - }); +} +function bit2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgBinaryVectorBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/halfvec.js +class PgHalfVectorBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgHalfVectorBuilder"; + constructor(name, config) { + super(name, "array", "PgHalfVector"); + this.config.dimensions = config.dimensions; } - update(table) { - return new PgUpdateBuilder(table, this.session, this.dialect); + build(table) { + return new PgHalfVector2(table, this.config); } - insert(table) { - return new PgInsertBuilder(table, this.session, this.dialect); +} + +class PgHalfVector2 extends PgColumn2 { + static [entityKind2] = "PgHalfVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `halfvec(${this.dimensions})`; } - delete(table) { - return new PgDeleteBase(table, this.session, this.dialect); + mapToDriverValue(value) { + return JSON.stringify(value); } - refreshMaterializedView(view) { - return new PgRefreshMaterializedView(view, this.session, this.dialect); + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); } - authToken; - execute(query) { - const sequel = typeof query === "string" ? sql.raw(query) : query.getSQL(); - const builtQuery = this.dialect.sqlToQuery(sequel); - const prepared = this.session.prepareQuery(builtQuery, undefined, undefined, false); - return new PgRaw(() => prepared.execute(undefined, this.authToken), sequel, builtQuery, (result) => prepared.mapResult(result, true)); +} +function halfvec2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgHalfVectorBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/sparsevec.js +class PgSparseVectorBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgSparseVectorBuilder"; + constructor(name, config) { + super(name, "string", "PgSparseVector"); + this.config.dimensions = config.dimensions; } - transaction(transaction, config) { - return this.session.transaction(transaction, config); + build(table) { + return new PgSparseVector2(table, this.config); } } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/cache/core/cache.js -class Cache { - static [entityKind] = "Cache"; +class PgSparseVector2 extends PgColumn2 { + static [entityKind2] = "PgSparseVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `sparsevec(${this.dimensions})`; + } +} +function sparsevec2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgSparseVectorBuilder2(name, config); } -class NoopCache extends Cache { - strategy() { - return "all"; +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/vector_extension/vector.js +class PgVectorBuilder2 extends PgColumnBuilder2 { + static [entityKind2] = "PgVectorBuilder"; + constructor(name, config) { + super(name, "array", "PgVector"); + this.config.dimensions = config.dimensions; } - static [entityKind] = "NoopCache"; - async get(_key) { - return; + build(table) { + return new PgVector2(table, this.config); } - async put(_hashedQuery, _response, _tables, _config) {} - async onMutate(_params) {} -} -async function hashQuery(sql2, params) { - const dataToHash = `${sql2}-${JSON.stringify(params)}`; - const encoder = new TextEncoder; - const data = encoder.encode(dataToHash); - const hashBuffer = await crypto.subtle.digest("SHA-256", data); - const hashArray = [...new Uint8Array(hashBuffer)]; - const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); - return hashHex; } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/pg-core/session.js -class PgPreparedQuery { - constructor(query, cache, queryMetadata, cacheConfig) { - this.query = query; - this.cache = cache; - this.queryMetadata = queryMetadata; - this.cacheConfig = cacheConfig; - if (cache && cache.strategy() === "all" && cacheConfig === undefined) { - this.cacheConfig = { enable: true, autoInvalidate: true }; - } - if (!this.cacheConfig?.enable) { - this.cacheConfig = undefined; - } +class PgVector2 extends PgColumn2 { + static [entityKind2] = "PgVector"; + dimensions = this.config.dimensions; + getSQLType() { + return `vector(${this.dimensions})`; } - authToken; - getQuery() { - return this.query; + mapToDriverValue(value) { + return JSON.stringify(value); } - mapResult(response, _isFromBatch) { - return response; + mapFromDriverValue(value) { + return value.slice(1, -1).split(",").map((v) => Number.parseFloat(v)); } - setToken(token) { - this.authToken = token; - return this; +} +function vector2(a, b) { + const { name, config } = getColumnNameAndConfig2(a, b); + return new PgVectorBuilder2(name, config); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/columns/all.js +function getPgColumnBuilders2() { + return { + bigint: bigint2, + bigserial: bigserial2, + boolean: boolean3, + char: char2, + cidr: cidr2, + customType: customType2, + date: date3, + doublePrecision: doublePrecision2, + inet: inet2, + integer: integer2, + interval: interval2, + json: json2, + jsonb: jsonb2, + line: line2, + macaddr: macaddr2, + macaddr8: macaddr82, + numeric: numeric2, + point: point2, + geometry: geometry2, + real: real2, + serial: serial2, + smallint: smallint2, + smallserial: smallserial2, + text: text2, + time: time2, + timestamp: timestamp2, + uuid: uuid2, + varchar: varchar2, + bit: bit2, + halfvec: halfvec2, + sparsevec: sparsevec2, + vector: vector2 + }; +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/table.js +var InlineForeignKeys2 = Symbol.for("drizzle:PgInlineForeignKeys"); +var EnableRLS2 = Symbol.for("drizzle:EnableRLS"); + +class PgTable2 extends Table2 { + static [entityKind2] = "PgTable"; + static Symbol = Object.assign({}, Table2.Symbol, { + InlineForeignKeys: InlineForeignKeys2, + EnableRLS: EnableRLS2 + }); + [InlineForeignKeys2] = []; + [EnableRLS2] = false; + [Table2.Symbol.ExtraConfigBuilder] = undefined; + [Table2.Symbol.ExtraConfigColumns] = {}; +} +function pgTableWithSchema2(name, columns, extraConfig, schema, baseName = name) { + const rawTable = new PgTable2(name, schema, baseName); + const parsedColumns = typeof columns === "function" ? columns(getPgColumnBuilders2()) : columns; + const builtColumns = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.build(rawTable); + rawTable[InlineForeignKeys2].push(...colBuilder.buildForeignKeys(column, rawTable)); + return [name2, column]; + })); + const builtColumnsForExtraConfig = Object.fromEntries(Object.entries(parsedColumns).map(([name2, colBuilderBase]) => { + const colBuilder = colBuilderBase; + colBuilder.setName(name2); + const column = colBuilder.buildExtraConfigColumn(rawTable); + return [name2, column]; + })); + const table = Object.assign(rawTable, builtColumns); + table[Table2.Symbol.Columns] = builtColumns; + table[Table2.Symbol.ExtraConfigColumns] = builtColumnsForExtraConfig; + if (extraConfig) { + table[PgTable2.Symbol.ExtraConfigBuilder] = extraConfig; } - static [entityKind] = "PgPreparedQuery"; - joinsNotNullableMap; - async queryWithCache(queryString, params, query) { - if (this.cache === undefined || is(this.cache, NoopCache) || this.queryMetadata === undefined) { - try { - return await query(); - } catch (e2) { - throw new DrizzleQueryError(queryString, params, e2); - } - } - if (this.cacheConfig && !this.cacheConfig.enable) { - try { - return await query(); - } catch (e2) { - throw new DrizzleQueryError(queryString, params, e2); - } + return Object.assign(table, { + enableRLS: () => { + table[PgTable2.Symbol.EnableRLS] = true; + return table; } - if ((this.queryMetadata.type === "insert" || this.queryMetadata.type === "update" || this.queryMetadata.type === "delete") && this.queryMetadata.tables.length > 0) { - try { - const [res] = await Promise.all([ - query(), - this.cache.onMutate({ tables: this.queryMetadata.tables }) - ]); - return res; - } catch (e2) { - throw new DrizzleQueryError(queryString, params, e2); + }); +} +var pgTable2 = (name, columns, extraConfig) => { + return pgTableWithSchema2(name, columns, extraConfig, undefined); +}; + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/indexes.js +class IndexBuilderOn2 { + constructor(unique, name) { + this.unique = unique; + this.name = name; + } + static [entityKind2] = "PgIndexBuilderOn"; + on(...columns) { + return new IndexBuilder2(columns.map((it) => { + if (is2(it, SQL2)) { + return it; } - } - if (!this.cacheConfig) { - try { - return await query(); - } catch (e2) { - throw new DrizzleQueryError(queryString, params, e2); + it = it; + const clonedIndexedColumn = new IndexedColumn2(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), this.unique, false, this.name); + } + onOnly(...columns) { + return new IndexBuilder2(columns.map((it) => { + if (is2(it, SQL2)) { + return it; } - } - if (this.queryMetadata.type === "select") { - const fromCache = await this.cache.get(this.cacheConfig.tag ?? await hashQuery(queryString, params), this.queryMetadata.tables, this.cacheConfig.tag !== undefined, this.cacheConfig.autoInvalidate); - if (fromCache === undefined) { - let result; - try { - result = await query(); - } catch (e2) { - throw new DrizzleQueryError(queryString, params, e2); - } - await this.cache.put(this.cacheConfig.tag ?? await hashQuery(queryString, params), result, this.cacheConfig.autoInvalidate ? this.queryMetadata.tables : [], this.cacheConfig.tag !== undefined, this.cacheConfig.config); - return result; + it = it; + const clonedIndexedColumn = new IndexedColumn2(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = it.defaultConfig; + return clonedIndexedColumn; + }), this.unique, true, this.name); + } + using(method, ...columns) { + return new IndexBuilder2(columns.map((it) => { + if (is2(it, SQL2)) { + return it; } - return fromCache; - } - try { - return await query(); - } catch (e2) { - throw new DrizzleQueryError(queryString, params, e2); - } + it = it; + const clonedIndexedColumn = new IndexedColumn2(it.name, !!it.keyAsName, it.columnType, it.indexConfig); + it.indexConfig = JSON.parse(JSON.stringify(it.defaultConfig)); + return clonedIndexedColumn; + }), this.unique, true, this.name, method); } } -class PgSession { - constructor(dialect) { - this.dialect = dialect; +class IndexBuilder2 { + static [entityKind2] = "PgIndexBuilder"; + config; + constructor(columns, unique, only, name, method = "btree") { + this.config = { + name, + columns, + unique, + only, + method + }; } - static [entityKind] = "PgSession"; - execute(query, token) { - return tracer.startActiveSpan("drizzle.operation", () => { - const prepared = tracer.startActiveSpan("drizzle.prepareQuery", () => { - return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false); - }); - return prepared.setToken(token).execute(undefined, token); - }); + concurrently() { + this.config.concurrently = true; + return this; } - all(query) { - return this.prepareQuery(this.dialect.sqlToQuery(query), undefined, undefined, false).all(); + with(obj) { + this.config.with = obj; + return this; } - async count(sql2, token) { - const res = await this.execute(sql2, token); - return Number(res[0]["count"]); + where(condition) { + this.config.where = condition; + return this; + } + build(table) { + return new Index2(this.config, table); } } -class PgTransaction extends PgDatabase { - constructor(dialect, session, schema, nestedIndex = 0) { - super(dialect, session, schema); - this.schema = schema; - this.nestedIndex = nestedIndex; - } - static [entityKind] = "PgTransaction"; - rollback() { - throw new TransactionRollbackError; - } - getTransactionConfigSQL(config) { - const chunks = []; - if (config.isolationLevel) { - chunks.push(`isolation level ${config.isolationLevel}`); - } - if (config.accessMode) { - chunks.push(config.accessMode); - } - if (typeof config.deferrable === "boolean") { - chunks.push(config.deferrable ? "deferrable" : "not deferrable"); - } - return sql.raw(chunks.join(" ")); +class Index2 { + static [entityKind2] = "PgIndex"; + config; + constructor(config, table) { + this.config = { ...config, table }; } - setTransaction(config) { - return this.session.execute(sql`set transaction ${this.getTransactionConfigSQL(config)}`); +} +function index2(name) { + return new IndexBuilderOn2(false, name); +} +function uniqueIndex2(name) { + return new IndexBuilderOn2(true, name); +} + +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/pg-core/primary-keys.js +function primaryKey2(...config) { + if (config[0].columns) { + return new PrimaryKeyBuilder2(config[0].columns, config[0].name); } + return new PrimaryKeyBuilder2(config); } -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/logger.js -class ConsoleLogWriter { - static [entityKind] = "ConsoleLogWriter"; - write(message) { - console.log(message); +class PrimaryKeyBuilder2 { + static [entityKind2] = "PgPrimaryKeyBuilder"; + columns; + name; + constructor(columns, name) { + this.columns = columns; + this.name = name; + } + build(table) { + return new PrimaryKey2(table, this.columns, this.name); } } -class DefaultLogger { - static [entityKind] = "DefaultLogger"; - writer; - constructor(config) { - this.writer = config?.writer ?? new ConsoleLogWriter; +class PrimaryKey2 { + constructor(table, columns, name) { + this.table = table; + this.columns = columns; + this.name = name; } - logQuery(query, params) { - const stringifiedParams = params.map((p) => { - try { - return JSON.stringify(p); - } catch { - return String(p); - } - }); - const paramsStr = stringifiedParams.length ? ` -- params: [${stringifiedParams.join(", ")}]` : ""; - this.writer.write(`Query: ${query}${paramsStr}`); + static [entityKind2] = "PgPrimaryKey"; + columns; + name; + getName() { + return this.name ?? `${this.table[PgTable2.Symbol.Name]}_${this.columns.map((column) => column.name).join("_")}_pk`; } } -class NoopLogger { - static [entityKind] = "NoopLogger"; - logQuery() {} +// ../db-schema/node_modules/.pnpm/drizzle-orm@0.44.0/node_modules/drizzle-orm/relations.js +class Relations2 { + constructor(table, config) { + this.table = table; + this.config = config; + } + static [entityKind2] = "Relations"; +} +function relations(table, relations2) { + return new Relations2(table, (helpers) => Object.fromEntries(Object.entries(relations2(helpers)).map(([key, value]) => [ + key, + value.withFieldName(key) + ]))); } -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js -var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1); -var _32n = /* @__PURE__ */ BigInt(32); -function fromBig(n, le = false) { +// ../db-schema/node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/_u64.js +var U32_MASK642 = /* @__PURE__ */ BigInt(2 ** 32 - 1); +var _32n2 = /* @__PURE__ */ BigInt(32); +function fromBig2(n, le = false) { if (le) - return { h: Number(n & U32_MASK64), l: Number(n >> _32n & U32_MASK64) }; - return { h: Number(n >> _32n & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 }; + return { h: Number(n & U32_MASK642), l: Number(n >> _32n2 & U32_MASK642) }; + return { h: Number(n >> _32n2 & U32_MASK642) | 0, l: Number(n & U32_MASK642) | 0 }; } -function split2(lst, le = false) { +function split3(lst, le = false) { const len = lst.length; let Ah = new Uint32Array(len); let Al = new Uint32Array(len); for (let i = 0;i < len; i++) { - const { h, l } = fromBig(lst[i], le); + const { h, l } = fromBig2(lst[i], le); [Ah[i], Al[i]] = [h, l]; } return [Ah, Al]; } -var rotlSH = (h, l, s) => h << s | l >>> 32 - s; -var rotlSL = (h, l, s) => l << s | h >>> 32 - s; -var rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s; -var rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s; +var rotlSH2 = (h, l, s) => h << s | l >>> 32 - s; +var rotlSL2 = (h, l, s) => l << s | h >>> 32 - s; +var rotlBH2 = (h, l, s) => l << s - 32 | h >>> 64 - s; +var rotlBL2 = (h, l, s) => h << s - 32 | l >>> 64 - s; -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js -function isBytes(a) { +// ../db-schema/node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/utils.js +function isBytes2(a) { return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a && a.BYTES_PER_ELEMENT === 1; } -function anumber(n, title = "") { +function anumber2(n, title = "") { if (typeof n !== "number") { const prefix = title && `"${title}" `; throw new TypeError(`${prefix}expected number, got ${typeof n}`); @@ -159451,8 +139905,8 @@ function anumber(n, title = "") { throw new RangeError(`${prefix}expected integer >= 0, got ${n}`); } } -function abytes(value, length, title = "") { - const bytes = isBytes(value); +function abytes2(value, length, title = "") { + const bytes = isBytes2(value); const len = value?.length; const needsLen = length !== undefined; if (!bytes || needsLen && len !== length) { @@ -159466,39 +139920,39 @@ function abytes(value, length, title = "") { } return value; } -function aexists(instance, checkFinished = true) { +function aexists2(instance, checkFinished = true) { if (instance.destroyed) throw new Error("Hash instance has been destroyed"); if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called"); } -function aoutput(out, instance) { - abytes(out, undefined, "digestInto() output"); +function aoutput2(out, instance) { + abytes2(out, undefined, "digestInto() output"); const min = instance.outputLen; if (out.length < min) { throw new RangeError('"digestInto() output" expected to be of length >=' + min); } } -function u32(arr) { +function u322(arr) { return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4)); } -function clean(...arrays) { +function clean2(...arrays) { for (let i = 0;i < arrays.length; i++) { arrays[i].fill(0); } } -var isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); -function byteSwap(word) { +var isLE2 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)(); +function byteSwap2(word) { return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255; } -function byteSwap32(arr) { +function byteSwap322(arr) { for (let i = 0;i < arr.length; i++) { - arr[i] = byteSwap(arr[i]); + arr[i] = byteSwap2(arr[i]); } return arr; } -var swap32IfBE = isLE ? (u) => u : byteSwap32; -function createHasher(hashCons, info = {}) { +var swap32IfBE2 = isLE2 ? (u) => u : byteSwap322; +function createHasher2(hashCons, info = {}) { const hashC = (msg, opts) => hashCons(opts).update(msg).digest(); const tmp = hashCons(undefined); hashC.outputLen = tmp.outputLen; @@ -159508,39 +139962,39 @@ function createHasher(hashCons, info = {}) { Object.assign(hashC, info); return Object.freeze(hashC); } -var oidNist = (suffix) => ({ +var oidNist2 = (suffix) => ({ oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix]) }); -// node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha3.js -var _0n = BigInt(0); -var _1n = BigInt(1); -var _2n = BigInt(2); -var _7n = BigInt(7); -var _256n = BigInt(256); -var _0x71n = BigInt(113); -var SHA3_PI = []; -var SHA3_ROTL = []; -var _SHA3_IOTA = []; -for (let round = 0, R = _1n, x = 1, y = 0;round < 24; round++) { +// ../db-schema/node_modules/.pnpm/@noble+hashes@2.2.0/node_modules/@noble/hashes/sha3.js +var _0n2 = BigInt(0); +var _1n2 = BigInt(1); +var _2n2 = BigInt(2); +var _7n2 = BigInt(7); +var _256n2 = BigInt(256); +var _0x71n2 = BigInt(113); +var SHA3_PI2 = []; +var SHA3_ROTL2 = []; +var _SHA3_IOTA2 = []; +for (let round = 0, R = _1n2, x = 1, y = 0;round < 24; round++) { [x, y] = [y, (2 * x + 3 * y) % 5]; - SHA3_PI.push(2 * (5 * y + x)); - SHA3_ROTL.push((round + 1) * (round + 2) / 2 % 64); - let t2 = _0n; + SHA3_PI2.push(2 * (5 * y + x)); + SHA3_ROTL2.push((round + 1) * (round + 2) / 2 % 64); + let t2 = _0n2; for (let j = 0;j < 7; j++) { - R = (R << _1n ^ (R >> _7n) * _0x71n) % _256n; - if (R & _2n) - t2 ^= _1n << (_1n << BigInt(j)) - _1n; + R = (R << _1n2 ^ (R >> _7n2) * _0x71n2) % _256n2; + if (R & _2n2) + t2 ^= _1n2 << (_1n2 << BigInt(j)) - _1n2; } - _SHA3_IOTA.push(t2); + _SHA3_IOTA2.push(t2); } -var IOTAS = split2(_SHA3_IOTA, true); -var SHA3_IOTA_H = IOTAS[0]; -var SHA3_IOTA_L = IOTAS[1]; -var rotlH = (h, l, s) => s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s); -var rotlL = (h, l, s) => s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s); -function keccakP(s, rounds = 24) { - anumber(rounds, "rounds"); +var IOTAS2 = split3(_SHA3_IOTA2, true); +var SHA3_IOTA_H2 = IOTAS2[0]; +var SHA3_IOTA_L2 = IOTAS2[1]; +var rotlH2 = (h, l, s) => s > 32 ? rotlBH2(h, l, s) : rotlSH2(h, l, s); +var rotlL2 = (h, l, s) => s > 32 ? rotlBL2(h, l, s) : rotlSL2(h, l, s); +function keccakP2(s, rounds = 24) { + anumber2(rounds, "rounds"); if (rounds < 1 || rounds > 24) throw new Error('"rounds" expected integer 1..24'); const B = new Uint32Array(5 * 2); @@ -159552,8 +140006,8 @@ function keccakP(s, rounds = 24) { const idx0 = (x + 2) % 10; const B0 = B[idx0]; const B1 = B[idx0 + 1]; - const Th = rotlH(B0, B1, 1) ^ B[idx1]; - const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1]; + const Th = rotlH2(B0, B1, 1) ^ B[idx1]; + const Tl = rotlL2(B0, B1, 1) ^ B[idx1 + 1]; for (let y = 0;y < 50; y += 10) { s[x + y] ^= Th; s[x + y + 1] ^= Tl; @@ -159562,10 +140016,10 @@ function keccakP(s, rounds = 24) { let curH = s[2]; let curL = s[3]; for (let t2 = 0;t2 < 24; t2++) { - const shift = SHA3_ROTL[t2]; - const Th = rotlH(curH, curL, shift); - const Tl = rotlL(curH, curL, shift); - const PI = SHA3_PI[t2]; + const shift = SHA3_ROTL2[t2]; + const Th = rotlH2(curH, curL, shift); + const Tl = rotlL2(curH, curL, shift); + const PI = SHA3_PI2[t2]; curH = s[PI]; curL = s[PI + 1]; s[PI] = Th; @@ -159584,13 +140038,13 @@ function keccakP(s, rounds = 24) { s[y + 8] ^= ~b0 & b2; s[y + 9] ^= ~b1 & b3; } - s[0] ^= SHA3_IOTA_H[round]; - s[1] ^= SHA3_IOTA_L[round]; + s[0] ^= SHA3_IOTA_H2[round]; + s[1] ^= SHA3_IOTA_L2[round]; } - clean(B); + clean2(B); } -class Keccak { +class Keccak2 { state; pos = 0; posOut = 0; @@ -159610,25 +140064,25 @@ class Keccak { this.enableXOF = enableXOF; this.canXOF = enableXOF; this.rounds = rounds; - anumber(outputLen, "outputLen"); + anumber2(outputLen, "outputLen"); if (!(0 < blockLen && blockLen < 200)) throw new Error("only keccak-f1600 function is supported"); this.state = new Uint8Array(200); - this.state32 = u32(this.state); + this.state32 = u322(this.state); } clone() { return this._cloneInto(); } keccak() { - swap32IfBE(this.state32); - keccakP(this.state32, this.rounds); - swap32IfBE(this.state32); + swap32IfBE2(this.state32); + keccakP2(this.state32, this.rounds); + swap32IfBE2(this.state32); this.posOut = 0; this.pos = 0; } update(data) { - aexists(this); - abytes(data); + aexists2(this); + abytes2(data); const { blockLen, state } = this; const len = data.length; for (let pos = 0;pos < len; ) { @@ -159652,8 +140106,8 @@ class Keccak { this.keccak(); } writeInto(out) { - aexists(this, false); - abytes(out); + aexists2(this, false); + abytes2(out); this.finish(); const bufferOut = this.state; const { blockLen } = this; @@ -159673,11 +140127,11 @@ class Keccak { return this.writeInto(out); } xof(bytes) { - anumber(bytes); + anumber2(bytes); return this.xofInto(new Uint8Array(bytes)); } digestInto(out) { - aoutput(out, this); + aoutput2(out, this); if (this.finished) throw new Error("digest() was already called"); this.writeInto(out.subarray(0, this.outputLen)); @@ -159690,11 +140144,11 @@ class Keccak { } destroy() { this.destroyed = true; - clean(this.state); + clean2(this.state); } _cloneInto(to) { const { blockLen, suffix, outputLen, rounds, enableXOF } = this; - to ||= new Keccak(blockLen, suffix, outputLen, enableXOF, rounds); + to ||= new Keccak2(blockLen, suffix, outputLen, enableXOF, rounds); to.blockLen = blockLen; to.state32.set(this.state32); to.pos = this.pos; @@ -159703,29 +140157,29 @@ class Keccak { to.rounds = rounds; to.suffix = suffix; to.outputLen = outputLen; - to.enableXOF = enableXOF; - to.canXOF = this.canXOF; - to.destroyed = this.destroyed; - return to; - } -} -var genKeccak = (suffix, blockLen, outputLen, info = {}) => createHasher(() => new Keccak(blockLen, suffix, outputLen), info); -var sha3_512 = /* @__PURE__ */ genKeccak(6, 72, 64, /* @__PURE__ */ oidNist(10)); - -// node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.mjs -var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; -var mathceil = Math.ceil; -var mathfloor = Math.floor; -var bignumberError = "[BigNumber Error] "; -var tooManyDigits = bignumberError + "Number primitive has more than 15 significant digits: "; -var BASE = 100000000000000; -var LOG_BASE = 14; -var MAX_SAFE_INTEGER = 9007199254740991; -var POWS_TEN = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000]; -var SQRT_BASE = 1e7; -var MAX = 1e9; -function clone2(configObject) { - var div, convertBase, parseNumeric, P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, ONE = new BigNumber(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { + to.enableXOF = enableXOF; + to.canXOF = this.canXOF; + to.destroyed = this.destroyed; + return to; + } +} +var genKeccak2 = (suffix, blockLen, outputLen, info = {}) => createHasher2(() => new Keccak2(blockLen, suffix, outputLen), info); +var sha3_5122 = /* @__PURE__ */ genKeccak2(6, 72, 64, /* @__PURE__ */ oidNist2(10)); + +// ../db-schema/node_modules/.pnpm/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.mjs +var isNumeric2 = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i; +var mathceil2 = Math.ceil; +var mathfloor2 = Math.floor; +var bignumberError2 = "[BigNumber Error] "; +var tooManyDigits2 = bignumberError2 + "Number primitive has more than 15 significant digits: "; +var BASE2 = 100000000000000; +var LOG_BASE2 = 14; +var MAX_SAFE_INTEGER2 = 9007199254740991; +var POWS_TEN2 = [1, 10, 100, 1000, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 10000000000, 100000000000, 1000000000000, 10000000000000]; +var SQRT_BASE2 = 1e7; +var MAX2 = 1e9; +function clone3(configObject) { + var div, convertBase, parseNumeric, P = BigNumber2.prototype = { constructor: BigNumber2, toString: null, valueOf: null }, ONE = new BigNumber2(1), DECIMAL_PLACES = 20, ROUNDING_MODE = 4, TO_EXP_NEG = -7, TO_EXP_POS = 21, MIN_EXP = -1e7, MAX_EXP = 1e7, CRYPTO = false, MODULO_MODE = 1, POW_PRECISION = 0, FORMAT = { prefix: "", groupSize: 3, secondaryGroupSize: 0, @@ -159735,10 +140189,10 @@ function clone2(configObject) { fractionGroupSeparator: "\xA0", suffix: "" }, ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz", alphabetHasNormalDecimalDigits = true; - function BigNumber(v, b) { - var alphabet, c, caseChanged, e2, i, isNum, len, str, x = this; - if (!(x instanceof BigNumber)) - return new BigNumber(v, b); + function BigNumber2(v, b) { + var alphabet2, c, caseChanged, e2, i, isNum, len, str, x = this; + if (!(x instanceof BigNumber2)) + return new BigNumber2(v, b); if (b == null) { if (v && v._isBigNumber === true) { x.s = v.s; @@ -159767,7 +140221,7 @@ function clone2(configObject) { } str = String(v); } else { - if (!isNumeric.test(str = String(v))) + if (!isNumeric2.test(str = String(v))) return parseNumeric(x, str, isNum); x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; } @@ -159782,9 +140236,9 @@ function clone2(configObject) { e2 = str.length; } } else { - intCheck(b, 2, ALPHABET.length, "Base"); + intCheck2(b, 2, ALPHABET.length, "Base"); if (b == 10 && alphabetHasNormalDecimalDigits) { - x = new BigNumber(v); + x = new BigNumber2(v); return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); } str = String(v); @@ -159792,16 +140246,16 @@ function clone2(configObject) { if (v * 0 != 0) return parseNumeric(x, str, isNum, b); x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1; - if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { - throw Error(tooManyDigits + v); + if (BigNumber2.DEBUG && str.replace(/^0\.0*|\./, "").length > 15) { + throw Error(tooManyDigits2 + v); } } else { x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; } - alphabet = ALPHABET.slice(0, b); + alphabet2 = ALPHABET.slice(0, b); e2 = i = 0; for (len = str.length;i < len; i++) { - if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (alphabet2.indexOf(c = str.charAt(i)) < 0) { if (c == ".") { if (i > e2) { e2 = len; @@ -159831,8 +140285,8 @@ function clone2(configObject) { ; if (str = str.slice(i, ++len)) { len -= i; - if (isNum && BigNumber.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) { - throw Error(tooManyDigits + x.s * v); + if (isNum && BigNumber2.DEBUG && len > 15 && (v > MAX_SAFE_INTEGER2 || v !== mathfloor2(v))) { + throw Error(tooManyDigits2 + x.s * v); } if ((e2 = e2 - i - 1) > MAX_EXP) { x.c = x.e = null; @@ -159841,16 +140295,16 @@ function clone2(configObject) { } else { x.e = e2; x.c = []; - i = (e2 + 1) % LOG_BASE; + i = (e2 + 1) % LOG_BASE2; if (e2 < 0) - i += LOG_BASE; + i += LOG_BASE2; if (i < len) { if (i) x.c.push(+str.slice(0, i)); - for (len -= LOG_BASE;i < len; ) { - x.c.push(+str.slice(i, i += LOG_BASE)); + for (len -= LOG_BASE2;i < len; ) { + x.c.push(+str.slice(i, i += LOG_BASE2)); } - i = LOG_BASE - (str = str.slice(i)).length; + i = LOG_BASE2 - (str = str.slice(i)).length; } else { i -= len; } @@ -159862,56 +140316,56 @@ function clone2(configObject) { x.c = [x.e = 0]; } } - BigNumber.clone = clone2; - BigNumber.ROUND_UP = 0; - BigNumber.ROUND_DOWN = 1; - BigNumber.ROUND_CEIL = 2; - BigNumber.ROUND_FLOOR = 3; - BigNumber.ROUND_HALF_UP = 4; - BigNumber.ROUND_HALF_DOWN = 5; - BigNumber.ROUND_HALF_EVEN = 6; - BigNumber.ROUND_HALF_CEIL = 7; - BigNumber.ROUND_HALF_FLOOR = 8; - BigNumber.EUCLID = 9; - BigNumber.config = BigNumber.set = function(obj) { + BigNumber2.clone = clone3; + BigNumber2.ROUND_UP = 0; + BigNumber2.ROUND_DOWN = 1; + BigNumber2.ROUND_CEIL = 2; + BigNumber2.ROUND_FLOOR = 3; + BigNumber2.ROUND_HALF_UP = 4; + BigNumber2.ROUND_HALF_DOWN = 5; + BigNumber2.ROUND_HALF_EVEN = 6; + BigNumber2.ROUND_HALF_CEIL = 7; + BigNumber2.ROUND_HALF_FLOOR = 8; + BigNumber2.EUCLID = 9; + BigNumber2.config = BigNumber2.set = function(obj) { var p, v; if (obj != null) { if (typeof obj == "object") { if (obj.hasOwnProperty(p = "DECIMAL_PLACES")) { v = obj[p]; - intCheck(v, 0, MAX, p); + intCheck2(v, 0, MAX2, p); DECIMAL_PLACES = v; } if (obj.hasOwnProperty(p = "ROUNDING_MODE")) { v = obj[p]; - intCheck(v, 0, 8, p); + intCheck2(v, 0, 8, p); ROUNDING_MODE = v; } if (obj.hasOwnProperty(p = "EXPONENTIAL_AT")) { v = obj[p]; if (v && v.pop) { - intCheck(v[0], -MAX, 0, p); - intCheck(v[1], 0, MAX, p); + intCheck2(v[0], -MAX2, 0, p); + intCheck2(v[1], 0, MAX2, p); TO_EXP_NEG = v[0]; TO_EXP_POS = v[1]; } else { - intCheck(v, -MAX, MAX, p); + intCheck2(v, -MAX2, MAX2, p); TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); } } if (obj.hasOwnProperty(p = "RANGE")) { v = obj[p]; if (v && v.pop) { - intCheck(v[0], -MAX, -1, p); - intCheck(v[1], 1, MAX, p); + intCheck2(v[0], -MAX2, -1, p); + intCheck2(v[1], 1, MAX2, p); MIN_EXP = v[0]; MAX_EXP = v[1]; } else { - intCheck(v, -MAX, MAX, p); + intCheck2(v, -MAX2, MAX2, p); if (v) { MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); } else { - throw Error(bignumberError + p + " cannot be zero: " + v); + throw Error(bignumberError2 + p + " cannot be zero: " + v); } } } @@ -159923,23 +140377,23 @@ function clone2(configObject) { CRYPTO = v; } else { CRYPTO = !v; - throw Error(bignumberError + "crypto unavailable"); + throw Error(bignumberError2 + "crypto unavailable"); } } else { CRYPTO = v; } } else { - throw Error(bignumberError + p + " not true or false: " + v); + throw Error(bignumberError2 + p + " not true or false: " + v); } } if (obj.hasOwnProperty(p = "MODULO_MODE")) { v = obj[p]; - intCheck(v, 0, 9, p); + intCheck2(v, 0, 9, p); MODULO_MODE = v; } if (obj.hasOwnProperty(p = "POW_PRECISION")) { v = obj[p]; - intCheck(v, 0, MAX, p); + intCheck2(v, 0, MAX2, p); POW_PRECISION = v; } if (obj.hasOwnProperty(p = "FORMAT")) { @@ -159947,7 +140401,7 @@ function clone2(configObject) { if (typeof v == "object") FORMAT = v; else - throw Error(bignumberError + p + " not an object: " + v); + throw Error(bignumberError2 + p + " not an object: " + v); } if (obj.hasOwnProperty(p = "ALPHABET")) { v = obj[p]; @@ -159955,11 +140409,11 @@ function clone2(configObject) { alphabetHasNormalDecimalDigits = v.slice(0, 10) == "0123456789"; ALPHABET = v; } else { - throw Error(bignumberError + p + " invalid: " + v); + throw Error(bignumberError2 + p + " invalid: " + v); } } } else { - throw Error(bignumberError + "Object expected: " + obj); + throw Error(bignumberError2 + "Object expected: " + obj); } } return { @@ -159974,27 +140428,27 @@ function clone2(configObject) { ALPHABET }; }; - BigNumber.isBigNumber = function(v) { + BigNumber2.isBigNumber = function(v) { if (!v || v._isBigNumber !== true) return false; - if (!BigNumber.DEBUG) + if (!BigNumber2.DEBUG) return true; var i, n, c = v.c, e2 = v.e, s = v.s; out: if ({}.toString.call(c) == "[object Array]") { - if ((s === 1 || s === -1) && e2 >= -MAX && e2 <= MAX && e2 === mathfloor(e2)) { + if ((s === 1 || s === -1) && e2 >= -MAX2 && e2 <= MAX2 && e2 === mathfloor2(e2)) { if (c[0] === 0) { if (e2 === 0 && c.length === 1) return true; break out; } - i = (e2 + 1) % LOG_BASE; + i = (e2 + 1) % LOG_BASE2; if (i < 1) - i += LOG_BASE; + i += LOG_BASE2; if (String(c[0]).length == i) { for (i = 0;i < c.length; i++) { n = c[i]; - if (n < 0 || n >= BASE || n !== mathfloor(n)) + if (n < 0 || n >= BASE2 || n !== mathfloor2(n)) break out; } if (n !== 0) @@ -160004,28 +140458,28 @@ function clone2(configObject) { } else if (c === null && e2 === null && (s === null || s === 1 || s === -1)) { return true; } - throw Error(bignumberError + "Invalid BigNumber: " + v); + throw Error(bignumberError2 + "Invalid BigNumber: " + v); }; - BigNumber.maximum = BigNumber.max = function() { + BigNumber2.maximum = BigNumber2.max = function() { return maxOrMin(arguments, -1); }; - BigNumber.minimum = BigNumber.min = function() { + BigNumber2.minimum = BigNumber2.min = function() { return maxOrMin(arguments, 1); }; - BigNumber.random = function() { + BigNumber2.random = function() { var pow2_53 = 9007199254740992; var random53bitInt = Math.random() * pow2_53 & 2097151 ? function() { - return mathfloor(Math.random() * pow2_53); + return mathfloor2(Math.random() * pow2_53); } : function() { return (Math.random() * 1073741824 | 0) * 8388608 + (Math.random() * 8388608 | 0); }; return function(dp) { - var a, b, e2, k, v, i = 0, c = [], rand = new BigNumber(ONE); + var a, b, e2, k, v, i = 0, c = [], rand = new BigNumber2(ONE); if (dp == null) dp = DECIMAL_PLACES; else - intCheck(dp, 0, MAX); - k = mathceil(dp / LOG_BASE); + intCheck2(dp, 0, MAX2); + k = mathceil2(dp / LOG_BASE2); if (CRYPTO) { if (crypto.getRandomValues) { a = crypto.getRandomValues(new Uint32Array(k *= 2)); @@ -160055,7 +140509,7 @@ function clone2(configObject) { i = k / 7; } else { CRYPTO = false; - throw Error(bignumberError + "crypto unavailable"); + throw Error(bignumberError2 + "crypto unavailable"); } } if (!CRYPTO) { @@ -160066,42 +140520,42 @@ function clone2(configObject) { } } k = c[--i]; - dp %= LOG_BASE; + dp %= LOG_BASE2; if (k && dp) { - v = POWS_TEN[LOG_BASE - dp]; - c[i] = mathfloor(k / v) * v; + v = POWS_TEN2[LOG_BASE2 - dp]; + c[i] = mathfloor2(k / v) * v; } for (;c[i] === 0; c.pop(), i--) ; if (i < 0) { c = [e2 = 0]; } else { - for (e2 = -1;c[0] === 0; c.splice(0, 1), e2 -= LOG_BASE) + for (e2 = -1;c[0] === 0; c.splice(0, 1), e2 -= LOG_BASE2) ; for (i = 1, v = c[0];v >= 10; v /= 10, i++) ; - if (i < LOG_BASE) - e2 -= LOG_BASE - i; + if (i < LOG_BASE2) + e2 -= LOG_BASE2 - i; } rand.e = e2; rand.c = c; return rand; }; }(); - BigNumber.sum = function() { - var i = 1, args = arguments, sum = new BigNumber(args[0]); + BigNumber2.sum = function() { + var i = 1, args = arguments, sum = new BigNumber2(args[0]); for (;i < args.length; ) sum = sum.plus(args[i++]); return sum; }; convertBase = function() { var decimal = "0123456789"; - function toBaseOut(str, baseIn, baseOut, alphabet) { + function toBaseOut(str, baseIn, baseOut, alphabet2) { var j, arr = [0], arrL, i = 0, len = str.length; for (;i < len; ) { for (arrL = arr.length;arrL--; arr[arrL] *= baseIn) ; - arr[0] += alphabet.indexOf(str.charAt(i++)); + arr[0] += alphabet2.indexOf(str.charAt(i++)); for (j = 0;j < arr.length; j++) { if (arr[j] > baseOut - 1) { if (arr[j + 1] == null) @@ -160114,23 +140568,23 @@ function clone2(configObject) { return arr.reverse(); } return function(str, baseIn, baseOut, sign, callerIsToString) { - var alphabet, d, e2, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; + var alphabet2, d, e2, k, r, x, xc, y, i = str.indexOf("."), dp = DECIMAL_PLACES, rm = ROUNDING_MODE; if (i >= 0) { k = POW_PRECISION; POW_PRECISION = 0; str = str.replace(".", ""); - y = new BigNumber(baseIn); + y = new BigNumber2(baseIn); x = y.pow(str.length - i); POW_PRECISION = k; - y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, "0"), 10, baseOut, decimal); + y.c = toBaseOut(toFixedPoint2(coeffToString2(x.c), x.e, "0"), 10, baseOut, decimal); y.e = y.c.length; } - xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet = ALPHABET, decimal) : (alphabet = decimal, ALPHABET)); + xc = toBaseOut(str, baseIn, baseOut, callerIsToString ? (alphabet2 = ALPHABET, decimal) : (alphabet2 = decimal, ALPHABET)); e2 = k = xc.length; for (;xc[--k] == 0; xc.pop()) ; if (!xc[0]) - return alphabet.charAt(0); + return alphabet2.charAt(0); if (i < 0) { --e2; } else { @@ -160148,7 +140602,7 @@ function clone2(configObject) { r = r || d < 0 || xc[d + 1] != null; r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) : i > k || i == k && (rm == 4 || r || rm == 6 && xc[d - 1] & 1 || rm == (x.s < 0 ? 8 : 7)); if (d < 1 || !xc[0]) { - str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0); + str = r ? toFixedPoint2(alphabet2.charAt(1), -dp, alphabet2.charAt(0)) : alphabet2.charAt(0); } else { xc.length = d; if (r) { @@ -160162,29 +140616,29 @@ function clone2(configObject) { } for (k = xc.length;!xc[--k]; ) ; - for (i = 0, str = "";i <= k; str += alphabet.charAt(xc[i++])) + for (i = 0, str = "";i <= k; str += alphabet2.charAt(xc[i++])) ; - str = toFixedPoint(str, e2, alphabet.charAt(0)); + str = toFixedPoint2(str, e2, alphabet2.charAt(0)); } return str; }; }(); div = function() { function multiply(x, k, base) { - var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE, khi = k / SQRT_BASE | 0; + var m, temp, xlo, xhi, carry = 0, i = x.length, klo = k % SQRT_BASE2, khi = k / SQRT_BASE2 | 0; for (x = x.slice();i--; ) { - xlo = x[i] % SQRT_BASE; - xhi = x[i] / SQRT_BASE | 0; + xlo = x[i] % SQRT_BASE2; + xhi = x[i] / SQRT_BASE2 | 0; m = khi * xlo + xhi * klo; - temp = klo * xlo + m % SQRT_BASE * SQRT_BASE + carry; - carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + temp = klo * xlo + m % SQRT_BASE2 * SQRT_BASE2 + carry; + carry = (temp / base | 0) + (m / SQRT_BASE2 | 0) + khi * xhi; x[i] = temp % base; } if (carry) x = [carry].concat(x); return x; } - function compare(a, b, aL, bL) { + function compare2(a, b, aL, bL) { var i, cmp; if (aL != bL) { cmp = aL > bL ? 1 : -1; @@ -160211,16 +140665,16 @@ function clone2(configObject) { return function(x, y, dp, rm, base) { var cmp, e2, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, yL, yz, s = x.s == y.s ? 1 : -1, xc = x.c, yc = y.c; if (!xc || !xc[0] || !yc || !yc[0]) { - return new BigNumber(!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s * 0 : s / 0); + return new BigNumber2(!x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : xc && xc[0] == 0 || !yc ? s * 0 : s / 0); } - q = new BigNumber(s); + q = new BigNumber2(s); qc = q.c = []; e2 = x.e - y.e; s = dp + e2 + 1; if (!base) { - base = BASE; - e2 = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); - s = s / LOG_BASE | 0; + base = BASE2; + e2 = bitFloor2(x.e / LOG_BASE2) - bitFloor2(y.e / LOG_BASE2); + s = s / LOG_BASE2 | 0; } for (i = 0;yc[i] == (xc[i] || 0); i++) ; @@ -160234,7 +140688,7 @@ function clone2(configObject) { yL = yc.length; i = 0; s += 2; - n = mathfloor(base / (yc[0] + 1)); + n = mathfloor2(base / (yc[0] + 1)); if (n > 1) { yc = multiply(yc, n, base); xc = multiply(xc, n, base); @@ -160253,19 +140707,19 @@ function clone2(configObject) { yc0++; do { n = 0; - cmp = compare(yc, rem, yL, remL); + cmp = compare2(yc, rem, yL, remL); if (cmp < 0) { rem0 = rem[0]; if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); - n = mathfloor(rem0 / yc0); + n = mathfloor2(rem0 / yc0); if (n > 1) { if (n >= base) n = base - 1; prod = multiply(yc, n, base); prodL = prod.length; remL = rem.length; - while (compare(prod, rem, prodL, remL) == 1) { + while (compare2(prod, rem, prodL, remL) == 1) { n--; subtract(prod, yL < prodL ? yz : yc, prodL, base); prodL = prod.length; @@ -160283,7 +140737,7 @@ function clone2(configObject) { subtract(rem, prod, remL, base); remL = rem.length; if (cmp == -1) { - while (compare(yc, rem, yL, remL) < 1) { + while (compare2(yc, rem, yL, remL) < 1) { n++; subtract(rem, yL < remL ? yz : yc, remL, base); remL = rem.length; @@ -160305,10 +140759,10 @@ function clone2(configObject) { if (!qc[0]) qc.splice(0, 1); } - if (base == BASE) { + if (base == BASE2) { for (i = 1, s = qc[0];s >= 10; s /= 10, i++) ; - round(q, dp + (q.e = i + e2 * LOG_BASE - 1) + 1, rm, more); + round(q, dp + (q.e = i + e2 * LOG_BASE2 - 1) + 1, rm, more); } else { q.e = e2; q.r = +more; @@ -160321,26 +140775,26 @@ function clone2(configObject) { if (rm == null) rm = ROUNDING_MODE; else - intCheck(rm, 0, 8); + intCheck2(rm, 0, 8); if (!n.c) return n.toString(); c0 = n.c[0]; ne2 = n.e; if (i == null) { - str = coeffToString(n.c); - str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential(str, ne2) : toFixedPoint(str, ne2, "0"); + str = coeffToString2(n.c); + str = id == 1 || id == 2 && (ne2 <= TO_EXP_NEG || ne2 >= TO_EXP_POS) ? toExponential2(str, ne2) : toFixedPoint2(str, ne2, "0"); } else { - n = round(new BigNumber(n), i, rm); + n = round(new BigNumber2(n), i, rm); e2 = n.e; - str = coeffToString(n.c); + str = coeffToString2(n.c); len = str.length; if (id == 1 || id == 2 && (i <= e2 || e2 <= TO_EXP_NEG)) { for (;len < i; str += "0", len++) ; - str = toExponential(str, e2); + str = toExponential2(str, e2); } else { i -= ne2 + (id === 2 && e2 > ne2); - str = toFixedPoint(str, e2, "0"); + str = toFixedPoint2(str, e2, "0"); if (e2 + 1 > len) { if (--i > 0) for (str += ".";i--; str += "0") @@ -160359,10 +140813,10 @@ function clone2(configObject) { return n.s < 0 && c0 ? "-" + str : str; } function maxOrMin(args, n) { - var k, y, i = 1, x = new BigNumber(args[0]); + var k, y, i = 1, x = new BigNumber2(args[0]); for (;i < args.length; i++) { - y = new BigNumber(args[i]); - if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) { + y = new BigNumber2(args[i]); + if (!y.s || (k = compare2(x, y)) === n || k === 0 && x.s === n) { x = y; } } @@ -160374,7 +140828,7 @@ function clone2(configObject) { ; for (j = c[0];j >= 10; j /= 10, i++) ; - if ((e2 = i + e2 * LOG_BASE - 1) > MAX_EXP) { + if ((e2 = i + e2 * LOG_BASE2 - 1) > MAX_EXP) { n.c = n.e = null; } else if (e2 < MIN_EXP) { n.c = [n.e = 0]; @@ -160401,10 +140855,10 @@ function clone2(configObject) { s = s.replace(dotAfter, "$1").replace(dotBefore, "0.$1"); } if (str != s) - return new BigNumber(s, base); + return new BigNumber2(s, base); } - if (BigNumber.DEBUG) { - throw Error(bignumberError + "Not a" + (b ? " base " + b : "") + " number: " + str); + if (BigNumber2.DEBUG) { + throw Error(bignumberError2 + "Not a" + (b ? " base " + b : "") + " number: " + str); } x.s = null; } @@ -160412,27 +140866,27 @@ function clone2(configObject) { }; }(); function round(x, sd, rm, r) { - var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN; + var d, i, j, k, n, ni, rd, xc = x.c, pows10 = POWS_TEN2; if (xc) { out: { for (d = 1, k = xc[0];k >= 10; k /= 10, d++) ; i = sd - d; if (i < 0) { - i += LOG_BASE; + i += LOG_BASE2; j = sd; n = xc[ni = 0]; - rd = mathfloor(n / pows10[d - j - 1] % 10); + rd = mathfloor2(n / pows10[d - j - 1] % 10); } else { - ni = mathceil((i + 1) / LOG_BASE); + ni = mathceil2((i + 1) / LOG_BASE2); if (ni >= xc.length) { if (r) { for (;xc.length <= ni; xc.push(0)) ; n = rd = 0; d = 1; - i %= LOG_BASE; - j = i - LOG_BASE + 1; + i %= LOG_BASE2; + j = i - LOG_BASE2 + 1; } else { break out; } @@ -160440,9 +140894,9 @@ function clone2(configObject) { n = k = xc[ni]; for (d = 1;k >= 10; k /= 10, d++) ; - i %= LOG_BASE; - j = i - LOG_BASE + d; - rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10); + i %= LOG_BASE2; + j = i - LOG_BASE2 + d; + rd = j < 0 ? 0 : mathfloor2(n / pows10[d - j - 1] % 10); } } r = r || sd < 0 || xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); @@ -160451,7 +140905,7 @@ function clone2(configObject) { xc.length = 0; if (r) { sd -= x.e + 1; - xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + xc[0] = pows10[(LOG_BASE2 - sd % LOG_BASE2) % LOG_BASE2]; x.e = -sd || 0; } else { xc[0] = x.e = 0; @@ -160464,8 +140918,8 @@ function clone2(configObject) { ni--; } else { xc.length = ni + 1; - k = pows10[LOG_BASE - i]; - xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + k = pows10[LOG_BASE2 - i]; + xc[ni] = j > 0 ? mathfloor2(n / pows10[d - j] % pows10[j]) * k : 0; } if (r) { for (;; ) { @@ -160477,13 +140931,13 @@ function clone2(configObject) { ; if (i != k) { x.e++; - if (xc[0] == BASE) + if (xc[0] == BASE2) xc[0] = 1; } break; } else { xc[ni] += k; - if (xc[ni] != BASE) + if (xc[ni] != BASE2) break; xc[ni--] = 0; k = 1; @@ -160505,32 +140959,32 @@ function clone2(configObject) { var str, e2 = n.e; if (e2 === null) return n.toString(); - str = coeffToString(n.c); - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(str, e2) : toFixedPoint(str, e2, "0"); + str = coeffToString2(n.c); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(str, e2) : toFixedPoint2(str, e2, "0"); return n.s < 0 ? "-" + str : str; } P.absoluteValue = P.abs = function() { - var x = new BigNumber(this); + var x = new BigNumber2(this); if (x.s < 0) x.s = 1; return x; }; P.comparedTo = function(y, b) { - return compare(this, new BigNumber(y, b)); + return compare2(this, new BigNumber2(y, b)); }; P.decimalPlaces = P.dp = function(dp, rm) { var c, n, v, x = this; if (dp != null) { - intCheck(dp, 0, MAX); + intCheck2(dp, 0, MAX2); if (rm == null) rm = ROUNDING_MODE; else - intCheck(rm, 0, 8); - return round(new BigNumber(x), dp + x.e + 1, rm); + intCheck2(rm, 0, 8); + return round(new BigNumber2(x), dp + x.e + 1, rm); } if (!(c = x.c)) return null; - n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + n = ((v = c.length - 1) - bitFloor2(this.e / LOG_BASE2)) * LOG_BASE2; if (v = c[v]) for (;v % 10 == 0; v /= 10, n--) ; @@ -160539,49 +140993,49 @@ function clone2(configObject) { return n; }; P.dividedBy = P.div = function(y, b) { - return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + return div(this, new BigNumber2(y, b), DECIMAL_PLACES, ROUNDING_MODE); }; P.dividedToIntegerBy = P.idiv = function(y, b) { - return div(this, new BigNumber(y, b), 0, 1); + return div(this, new BigNumber2(y, b), 0, 1); }; P.exponentiatedBy = P.pow = function(n, m) { var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y, x = this; - n = new BigNumber(n); + n = new BigNumber2(n); if (n.c && !n.isInteger()) { - throw Error(bignumberError + "Exponent not an integer: " + valueOf(n)); + throw Error(bignumberError2 + "Exponent not an integer: " + valueOf(n)); } if (m != null) - m = new BigNumber(m); + m = new BigNumber2(m); nIsBig = n.e > 14; if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { - y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n))); + y = new BigNumber2(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd2(n)) : +valueOf(n))); return m ? y.mod(m) : y; } nIsNeg = n.s < 0; if (m) { if (m.c ? !m.c[0] : !m.s) - return new BigNumber(NaN); + return new BigNumber2(NaN); isModExp = !nIsNeg && x.isInteger() && m.isInteger(); if (isModExp) x = x.mod(m); } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 ? x.c[0] > 1 || nIsBig && x.c[1] >= 240000000 : x.c[0] < 80000000000000 || nIsBig && x.c[0] <= 99999750000000))) { - k = x.s < 0 && isOdd(n) ? -0 : 0; + k = x.s < 0 && isOdd2(n) ? -0 : 0; if (x.e > -1) k = 1 / k; - return new BigNumber(nIsNeg ? 1 / k : k); + return new BigNumber2(nIsNeg ? 1 / k : k); } else if (POW_PRECISION) { - k = mathceil(POW_PRECISION / LOG_BASE + 2); + k = mathceil2(POW_PRECISION / LOG_BASE2 + 2); } if (nIsBig) { - half = new BigNumber(0.5); + half = new BigNumber2(0.5); if (nIsNeg) n.s = 1; - nIsOdd = isOdd(n); + nIsOdd = isOdd2(n); } else { i = Math.abs(+valueOf(n)); nIsOdd = i % 2; } - y = new BigNumber(ONE); + y = new BigNumber2(ONE); for (;; ) { if (nIsOdd) { y = y.times(x); @@ -160595,7 +141049,7 @@ function clone2(configObject) { } } if (i) { - i = mathfloor(i / 2); + i = mathfloor2(i / 2); if (i === 0) break; nIsOdd = i % 2; @@ -160603,7 +141057,7 @@ function clone2(configObject) { n = n.times(half); round(n, n.e + 1, 1); if (n.e > 14) { - nIsOdd = isOdd(n); + nIsOdd = isOdd2(n); } else { i = +valueOf(n); if (i === 0) @@ -160626,33 +141080,33 @@ function clone2(configObject) { return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; }; P.integerValue = function(rm) { - var n = new BigNumber(this); + var n = new BigNumber2(this); if (rm == null) rm = ROUNDING_MODE; else - intCheck(rm, 0, 8); + intCheck2(rm, 0, 8); return round(n, n.e + 1, rm); }; P.isEqualTo = P.eq = function(y, b) { - return compare(this, new BigNumber(y, b)) === 0; + return compare2(this, new BigNumber2(y, b)) === 0; }; P.isFinite = function() { return !!this.c; }; P.isGreaterThan = P.gt = function(y, b) { - return compare(this, new BigNumber(y, b)) > 0; + return compare2(this, new BigNumber2(y, b)) > 0; }; P.isGreaterThanOrEqualTo = P.gte = function(y, b) { - return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + return (b = compare2(this, new BigNumber2(y, b))) === 1 || b === 0; }; P.isInteger = function() { - return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + return !!this.c && bitFloor2(this.e / LOG_BASE2) > this.c.length - 2; }; P.isLessThan = P.lt = function(y, b) { - return compare(this, new BigNumber(y, b)) < 0; + return compare2(this, new BigNumber2(y, b)) < 0; }; P.isLessThanOrEqualTo = P.lte = function(y, b) { - return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + return (b = compare2(this, new BigNumber2(y, b))) === -1 || b === 0; }; P.isNaN = function() { return !this.s; @@ -160668,24 +141122,24 @@ function clone2(configObject) { }; P.minus = function(y, b) { var i, j, t2, xLTy, x = this, a = x.s; - y = new BigNumber(y, b); + y = new BigNumber2(y, b); b = y.s; if (!a || !b) - return new BigNumber(NaN); + return new BigNumber2(NaN); if (a != b) { y.s = -b; return x.plus(y); } - var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; + var xe = x.e / LOG_BASE2, ye = y.e / LOG_BASE2, xc = x.c, yc = y.c; if (!xe || !ye) { if (!xc || !yc) - return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + return xc ? (y.s = -b, y) : new BigNumber2(yc ? x : NaN); if (!xc[0] || !yc[0]) { - return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : ROUNDING_MODE == 3 ? -0 : 0); + return yc[0] ? (y.s = -b, y) : new BigNumber2(xc[0] ? x : ROUNDING_MODE == 3 ? -0 : 0); } } - xe = bitFloor(xe); - ye = bitFloor(ye); + xe = bitFloor2(xe); + ye = bitFloor2(ye); xc = xc.slice(); if (a = xe - ye) { if (xLTy = a < 0) { @@ -160718,13 +141172,13 @@ function clone2(configObject) { if (b > 0) for (;b--; xc[i++] = 0) ; - b = BASE - 1; + b = BASE2 - 1; for (;j > a; ) { if (xc[--j] < yc[j]) { for (i = j;i && !xc[--i]; xc[i] = b) ; --xc[i]; - xc[j] += BASE; + xc[j] += BASE2; } xc[j] -= yc[j]; } @@ -160739,11 +141193,11 @@ function clone2(configObject) { }; P.modulo = P.mod = function(y, b) { var q, s, x = this; - y = new BigNumber(y, b); + y = new BigNumber2(y, b); if (!x.c || !y.s || y.c && !y.c[0]) { - return new BigNumber(NaN); + return new BigNumber2(NaN); } else if (!y.c || x.c && !x.c[0]) { - return new BigNumber(x); + return new BigNumber2(x); } if (MODULO_MODE == 9) { s = y.s; @@ -160760,7 +141214,7 @@ function clone2(configObject) { return y; }; P.multipliedBy = P.times = function(y, b) { - var c, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber(y, b)).c; + var c, e2, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, base, sqrtBase, x = this, xc = x.c, yc = (y = new BigNumber2(y, b)).c; if (!xc || !yc || !xc[0] || !yc[0]) { if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { y.c = y.e = y.s = null; @@ -160775,7 +141229,7 @@ function clone2(configObject) { } return y; } - e2 = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + e2 = bitFloor2(x.e / LOG_BASE2) + bitFloor2(y.e / LOG_BASE2); y.s *= x.s; xcL = xc.length; ycL = yc.length; @@ -160789,8 +141243,8 @@ function clone2(configObject) { } for (i = xcL + ycL, zc = [];i--; zc.push(0)) ; - base = BASE; - sqrtBase = SQRT_BASE; + base = BASE2; + sqrtBase = SQRT_BASE2; for (i = ycL;--i >= 0; ) { c = 0; ylo = yc[i] % sqrtBase; @@ -160813,29 +141267,29 @@ function clone2(configObject) { return normalise(y, zc, e2); }; P.negated = function() { - var x = new BigNumber(this); + var x = new BigNumber2(this); x.s = -x.s || null; return x; }; P.plus = function(y, b) { var t2, x = this, a = x.s; - y = new BigNumber(y, b); + y = new BigNumber2(y, b); b = y.s; if (!a || !b) - return new BigNumber(NaN); + return new BigNumber2(NaN); if (a != b) { y.s = -b; return x.minus(y); } - var xe = x.e / LOG_BASE, ye = y.e / LOG_BASE, xc = x.c, yc = y.c; + var xe = x.e / LOG_BASE2, ye = y.e / LOG_BASE2, xc = x.c, yc = y.c; if (!xe || !ye) { if (!xc || !yc) - return new BigNumber(a / 0); + return new BigNumber2(a / 0); if (!xc[0] || !yc[0]) - return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + return yc[0] ? y : new BigNumber2(xc[0] ? x : a * 0); } - xe = bitFloor(xe); - ye = bitFloor(ye); + xe = bitFloor2(xe); + ye = bitFloor2(ye); xc = xc.slice(); if (a = xe - ye) { if (a > 0) { @@ -160859,8 +141313,8 @@ function clone2(configObject) { b = a; } for (a = 0;b; ) { - a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; - xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + a = (xc[--b] = xc[b] + yc[b] + a) / BASE2 | 0; + xc[b] = BASE2 === xc[b] ? 0 : xc[b] % BASE2; } if (a) { xc = [a].concat(xc); @@ -160871,17 +141325,17 @@ function clone2(configObject) { P.precision = P.sd = function(sd, rm) { var c, n, v, x = this; if (sd != null && sd !== !!sd) { - intCheck(sd, 1, MAX); + intCheck2(sd, 1, MAX2); if (rm == null) rm = ROUNDING_MODE; else - intCheck(rm, 0, 8); - return round(new BigNumber(x), sd, rm); + intCheck2(rm, 0, 8); + return round(new BigNumber2(x), sd, rm); } if (!(c = x.c)) return null; v = c.length - 1; - n = v * LOG_BASE + 1; + n = v * LOG_BASE2 + 1; if (v = c[v]) { for (;v % 10 == 0; v /= 10, n--) ; @@ -160893,30 +141347,30 @@ function clone2(configObject) { return n; }; P.shiftedBy = function(k) { - intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + intCheck2(k, -MAX_SAFE_INTEGER2, MAX_SAFE_INTEGER2); return this.times("1e" + k); }; P.squareRoot = P.sqrt = function() { - var m, n, r, rep, t2, x = this, c = x.c, s = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber("0.5"); + var m, n, r, rep, t2, x = this, c = x.c, s = x.s, e2 = x.e, dp = DECIMAL_PLACES + 4, half = new BigNumber2("0.5"); if (s !== 1 || !c || !c[0]) { - return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + return new BigNumber2(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); } s = Math.sqrt(+valueOf(x)); if (s == 0 || s == 1 / 0) { - n = coeffToString(c); + n = coeffToString2(c); if ((n.length + e2) % 2 == 0) n += "0"; s = Math.sqrt(+n); - e2 = bitFloor((e2 + 1) / 2) - (e2 < 0 || e2 % 2); + e2 = bitFloor2((e2 + 1) / 2) - (e2 < 0 || e2 % 2); if (s == 1 / 0) { n = "5e" + e2; } else { n = s.toExponential(); n = n.slice(0, n.indexOf("e") + 1) + e2; } - r = new BigNumber(n); + r = new BigNumber2(n); } else { - r = new BigNumber(s + ""); + r = new BigNumber2(s + ""); } if (r.c[0]) { e2 = r.e; @@ -160926,7 +141380,7 @@ function clone2(configObject) { for (;; ) { t2 = r; r = half.times(t2.plus(div(x, t2, dp, 1))); - if (coeffToString(t2.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) { + if (coeffToString2(t2.c).slice(0, s) === (n = coeffToString2(r.c)).slice(0, s)) { if (r.e < e2) --s; n = n.slice(s - 3, s + 1); @@ -160955,14 +141409,14 @@ function clone2(configObject) { }; P.toExponential = function(dp, rm) { if (dp != null) { - intCheck(dp, 0, MAX); + intCheck2(dp, 0, MAX2); dp++; } return format(this, dp, rm, 1); }; P.toFixed = function(dp, rm) { if (dp != null) { - intCheck(dp, 0, MAX); + intCheck2(dp, 0, MAX2); dp = dp + this.e + 1; } return format(this, dp, rm); @@ -160980,7 +141434,7 @@ function clone2(configObject) { format2 = FORMAT; } } else if (typeof format2 != "object") { - throw Error(bignumberError + "Argument not an object: " + format2); + throw Error(bignumberError2 + "Argument not an object: " + format2); } str = x.toFixed(dp, rm); if (x.c) { @@ -161008,23 +141462,23 @@ function clone2(configObject) { P.toFraction = function(md) { var d, d0, d1, d2, e2, exp, n, n0, n1, q, r, s, x = this, xc = x.c; if (md != null) { - n = new BigNumber(md); + n = new BigNumber2(md); if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error(bignumberError + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); + throw Error(bignumberError2 + "Argument " + (n.isInteger() ? "out of range: " : "not an integer: ") + valueOf(n)); } } if (!xc) - return new BigNumber(x); - d = new BigNumber(ONE); - n1 = d0 = new BigNumber(ONE); - d1 = n0 = new BigNumber(ONE); - s = coeffToString(xc); + return new BigNumber2(x); + d = new BigNumber2(ONE); + n1 = d0 = new BigNumber2(ONE); + d1 = n0 = new BigNumber2(ONE); + s = coeffToString2(xc); e2 = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN[(exp = e2 % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + d.c[0] = POWS_TEN2[(exp = e2 % LOG_BASE2) < 0 ? LOG_BASE2 + exp : exp]; md = !md || n.comparedTo(d) > 0 ? e2 > 0 ? d : n1 : n; exp = MAX_EXP; MAX_EXP = 1 / 0; - n = new BigNumber(s); + n = new BigNumber2(s); n0.c[0] = 0; for (;; ) { q = div(n, d, 0, 1); @@ -161052,7 +141506,7 @@ function clone2(configObject) { }; P.toPrecision = function(sd, rm) { if (sd != null) - intCheck(sd, 1, MAX); + intCheck2(sd, 1, MAX2); return format(this, sd, rm, 2); }; P.toString = function(b) { @@ -161067,13 +141521,13 @@ function clone2(configObject) { } } else { if (b == null) { - str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential(coeffToString(n.c), e2) : toFixedPoint(coeffToString(n.c), e2, "0"); + str = e2 <= TO_EXP_NEG || e2 >= TO_EXP_POS ? toExponential2(coeffToString2(n.c), e2) : toFixedPoint2(coeffToString2(n.c), e2, "0"); } else if (b === 10 && alphabetHasNormalDecimalDigits) { - n = round(new BigNumber(n), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n.c), n.e, "0"); + n = round(new BigNumber2(n), DECIMAL_PLACES + e2 + 1, ROUNDING_MODE); + str = toFixedPoint2(coeffToString2(n.c), n.e, "0"); } else { - intCheck(b, 2, ALPHABET.length, "Base"); - str = convertBase(toFixedPoint(coeffToString(n.c), e2, "0"), 10, b, s, true); + intCheck2(b, 2, ALPHABET.length, "Base"); + str = convertBase(toFixedPoint2(coeffToString2(n.c), e2, "0"), 10, b, s, true); } if (s < 0 && n.c[0]) str = "-" + str; @@ -161087,18 +141541,18 @@ function clone2(configObject) { P[Symbol.toStringTag] = "BigNumber"; P[Symbol.for("nodejs.util.inspect.custom")] = P.valueOf; if (configObject != null) - BigNumber.set(configObject); - return BigNumber; + BigNumber2.set(configObject); + return BigNumber2; } -function bitFloor(n) { +function bitFloor2(n) { var i = n | 0; return n > 0 || n === i ? i : i - 1; } -function coeffToString(a) { +function coeffToString2(a) { var s, z, i = 1, j = a.length, r = a[0] + ""; for (;i < j; ) { s = a[i++] + ""; - z = LOG_BASE - s.length; + z = LOG_BASE2 - s.length; for (;z--; s = "0" + s) ; r += s; @@ -161107,7 +141561,7 @@ function coeffToString(a) { ; return r.slice(0, j + 1 || 1); } -function compare(x, y) { +function compare2(x, y) { var a, b, xc = x.c, yc = y.c, i = x.s, j = y.s, k = x.e, l = y.e; if (!i || !j) return null; @@ -161129,19 +141583,19 @@ function compare(x, y) { return xc[i] > yc[i] ^ a ? 1 : -1; return k == l ? 0 : k > l ^ a ? 1 : -1; } -function intCheck(n, min, max, name) { - if (n < min || n > max || n !== mathfloor(n)) { - throw Error(bignumberError + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); +function intCheck2(n, min, max, name) { + if (n < min || n > max || n !== mathfloor2(n)) { + throw Error(bignumberError2 + (name || "Argument") + (typeof n == "number" ? n < min || n > max ? " out of range: " : " not an integer: " : " not a primitive number: ") + String(n)); } } -function isOdd(n) { +function isOdd2(n) { var k = n.c.length - 1; - return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + return bitFloor2(n.e / LOG_BASE2) == k && n.c[k] % 2 != 0; } -function toExponential(str, e2) { +function toExponential2(str, e2) { return (str.length > 1 ? str.charAt(0) + "." + str.slice(1) : str) + (e2 < 0 ? "e" : "e+") + e2; } -function toFixedPoint(str, e2, z) { +function toFixedPoint2(str, e2, z) { var len, zs; if (e2 < 0) { for (zs = z + ".";++e2; zs += z) @@ -161159,13 +141613,13 @@ function toFixedPoint(str, e2, z) { } return str; } -var BigNumber = clone2(); -var bignumber_default = BigNumber; +var BigNumber2 = clone3(); +var bignumber_default2 = BigNumber2; -// node_modules/.pnpm/@paralleldrive+cuid2@3.3.0/node_modules/@paralleldrive/cuid2/src/index.js -var defaultLength = 24; -var bigLength = 32; -var createRandom = () => { +// ../db-schema/node_modules/.pnpm/@paralleldrive+cuid2@3.3.0/node_modules/@paralleldrive/cuid2/src/index.js +var defaultLength2 = 24; +var bigLength2 = 32; +var createRandom2 = () => { if (typeof globalThis !== "undefined" && globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") { return () => { const buffer = new Uint32Array(1); @@ -161175,59 +141629,59 @@ var createRandom = () => { } return Math.random; }; -var random = createRandom(); -var createEntropy = (length = 4, rand = random) => { +var random2 = createRandom2(); +var createEntropy2 = (length = 4, rand = random2) => { let entropy = ""; while (entropy.length < length) { entropy = entropy + Math.floor(rand() * 36).toString(36); } return entropy; }; -function bufToBigInt(buf) { - let value = new bignumber_default(0); +function bufToBigInt2(buf) { + let value = new bignumber_default2(0); for (const i of buf.values()) { value = value.multipliedBy(256).plus(i); } return value; } -var hash = (input = "") => { +var hash2 = (input = "") => { const encoder = new TextEncoder; - return bufToBigInt(sha3_512(encoder.encode(input))).toString(36).slice(1); + return bufToBigInt2(sha3_5122(encoder.encode(input))).toString(36).slice(1); }; -var alphabet = Array.from({ length: 26 }, (x, i) => String.fromCharCode(i + 97)); -var randomLetter = (rand) => alphabet[Math.floor(rand() * alphabet.length)]; -var createFingerprint = ({ +var alphabet2 = Array.from({ length: 26 }, (x, i) => String.fromCharCode(i + 97)); +var randomLetter2 = (rand) => alphabet2[Math.floor(rand() * alphabet2.length)]; +var createFingerprint2 = ({ globalObj = typeof global !== "undefined" ? global : typeof window !== "undefined" ? window : {}, - random: rand = random + random: rand = random2 } = {}) => { const globals = Object.keys(globalObj).toString(); - const sourceString = globals.length ? globals + createEntropy(bigLength, rand) : createEntropy(bigLength, rand); - return hash(sourceString).substring(0, bigLength); + const sourceString = globals.length ? globals + createEntropy2(bigLength2, rand) : createEntropy2(bigLength2, rand); + return hash2(sourceString).substring(0, bigLength2); }; -var createCounter = (count) => () => { - return count++; +var createCounter2 = (count2) => () => { + return count2++; }; -var initialCountMax = 476782367; -var init = ({ - random: rand = random, - counter = createCounter(Math.floor(rand() * initialCountMax)), - length = defaultLength, - fingerprint = createFingerprint({ random: rand }) +var initialCountMax2 = 476782367; +var init2 = ({ + random: rand = random2, + counter = createCounter2(Math.floor(rand() * initialCountMax2)), + length = defaultLength2, + fingerprint = createFingerprint2({ random: rand }) } = {}) => { - if (length > bigLength) { - throw new Error(`Length must be between 2 and ${bigLength}. Received: ${length}`); + if (length > bigLength2) { + throw new Error(`Length must be between 2 and ${bigLength2}. Received: ${length}`); } return function cuid2() { - const firstLetter = randomLetter(rand); - const time2 = Date.now().toString(36); - const count = counter().toString(36); - const salt = createEntropy(length, rand); - const hashInput = `${time2 + salt + count + fingerprint}`; - return `${firstLetter + hash(hashInput).substring(1, length)}`; + const firstLetter = randomLetter2(rand); + const time3 = Date.now().toString(36); + const count2 = counter().toString(36); + const salt = createEntropy2(length, rand); + const hashInput = `${time3 + salt + count2 + fingerprint}`; + return `${firstLetter + hash2(hashInput).substring(1, length)}`; }; }; -var createId = lazy(init); -function lazy(fn) { +var createId2 = lazy2(init2); +function lazy2(fn) { let initialized; return () => { if (!initialized) { @@ -161237,13 +141691,13 @@ function lazy(fn) { }; } -// src/db/schema.ts -var roleEnum = pgEnum("role", ["ADMIN", "AUTHOR", "USER"]); -var authProvider = pgEnum("AuthProvider", [ +// ../db-schema/src/db/schema.ts +var roleEnum2 = pgEnum2("role", ["ADMIN", "AUTHOR", "USER"]); +var authProvider2 = pgEnum2("AuthProvider", [ "GOOGLE_OAUTH", "EMAIL_PASSWORD" ]); -var languageEnum = pgEnum("Language", [ +var languageEnum2 = pgEnum2("Language", [ "CPP", "JAVA", "PYTHON", @@ -161251,13 +141705,13 @@ var languageEnum = pgEnum("Language", [ "C", "CSHARP" ]); -var jobStatusEnum = pgEnum("JobStatus", [ +var jobStatusEnum2 = pgEnum2("JobStatus", [ "PENDING", "RUNNING", "FAILED", "COMPLETED" ]); -var verdictEnum = pgEnum("Verdict", [ +var verdictEnum2 = pgEnum2("Verdict", [ "PENDING", "ACCEPTED", "WRONG_ANSWER", @@ -161266,562 +141720,252 @@ var verdictEnum = pgEnum("Verdict", [ "RUNTIME_ERROR", "COMPILE_ERROR" ]); -var difficultyEnum = pgEnum("Difficulty", [ +var difficultyEnum2 = pgEnum2("Difficulty", [ "EASY", "MEDIUM", "HARD", "EXPERT" ]); -var problemStatusEnum = pgEnum("ProblemStatus", [ +var problemStatusEnum2 = pgEnum2("ProblemStatus", [ "DRAFT", "DONE", "PENDING", "APPROVED", "REJECTED" ]); -var submissionModeEnum = pgEnum("SubmissionMode", [ +var submissionModeEnum2 = pgEnum2("SubmissionMode", [ "SUBMIT", "RUN" ]); -var user = pgTable("user", { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - email: text("email"), - displayName: text("display_name"), - avatarUrl: text("avatar_url"), - username: text("username").notNull(), - role: roleEnum("role").notNull().default("USER"), - is2FaAuthEnabled: boolean2("is2fa_auth_enabled").default(false).notNull(), - isBanned: boolean2("is_banned").default(false).notNull(), - isEmailVerified: boolean2("is_email_verified").default(false).notNull(), - verificationToken: text("verification_token"), - createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +var user2 = pgTable2("user", { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + email: text2("email"), + displayName: text2("display_name"), + avatarUrl: text2("avatar_url"), + username: text2("username").notNull(), + role: roleEnum2("role").notNull().default("USER"), + is2FaAuthEnabled: boolean3("is2fa_auth_enabled").default(false).notNull(), + isBanned: boolean3("is_banned").default(false).notNull(), + isEmailVerified: boolean3("is_email_verified").default(false).notNull(), + verificationToken: text2("verification_token"), + createdAt: timestamp2("created_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp2("updated_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull() }, (table) => [ - uniqueIndex("user_email_key").using("btree", table.email.asc().nullsLast()), - uniqueIndex("user_username_key").using("btree", table.username.asc().nullsLast()) + uniqueIndex2("user_email_key").using("btree", table.email.asc().nullsLast()), + uniqueIndex2("user_username_key").using("btree", table.username.asc().nullsLast()) ]); -var authMethodColumns = { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - userId: text("user_id").notNull(), - provider: authProvider("provider").notNull(), - googleSub: text("google_sub"), - googleEmail: text("google_email"), - email: text("email"), - passwordHash: text("password_hash"), - createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +var authMethodColumns2 = { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + userId: text2("user_id").notNull(), + provider: authProvider2("provider").notNull(), + googleSub: text2("google_sub"), + googleEmail: text2("google_email"), + email: text2("email"), + passwordHash: text2("password_hash"), + createdAt: timestamp2("created_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp2("updated_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull() }; -var authMethod = pgTable("auth_method", authMethodColumns, (table) => [ - uniqueIndex("auth_method_google_email_key").using("btree", table.googleEmail.asc().nullsLast()), - uniqueIndex("auth_method_google_sub_key").using("btree", table.googleSub.asc().nullsLast()), - index("auth_method_provider_idx").using("btree", table.provider.asc().nullsLast()), - uniqueIndex("auth_method_user_id_key").using("btree", table.userId.asc().nullsLast()), - foreignKey({ +var authMethod2 = pgTable2("auth_method", authMethodColumns2, (table) => [ + uniqueIndex2("auth_method_google_email_key").using("btree", table.googleEmail.asc().nullsLast()), + uniqueIndex2("auth_method_google_sub_key").using("btree", table.googleSub.asc().nullsLast()), + index2("auth_method_provider_idx").using("btree", table.provider.asc().nullsLast()), + uniqueIndex2("auth_method_user_id_key").using("btree", table.userId.asc().nullsLast()), + foreignKey2({ columns: [table.userId], - foreignColumns: [user.id], + foreignColumns: [user2.id], name: "auth_method_user_id_fkey" }).onUpdate("cascade").onDelete("cascade") ]); -var session = pgTable("session", { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade", onUpdate: "cascade" }), - sessionToken: text("session_token").notNull(), - expires: timestamp("expires", { precision: 3, mode: "string" }).notNull() +var session2 = pgTable2("session", { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + userId: text2("user_id").notNull().references(() => user2.id, { onDelete: "cascade", onUpdate: "cascade" }), + sessionToken: text2("session_token").notNull(), + expires: timestamp2("expires", { precision: 3, mode: "string" }).notNull() }, (table) => [ - index("session_user_id_idx").using("btree", table.userId.asc().nullsLast()) + index2("session_user_id_idx").using("btree", table.userId.asc().nullsLast()) ]); -var problem = pgTable("problem", { - id: text("id").primaryKey().$defaultFn(() => createId()), - title: text("title").notNull(), - description: text("description").notNull(), - slug: text("slug").notNull(), - difficulty: difficultyEnum("difficulty").notNull(), - authorId: text("author_id").notNull().references(() => user.id, { onDelete: "restrict" }), - inputFormat: text("input_format").notNull(), - outputFormat: text("output_format").notNull(), - constraints: text("constraints").notNull(), - status: problemStatusEnum("status").notNull().default("DRAFT"), - timeLimit: integer("time_limit").notNull(), - memoryLimit: integer("memory_limit").notNull(), - createdAt: timestamp("created_at").default(sql`now()`).notNull(), - updatedAt: timestamp("updated_at").default(sql`now()`).notNull() +var problem2 = pgTable2("problem", { + id: text2("id").primaryKey().$defaultFn(() => createId2()), + title: text2("title").notNull(), + description: text2("description").notNull(), + slug: text2("slug").notNull(), + difficulty: difficultyEnum2("difficulty").notNull(), + authorId: text2("author_id").notNull().references(() => user2.id, { onDelete: "restrict" }), + inputFormat: text2("input_format").notNull(), + outputFormat: text2("output_format").notNull(), + constraints: text2("constraints").notNull(), + status: problemStatusEnum2("status").notNull().default("DRAFT"), + timeLimit: integer2("time_limit").notNull(), + memoryLimit: integer2("memory_limit").notNull(), + createdAt: timestamp2("created_at").default(sql2`now()`).notNull(), + updatedAt: timestamp2("updated_at").default(sql2`now()`).notNull() }, (t2) => [ - index("problem_author_idx").on(t2.authorId), - index("problem_difficulty_idx").on(t2.difficulty) + index2("problem_author_idx").on(t2.authorId), + index2("problem_difficulty_idx").on(t2.difficulty) ]); -var tagColumns = { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - name: text("name").notNull() +var tagColumns2 = { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + name: text2("name").notNull() }; -var tag = pgTable("tag", tagColumns, (table) => [ - uniqueIndex("tag_name_key").using("btree", table.name.asc().nullsLast()) +var tag2 = pgTable2("tag", tagColumns2, (table) => [ + uniqueIndex2("tag_name_key").using("btree", table.name.asc().nullsLast()) ]); -var problemTag = pgTable("problem_tag", { - problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - tagId: text("tag_id").notNull().references(() => tag.id, { onDelete: "cascade", onUpdate: "cascade" }) +var problemTag2 = pgTable2("problem_tag", { + problemId: text2("problem_id").notNull().references(() => problem2.id, { onDelete: "cascade", onUpdate: "cascade" }), + tagId: text2("tag_id").notNull().references(() => tag2.id, { onDelete: "cascade", onUpdate: "cascade" }) }, (table) => [ - primaryKey({ columns: [table.problemId, table.tagId] }) + primaryKey2({ columns: [table.problemId, table.tagId] }) ]); -var testcase = pgTable("testcase", { - id: text("id").primaryKey().$defaultFn(() => createId()), - problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade" }), - s3Key: text("s3_key").notNull(), - isSample: boolean2("is_sample").default(false).notNull(), - isHidden: boolean2("is_hidden").default(true).notNull(), - order: smallint("order").default(0).notNull(), - batch: smallint("batch").default(0).notNull(), - createdAt: timestamp("created_at").default(sql`now()`).notNull() +var testcase2 = pgTable2("testcase", { + id: text2("id").primaryKey().$defaultFn(() => createId2()), + problemId: text2("problem_id").notNull().references(() => problem2.id, { onDelete: "cascade" }), + s3Key: text2("s3_key").notNull(), + isSample: boolean3("is_sample").default(false).notNull(), + isHidden: boolean3("is_hidden").default(true).notNull(), + order: smallint2("order").default(0).notNull(), + batch: smallint2("batch").default(0).notNull(), + createdAt: timestamp2("created_at").default(sql2`now()`).notNull() }, (t2) => [ - index("testcase_problem_idx").on(t2.problemId), - index("testcase_sample_idx").on(t2.isSample) + index2("testcase_problem_idx").on(t2.problemId), + index2("testcase_sample_idx").on(t2.isSample) ]); -var hint = pgTable("hint", { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - order: smallint("order").notNull().default(0), - title: text("title").notNull(), - content: text("content").notNull(), - createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +var hint2 = pgTable2("hint", { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + problemId: text2("problem_id").notNull().references(() => problem2.id, { onDelete: "cascade", onUpdate: "cascade" }), + order: smallint2("order").notNull().default(0), + title: text2("title").notNull(), + content: text2("content").notNull(), + createdAt: timestamp2("created_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp2("updated_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull() }, (table) => [ - index("hints_problem_id_idx").using("btree", table.problemId.asc().nullsLast()) + index2("hints_problem_id_idx").using("btree", table.problemId.asc().nullsLast()) ]); -var editorial = pgTable("editorial", { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - contentS3Key: text("content_s3_key").notNull(), - editorialLink: text("editorial_link"), - solutionS3Key: text("solution_s3_key").notNull(), - createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +var editorial2 = pgTable2("editorial", { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + problemId: text2("problem_id").notNull().references(() => problem2.id, { onDelete: "cascade", onUpdate: "cascade" }), + contentS3Key: text2("content_s3_key").notNull(), + editorialLink: text2("editorial_link"), + solutionS3Key: text2("solution_s3_key").notNull(), + createdAt: timestamp2("created_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp2("updated_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull() }, (table) => [ - uniqueIndex("editorial_problem_id_key").using("btree", table.problemId.asc().nullsLast()) + uniqueIndex2("editorial_problem_id_key").using("btree", table.problemId.asc().nullsLast()) ]); -var submission = pgTable("submission", { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - problemId: text("problem_id").notNull().references(() => problem.id, { onDelete: "cascade", onUpdate: "cascade" }), - userId: text("user_id").notNull().references(() => user.id, { onDelete: "cascade", onUpdate: "cascade" }), - mode: submissionModeEnum("mode").notNull(), - code: text("code").notNull(), - language: languageEnum("language").notNull().default("CPP"), - status: jobStatusEnum("status").notNull().default("PENDING"), - totalTestcases: integer("total_testcases").notNull().default(0), - passedTestcases: integer("passed_testcases").notNull().default(0), - failedTestcases: integer("failed_testcases").notNull().default(0), - timeTaken: integer("time_taken").notNull().default(0), - memoryTaken: integer("memory_taken").notNull().default(0), - createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +var submission2 = pgTable2("submission", { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + problemId: text2("problem_id").notNull().references(() => problem2.id, { onDelete: "cascade", onUpdate: "cascade" }), + userId: text2("user_id").notNull().references(() => user2.id, { onDelete: "cascade", onUpdate: "cascade" }), + mode: submissionModeEnum2("mode").notNull(), + code: text2("code").notNull(), + language: languageEnum2("language").notNull().default("CPP"), + status: jobStatusEnum2("status").notNull().default("PENDING"), + totalTestcases: integer2("total_testcases").notNull().default(0), + passedTestcases: integer2("passed_testcases").notNull().default(0), + failedTestcases: integer2("failed_testcases").notNull().default(0), + timeTaken: integer2("time_taken").notNull().default(0), + memoryTaken: integer2("memory_taken").notNull().default(0), + createdAt: timestamp2("created_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp2("updated_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull() }, (table) => [ - index("submission_user_problem_idx").using("btree", table.userId.asc(), table.problemId.asc()), - index("submission_problem_id_idx").using("btree", table.problemId.asc().nullsLast()), - index("submission_user_id_idx").using("btree", table.userId.asc().nullsLast()), - index("submission_status_idx").using("btree", table.status.asc().nullsLast()), - index("submission_created_at_idx").using("btree", table.createdAt.asc().nullsLast()) + index2("submission_user_problem_idx").using("btree", table.userId.asc(), table.problemId.asc()), + index2("submission_problem_id_idx").using("btree", table.problemId.asc().nullsLast()), + index2("submission_user_id_idx").using("btree", table.userId.asc().nullsLast()), + index2("submission_status_idx").using("btree", table.status.asc().nullsLast()), + index2("submission_created_at_idx").using("btree", table.createdAt.asc().nullsLast()) ]); -var executionResult = pgTable("execution_result", { - id: text("id").primaryKey().notNull().$defaultFn(() => createId()), - submissionId: text("submission_id").notNull().references(() => submission.id, { onDelete: "cascade", onUpdate: "cascade" }), - verdict: verdictEnum("verdict").notNull().default("PENDING"), - stdout: text("stdout"), - stderr: text("stderr"), - createdAt: timestamp("created_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull(), - updatedAt: timestamp("updated_at", { precision: 3, mode: "string" }).default(sql`(now() AT TIME ZONE 'UTC'::text)`).notNull() +var executionResult2 = pgTable2("execution_result", { + id: text2("id").primaryKey().notNull().$defaultFn(() => createId2()), + submissionId: text2("submission_id").notNull().references(() => submission2.id, { onDelete: "cascade", onUpdate: "cascade" }), + verdict: verdictEnum2("verdict").notNull().default("PENDING"), + stdout: text2("stdout"), + stderr: text2("stderr"), + createdAt: timestamp2("created_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull(), + updatedAt: timestamp2("updated_at", { precision: 3, mode: "string" }).default(sql2`(now() AT TIME ZONE 'UTC'::text)`).notNull() }, (table) => [ - index("execution_result_submission_verdict_idx").using("btree", table.submissionId.asc(), table.verdict.asc()), - index("execution_result_submission_id_idx").using("btree", table.submissionId.asc().nullsLast()) + index2("execution_result_submission_verdict_idx").using("btree", table.submissionId.asc(), table.verdict.asc()), + index2("execution_result_submission_id_idx").using("btree", table.submissionId.asc().nullsLast()) ]); -// node_modules/.pnpm/pg@8.20.0/node_modules/pg/esm/index.mjs -var import_lib = __toESM(require_lib5(), 1); -var Client = import_lib.default.Client; -var Pool = import_lib.default.Pool; -var Connection = import_lib.default.Connection; -var types = import_lib.default.types; -var Query = import_lib.default.Query; -var DatabaseError = import_lib.default.DatabaseError; -var escapeIdentifier = import_lib.default.escapeIdentifier; -var escapeLiteral = import_lib.default.escapeLiteral; -var Result = import_lib.default.Result; -var TypeOverrides = import_lib.default.TypeOverrides; -var defaults = import_lib.default.defaults; -var esm_default = import_lib.default; - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/session.js -var { Pool: Pool2, types: types2 } = esm_default; - -class NodePgPreparedQuery extends PgPreparedQuery { - constructor(client, queryString, params, logger, cache, queryMetadata, cacheConfig, fields, name, _isResponseInArrayMode, customResultMapper) { - super({ sql: queryString, params }, cache, queryMetadata, cacheConfig); - this.client = client; - this.queryString = queryString; - this.params = params; - this.logger = logger; - this.fields = fields; - this._isResponseInArrayMode = _isResponseInArrayMode; - this.customResultMapper = customResultMapper; - this.rawQueryConfig = { - name, - text: queryString, - types: { - getTypeParser: (typeId, format) => { - if (typeId === types2.builtins.TIMESTAMPTZ) { - return (val) => val; - } - if (typeId === types2.builtins.TIMESTAMP) { - return (val) => val; - } - if (typeId === types2.builtins.DATE) { - return (val) => val; - } - if (typeId === types2.builtins.INTERVAL) { - return (val) => val; - } - if (typeId === 1231) { - return (val) => val; - } - if (typeId === 1115) { - return (val) => val; - } - if (typeId === 1185) { - return (val) => val; - } - if (typeId === 1187) { - return (val) => val; - } - if (typeId === 1182) { - return (val) => val; - } - return types2.getTypeParser(typeId, format); - } - } - }; - this.queryConfig = { - name, - text: queryString, - rowMode: "array", - types: { - getTypeParser: (typeId, format) => { - if (typeId === types2.builtins.TIMESTAMPTZ) { - return (val) => val; - } - if (typeId === types2.builtins.TIMESTAMP) { - return (val) => val; - } - if (typeId === types2.builtins.DATE) { - return (val) => val; - } - if (typeId === types2.builtins.INTERVAL) { - return (val) => val; - } - if (typeId === 1231) { - return (val) => val; - } - if (typeId === 1115) { - return (val) => val; - } - if (typeId === 1185) { - return (val) => val; - } - if (typeId === 1187) { - return (val) => val; - } - if (typeId === 1182) { - return (val) => val; - } - return types2.getTypeParser(typeId, format); - } - } - }; - } - static [entityKind] = "NodePgPreparedQuery"; - rawQueryConfig; - queryConfig; - async execute(placeholderValues = {}) { - return tracer.startActiveSpan("drizzle.execute", async () => { - const params = fillPlaceholders(this.params, placeholderValues); - this.logger.logQuery(this.rawQueryConfig.text, params); - const { fields, rawQueryConfig: rawQuery, client, queryConfig: query, joinsNotNullableMap, customResultMapper } = this; - if (!fields && !customResultMapper) { - return tracer.startActiveSpan("drizzle.driver.execute", async (span) => { - span?.setAttributes({ - "drizzle.query.name": rawQuery.name, - "drizzle.query.text": rawQuery.text, - "drizzle.query.params": JSON.stringify(params) - }); - return this.queryWithCache(rawQuery.text, params, async () => { - return await client.query(rawQuery, params); - }); - }); - } - const result = await tracer.startActiveSpan("drizzle.driver.execute", (span) => { - span?.setAttributes({ - "drizzle.query.name": query.name, - "drizzle.query.text": query.text, - "drizzle.query.params": JSON.stringify(params) - }); - return this.queryWithCache(query.text, params, async () => { - return await client.query(query, params); - }); - }); - return tracer.startActiveSpan("drizzle.mapResponse", () => { - return customResultMapper ? customResultMapper(result.rows) : result.rows.map((row) => mapResultRow(fields, row, joinsNotNullableMap)); - }); - }); - } - all(placeholderValues = {}) { - return tracer.startActiveSpan("drizzle.execute", () => { - const params = fillPlaceholders(this.params, placeholderValues); - this.logger.logQuery(this.rawQueryConfig.text, params); - return tracer.startActiveSpan("drizzle.driver.execute", (span) => { - span?.setAttributes({ - "drizzle.query.name": this.rawQueryConfig.name, - "drizzle.query.text": this.rawQueryConfig.text, - "drizzle.query.params": JSON.stringify(params) - }); - return this.queryWithCache(this.rawQueryConfig.text, params, async () => { - return this.client.query(this.rawQueryConfig, params); - }).then((result) => result.rows); - }); - }); - } - isResponseInArrayMode() { - return this._isResponseInArrayMode; - } -} - -class NodePgSession extends PgSession { - constructor(client, dialect, schema, options = {}) { - super(dialect); - this.client = client; - this.schema = schema; - this.options = options; - this.logger = options.logger ?? new NoopLogger; - this.cache = options.cache ?? new NoopCache; - } - static [entityKind] = "NodePgSession"; - logger; - cache; - prepareQuery(query, fields, name, isResponseInArrayMode, customResultMapper, queryMetadata, cacheConfig) { - return new NodePgPreparedQuery(this.client, query.sql, query.params, this.logger, this.cache, queryMetadata, cacheConfig, fields, name, isResponseInArrayMode, customResultMapper); - } - async transaction(transaction, config) { - const session2 = this.client instanceof Pool2 ? new NodePgSession(await this.client.connect(), this.dialect, this.schema, this.options) : this; - const tx = new NodePgTransaction(this.dialect, session2, this.schema); - await tx.execute(sql`begin${config ? sql` ${tx.getTransactionConfigSQL(config)}` : undefined}`); - try { - const result = await transaction(tx); - await tx.execute(sql`commit`); - return result; - } catch (error) { - await tx.execute(sql`rollback`); - throw error; - } finally { - if (this.client instanceof Pool2) { - session2.client.release(); - } - } - } - async count(sql2) { - const res = await this.execute(sql2); - return Number(res["rows"][0]["count"]); - } -} - -class NodePgTransaction extends PgTransaction { - static [entityKind] = "NodePgTransaction"; - async transaction(transaction) { - const savepointName = `sp${this.nestedIndex + 1}`; - const tx = new NodePgTransaction(this.dialect, this.session, this.schema, this.nestedIndex + 1); - await tx.execute(sql.raw(`savepoint ${savepointName}`)); - try { - const result = await transaction(tx); - await tx.execute(sql.raw(`release savepoint ${savepointName}`)); - return result; - } catch (err) { - await tx.execute(sql.raw(`rollback to savepoint ${savepointName}`)); - throw err; - } - } -} - -// node_modules/.pnpm/drizzle-orm@0.44.7_@types+pg@8.20.0_pg@8.20.0/node_modules/drizzle-orm/node-postgres/driver.js -class NodePgDriver { - constructor(client, dialect, options = {}) { - this.client = client; - this.dialect = dialect; - this.options = options; - } - static [entityKind] = "NodePgDriver"; - createSession(schema) { - return new NodePgSession(this.client, this.dialect, schema, { - logger: this.options.logger, - cache: this.options.cache - }); - } -} - -class NodePgDatabase extends PgDatabase { - static [entityKind] = "NodePgDatabase"; -} -function construct(client, config = {}) { - const dialect = new PgDialect({ casing: config.casing }); - let logger; - if (config.logger === true) { - logger = new DefaultLogger; - } else if (config.logger !== false) { - logger = config.logger; - } - let schema; - if (config.schema) { - const tablesConfig = extractTablesRelationalConfig(config.schema, createTableRelationsHelpers); - schema = { - fullSchema: config.schema, - schema: tablesConfig.tables, - tableNamesMap: tablesConfig.tableNamesMap - }; - } - const driver = new NodePgDriver(client, dialect, { logger, cache: config.cache }); - const session2 = driver.createSession(schema); - const db = new NodePgDatabase(dialect, session2, schema); - db.$client = client; - db.$cache = config.cache; - if (db.$cache) { - db.$cache["invalidate"] = config.cache?.onMutate; - } - return db; -} -function drizzle(...params) { - if (typeof params[0] === "string") { - const instance = new esm_default.Pool({ - connectionString: params[0] - }); - return construct(instance, params[1]); - } - if (isConfig(params[0])) { - const { connection, client, ...drizzleConfig } = params[0]; - if (client) - return construct(client, drizzleConfig); - const instance = typeof connection === "string" ? new esm_default.Pool({ - connectionString: connection - }) : new esm_default.Pool(connection); - return construct(instance, drizzleConfig); - } - return construct(params[0], params[1]); -} -((drizzle2) => { - function mock(config) { - return construct({}, config); - } - drizzle2.mock = mock; -})(drizzle || (drizzle = {})); - -// src/loaders/logger.ts -var import_winston = __toESM(require_winston(), 1); -var import_winston_daily_rotate_file = __toESM(require_winston_daily_rotate_file(), 1); - -// src/utils/constants.ts -var import_unique_username_generator = __toESM(require_dist3(), 1); - -// src/config/index.ts -var import_dotenv = __toESM(require_main(), 1); -import path from "path"; -var __dirname = "/Users/shivamverma/Desktop/CodeSM/backend/src/config"; -import_dotenv.default.config({ path: path.join(__dirname, "../../.env") }); -var envSchema = create$3().shape({ - NODE_ENV: create$6().oneOf(["dev", "production"]).default("dev"), - DATABASE_URL: create$6().required("Database URL is Required"), - PORT: create$6().default("8000"), - ALLOWED_ORIGINS: create$6(), - GOOGLE_CLIENT_ID: create$6().required(), - GOOGLE_CLIENT_SECRET: create$6().required(), - GOOGLE_CALLBACK_URL: create$6().required(), - GEMINI_API_KEY: create$6().optional(), - LOG_LEVEL: create$6().oneOf(["error", "warn", "info", "http", "verbose", "debug", "silly"]).default("info"), - API_VERSION: create$6().default("v1"), - MAX_API_REQUEST_RETRIES: create$5().integer().default(3), - CLIENT_URL: create$6().default("https://code-sm.vercel.app"), - MURF_API_KEY: create$6().optional(), - REDIS_HOST: create$6().required(), - REDIS_PASSWORD: create$6().required(), - REDIS_PORT: create$6().required(), - REDIS_USER: create$6().required(), - REDIS_URL: create$6().required(), - REFRESH_TOKEN_EXPIRY: create$6().required(), - REFRESH_TOKEN_SECRET: create$6().required(), - MONGO_URI: create$6().required(), - ACCESS_TOKEN_EXPIRY: create$6().required(), - ACCESS_TOKEN_SECRET: create$6().required(), - AWS_ACCESS_KEY_ID: create$6().required(), - AWS_BUCKET_NAME: create$6().required(), - AWS_REGION: create$6().required(), - VITE_API_URL: create$6().required(), - EMAIL_FROM: create$6().required(), - EMAIL_HOST: create$6().required(), - EMAIL_PASS: create$6().required(), - EMAIL_PORT: create$5().required(), - EMAIL_USER: create$6().required(), - SMTP_VERIFY_URL: create$6().required(), - GOOGLE_REDIRECT_URI: create$6().required(), - JWT_SECRET: create$6().required() -}); -var parsedEnv = envSchema.validateSync(process.env, { - abortEarly: false, - stripUnknown: true -}); -var env = parsedEnv; -var config_default = env; - -// src/utils/constants.ts -var loggerConfig = { - level: config_default.LOG_LEVEL || "info" -}; -var apiPrefix = "/api" + `/${config_default.API_VERSION}`; -var usernameGeneratorConfig = { - dictionaries: [import_unique_username_generator.adjectives, import_unique_username_generator.nouns] +// ../db-schema/src/db/relations.ts +var exports_relations = {}; +__export(exports_relations, { + userRelations: () => userRelations, + testcaseRelations: () => testcaseRelations, + tagRelations: () => tagRelations, + submissionRelations: () => submissionRelations, + problemTagsRelations: () => problemTagsRelations, + problemRelations: () => problemRelations, + hintRelations: () => hintRelations, + executionResultRelations: () => executionResultRelations, + editorialRelations: () => editorialRelations +}); +var userRelations = relations(user2, ({ many }) => ({ + problem: many(problem2), + submission: many(submission2), + session: many(session2) +})); +var problemRelations = relations(problem2, ({ many }) => ({ + testcase: many(testcase2), + hint: many(hint2), + editorial: many(editorial2) +})); +var submissionRelations = relations(submission2, ({ one }) => ({ + problem: one(problem2, { + fields: [submission2.problemId], + references: [problem2.id] + }), + user: one(user2, { + fields: [submission2.userId], + references: [user2.id] + }) +})); +var executionResultRelations = relations(executionResult2, ({ one }) => ({ + submission: one(submission2, { + fields: [executionResult2.submissionId], + references: [submission2.id] + }) +})); +var testcaseRelations = relations(testcase2, ({ one }) => ({ + problem: one(problem2, { + fields: [testcase2.problemId], + references: [problem2.id] + }) +})); +var hintRelations = relations(hint2, ({ one }) => ({ + problem: one(problem2, { + fields: [hint2.problemId], + references: [problem2.id] + }) +})); +var editorialRelations = relations(editorial2, ({ one }) => ({ + problem: one(problem2, { + fields: [editorial2.problemId], + references: [problem2.id] + }) +})); +var problemTagsRelations = relations(problemTag2, ({ one }) => ({ + problem: one(problem2, { + fields: [problemTag2.problemId], + references: [problem2.id] + }), + tag: one(tag2, { + fields: [problemTag2.tagId], + references: [tag2.id] + }) +})); +var tagRelations = relations(tag2, ({ many }) => ({ + problems: many(problemTag2) +})); + +// ../db-schema/src/index.ts +var schema = { + ...exports_schema, + ...exports_relations }; -// src/loaders/logger.ts -var transports = []; -if (true) { - transports.push(new import_winston.default.transports.Console); - const extraTransports = [ - new import_winston_daily_rotate_file.default({ - filename: "./logs/error/error-%DATE%.log", - datePattern: "YYYY-MM-DD", - level: "error", - zippedArchive: true, - format: import_winston.default.format.combine(import_winston.default.format.timestamp({ - format: "YYYY-MM-DD HH:mm:ss" - }), import_winston.default.format.errors({ stack: true }), import_winston.default.format.splat(), import_winston.default.format.json()) - }), - new import_winston_daily_rotate_file.default({ - filename: "./logs/combined/combined-%DATE%.log", - datePattern: "YYYY-MM-DD", - zippedArchive: true, - maxSize: "20m", - maxFiles: "14d", - format: import_winston.default.format.combine(import_winston.default.format.timestamp({ - format: "YYYY-MM-DD HH:mm:ss" - }), import_winston.default.format.errors({ stack: true }), import_winston.default.format.splat(), import_winston.default.format.json()) - }) - ]; - transports.push(...extraTransports); -} else {} -var LoggerInstance = import_winston.default.createLogger({ - level: loggerConfig.level, - levels: import_winston.default.config.npm.levels, - format: import_winston.default.format.combine(import_winston.default.format.timestamp({ - format: "YYYY-MM-DD HH:mm:ss" - }), import_winston.default.format.errors({ stack: true }), import_winston.default.format.splat(), import_winston.default.format.json()), - transports -}); -var logger_default = LoggerInstance; - // src/loaders/postgres.ts -var import_db_schema = __toESM(require_dist4(), 1); function createDrizzle(pool) { - return drizzle(pool, { schema: import_db_schema.schema }); + return drizzle(pool, { schema }); } var db; var pool; @@ -163619,7 +143763,7 @@ var getAllowedOrigins = () => { if (config_default.NODE_ENV === "production") { return config_default.ALLOWED_ORIGINS ? config_default.ALLOWED_ORIGINS.split(",").map((o) => o.trim()) : []; } - return ["http://localhost:3000", "https://dev.verlyai.xyz", "https://verlyai.xyz", "http://localhost:5173"]; + return ["http://localhost:3000", "http://localhost:5173", "https://code-sm.vercel.app"]; }; var isAllowedOrigin = (origin) => { if (!origin || typeof origin !== "string") @@ -163831,13 +143975,13 @@ var transporter = import_nodemailer.default.createTransport({ } }); var sendEmail = async (options) => { - const { to, subject, text: text2, html, senderName, senderEmail } = options; + const { to, subject, text: text3, html, senderName, senderEmail } = options; const from = senderName && senderEmail ? `"${senderName}" <${senderEmail}>` : config_default.EMAIL_USER; const mailOptions = { from, to, subject, - text: text2, + text: text3, html }; try { @@ -163856,9 +144000,9 @@ var sendEmail = async (options) => { // src/api/emails/emails/onboarding.ts var baseUrl = config_default.CLIENT_URL.replace(/\/$/, ""); -var sendOnboardingWelcomeEmail = async (email, user2) => { +var sendOnboardingWelcomeEmail = async (email, user3) => { const subject = "Welcome to CodeSM \u2014 your account is ready"; - const avatarBlock = user2.heroImageUrl ? `

` : ""; + const avatarBlock = user3.heroImageUrl ? `

` : ""; const html = ` @@ -163877,7 +144021,7 @@ var sendOnboardingWelcomeEmail = async (email, user2) => {

Welcome aboard

${avatarBlock} -

Hi ${user2.name}

+

Hi ${user3.name}

Thanks for verifying your email. CodeSM is where you practice coding problems, join contests, run submissions, and discuss solutions with the community. Here is how to get the most out of your account. @@ -163957,7 +144101,7 @@ var sendOnboardingWelcomeEmail = async (email, user2) => { return sendEmail({ to: email, subject, - text: `Welcome to CodeSM, ${user2.name}! Your email is verified. Open ${baseUrl}/ to get started.`, + text: `Welcome to CodeSM, ${user3.name}! Your email is verified. Open ${baseUrl}/ to get started.`, html, senderName: "CodeSM", senderEmail: config_default.EMAIL_USER @@ -164046,15 +144190,15 @@ var verifyEmail = async (token) => { if (users.length === 0) { throw new ApiError_default("Invalid or expired verification token", E.BAD_REQUEST); } - const user2 = users[0]; + const user3 = users[0]; await db.update(user).set({ isEmailVerified: true, verificationToken: null - }).where(eq(user.id, user2.id)); - if (user2.email) { - await sendOnboardingWelcomeEmail(user2.email, { - name: user2.displayName || "User", - heroImageUrl: user2.avatarUrl || undefined + }).where(eq(user.id, user3.id)); + if (user3.email) { + await sendOnboardingWelcomeEmail(user3.email, { + name: user3.displayName || "User", + heroImageUrl: user3.avatarUrl || undefined }).catch((error) => { logger_default.error("Failed to send onboarding email after verification:", error); }); @@ -164223,8 +144367,8 @@ var googleOAuthCallback = asyncHandler_default(async (req, res, next) => { res.redirect(302, redirectUrl); }); var getCurrentUser = asyncHandler_default(async (req, res, next) => { - const user2 = req.user; - if (!user2) { + const user3 = req.user; + if (!user3) { return res.status(E.UNAUTHORIZED).json({ success: false, message: "User not found or not authenticated" @@ -164233,49 +144377,14 @@ var getCurrentUser = asyncHandler_default(async (req, res, next) => { res.status(E.OK).json({ success: true, data: { - id: user2.id, - email: user2.email, - username: user2.username, - role: user2.role + id: user3.id, + email: user3.email, + username: user3.username, + role: user3.role } }); }); -// src/middlewares/auth.middleware.ts -var import_jsonwebtoken4 = __toESM(require_jsonwebtoken(), 1); -var verifyJWT2 = asyncHandler_default(async (req, res, next) => { - try { - const token = req.headers.authorization?.startsWith("Bearer ") ? req.headers.authorization.split(" ")[1] : req.cookies?.token; - if (!token) { - throw new ApiError_default("Unauthorized Request: No token provided", 401); - } - const secret = process.env.ACCESS_TOKEN_SECRET; - if (!secret) { - throw new ApiError_default("Server misconfiguration: ACCESS_TOKEN_SECRET missing", 500); - } - const decodedToken = import_jsonwebtoken4.default.verify(token, secret); - const userId = decodedToken?.userId; - if (!userId) { - throw new ApiError_default("Invalid Access Token", 401); - } - const users = await db.select().from(user).where(eq(user.id, userId)).limit(1); - if (users.length === 0) { - throw new ApiError_default("Invalid Access Token", 401); - } - const user2 = users[0]; - req.user = user2; - next(); - } catch (error) { - const statusCode = error instanceof ApiError_default ? error.statusCode : 500; - const message = error instanceof ApiError_default ? error.message : "Internal Server Error"; - console.error("JWT Verification Error:", error instanceof Error ? error.message : String(error)); - return res.status(statusCode).json({ - status: "error", - message - }); - } -}); - // src/api/auth/auth-schema.ts var emailPasswordLoginSchema = create$3().shape({ email: create$6().email("Invalid email format").required("Email is required"), @@ -164294,7 +144403,7 @@ router.get("/verify-email", verifyEmail2); router.post("/login", validate("body", emailPasswordLoginSchema), emailPasswordLogin); router.get("/google", initiateGoogleAuth); router.get("/google/callback", googleOAuthCallback); -router.get("/me", verifyJWT2, getCurrentUser); +router.get("/me", verifyJWT, getCurrentUser); var auth_route_default = router; // src/api/problem/problem-route.ts @@ -164323,6 +144432,936 @@ var createProblemSchema = create$3({ sampleTestcases: create$5().required() }); +// node_modules/.pnpm/@google+generative-ai@0.24.1/node_modules/@google/generative-ai/dist/index.mjs +var SchemaType; +(function(SchemaType2) { + SchemaType2["STRING"] = "string"; + SchemaType2["NUMBER"] = "number"; + SchemaType2["INTEGER"] = "integer"; + SchemaType2["BOOLEAN"] = "boolean"; + SchemaType2["ARRAY"] = "array"; + SchemaType2["OBJECT"] = "object"; +})(SchemaType || (SchemaType = {})); +var ExecutableCodeLanguage; +(function(ExecutableCodeLanguage2) { + ExecutableCodeLanguage2["LANGUAGE_UNSPECIFIED"] = "language_unspecified"; + ExecutableCodeLanguage2["PYTHON"] = "python"; +})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {})); +var Outcome; +(function(Outcome2) { + Outcome2["OUTCOME_UNSPECIFIED"] = "outcome_unspecified"; + Outcome2["OUTCOME_OK"] = "outcome_ok"; + Outcome2["OUTCOME_FAILED"] = "outcome_failed"; + Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded"; +})(Outcome || (Outcome = {})); +var POSSIBLE_ROLES = ["user", "model", "function", "system"]; +var HarmCategory; +(function(HarmCategory2) { + HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; +})(HarmCategory || (HarmCategory = {})); +var HarmBlockThreshold; +(function(HarmBlockThreshold2) { + HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +var HarmProbability; +(function(HarmProbability2) { + HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE"; + HarmProbability2["LOW"] = "LOW"; + HarmProbability2["MEDIUM"] = "MEDIUM"; + HarmProbability2["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +var BlockReason; +(function(BlockReason2) { + BlockReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + BlockReason2["SAFETY"] = "SAFETY"; + BlockReason2["OTHER"] = "OTHER"; +})(BlockReason || (BlockReason = {})); +var FinishReason; +(function(FinishReason2) { + FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + FinishReason2["STOP"] = "STOP"; + FinishReason2["MAX_TOKENS"] = "MAX_TOKENS"; + FinishReason2["SAFETY"] = "SAFETY"; + FinishReason2["RECITATION"] = "RECITATION"; + FinishReason2["LANGUAGE"] = "LANGUAGE"; + FinishReason2["BLOCKLIST"] = "BLOCKLIST"; + FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + FinishReason2["SPII"] = "SPII"; + FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + FinishReason2["OTHER"] = "OTHER"; +})(FinishReason || (FinishReason = {})); +var TaskType; +(function(TaskType2) { + TaskType2["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED"; + TaskType2["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY"; + TaskType2["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT"; + TaskType2["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY"; + TaskType2["CLASSIFICATION"] = "CLASSIFICATION"; + TaskType2["CLUSTERING"] = "CLUSTERING"; +})(TaskType || (TaskType = {})); +var FunctionCallingMode; +(function(FunctionCallingMode2) { + FunctionCallingMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + FunctionCallingMode2["AUTO"] = "AUTO"; + FunctionCallingMode2["ANY"] = "ANY"; + FunctionCallingMode2["NONE"] = "NONE"; +})(FunctionCallingMode || (FunctionCallingMode = {})); +var DynamicRetrievalMode; +(function(DynamicRetrievalMode2) { + DynamicRetrievalMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + DynamicRetrievalMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalMode || (DynamicRetrievalMode = {})); + +class GoogleGenerativeAIError extends Error { + constructor(message) { + super(`[GoogleGenerativeAI Error]: ${message}`); + } +} + +class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError { + constructor(message, response) { + super(message); + this.response = response; + } +} + +class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError { + constructor(message, status, statusText, errorDetails) { + super(message); + this.status = status; + this.statusText = statusText; + this.errorDetails = errorDetails; + } +} + +class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError { +} + +class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError { +} +var DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com"; +var DEFAULT_API_VERSION = "v1beta"; +var PACKAGE_VERSION = "0.24.1"; +var PACKAGE_LOG_HEADER = "genai-js"; +var Task; +(function(Task2) { + Task2["GENERATE_CONTENT"] = "generateContent"; + Task2["STREAM_GENERATE_CONTENT"] = "streamGenerateContent"; + Task2["COUNT_TOKENS"] = "countTokens"; + Task2["EMBED_CONTENT"] = "embedContent"; + Task2["BATCH_EMBED_CONTENTS"] = "batchEmbedContents"; +})(Task || (Task = {})); + +class RequestUrl { + constructor(model, task, apiKey, stream, requestOptions) { + this.model = model; + this.task = task; + this.apiKey = apiKey; + this.stream = stream; + this.requestOptions = requestOptions; + } + toString() { + var _a, _b; + const apiVersion = ((_a = this.requestOptions) === null || _a === undefined ? undefined : _a.apiVersion) || DEFAULT_API_VERSION; + const baseUrl2 = ((_b = this.requestOptions) === null || _b === undefined ? undefined : _b.baseUrl) || DEFAULT_BASE_URL; + let url = `${baseUrl2}/${apiVersion}/${this.model}:${this.task}`; + if (this.stream) { + url += "?alt=sse"; + } + return url; + } +} +function getClientHeaders(requestOptions) { + const clientHeaders = []; + if (requestOptions === null || requestOptions === undefined ? undefined : requestOptions.apiClient) { + clientHeaders.push(requestOptions.apiClient); + } + clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`); + return clientHeaders.join(" "); +} +async function getHeaders(url) { + var _a; + const headers = new Headers; + headers.append("Content-Type", "application/json"); + headers.append("x-goog-api-client", getClientHeaders(url.requestOptions)); + headers.append("x-goog-api-key", url.apiKey); + let customHeaders = (_a = url.requestOptions) === null || _a === undefined ? undefined : _a.customHeaders; + if (customHeaders) { + if (!(customHeaders instanceof Headers)) { + try { + customHeaders = new Headers(customHeaders); + } catch (e2) { + throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e2.message}`); + } + } + for (const [headerName, headerValue] of customHeaders.entries()) { + if (headerName === "x-goog-api-key") { + throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`); + } else if (headerName === "x-goog-api-client") { + throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`); + } + headers.append(headerName, headerValue); + } + } + return headers; +} +async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) { + const url = new RequestUrl(model, task, apiKey, stream, requestOptions); + return { + url: url.toString(), + fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }) + }; +} +async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, fetchFn = fetch) { + const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions); + return makeRequest(url, fetchOptions, fetchFn); +} +async function makeRequest(url, fetchOptions, fetchFn = fetch) { + let response; + try { + response = await fetchFn(url, fetchOptions); + } catch (e2) { + handleResponseError(e2, url); + } + if (!response.ok) { + await handleResponseNotOk(response, url); + } + return response; +} +function handleResponseError(e2, url) { + let err = e2; + if (err.name === "AbortError") { + err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e2.message}`); + err.stack = e2.stack; + } else if (!(e2 instanceof GoogleGenerativeAIFetchError || e2 instanceof GoogleGenerativeAIRequestInputError)) { + err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e2.message}`); + err.stack = e2.stack; + } + throw err; +} +async function handleResponseNotOk(response, url) { + let message = ""; + let errorDetails; + try { + const json3 = await response.json(); + message = json3.error.message; + if (json3.error.details) { + message += ` ${JSON.stringify(json3.error.details)}`; + errorDetails = json3.error.details; + } + } catch (e2) {} + throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails); +} +function buildFetchOptions(requestOptions) { + const fetchOptions = {}; + if ((requestOptions === null || requestOptions === undefined ? undefined : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === undefined ? undefined : requestOptions.timeout) >= 0) { + const controller = new AbortController; + if ((requestOptions === null || requestOptions === undefined ? undefined : requestOptions.timeout) >= 0) { + setTimeout(() => controller.abort(), requestOptions.timeout); + } + if (requestOptions === null || requestOptions === undefined ? undefined : requestOptions.signal) { + requestOptions.signal.addEventListener("abort", () => { + controller.abort(); + }); + } + fetchOptions.signal = controller.signal; + } + return fetchOptions; +} +function addHelpers(response) { + response.text = () => { + if (response.candidates && response.candidates.length > 0) { + if (response.candidates.length > 1) { + console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning text from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); + } + if (hadBadFinishReason(response.candidates[0])) { + throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); + } + return getText(response); + } else if (response.promptFeedback) { + throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response); + } + return ""; + }; + response.functionCall = () => { + if (response.candidates && response.candidates.length > 0) { + if (response.candidates.length > 1) { + console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning function calls from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); + } + if (hadBadFinishReason(response.candidates[0])) { + throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); + } + console.warn(`response.functionCall() is deprecated. ` + `Use response.functionCalls() instead.`); + return getFunctionCalls(response)[0]; + } else if (response.promptFeedback) { + throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); + } + return; + }; + response.functionCalls = () => { + if (response.candidates && response.candidates.length > 0) { + if (response.candidates.length > 1) { + console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning function calls from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); + } + if (hadBadFinishReason(response.candidates[0])) { + throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); + } + return getFunctionCalls(response); + } else if (response.promptFeedback) { + throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); + } + return; + }; + return response; +} +function getText(response) { + var _a, _b, _c, _d; + const textStrings = []; + if ((_b = (_a = response.candidates) === null || _a === undefined ? undefined : _a[0].content) === null || _b === undefined ? undefined : _b.parts) { + for (const part of (_d = (_c = response.candidates) === null || _c === undefined ? undefined : _c[0].content) === null || _d === undefined ? undefined : _d.parts) { + if (part.text) { + textStrings.push(part.text); + } + if (part.executableCode) { + textStrings.push("\n```" + part.executableCode.language + ` +` + part.executableCode.code + "\n```\n"); + } + if (part.codeExecutionResult) { + textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n"); + } + } + } + if (textStrings.length > 0) { + return textStrings.join(""); + } else { + return ""; + } +} +function getFunctionCalls(response) { + var _a, _b, _c, _d; + const functionCalls = []; + if ((_b = (_a = response.candidates) === null || _a === undefined ? undefined : _a[0].content) === null || _b === undefined ? undefined : _b.parts) { + for (const part of (_d = (_c = response.candidates) === null || _c === undefined ? undefined : _c[0].content) === null || _d === undefined ? undefined : _d.parts) { + if (part.functionCall) { + functionCalls.push(part.functionCall); + } + } + } + if (functionCalls.length > 0) { + return functionCalls; + } else { + return; + } +} +var badFinishReasons = [ + FinishReason.RECITATION, + FinishReason.SAFETY, + FinishReason.LANGUAGE +]; +function hadBadFinishReason(candidate) { + return !!candidate.finishReason && badFinishReasons.includes(candidate.finishReason); +} +function formatBlockErrorMessage(response) { + var _a, _b, _c; + let message = ""; + if ((!response.candidates || response.candidates.length === 0) && response.promptFeedback) { + message += "Response was blocked"; + if ((_a = response.promptFeedback) === null || _a === undefined ? undefined : _a.blockReason) { + message += ` due to ${response.promptFeedback.blockReason}`; + } + if ((_b = response.promptFeedback) === null || _b === undefined ? undefined : _b.blockReasonMessage) { + message += `: ${response.promptFeedback.blockReasonMessage}`; + } + } else if ((_c = response.candidates) === null || _c === undefined ? undefined : _c[0]) { + const firstCandidate = response.candidates[0]; + if (hadBadFinishReason(firstCandidate)) { + message += `Candidate was blocked due to ${firstCandidate.finishReason}`; + if (firstCandidate.finishMessage) { + message += `: ${firstCandidate.finishMessage}`; + } + } + } + return message; +} +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} +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 = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() { + return this; + }, i; + function verb(n) { + if (g[n]) + i[n] = function(v) { + return new Promise(function(a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e2) { + settle(q[0][3], e2); + } + } + 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]); + } +} +var responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +function processStream(response) { + const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true })); + const responseStream = getResponseStream(inputStream); + const [stream1, stream2] = responseStream.tee(); + return { + stream: generateResponseSequence(stream1), + response: getResponsePromise(stream2) + }; +} +async function getResponsePromise(stream) { + const allResponses = []; + const reader = stream.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + return addHelpers(aggregateResponses(allResponses)); + } + allResponses.push(value); + } +} +function generateResponseSequence(stream) { + return __asyncGenerator(this, arguments, function* generateResponseSequence_1() { + const reader = stream.getReader(); + while (true) { + const { value, done } = yield __await(reader.read()); + if (done) { + break; + } + yield yield __await(addHelpers(value)); + } + }); +} +function getResponseStream(inputStream) { + const reader = inputStream.getReader(); + const stream = new ReadableStream({ + start(controller) { + let currentText = ""; + return pump(); + function pump() { + return reader.read().then(({ value, done }) => { + if (done) { + if (currentText.trim()) { + controller.error(new GoogleGenerativeAIError("Failed to parse stream")); + return; + } + controller.close(); + return; + } + currentText += value; + let match = currentText.match(responseLineRE); + let parsedResponse; + while (match) { + try { + parsedResponse = JSON.parse(match[1]); + } catch (e2) { + controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`)); + return; + } + controller.enqueue(parsedResponse); + currentText = currentText.substring(match[0].length); + match = currentText.match(responseLineRE); + } + return pump(); + }).catch((e2) => { + let err = e2; + err.stack = e2.stack; + if (err.name === "AbortError") { + err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream"); + } else { + err = new GoogleGenerativeAIError("Error reading from the stream"); + } + throw err; + }); + } + } + }); + return stream; +} +function aggregateResponses(responses) { + const lastResponse = responses[responses.length - 1]; + const aggregatedResponse = { + promptFeedback: lastResponse === null || lastResponse === undefined ? undefined : lastResponse.promptFeedback + }; + for (const response of responses) { + if (response.candidates) { + let candidateIndex = 0; + for (const candidate of response.candidates) { + if (!aggregatedResponse.candidates) { + aggregatedResponse.candidates = []; + } + if (!aggregatedResponse.candidates[candidateIndex]) { + aggregatedResponse.candidates[candidateIndex] = { + index: candidateIndex + }; + } + aggregatedResponse.candidates[candidateIndex].citationMetadata = candidate.citationMetadata; + aggregatedResponse.candidates[candidateIndex].groundingMetadata = candidate.groundingMetadata; + aggregatedResponse.candidates[candidateIndex].finishReason = candidate.finishReason; + aggregatedResponse.candidates[candidateIndex].finishMessage = candidate.finishMessage; + aggregatedResponse.candidates[candidateIndex].safetyRatings = candidate.safetyRatings; + if (candidate.content && candidate.content.parts) { + if (!aggregatedResponse.candidates[candidateIndex].content) { + aggregatedResponse.candidates[candidateIndex].content = { + role: candidate.content.role || "user", + parts: [] + }; + } + const newPart = {}; + for (const part of candidate.content.parts) { + if (part.text) { + newPart.text = part.text; + } + if (part.functionCall) { + newPart.functionCall = part.functionCall; + } + if (part.executableCode) { + newPart.executableCode = part.executableCode; + } + if (part.codeExecutionResult) { + newPart.codeExecutionResult = part.codeExecutionResult; + } + if (Object.keys(newPart).length === 0) { + newPart.text = ""; + } + aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart); + } + } + } + candidateIndex++; + } + if (response.usageMetadata) { + aggregatedResponse.usageMetadata = response.usageMetadata; + } + } + return aggregatedResponse; +} +async function generateContentStream(apiKey, model, params, requestOptions) { + const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, true, JSON.stringify(params), requestOptions); + return processStream(response); +} +async function generateContent(apiKey, model, params, requestOptions) { + const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); + const responseJson = await response.json(); + const enhancedResponse = addHelpers(responseJson); + return { + response: enhancedResponse + }; +} +function formatSystemInstruction(input) { + if (input == null) { + return; + } else if (typeof input === "string") { + return { role: "system", parts: [{ text: input }] }; + } else if (input.text) { + return { role: "system", parts: [input] }; + } else if (input.parts) { + if (!input.role) { + return { role: "system", parts: input.parts }; + } else { + return input; + } + } +} +function formatNewContent(request) { + let newParts = []; + if (typeof request === "string") { + newParts = [{ text: request }]; + } else { + for (const partOrString of request) { + if (typeof partOrString === "string") { + newParts.push({ text: partOrString }); + } else { + newParts.push(partOrString); + } + } + } + return assignRoleToPartsAndValidateSendMessageRequest(newParts); +} +function assignRoleToPartsAndValidateSendMessageRequest(parts) { + const userContent = { role: "user", parts: [] }; + const functionContent = { role: "function", parts: [] }; + let hasUserContent = false; + let hasFunctionContent = false; + for (const part of parts) { + if ("functionResponse" in part) { + functionContent.parts.push(part); + hasFunctionContent = true; + } else { + userContent.parts.push(part); + hasUserContent = true; + } + } + if (hasUserContent && hasFunctionContent) { + throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."); + } + if (!hasUserContent && !hasFunctionContent) { + throw new GoogleGenerativeAIError("No content is provided for sending chat message."); + } + if (hasUserContent) { + return userContent; + } + return functionContent; +} +function formatCountTokensInput(params, modelParams) { + var _a; + let formattedGenerateContentRequest = { + model: modelParams === null || modelParams === undefined ? undefined : modelParams.model, + generationConfig: modelParams === null || modelParams === undefined ? undefined : modelParams.generationConfig, + safetySettings: modelParams === null || modelParams === undefined ? undefined : modelParams.safetySettings, + tools: modelParams === null || modelParams === undefined ? undefined : modelParams.tools, + toolConfig: modelParams === null || modelParams === undefined ? undefined : modelParams.toolConfig, + systemInstruction: modelParams === null || modelParams === undefined ? undefined : modelParams.systemInstruction, + cachedContent: (_a = modelParams === null || modelParams === undefined ? undefined : modelParams.cachedContent) === null || _a === undefined ? undefined : _a.name, + contents: [] + }; + const containsGenerateContentRequest = params.generateContentRequest != null; + if (params.contents) { + if (containsGenerateContentRequest) { + throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both."); + } + formattedGenerateContentRequest.contents = params.contents; + } else if (containsGenerateContentRequest) { + formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest); + } else { + const content = formatNewContent(params); + formattedGenerateContentRequest.contents = [content]; + } + return { generateContentRequest: formattedGenerateContentRequest }; +} +function formatGenerateContentInput(params) { + let formattedRequest; + if (params.contents) { + formattedRequest = params; + } else { + const content = formatNewContent(params); + formattedRequest = { contents: [content] }; + } + if (params.systemInstruction) { + formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction); + } + return formattedRequest; +} +function formatEmbedContentInput(params) { + if (typeof params === "string" || Array.isArray(params)) { + const content = formatNewContent(params); + return { content }; + } + return params; +} +var VALID_PART_FIELDS = [ + "text", + "inlineData", + "functionCall", + "functionResponse", + "executableCode", + "codeExecutionResult" +]; +var VALID_PARTS_PER_ROLE = { + user: ["text", "inlineData"], + function: ["functionResponse"], + model: ["text", "functionCall", "executableCode", "codeExecutionResult"], + system: ["text"] +}; +function validateChatHistory(history) { + let prevContent = false; + for (const currContent of history) { + const { role, parts } = currContent; + if (!prevContent && role !== "user") { + throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`); + } + if (!POSSIBLE_ROLES.includes(role)) { + throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`); + } + if (!Array.isArray(parts)) { + throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts"); + } + if (parts.length === 0) { + throw new GoogleGenerativeAIError("Each Content should have at least one part"); + } + const countFields = { + text: 0, + inlineData: 0, + functionCall: 0, + functionResponse: 0, + fileData: 0, + executableCode: 0, + codeExecutionResult: 0 + }; + for (const part of parts) { + for (const key of VALID_PART_FIELDS) { + if (key in part) { + countFields[key] += 1; + } + } + } + const validParts = VALID_PARTS_PER_ROLE[role]; + for (const key of VALID_PART_FIELDS) { + if (!validParts.includes(key) && countFields[key] > 0) { + throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`); + } + } + prevContent = true; + } +} +function isValidResponse(response) { + var _a; + if (response.candidates === undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === undefined ? undefined : _a.content; + if (content === undefined) { + return false; + } + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} +var SILENT_ERROR = "SILENT_ERROR"; + +class ChatSession { + constructor(apiKey, model, params, _requestOptions = {}) { + this.model = model; + this.params = params; + this._requestOptions = _requestOptions; + this._history = []; + this._sendPromise = Promise.resolve(); + this._apiKey = apiKey; + if (params === null || params === undefined ? undefined : params.history) { + validateChatHistory(params.history); + this._history = params.history; + } + } + async getHistory() { + await this._sendPromise; + return this._history; + } + async sendMessage(request, requestOptions = {}) { + var _a, _b, _c, _d, _e, _f; + await this._sendPromise; + const newContent = formatNewContent(request); + const generateContentRequest = { + safetySettings: (_a = this.params) === null || _a === undefined ? undefined : _a.safetySettings, + generationConfig: (_b = this.params) === null || _b === undefined ? undefined : _b.generationConfig, + tools: (_c = this.params) === null || _c === undefined ? undefined : _c.tools, + toolConfig: (_d = this.params) === null || _d === undefined ? undefined : _d.toolConfig, + systemInstruction: (_e = this.params) === null || _e === undefined ? undefined : _e.systemInstruction, + cachedContent: (_f = this.params) === null || _f === undefined ? undefined : _f.cachedContent, + contents: [...this._history, newContent] + }; + const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + let finalResult; + this._sendPromise = this._sendPromise.then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)).then((result) => { + var _a2; + if (isValidResponse(result.response)) { + this._history.push(newContent); + const responseContent = Object.assign({ + parts: [], + role: "model" + }, (_a2 = result.response.candidates) === null || _a2 === undefined ? undefined : _a2[0].content); + this._history.push(responseContent); + } else { + const blockErrorMessage = formatBlockErrorMessage(result.response); + if (blockErrorMessage) { + console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); + } + } + finalResult = result; + }).catch((e2) => { + this._sendPromise = Promise.resolve(); + throw e2; + }); + await this._sendPromise; + return finalResult; + } + async sendMessageStream(request, requestOptions = {}) { + var _a, _b, _c, _d, _e, _f; + await this._sendPromise; + const newContent = formatNewContent(request); + const generateContentRequest = { + safetySettings: (_a = this.params) === null || _a === undefined ? undefined : _a.safetySettings, + generationConfig: (_b = this.params) === null || _b === undefined ? undefined : _b.generationConfig, + tools: (_c = this.params) === null || _c === undefined ? undefined : _c.tools, + toolConfig: (_d = this.params) === null || _d === undefined ? undefined : _d.toolConfig, + systemInstruction: (_e = this.params) === null || _e === undefined ? undefined : _e.systemInstruction, + cachedContent: (_f = this.params) === null || _f === undefined ? undefined : _f.cachedContent, + contents: [...this._history, newContent] + }; + const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions); + this._sendPromise = this._sendPromise.then(() => streamPromise).catch((_ignored) => { + throw new Error(SILENT_ERROR); + }).then((streamResult) => streamResult.response).then((response) => { + if (isValidResponse(response)) { + this._history.push(newContent); + const responseContent = Object.assign({}, response.candidates[0].content); + if (!responseContent.role) { + responseContent.role = "model"; + } + this._history.push(responseContent); + } else { + const blockErrorMessage = formatBlockErrorMessage(response); + if (blockErrorMessage) { + console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); + } + } + }).catch((e2) => { + if (e2.message !== SILENT_ERROR) { + console.error(e2); + } + }); + return streamPromise; + } +} +async function countTokens(apiKey, model, params, singleRequestOptions) { + const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions); + return response.json(); +} +async function embedContent(apiKey, model, params, requestOptions) { + const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); + return response.json(); +} +async function batchEmbedContents(apiKey, model, params, requestOptions) { + const requestsWithModel = params.requests.map((request) => { + return Object.assign(Object.assign({}, request), { model }); + }); + const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions); + return response.json(); +} + +class GenerativeModel { + constructor(apiKey, modelParams, _requestOptions = {}) { + this.apiKey = apiKey; + this._requestOptions = _requestOptions; + if (modelParams.model.includes("/")) { + this.model = modelParams.model; + } else { + this.model = `models/${modelParams.model}`; + } + this.generationConfig = modelParams.generationConfig || {}; + this.safetySettings = modelParams.safetySettings || []; + this.tools = modelParams.tools; + this.toolConfig = modelParams.toolConfig; + this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction); + this.cachedContent = modelParams.cachedContent; + } + async generateContent(request, requestOptions = {}) { + var _a; + const formattedParams = formatGenerateContentInput(request); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === undefined ? undefined : _a.name }, formattedParams), generativeModelRequestOptions); + } + async generateContentStream(request, requestOptions = {}) { + var _a; + const formattedParams = formatGenerateContentInput(request); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === undefined ? undefined : _a.name }, formattedParams), generativeModelRequestOptions); + } + startChat(startChatParams) { + var _a; + return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === undefined ? undefined : _a.name }, startChatParams), this._requestOptions); + } + async countTokens(request, requestOptions = {}) { + const formattedParams = formatCountTokensInput(request, { + model: this.model, + generationConfig: this.generationConfig, + safetySettings: this.safetySettings, + tools: this.tools, + toolConfig: this.toolConfig, + systemInstruction: this.systemInstruction, + cachedContent: this.cachedContent + }); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); + } + async embedContent(request, requestOptions = {}) { + const formattedParams = formatEmbedContentInput(request); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); + } + async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) { + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions); + } +} + +class GoogleGenerativeAI { + constructor(apiKey) { + this.apiKey = apiKey; + } + getGenerativeModel(modelParams, requestOptions) { + if (!modelParams.model) { + throw new GoogleGenerativeAIError(`Must provide a model name. ` + `Example: genai.getGenerativeModel({ model: 'my-model-name' })`); + } + return new GenerativeModel(this.apiKey, modelParams, requestOptions); + } + getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) { + if (!cachedContent.name) { + throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field."); + } + if (!cachedContent.model) { + throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field."); + } + const disallowedDuplicates = ["model", "systemInstruction"]; + for (const key of disallowedDuplicates) { + if ((modelParams === null || modelParams === undefined ? undefined : modelParams[key]) && cachedContent[key] && (modelParams === null || modelParams === undefined ? undefined : modelParams[key]) !== cachedContent[key]) { + if (key === "model") { + const modelParamsComp = modelParams.model.startsWith("models/") ? modelParams.model.replace("models/", "") : modelParams.model; + const cachedContentComp = cachedContent.model.startsWith("models/") ? cachedContent.model.replace("models/", "") : cachedContent.model; + if (modelParamsComp === cachedContentComp) { + continue; + } + } + throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` + ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`); + } + } + const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent }); + return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions); + } +} + // src/api/problem/problem-helper.ts var verifyProblemCreationPermission = async (userId) => { const users = await db.select().from(user).where(eq(user.id, userId)); @@ -164333,6 +145372,75 @@ var verifyProblemCreationPermission = async (userId) => { throw new Error("You do not have permission to create problems"); } }; +var genAI = new GoogleGenerativeAI(config_default.GEMINI_API_KEY); +var model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" }); +async function generateHintsWithAI(problem3) { + const prompt = ` + You are an expert programming tutor for a competitive programming platform called "codesm". + Your task is to provide a series of high-quality, step-by-step hints for the following programming problem. + + **RULES:** + 1. **DO NOT** provide the final code solution or large snippets of code in any language. Your goal is to guide, not to solve. + 2. Break down the solution into 4 logical steps or hints. + 3. The hints must be progressive. Start with a high-level conceptual hint and gradually get more specific. + 4. The final hint can suggest the main algorithm, data structure, or key observation needed to solve the problem efficiently (e.g., "Consider using a hash map to track frequencies" or "Think about a two-pointer approach"). + 5. Tailor the tone and complexity of the hints based on the problem's **difficulty** and **tags**. + 6. The response **MUST** be a valid JSON object. Do not include any markdown formatting (like \`\`\`) or any text outside of the JSON structure. + + **OUTPUT FORMAT:** + Your output must be a JSON object with a single key "hints", which is an array of hint objects. Each hint object must have a "title" and a "content" key. + Example format: + { + "hints": [ + { + "title": "Understanding the Problem", + "content": "First, make sure you understand what the input represents and what the expected output should be. Look at the examples carefully.", + "order": "1", + }, + { + "title": "Thinking about the Logic", + "content": "Think about the logic of the problem and how you can solve it efficiently.", + "order": "2", + }, + { + "title": "Choosing the Right Approach", + "content": "What data structure would be efficient for storing and retrieving data quickly?", + "order": "3", + }, + { + "title": "Let's Try Coding", + "content": "Try to code the solution using the hints above. If you get stuck, come back and we'll help you further!", + "order": "4", + } + ] + } + + **PROBLEM TO ANALYZE:** + Title: ${problem3.title} + Difficulty (800-3000): ${problem3.difficulty} + Description: ${problem3.description} + Input Format: ${problem3.inputFormat} + Output Format: ${problem3.outputFormat} + Constraints: ${problem3.constraints} + `; + try { + const result = await model.generateContent(prompt); + const response = await result.response; + const text3 = response.text().replace(/```json/g, "").replace(/```/g, "").trim(); + const parsedResult = JSON.parse(text3); + if (!parsedResult.hints || !Array.isArray(parsedResult.hints)) { + throw new Error("AI response did not follow the expected JSON format."); + } + return parsedResult.hints; + } catch (error) { + console.error("AI Generation Error:", error); + return [{ + title: "Hints Unavailable", + content: "We couldn't generate hints for this problem at the moment. Please try again later or check the editorial.", + order: 0 + }]; + } +} // node_modules/.pnpm/@aws-sdk+middleware-expect-continue@3.972.10/node_modules/@aws-sdk/middleware-expect-continue/dist-es/index.js var import_protocol_http = __toESM(require_dist_cjs2(), 1); @@ -164500,8 +145608,8 @@ var { __spread, __spreadArrays, __spreadArray, - __await, - __asyncGenerator, + __await: __await2, + __asyncGenerator: __asyncGenerator2, __asyncDelegator, __asyncValues, __makeTemplateObject, @@ -165892,15 +147000,15 @@ class S3ExpressIdentityProviderImpl { console.warn(`Error while clearing expired entries in S3ExpressIdentityCache: ` + error); }); - const session2 = await this.createSessionFn(key); - if (!session2.Credentials?.AccessKeyId || !session2.Credentials?.SecretAccessKey) { + const session3 = await this.createSessionFn(key); + if (!session3.Credentials?.AccessKeyId || !session3.Credentials?.SecretAccessKey) { throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey."); } const identity = { - accessKeyId: session2.Credentials.AccessKeyId, - secretAccessKey: session2.Credentials.SecretAccessKey, - sessionToken: session2.Credentials.SessionToken, - expiration: session2.Credentials.Expiration ? new Date(session2.Credentials.Expiration) : undefined + accessKeyId: session3.Credentials.AccessKeyId, + secretAccessKey: session3.Credentials.SecretAccessKey, + sessionToken: session3.Credentials.SessionToken, + expiration: session3.Credentials.Expiration ? new Date(session3.Credentials.Expiration) : undefined }; return identity; } @@ -166051,8 +147159,8 @@ var getS3ExpressHttpSigningPlugin = (config) => ({ } }); // node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.972.30/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/s3Configuration.js -var resolveS3Config = (input, { session: session2 }) => { - const [s3ClientProvider, CreateSessionCommandCtor] = session2; +var resolveS3Config = (input, { session: session3 }) => { + const [s3ClientProvider, CreateSessionCommandCtor] = session3; const { forcePathStyle, useAccelerateEndpoint, disableMultiregionAccessPoints, followRegionRedirects, s3ExpressIdentityProvider, bucketEndpoint, expectContinueHeader } = input; return Object.assign(input, { forcePathStyle: forcePathStyle ?? false, @@ -166197,7 +147305,7 @@ var getValidateBucketNamePlugin = (options) => ({ }); // node_modules/.pnpm/@aws-sdk+middleware-sdk-s3@3.972.30/node_modules/@aws-sdk/middleware-sdk-s3/dist-es/protocol/S3RestXmlProtocol.js var import_protocols = __toESM(require_protocols2(), 1); -var import_schema6 = __toESM(require_schema3(), 1); +var import_schema6 = __toESM(require_schema(), 1); class S3RestXmlProtocol extends import_protocols.AwsRestXmlProtocol { async serializeRequest(operationSchema, input, context) { @@ -166226,7 +147334,7 @@ class S3RestXmlProtocol extends import_protocols.AwsRestXmlProtocol { var import_middleware_user_agent = __toESM(require_dist_cjs31(), 1); var import_config_resolver2 = __toESM(require_dist_cjs32(), 1); var import_core3 = __toESM(require_dist_cjs24(), 1); -var import_schema8 = __toESM(require_schema3(), 1); +var import_schema8 = __toESM(require_schema(), 1); // node_modules/.pnpm/@smithy+eventstream-serde-config-resolver@4.3.14/node_modules/@smithy/eventstream-serde-config-resolver/dist-es/EventStreamSerdeConfig.js var resolveEventStreamSerdeConfig = (input) => Object.assign(input, { @@ -166714,7 +147822,7 @@ var commonParams = { }; // node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/schemas/schemas_0.js -var import_schema7 = __toESM(require_schema3(), 1); +var import_schema7 = __toESM(require_schema(), 1); // node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/models/S3ServiceException.js var import_smithy_client3 = __toESM(require_dist_cjs21(), 1); @@ -172105,1876 +153213,17844 @@ var WriteGetObjectResponse$ = [ () => __Unit ]; -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateSessionCommand.js -class CreateSessionCommand extends import_smithy_client4.Command.classBuilder().ep({ - ...commonParams, - DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, - Bucket: { type: "contextParams", name: "Bucket" } -}).m(function(Command, cs2, config, o2) { - return [ - import_middleware_endpoint2.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), - getThrow200ExceptionsPlugin(config) - ]; -}).s("AmazonS3", "CreateSession", {}).n("S3Client", "CreateSessionCommand").sc(CreateSession$).build() { +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/commands/CreateSessionCommand.js +class CreateSessionCommand extends import_smithy_client4.Command.classBuilder().ep({ + ...commonParams, + DisableS3ExpressSessionAuth: { type: "staticContextParams", value: true }, + Bucket: { type: "contextParams", name: "Bucket" } +}).m(function(Command, cs2, config, o2) { + return [ + import_middleware_endpoint2.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + getThrow200ExceptionsPlugin(config) + ]; +}).s("AmazonS3", "CreateSession", {}).n("S3Client", "CreateSessionCommand").sc(CreateSession$).build() { +} +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/package.json +var package_default = { + name: "@aws-sdk/client-s3", + description: "AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native", + version: "3.1032.0", + scripts: { + build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", + "build:cjs": "node ../../scripts/compilation/inline client-s3", + "build:es": "tsc -p tsconfig.es.json", + "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"', + "build:types": "tsc -p tsconfig.types.json", + "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", + clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo", + "extract:docs": "api-extractor run --local", + "generate:client": "node ../../scripts/generate-clients/single-service --solo s3", + test: "yarn g:vitest run", + "test:browser": "node ./test/browser-build/esbuild && yarn g:vitest run -c vitest.config.browser.mts", + "test:browser:watch": "node ./test/browser-build/esbuild && yarn g:vitest watch -c vitest.config.browser.mts", + "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts && yarn test:browser", + "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts", + "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs", + "test:integration": "yarn g:vitest run -c vitest.config.integ.mts", + "test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.mts", + "test:watch": "yarn g:vitest watch" + }, + main: "./dist-cjs/index.js", + types: "./dist-types/index.d.ts", + module: "./dist-es/index.js", + sideEffects: false, + dependencies: { + "@aws-crypto/sha1-browser": "5.2.0", + "@aws-crypto/sha256-browser": "5.2.0", + "@aws-crypto/sha256-js": "5.2.0", + "@aws-sdk/core": "^3.974.1", + "@aws-sdk/credential-provider-node": "^3.972.32", + "@aws-sdk/middleware-bucket-endpoint": "^3.972.10", + "@aws-sdk/middleware-expect-continue": "^3.972.10", + "@aws-sdk/middleware-flexible-checksums": "^3.974.9", + "@aws-sdk/middleware-host-header": "^3.972.10", + "@aws-sdk/middleware-location-constraint": "^3.972.10", + "@aws-sdk/middleware-logger": "^3.972.10", + "@aws-sdk/middleware-recursion-detection": "^3.972.11", + "@aws-sdk/middleware-sdk-s3": "^3.972.30", + "@aws-sdk/middleware-ssec": "^3.972.10", + "@aws-sdk/middleware-user-agent": "^3.972.31", + "@aws-sdk/region-config-resolver": "^3.972.12", + "@aws-sdk/signature-v4-multi-region": "^3.996.18", + "@aws-sdk/types": "^3.973.8", + "@aws-sdk/util-endpoints": "^3.996.7", + "@aws-sdk/util-user-agent-browser": "^3.972.10", + "@aws-sdk/util-user-agent-node": "^3.973.17", + "@smithy/config-resolver": "^4.4.16", + "@smithy/core": "^3.23.15", + "@smithy/eventstream-serde-browser": "^4.2.14", + "@smithy/eventstream-serde-config-resolver": "^4.3.14", + "@smithy/eventstream-serde-node": "^4.2.14", + "@smithy/fetch-http-handler": "^5.3.17", + "@smithy/hash-blob-browser": "^4.2.15", + "@smithy/hash-node": "^4.2.14", + "@smithy/hash-stream-node": "^4.2.14", + "@smithy/invalid-dependency": "^4.2.14", + "@smithy/md5-js": "^4.2.14", + "@smithy/middleware-content-length": "^4.2.14", + "@smithy/middleware-endpoint": "^4.4.30", + "@smithy/middleware-retry": "^4.5.3", + "@smithy/middleware-serde": "^4.2.18", + "@smithy/middleware-stack": "^4.2.14", + "@smithy/node-config-provider": "^4.3.14", + "@smithy/node-http-handler": "^4.5.3", + "@smithy/protocol-http": "^5.3.14", + "@smithy/smithy-client": "^4.12.11", + "@smithy/types": "^4.14.1", + "@smithy/url-parser": "^4.2.14", + "@smithy/util-base64": "^4.3.2", + "@smithy/util-body-length-browser": "^4.2.2", + "@smithy/util-body-length-node": "^4.2.3", + "@smithy/util-defaults-mode-browser": "^4.3.47", + "@smithy/util-defaults-mode-node": "^4.2.52", + "@smithy/util-endpoints": "^3.4.1", + "@smithy/util-middleware": "^4.2.14", + "@smithy/util-retry": "^4.3.2", + "@smithy/util-stream": "^4.5.23", + "@smithy/util-utf8": "^4.2.2", + "@smithy/util-waiter": "^4.2.16", + tslib: "^2.6.2" + }, + devDependencies: { + "@aws-sdk/signature-v4-crt": "3.1032.0", + "@smithy/snapshot-testing": "^2.0.6", + "@tsconfig/node20": "20.1.8", + "@types/node": "^20.14.8", + concurrently: "7.0.0", + "downlevel-dts": "0.10.1", + premove: "4.0.0", + typescript: "~5.8.3", + vitest: "^4.0.17" + }, + engines: { + node: ">=20.0.0" + }, + typesVersions: { + "<4.5": { + "dist-types/*": [ + "dist-types/ts3.4/*" + ] + } + }, + files: [ + "dist-*/**" + ], + author: { + name: "AWS SDK for JavaScript Team", + url: "https://aws.amazon.com/javascript/" + }, + license: "Apache-2.0", + browser: { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" + }, + "react-native": { + "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" + }, + homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3", + repository: { + type: "git", + url: "https://github.com/aws/aws-sdk-js-v3.git", + directory: "clients/client-s3" + } +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js +var import_client17 = __toESM(require_client3(), 1); +var import_httpAuthSchemes3 = __toESM(require_httpAuthSchemes(), 1); + +// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js +init_dist_es(); +var import_property_provider23 = __toESM(require_dist_cjs34(), 1); +var import_shared_ini_file_loader12 = __toESM(require_dist_cjs35(), 1); + +// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js +var import_property_provider9 = __toESM(require_dist_cjs34(), 1); +var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; +var remoteProvider = async (init3) => { + const { ENV_CMDS_FULL_URI: ENV_CMDS_FULL_URI2, ENV_CMDS_RELATIVE_URI: ENV_CMDS_RELATIVE_URI2, fromContainerMetadata: fromContainerMetadata3, fromInstanceMetadata: fromInstanceMetadata3 } = await Promise.resolve().then(() => (init_dist_es2(), exports_dist_es2)); + if (process.env[ENV_CMDS_RELATIVE_URI2] || process.env[ENV_CMDS_FULL_URI2]) { + init3.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); + const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es3(), exports_dist_es3)); + return import_property_provider9.chain(fromHttp2(init3), fromContainerMetadata3(init3)); + } + if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { + return async () => { + throw new import_property_provider9.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init3.logger }); + }; + } + init3.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); + return fromInstanceMetadata3(init3); +}; + +// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js +function memoizeChain(providers, treatAsExpired) { + const chain2 = internalCreateChain(providers); + let activeLock; + let passiveLock; + let credentials; + const provider = async (options) => { + if (options?.forceRefresh) { + return await chain2(options); + } + if (credentials?.expiration) { + if (credentials?.expiration?.getTime() < Date.now()) { + credentials = undefined; + } + } + if (activeLock) { + await activeLock; + } else if (!credentials || treatAsExpired?.(credentials)) { + if (credentials) { + if (!passiveLock) { + passiveLock = chain2(options).then((c2) => { + credentials = c2; + }).finally(() => { + passiveLock = undefined; + }); + } + } else { + activeLock = chain2(options).then((c2) => { + credentials = c2; + }).finally(() => { + activeLock = undefined; + }); + return provider(options); + } + } + return credentials; + }; + return provider; +} +var internalCreateChain = (providers) => async (awsIdentityProperties) => { + let lastProviderError; + for (const provider of providers) { + try { + return await provider(awsIdentityProperties); + } catch (err) { + lastProviderError = err; + if (err?.tryNextLink) { + continue; + } + throw err; + } + } + throw lastProviderError; +}; + +// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js +var multipleCredentialSourceWarningEmitted = false; +var defaultProvider = (init3 = {}) => memoizeChain([ + async () => { + const profile = init3.profile ?? process.env[import_shared_ini_file_loader12.ENV_PROFILE]; + if (profile) { + const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET]; + if (envStaticCredentialsAreSet) { + if (!multipleCredentialSourceWarningEmitted) { + const warnFn = init3.logger?.warn && init3.logger?.constructor?.name !== "NoOpLogger" ? init3.logger.warn.bind(init3.logger) : console.warn; + warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: + Multiple credential sources detected: + Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. + This SDK will proceed with the AWS_PROFILE value. + + However, a future version may change this behavior to prefer the ENV static credentials. + Please ensure that your environment only sets either the AWS_PROFILE or the + AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. +`); + multipleCredentialSourceWarningEmitted = true; + } + } + throw new import_property_provider23.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { + logger: init3.logger, + tryNextLink: true + }); + } + init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); + return fromEnv(init3)(); + }, + async (awsIdentityProperties) => { + init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); + const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init3; + if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { + throw new import_property_provider23.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init3.logger }); + } + const { fromSSO: fromSSO3 } = await Promise.resolve().then(() => (init_dist_es5(), exports_dist_es4)); + return fromSSO3(init3)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); + const { fromIni: fromIni3 } = await Promise.resolve().then(() => (init_dist_es9(), exports_dist_es7)); + return fromIni3(init3)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); + const { fromProcess: fromProcess3 } = await Promise.resolve().then(() => (init_dist_es7(), exports_dist_es5)); + return fromProcess3(init3)(awsIdentityProperties); + }, + async (awsIdentityProperties) => { + init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); + const { fromTokenFile: fromTokenFile3 } = await Promise.resolve().then(() => (init_dist_es8(), exports_dist_es6)); + return fromTokenFile3(init3)(awsIdentityProperties); + }, + async () => { + init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); + return (await remoteProvider(init3))(); + }, + async () => { + throw new import_property_provider23.CredentialsProviderError("Could not load credentials from any providers", { + tryNextLink: false, + logger: init3.logger + }); + } +], credentialsTreatedAsExpired); +var credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000; + +// node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.972.10/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/NodeUseArnRegionConfigOptions.js +var import_util_config_provider2 = __toESM(require_dist_cjs23(), 1); +var NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION"; +var NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region"; +var NODE_USE_ARN_REGION_CONFIG_OPTIONS = { + environmentVariableSelector: (env2) => import_util_config_provider2.booleanSelector(env2, NODE_USE_ARN_REGION_ENV_NAME, import_util_config_provider2.SelectorType.ENV), + configFileSelector: (profile) => import_util_config_provider2.booleanSelector(profile, NODE_USE_ARN_REGION_INI_NAME, import_util_config_provider2.SelectorType.CONFIG), + default: undefined +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js +var import_util_user_agent_node = __toESM(require_dist_cjs40(), 1); +var import_config_resolver = __toESM(require_dist_cjs32(), 1); + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js +var import_util_hex_encoding2 = __toESM(require_dist_cjs11(), 1); + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/Int64.js +var import_util_hex_encoding = __toESM(require_dist_cjs11(), 1); + +class Int64 { + bytes; + constructor(bytes) { + this.bytes = bytes; + if (bytes.byteLength !== 8) { + throw new Error("Int64 buffers must be exactly 8 bytes"); + } + } + static fromNumber(number2) { + if (number2 > 9223372036854776000 || number2 < -9223372036854776000) { + throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`); + } + const bytes = new Uint8Array(8); + for (let i2 = 7, remaining = Math.abs(Math.round(number2));i2 > -1 && remaining > 0; i2--, remaining /= 256) { + bytes[i2] = remaining; + } + if (number2 < 0) { + negate(bytes); + } + return new Int64(bytes); + } + valueOf() { + const bytes = this.bytes.slice(0); + const negative = bytes[0] & 128; + if (negative) { + negate(bytes); + } + return parseInt(import_util_hex_encoding.toHex(bytes), 16) * (negative ? -1 : 1); + } + toString() { + return String(this.valueOf()); + } +} +function negate(bytes) { + for (let i2 = 0;i2 < 8; i2++) { + bytes[i2] ^= 255; + } + for (let i2 = 7;i2 > -1; i2--) { + bytes[i2]++; + if (bytes[i2] !== 0) + break; + } +} + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js +class HeaderMarshaller { + toUtf8; + fromUtf8; + constructor(toUtf82, fromUtf84) { + this.toUtf8 = toUtf82; + this.fromUtf8 = fromUtf84; + } + format(headers) { + const chunks = []; + for (const headerName of Object.keys(headers)) { + const bytes = this.fromUtf8(headerName); + chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + } + const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); + let position = 0; + for (const chunk of chunks) { + out.set(chunk, position); + position += chunk.byteLength; + } + return out; + } + formatHeaderValue(header) { + switch (header.type) { + case "boolean": + return Uint8Array.from([header.value ? 0 : 1]); + case "byte": + return Uint8Array.from([2, header.value]); + case "short": + const shortView = new DataView(new ArrayBuffer(3)); + shortView.setUint8(0, 3); + shortView.setInt16(1, header.value, false); + return new Uint8Array(shortView.buffer); + case "integer": + const intView = new DataView(new ArrayBuffer(5)); + intView.setUint8(0, 4); + intView.setInt32(1, header.value, false); + return new Uint8Array(intView.buffer); + case "long": + const longBytes = new Uint8Array(9); + longBytes[0] = 5; + longBytes.set(header.value.bytes, 1); + return longBytes; + case "binary": + const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); + binView.setUint8(0, 6); + binView.setUint16(1, header.value.byteLength, false); + const binBytes = new Uint8Array(binView.buffer); + binBytes.set(header.value, 3); + return binBytes; + case "string": + const utf8Bytes = this.fromUtf8(header.value); + const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); + strView.setUint8(0, 7); + strView.setUint16(1, utf8Bytes.byteLength, false); + const strBytes = new Uint8Array(strView.buffer); + strBytes.set(utf8Bytes, 3); + return strBytes; + case "timestamp": + const tsBytes = new Uint8Array(9); + tsBytes[0] = 8; + tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); + return tsBytes; + case "uuid": + if (!UUID_PATTERN.test(header.value)) { + throw new Error(`Invalid UUID received: ${header.value}`); + } + const uuidBytes = new Uint8Array(17); + uuidBytes[0] = 9; + uuidBytes.set(import_util_hex_encoding2.fromHex(header.value.replace(/\-/g, "")), 1); + return uuidBytes; + } + } + parse(headers) { + const out = {}; + let position = 0; + while (position < headers.byteLength) { + const nameLength = headers.getUint8(position++); + const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); + position += nameLength; + switch (headers.getUint8(position++)) { + case 0: + out[name] = { + type: BOOLEAN_TAG, + value: true + }; + break; + case 1: + out[name] = { + type: BOOLEAN_TAG, + value: false + }; + break; + case 2: + out[name] = { + type: BYTE_TAG, + value: headers.getInt8(position++) + }; + break; + case 3: + out[name] = { + type: SHORT_TAG, + value: headers.getInt16(position, false) + }; + position += 2; + break; + case 4: + out[name] = { + type: INT_TAG, + value: headers.getInt32(position, false) + }; + position += 4; + break; + case 5: + out[name] = { + type: LONG_TAG, + value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) + }; + position += 8; + break; + case 6: + const binaryLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: BINARY_TAG, + value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) + }; + position += binaryLength; + break; + case 7: + const stringLength = headers.getUint16(position, false); + position += 2; + out[name] = { + type: STRING_TAG, + value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) + }; + position += stringLength; + break; + case 8: + out[name] = { + type: TIMESTAMP_TAG, + value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) + }; + position += 8; + break; + case 9: + const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); + position += 16; + out[name] = { + type: UUID_TAG, + value: `${import_util_hex_encoding2.toHex(uuidBytes.subarray(0, 4))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(4, 6))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(6, 8))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(8, 10))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(10))}` + }; + break; + default: + throw new Error(`Unrecognized header type tag`); + } + } + return out; + } +} +var HEADER_VALUE_TYPE; +(function(HEADER_VALUE_TYPE2) { + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; + HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; +})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); +var BOOLEAN_TAG = "boolean"; +var BYTE_TAG = "byte"; +var SHORT_TAG = "short"; +var INT_TAG = "integer"; +var LONG_TAG = "long"; +var BINARY_TAG = "binary"; +var STRING_TAG = "string"; +var TIMESTAMP_TAG = "timestamp"; +var UUID_TAG = "uuid"; +var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js +var PRELUDE_MEMBER_LENGTH = 4; +var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; +var CHECKSUM_LENGTH = 4; +var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; +function splitMessage({ byteLength, byteOffset, buffer }) { + if (byteLength < MINIMUM_MESSAGE_LENGTH) { + throw new Error("Provided message too short to accommodate event stream message overhead"); + } + const view = new DataView(buffer, byteOffset, byteLength); + const messageLength = view.getUint32(0, false); + if (byteLength !== messageLength) { + throw new Error("Reported message length does not match received message length"); + } + const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); + const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); + const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); + const checksummer = new Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); + if (expectedPreludeChecksum !== checksummer.digest()) { + throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); + } + checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); + if (expectedMessageChecksum !== checksummer.digest()) { + throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); + } + return { + headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), + body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)) + }; +} + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js +class EventStreamCodec { + headerMarshaller; + messageBuffer; + isEndOfStream; + constructor(toUtf82, fromUtf84) { + this.headerMarshaller = new HeaderMarshaller(toUtf82, fromUtf84); + this.messageBuffer = []; + this.isEndOfStream = false; + } + feed(message) { + this.messageBuffer.push(this.decode(message)); + } + endOfStream() { + this.isEndOfStream = true; + } + getMessage() { + const message = this.messageBuffer.pop(); + const isEndOfStream = this.isEndOfStream; + return { + getMessage() { + return message; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + getAvailableMessages() { + const messages = this.messageBuffer; + this.messageBuffer = []; + const isEndOfStream = this.isEndOfStream; + return { + getMessages() { + return messages; + }, + isEndOfStream() { + return isEndOfStream; + } + }; + } + encode({ headers: rawHeaders, body }) { + const headers = this.headerMarshaller.format(rawHeaders); + const length = headers.byteLength + body.byteLength + 16; + const out = new Uint8Array(length); + const view = new DataView(out.buffer, out.byteOffset, out.byteLength); + const checksum = new Crc32; + view.setUint32(0, length, false); + view.setUint32(4, headers.byteLength, false); + view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); + out.set(headers, 12); + out.set(body, headers.byteLength + 12); + view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); + return out; + } + decode(message) { + const { headers, body } = splitMessage(message); + return { headers: this.headerMarshaller.parse(headers), body }; + } + formatHeaders(rawHeaders) { + return this.headerMarshaller.format(rawHeaders); + } +} + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js +class MessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async* asyncIterator() { + for await (const bytes of this.options.inputStream) { + const decoded = this.options.decoder.decode(bytes); + yield decoded; + } + } +} + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js +class MessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async* asyncIterator() { + for await (const msg of this.options.messageStream) { + const encoded = this.options.encoder.encode(msg); + yield encoded; + } + if (this.options.includeEndFrame) { + yield new Uint8Array(0); + } + } +} + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js +class SmithyMessageDecoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async* asyncIterator() { + for await (const message of this.options.messageStream) { + const deserialized = await this.options.deserializer(message); + if (deserialized === undefined) + continue; + yield deserialized; + } + } +} + +// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js +class SmithyMessageEncoderStream { + options; + constructor(options) { + this.options = options; + } + [Symbol.asyncIterator]() { + return this.asyncIterator(); + } + async* asyncIterator() { + for await (const chunk of this.options.inputStream) { + const payloadBuf = this.options.serializer(chunk); + yield payloadBuf; + } + } +} + +// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.14/node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js +function getChunkedStream(source) { + let currentMessageTotalLength = 0; + let currentMessagePendingLength = 0; + let currentMessage = null; + let messageLengthBuffer = null; + const allocateMessage = (size) => { + if (typeof size !== "number") { + throw new Error("Attempted to allocate an event message where size was not a number: " + size); + } + currentMessageTotalLength = size; + currentMessagePendingLength = 4; + currentMessage = new Uint8Array(size); + const currentMessageView = new DataView(currentMessage.buffer); + currentMessageView.setUint32(0, size, false); + }; + const iterator = async function* () { + const sourceIterator = source[Symbol.asyncIterator](); + while (true) { + const { value, done } = await sourceIterator.next(); + if (done) { + if (!currentMessageTotalLength) { + return; + } else if (currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + } else { + throw new Error("Truncated event message received."); + } + return; + } + const chunkLength = value.length; + let currentOffset = 0; + while (currentOffset < chunkLength) { + if (!currentMessage) { + const bytesRemaining = chunkLength - currentOffset; + if (!messageLengthBuffer) { + messageLengthBuffer = new Uint8Array(4); + } + const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); + messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); + currentMessagePendingLength += numBytesForTotal; + currentOffset += numBytesForTotal; + if (currentMessagePendingLength < 4) { + break; + } + allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); + messageLengthBuffer = null; + } + const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); + currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); + currentMessagePendingLength += numBytesToWrite; + currentOffset += numBytesToWrite; + if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { + yield currentMessage; + currentMessage = null; + currentMessageTotalLength = 0; + currentMessagePendingLength = 0; + } + } + } + }; + return { + [Symbol.asyncIterator]: iterator + }; +} + +// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.14/node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js +function getMessageUnmarshaller(deserializer, toUtf82) { + return async function(message) { + const { value: messageType } = message.headers[":message-type"]; + if (messageType === "error") { + const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); + unmodeledError.name = message.headers[":error-code"].value; + throw unmodeledError; + } else if (messageType === "exception") { + const code = message.headers[":exception-type"].value; + const exception = { [code]: message }; + const deserializedException = await deserializer(exception); + if (deserializedException.$unknown) { + const error = new Error(toUtf82(message.body)); + error.name = code; + throw error; + } + throw deserializedException[code]; + } else if (messageType === "event") { + const event = { + [message.headers[":event-type"].value]: message + }; + const deserialized = await deserializer(event); + if (deserialized.$unknown) + return; + return deserialized; + } else { + throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); + } + }; +} + +// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.14/node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js +class EventStreamMarshaller { + eventStreamCodec; + utfEncoder; + constructor({ utf8Encoder, utf8Decoder }) { + this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder); + this.utfEncoder = utf8Encoder; + } + deserialize(body, deserializer) { + const inputStream = getChunkedStream(body); + return new SmithyMessageDecoderStream({ + messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), + deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) + }); + } + serialize(inputStream, serializer) { + return new MessageEncoderStream({ + messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }), + encoder: this.eventStreamCodec, + includeEndFrame: true + }); + } +} + +// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js +import { Readable } from "stream"; + +// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/utils.js +async function* readabletoIterable(readStream) { + let streamEnded = false; + let generationEnded = false; + const records = new Array; + readStream.on("error", (err) => { + if (!streamEnded) { + streamEnded = true; + } + if (err) { + throw err; + } + }); + readStream.on("data", (data) => { + records.push(data); + }); + readStream.on("end", () => { + streamEnded = true; + }); + while (!generationEnded) { + const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); + if (value) { + yield value; + } + generationEnded = streamEnded && records.length === 0; + } +} + +// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js +class EventStreamMarshaller2 { + universalMarshaller; + constructor({ utf8Encoder, utf8Decoder }) { + this.universalMarshaller = new EventStreamMarshaller({ + utf8Decoder, + utf8Encoder + }); + } + deserialize(body, deserializer) { + const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); + return this.universalMarshaller.deserialize(bodyIterable, deserializer); + } + serialize(input, serializer) { + return Readable.from(this.universalMarshaller.serialize(input, serializer)); + } +} + +// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/provider.js +var eventStreamSerdeProvider = (options) => new EventStreamMarshaller2(options); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js +var import_hash_node = __toESM(require_dist_cjs41(), 1); + +// node_modules/.pnpm/@smithy+hash-stream-node@4.2.14/node_modules/@smithy/hash-stream-node/dist-es/HashCalculator.js +var import_util_utf83 = __toESM(require_dist_cjs5(), 1); +import { Writable } from "stream"; + +class HashCalculator extends Writable { + hash; + constructor(hash4, options) { + super(options); + this.hash = hash4; + } + _write(chunk, encoding, callback) { + try { + this.hash.update(import_util_utf83.toUint8Array(chunk)); + } catch (err) { + return callback(err); + } + callback(); + } +} + +// node_modules/.pnpm/@smithy+hash-stream-node@4.2.14/node_modules/@smithy/hash-stream-node/dist-es/readableStreamHasher.js +var readableStreamHasher = (hashCtor, readableStream) => { + if (readableStream.readableFlowing !== null) { + throw new Error("Unable to calculate hash for flowing readable stream"); + } + const hash4 = new hashCtor; + const hashCalculator = new HashCalculator(hash4); + readableStream.pipe(hashCalculator); + return new Promise((resolve, reject) => { + readableStream.on("error", (err) => { + hashCalculator.end(); + reject(err); + }); + hashCalculator.on("error", reject); + hashCalculator.on("finish", () => { + hash4.digest().then(resolve).catch(reject); + }); + }); +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js +var import_middleware_retry = __toESM(require_dist_cjs39(), 1); +var import_node_config_provider3 = __toESM(require_dist_cjs36(), 1); +var import_node_http_handler2 = __toESM(require_dist_cjs9(), 1); +var import_smithy_client7 = __toESM(require_dist_cjs21(), 1); +var import_util_body_length_node = __toESM(require_dist_cjs42(), 1); +var import_util_defaults_mode_node = __toESM(require_dist_cjs43(), 1); +var import_util_retry = __toESM(require_dist_cjs30(), 1); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.shared.js +var import_httpAuthSchemes2 = __toESM(require_httpAuthSchemes(), 1); +var import_smithy_client6 = __toESM(require_dist_cjs21(), 1); +var import_url_parser2 = __toESM(require_dist_cjs19(), 1); +var import_util_base64 = __toESM(require_dist_cjs6(), 1); +var import_util_stream5 = __toESM(require_dist_cjs12(), 1); +var import_util_utf84 = __toESM(require_dist_cjs5(), 1); +var getRuntimeConfig = (config) => { + return { + apiVersion: "2006-03-01", + base64Decoder: config?.base64Decoder ?? import_util_base64.fromBase64, + base64Encoder: config?.base64Encoder ?? import_util_base64.toBase64, + disableHostPrefix: config?.disableHostPrefix ?? false, + endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, + extensions: config?.extensions ?? [], + getAwsChunkedEncodingStream: config?.getAwsChunkedEncodingStream ?? import_util_stream5.getAwsChunkedEncodingStream, + httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultS3HttpAuthSchemeProvider, + httpAuthSchemes: config?.httpAuthSchemes ?? [ + { + schemeId: "aws.auth#sigv4", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), + signer: new import_httpAuthSchemes2.AwsSdkSigV4Signer + }, + { + schemeId: "aws.auth#sigv4a", + identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), + signer: new import_httpAuthSchemes2.AwsSdkSigV4ASigner + } + ], + logger: config?.logger ?? new import_smithy_client6.NoOpLogger, + protocol: config?.protocol ?? S3RestXmlProtocol, + protocolSettings: config?.protocolSettings ?? { + defaultNamespace: "com.amazonaws.s3", + errorTypeRegistries, + xmlNamespace: "http://s3.amazonaws.com/doc/2006-03-01/", + version: "2006-03-01", + serviceTarget: "AmazonS3" + }, + sdkStreamMixin: config?.sdkStreamMixin ?? import_util_stream5.sdkStreamMixin, + serviceId: config?.serviceId ?? "S3", + signerConstructor: config?.signerConstructor ?? SignatureV4MultiRegion, + signingEscapePath: config?.signingEscapePath ?? false, + urlParser: config?.urlParser ?? import_url_parser2.parseUrl, + useArnRegion: config?.useArnRegion ?? undefined, + utf8Decoder: config?.utf8Decoder ?? import_util_utf84.fromUtf8, + utf8Encoder: config?.utf8Encoder ?? import_util_utf84.toUtf8 + }; +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js +var getRuntimeConfig2 = (config) => { + import_smithy_client7.emitWarningIfUnsupportedVersion(process.version); + const defaultsMode = import_util_defaults_mode_node.resolveDefaultsModeConfig(config); + const defaultConfigProvider = () => defaultsMode().then(import_smithy_client7.loadConfigsForDefaultMode); + const clientSharedValues = getRuntimeConfig(config); + import_client17.emitWarningIfUnsupportedVersion(process.version); + const loaderConfig = { + profile: config?.profile, + logger: clientSharedValues.logger + }; + return { + ...clientSharedValues, + ...config, + runtime: "node", + defaultsMode, + authSchemePreference: config?.authSchemePreference ?? import_node_config_provider3.loadConfig(import_httpAuthSchemes3.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), + bodyLengthChecker: config?.bodyLengthChecker ?? import_util_body_length_node.calculateBodyLength, + credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider, + defaultUserAgentProvider: config?.defaultUserAgentProvider ?? import_util_user_agent_node.createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), + disableS3ExpressSessionAuth: config?.disableS3ExpressSessionAuth ?? import_node_config_provider3.loadConfig(NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, loaderConfig), + eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider, + maxAttempts: config?.maxAttempts ?? import_node_config_provider3.loadConfig(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), + md5: config?.md5 ?? import_hash_node.Hash.bind(null, "md5"), + region: config?.region ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), + requestChecksumCalculation: config?.requestChecksumCalculation ?? import_node_config_provider3.loadConfig(NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, loaderConfig), + requestHandler: import_node_http_handler2.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), + responseChecksumValidation: config?.responseChecksumValidation ?? import_node_config_provider3.loadConfig(NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, loaderConfig), + retryMode: config?.retryMode ?? import_node_config_provider3.loadConfig({ + ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS, + default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE + }, config), + sha1: config?.sha1 ?? import_hash_node.Hash.bind(null, "sha1"), + sha256: config?.sha256 ?? import_hash_node.Hash.bind(null, "sha256"), + sigv4aSigningRegionSet: config?.sigv4aSigningRegionSet ?? import_node_config_provider3.loadConfig(import_httpAuthSchemes3.NODE_SIGV4A_CONFIG_OPTIONS, loaderConfig), + streamCollector: config?.streamCollector ?? import_node_http_handler2.streamCollector, + streamHasher: config?.streamHasher ?? readableStreamHasher, + useArnRegion: config?.useArnRegion ?? import_node_config_provider3.loadConfig(NODE_USE_ARN_REGION_CONFIG_OPTIONS, loaderConfig), + useDualstackEndpoint: config?.useDualstackEndpoint ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + useFipsEndpoint: config?.useFipsEndpoint ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), + userAgentAppId: config?.userAgentAppId ?? import_node_config_provider3.loadConfig(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) + }; +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js +var import_region_config_resolver = __toESM(require_dist_cjs44(), 1); +var import_protocol_http11 = __toESM(require_dist_cjs2(), 1); +var import_smithy_client8 = __toESM(require_dist_cjs21(), 1); + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthExtensionConfiguration.js +var getHttpAuthExtensionConfiguration = (runtimeConfig) => { + const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; + let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; + let _credentials = runtimeConfig.credentials; + return { + setHttpAuthScheme(httpAuthScheme) { + const index3 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); + if (index3 === -1) { + _httpAuthSchemes.push(httpAuthScheme); + } else { + _httpAuthSchemes.splice(index3, 1, httpAuthScheme); + } + }, + httpAuthSchemes() { + return _httpAuthSchemes; + }, + setHttpAuthSchemeProvider(httpAuthSchemeProvider) { + _httpAuthSchemeProvider = httpAuthSchemeProvider; + }, + httpAuthSchemeProvider() { + return _httpAuthSchemeProvider; + }, + setCredentials(credentials) { + _credentials = credentials; + }, + credentials() { + return _credentials; + } + }; +}; +var resolveHttpAuthRuntimeConfig = (config) => { + return { + httpAuthSchemes: config.httpAuthSchemes(), + httpAuthSchemeProvider: config.httpAuthSchemeProvider(), + credentials: config.credentials() + }; +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js +var resolveRuntimeExtensions = (runtimeConfig, extensions) => { + const extensionConfiguration = Object.assign(import_region_config_resolver.getAwsRegionExtensionConfiguration(runtimeConfig), import_smithy_client8.getDefaultExtensionConfiguration(runtimeConfig), import_protocol_http11.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); + extensions.forEach((extension) => extension.configure(extensionConfiguration)); + return Object.assign(runtimeConfig, import_region_config_resolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), import_smithy_client8.resolveDefaultRuntimeConfig(extensionConfiguration), import_protocol_http11.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); +}; + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/S3Client.js +class S3Client extends import_smithy_client9.Client { + config; + constructor(...[configuration]) { + const _config_0 = getRuntimeConfig2(configuration || {}); + super(_config_0); + this.initConfig = _config_0; + const _config_1 = resolveClientEndpointParameters(_config_0); + const _config_2 = import_middleware_user_agent.resolveUserAgentConfig(_config_1); + const _config_3 = resolveFlexibleChecksumsConfig(_config_2); + const _config_4 = import_middleware_retry2.resolveRetryConfig(_config_3); + const _config_5 = import_config_resolver2.resolveRegionConfig(_config_4); + const _config_6 = import_middleware_host_header.resolveHostHeaderConfig(_config_5); + const _config_7 = import_middleware_endpoint3.resolveEndpointConfig(_config_6); + const _config_8 = resolveEventStreamSerdeConfig(_config_7); + const _config_9 = resolveHttpAuthSchemeConfig(_config_8); + const _config_10 = resolveS3Config(_config_9, { session: [() => this, CreateSessionCommand] }); + const _config_11 = resolveRuntimeExtensions(_config_10, configuration?.extensions || []); + this.config = _config_11; + this.middlewareStack.use(import_schema8.getSchemaSerdePlugin(this.config)); + this.middlewareStack.use(import_middleware_user_agent.getUserAgentPlugin(this.config)); + this.middlewareStack.use(import_middleware_retry2.getRetryPlugin(this.config)); + this.middlewareStack.use(import_middleware_content_length.getContentLengthPlugin(this.config)); + this.middlewareStack.use(import_middleware_host_header.getHostHeaderPlugin(this.config)); + this.middlewareStack.use(import_middleware_logger.getLoggerPlugin(this.config)); + this.middlewareStack.use(import_middleware_recursion_detection.getRecursionDetectionPlugin(this.config)); + this.middlewareStack.use(import_core3.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { + httpAuthSchemeParametersProvider: defaultS3HttpAuthSchemeParametersProvider, + identityProviderConfigProvider: async (config) => new import_core3.DefaultIdentityProviderConfig({ + "aws.auth#sigv4": config.credentials, + "aws.auth#sigv4a": config.credentials + }) + })); + this.middlewareStack.use(import_core3.getHttpSigningPlugin(this.config)); + this.middlewareStack.use(getValidateBucketNamePlugin(this.config)); + this.middlewareStack.use(getAddExpectContinuePlugin(this.config)); + this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config)); + this.middlewareStack.use(getS3ExpressPlugin(this.config)); + this.middlewareStack.use(getS3ExpressHttpSigningPlugin(this.config)); + } + destroy() { + super.destroy(); + } +} + +// node_modules/.pnpm/@aws-sdk+middleware-ssec@3.972.10/node_modules/@aws-sdk/middleware-ssec/dist-es/index.js +function ssecMiddleware(options) { + return (next) => async (args) => { + const input = { ...args.input }; + const properties = [ + { + target: "SSECustomerKey", + hash: "SSECustomerKeyMD5" + }, + { + target: "CopySourceSSECustomerKey", + hash: "CopySourceSSECustomerKeyMD5" + } + ]; + for (const prop of properties) { + const value = input[prop.target]; + if (value) { + let valueForHash; + if (typeof value === "string") { + if (isValidBase64EncodedSSECustomerKey(value, options)) { + valueForHash = options.base64Decoder(value); + } else { + valueForHash = options.utf8Decoder(value); + input[prop.target] = options.base64Encoder(valueForHash); + } + } else { + valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value); + input[prop.target] = options.base64Encoder(valueForHash); + } + const hash4 = new options.md5; + hash4.update(valueForHash); + input[prop.hash] = options.base64Encoder(await hash4.digest()); + } + } + return next({ + ...args, + input + }); + }; +} +var ssecMiddlewareOptions = { + name: "ssecMiddleware", + step: "initialize", + tags: ["SSE"], + override: true +}; +var getSsecPlugin = (config) => ({ + applyToStack: (clientStack) => { + clientStack.add(ssecMiddleware(config), ssecMiddlewareOptions); + } +}); +function isValidBase64EncodedSSECustomerKey(str, options) { + const base64Regex = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; + if (!base64Regex.test(str)) + return false; + try { + const decodedBytes = options.base64Decoder(str); + return decodedBytes.length === 32; + } catch { + return false; + } +} + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectCommand.js +var import_middleware_endpoint4 = __toESM(require_dist_cjs38(), 1); +var import_smithy_client10 = __toESM(require_dist_cjs21(), 1); +class GetObjectCommand extends import_smithy_client10.Command.classBuilder().ep({ + ...commonParams, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } +}).m(function(Command, cs2, config, o2) { + return [ + import_middleware_endpoint4.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + getFlexibleChecksumsPlugin(config, { + requestChecksumRequired: false, + requestValidationModeMember: "ChecksumMode", + responseAlgorithms: ["CRC64NVME", "CRC32", "CRC32C", "SHA256", "SHA1"] + }), + getSsecPlugin(config), + getS3ExpiresMiddlewarePlugin(config) + ]; +}).s("AmazonS3", "GetObject", {}).n("S3Client", "GetObjectCommand").sc(GetObject$).build() { +} + +// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectCommand.js +var import_middleware_endpoint5 = __toESM(require_dist_cjs38(), 1); +var import_smithy_client11 = __toESM(require_dist_cjs21(), 1); +class PutObjectCommand extends import_smithy_client11.Command.classBuilder().ep({ + ...commonParams, + Bucket: { type: "contextParams", name: "Bucket" }, + Key: { type: "contextParams", name: "Key" } +}).m(function(Command, cs2, config, o2) { + return [ + import_middleware_endpoint5.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), + getFlexibleChecksumsPlugin(config, { + requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" }, + requestChecksumRequired: false + }), + getCheckContentLengthHeaderPlugin(config), + getThrow200ExceptionsPlugin(config), + getSsecPlugin(config) + ]; +}).s("AmazonS3", "PutObject", {}).n("S3Client", "PutObjectCommand").sc(PutObject$).build() { +} + +// node_modules/.pnpm/@aws-sdk+util-format-url@3.972.10/node_modules/@aws-sdk/util-format-url/dist-es/index.js +var import_querystring_builder = __toESM(require_dist_cjs8(), 1); +function formatUrl(request2) { + const { port, query } = request2; + let { protocol, path: path2, hostname } = request2; + if (protocol && protocol.slice(-1) !== ":") { + protocol += ":"; + } + if (port) { + hostname += `:${port}`; + } + if (path2 && path2.charAt(0) !== "/") { + path2 = `/${path2}`; + } + let queryString = query ? import_querystring_builder.buildQueryString(query) : ""; + if (queryString && queryString[0] !== "?") { + queryString = `?${queryString}`; + } + let auth = ""; + if (request2.username != null || request2.password != null) { + const username = request2.username ?? ""; + const password = request2.password ?? ""; + auth = `${username}:${password}@`; + } + let fragment = ""; + if (request2.fragment) { + fragment = `#${request2.fragment}`; + } + return `${protocol}//${auth}${hostname}${path2}${queryString}${fragment}`; +} + +// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/getSignedUrl.js +var import_middleware_endpoint6 = __toESM(require_dist_cjs38(), 1); +var import_protocol_http12 = __toESM(require_dist_cjs2(), 1); + +// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/constants.js +var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; +var SHA256_HEADER = "X-Amz-Content-Sha256"; + +// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/presigner.js +class S3RequestPresigner { + signer; + constructor(options) { + const resolvedOptions = { + service: options.signingName || options.service || "s3", + uriEscapePath: options.uriEscapePath || false, + applyChecksum: options.applyChecksum || false, + ...options + }; + this.signer = new SignatureV4MultiRegion(resolvedOptions); + } + presign(requestToSign, { unsignableHeaders = new Set, hoistableHeaders = new Set, unhoistableHeaders = new Set, ...options } = {}) { + this.prepareRequest(requestToSign, { + unsignableHeaders, + unhoistableHeaders, + hoistableHeaders + }); + return this.signer.presign(requestToSign, { + expiresIn: 900, + unsignableHeaders, + unhoistableHeaders, + ...options + }); + } + presignWithCredentials(requestToSign, credentials, { unsignableHeaders = new Set, hoistableHeaders = new Set, unhoistableHeaders = new Set, ...options } = {}) { + this.prepareRequest(requestToSign, { + unsignableHeaders, + unhoistableHeaders, + hoistableHeaders + }); + return this.signer.presignWithCredentials(requestToSign, credentials, { + expiresIn: 900, + unsignableHeaders, + unhoistableHeaders, + ...options + }); + } + prepareRequest(requestToSign, { unsignableHeaders = new Set, unhoistableHeaders = new Set, hoistableHeaders = new Set } = {}) { + unsignableHeaders.add("content-type"); + Object.keys(requestToSign.headers).map((header) => header.toLowerCase()).filter((header) => header.startsWith("x-amz-server-side-encryption")).forEach((header) => { + if (!hoistableHeaders.has(header)) { + unhoistableHeaders.add(header); + } + }); + requestToSign.headers[SHA256_HEADER] = UNSIGNED_PAYLOAD; + const currentHostHeader = requestToSign.headers.host; + const port = requestToSign.port; + const expectedHostHeader = `${requestToSign.hostname}${requestToSign.port != null ? ":" + port : ""}`; + if (!currentHostHeader || currentHostHeader === requestToSign.hostname && requestToSign.port != null) { + requestToSign.headers.host = expectedHostHeader; + } + } +} + +// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/getSignedUrl.js +var getSignedUrl = async (client, command, options = {}) => { + let s3Presigner; + let region; + if (typeof client.config.endpointProvider === "function") { + const endpointV2 = await import_middleware_endpoint6.getEndpointFromInstructions(command.input, command.constructor, client.config); + const authScheme = endpointV2.properties?.authSchemes?.[0]; + if (authScheme?.name === "sigv4a") { + region = authScheme?.signingRegionSet?.join(","); + } else { + region = authScheme?.signingRegion; + } + s3Presigner = new S3RequestPresigner({ + ...client.config, + signingName: authScheme?.signingName, + region: async () => region + }); + } else { + s3Presigner = new S3RequestPresigner(client.config); + } + const presignInterceptMiddleware = (next, context) => async (args) => { + const { request: request2 } = args; + if (!import_protocol_http12.HttpRequest.isInstance(request2)) { + throw new Error("Request to be presigned is not an valid HTTP request."); + } + delete request2.headers["amz-sdk-invocation-id"]; + delete request2.headers["amz-sdk-request"]; + delete request2.headers["x-amz-user-agent"]; + let presigned2; + const presignerOptions = { + ...options, + signingRegion: options.signingRegion ?? context["signing_region"] ?? region, + signingService: options.signingService ?? context["signing_service"] + }; + if (context.s3ExpressIdentity) { + presigned2 = await s3Presigner.presignWithCredentials(request2, context.s3ExpressIdentity, presignerOptions); + } else { + presigned2 = await s3Presigner.presign(request2, presignerOptions); + } + return { + response: {}, + output: { + $metadata: { httpStatusCode: 200 }, + presigned: presigned2 + } + }; + }; + const middlewareName = "presignInterceptMiddleware"; + const clientStack = client.middlewareStack.clone(); + clientStack.addRelativeTo(presignInterceptMiddleware, { + name: middlewareName, + relation: "before", + toMiddleware: "awsAuthMiddleware", + override: true + }); + const handler = command.resolveMiddleware(clientStack, client.config, {}); + const { output } = await handler({ input: command.input }); + const { presigned } = output; + return formatUrl(presigned); +}; + +// src/config/index.js +var import_dotenv2 = __toESM(require_main(), 1); +import_dotenv2.default.config({}); +var envSchema2 = create$3({ + API_VERSION: create$6().required(), + ACCESS_TOKEN_EXPIRY: create$6().required(), + ACCESS_TOKEN_SECRET: create$6().required(), + REFRESH_TOKEN_EXPIRY: create$6().required(), + REFRESH_TOKEN_SECRET: create$6().required(), + PORT: create$5().default(5000), + DATABASE_URL: create$6().required(), + MONGO_URI: create$6().required(), + CLIENT_URL: create$6().required(), + VITE_API_URL: create$6().required(), + AWS_ACCESS_KEY_ID: create$6().required(), + AWS_SECRET_ACCESS_KEY: create$6().required(), + AWS_REGION: create$6().required(), + AWS_BUCKET_NAME: create$6().required(), + CLOUDINARY_API_KEY: create$6().required(), + CLOUDINARY_API_SECRET: create$6().required(), + GOOGLE_CLIENT_ID: create$6().required(), + GOOGLE_CLIENT_SECRET: create$6().required(), + GOOGLE_CALLBACK_URL: create$6().required(), + GEMINI_API_KEY: create$6().required(), + MURF_API_KEY: create$6().required(), + REDIS_HOST: create$6().required(), + REDIS_PORT: create$5().required(), + REDIS_URL: create$6().required(), + REDIS_USER: create$6().required(), + ALLOWED_ORIGINS: create$6().required(), + SMTP_VERIFY_URL: create$6().required(), + EMAIL_FROM: create$6().required(), + EMAIL_HOST: create$6().required(), + EMAIL_PORT: create$5().required(), + EMAIL_USER: create$6().required(), + EMAIL_PASS: create$6().required(), + IDEMPOTENCY_SUBMIT_TTL_SEC: create$5().required() +}); +var parsedEnv2 = envSchema2.validateSync(process.env, { + abortEarly: false, + stripUnknown: true +}); +var env2 = parsedEnv2; +var config_default2 = env2; + +// src/services/aws.service.js +var s3Client = new S3Client({ + region: config_default2.AWS_REGION, + credentials: { + accessKeyId: config_default2.AWS_ACCESS_KEY_ID, + secretAccessKey: config_default2.AWS_SECRET_ACCESS_KEY + } +}); +async function generateUploadURL(key, filename) { + const params = new PutObjectCommand({ + Bucket: config_default2.AWS_BUCKET_NAME, + Key: `${key}/${filename}`, + ContentType: "application/json" + }); + const url = await getSignedUrl(s3Client, params, { expiresIn: 3600 }); + return url; +} +var streamToString = (stream) => new Promise((resolve, reject) => { + const chunks = []; + stream.on("data", (chunk) => chunks.push(chunk)); + stream.on("error", reject); + stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8"))); +}); +async function fetchTestcasesFromS3(s3Key) { + try { + const command = new GetObjectCommand({ + Bucket: config_default2.AWS_BUCKET_NAME, + Key: s3Key + }); + const response = await s3Client.send(command); + const jsonString = await streamToString(response.Body); + const data = JSON.parse(jsonString); + return data; + } catch (err) { + console.error("Error fetching testcases:", err); + return null; + } +} +async function fetchFileFromS3(s3Key) { + try { + const command = new GetObjectCommand({ + Bucket: config_default2.AWS_BUCKET_NAME, + Key: s3Key + }); + const response = await s3Client.send(command); + const text3 = await streamToString(response.Body); + return text3; + } catch (err) { + console.error("Error fetching file from S3:", err); + return null; + } +} + +// src/api/problem/problem-service.ts +var handleCreateProblem = async (userId, input) => { + await verifyProblemCreationPermission(userId); + try { + const existingProblem = await db.select().from(problem).where(eq(problem.slug, input.slug)); + if (existingProblem.length > 0) { + throw new ApiError_default("Problem already exists", E.BAD_REQUEST); + } + const problemId = createId(); + const key = `problems/${problemId}`; + const testcasePromises = Array.from({ length: input.testcases }).map((_, i2) => { + const fileName = `testcase_${i2}.json`; + return generateUploadURL(key, fileName).then((url) => ({ + url, + fileName, + order: i2, + isSample: false, + isHidden: i2 >= Math.min(3, input.testcases) + })); + }); + const samplePromises = Array.from({ length: input.sampleTestcases }).map((_, i2) => { + const fileName = `sampleTestcase_${i2}.json`; + return generateUploadURL(key, fileName).then((url) => ({ + url, + fileName, + order: i2, + isSample: true, + isHidden: false + })); + }); + const allTestData = await Promise.all([...testcasePromises, ...samplePromises]); + const uploadUrls = allTestData.map((d2) => d2.url); + await db.transaction(async (tx) => { + await tx.insert(problem).values({ + id: problemId, + title: input.title, + description: input.description, + slug: input.slug, + difficulty: input.difficulty, + authorId: userId, + inputFormat: input.inputFormat, + outputFormat: input.outputFormat, + constraints: input.constraints, + timeLimit: input.timeLimit, + memoryLimit: input.memoryLimit + }); + await tx.insert(editorial).values({ + problemId, + contentS3Key: `${key}/content.md`, + solutionS3Key: `${key}/solution.md`, + editorialLink: input.editorialLink + }); + if (input.tags && input.tags.length > 0) { + const uniqueTagNames = [...new Set(input.tags)]; + const tagIds = []; + for (const tagName of uniqueTagNames) { + const insertedTag = await tx.insert(tag).values({ name: tagName }).onConflictDoUpdate({ + target: tag.name, + set: { name: tagName } + }).returning({ id: tag.id }); + tagIds.push(insertedTag[0].id); + } + if (tagIds.length > 0) { + await tx.insert(problemTag).values(tagIds.map((tagId) => ({ + problemId, + tagId + }))).onConflictDoNothing(); + } + } + if (allTestData.length > 0) { + await tx.insert(testcase).values(allTestData.map((td) => ({ + problemId, + order: td.order, + isHidden: td.isHidden, + s3Key: `${key}/${td.fileName}`, + isSample: td.isSample + }))); + } + }); + return { + message: "Problem created successfully", + problemId, + uploadUrls, + uploadContentUrl: await generateUploadURL(key, "content.md"), + uploadSolutionUrl: await generateUploadURL(key, "solution.md") + }; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error creating problem:", error); + throw new ApiError_default("Failed to create problem", E.INTERNAL_SERVER_ERROR); + } +}; +var handleFinalizeProblem = async (userId, problemId) => { + try { + const problemResult = await db.select().from(problem).where(eq(problem.id, problemId)); + if (problemResult.length === 0) { + throw new ApiError_default("Problem not found", E.NOT_FOUND); + } + if (problemResult[0].authorId !== userId) { + throw new ApiError_default("You do not have permission to finalize this problem", E.FORBIDDEN); + } + const testcasesResult = await db.select().from(testcase).where(eq(testcase.problemId, problemId)); + if (testcasesResult.length === 0) { + throw new ApiError_default("No testcases found. Please upload testcases before finalizing.", E.BAD_REQUEST); + } + const sampleTestcases = testcasesResult.filter((tc) => tc.isSample); + const hiddenTestcases = testcasesResult.filter((tc) => !tc.isSample); + if (sampleTestcases.length === 0) { + throw new ApiError_default("At least one sample testcase is required.", E.BAD_REQUEST); + } + if (hiddenTestcases.length === 0) { + throw new ApiError_default("At least one hidden testcase is required.", E.BAD_REQUEST); + } + await Promise.all(testcasesResult.map(async (tc) => { + const response = await fetchTestcasesFromS3(tc.s3Key); + if (!response) { + throw new ApiError_default(`Testcase file not found in storage: ${tc.s3Key}`, E.BAD_REQUEST); + } + })); + const editorialResult = await db.select({ + solutionS3Key: editorial.solutionS3Key, + contentS3Key: editorial.contentS3Key + }).from(editorial).where(eq(editorial.problemId, problemId)).limit(1); + if (editorialResult.length === 0) { + throw new ApiError_default("Editorial not found. Please upload editorial before finalizing.", E.BAD_REQUEST); + } + const editorialData = editorialResult[0]; + const contentResponse = await fetchTestcasesFromS3(editorialData.contentS3Key); + if (!contentResponse) { + throw new ApiError_default("Content file not found in storage: /content.md", E.BAD_REQUEST); + } + const solutionResponse = await fetchTestcasesFromS3(editorialData.solutionS3Key); + if (!solutionResponse) { + throw new ApiError_default("Solution file not found in storage: /solution.md", E.BAD_REQUEST); + } + await db.update(problem).set({ + status: "DONE" + }).where(eq(problem.id, problemId)); + return { + message: "Problem finalized successfully", + status: true + }; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error finalizing problem:", error); + throw new ApiError_default("Failed to finalize problem", E.INTERNAL_SERVER_ERROR); + } +}; +var handleGetProblems = async (input) => { + try { + let cursorCreatedAt = null; + let cursorId = null; + if (input.cursor) { + try { + const decoded = Buffer.from(input.cursor, "base64").toString("utf-8"); + const [timeStr, id] = decoded.split(":"); + cursorCreatedAt = new Date(parseInt(timeStr)); + cursorId = id; + } catch (e3) { + throw new ApiError_default("Invalid cursor", E.BAD_REQUEST); + } + } + const problemsResult = await db.select({ + id: problem.id, + title: problem.title, + description: problem.description, + slug: problem.slug, + difficulty: problem.difficulty, + createdAt: problem.createdAt, + updatedAt: problem.updatedAt + }).from(problem).where(and(eq(problem.status, "DONE"), cursorCreatedAt && cursorId ? or(lt(problem.createdAt, cursorCreatedAt), and(eq(problem.createdAt, cursorCreatedAt), lt(problem.id, cursorId))) : undefined)).limit(input.limit + 1).orderBy(desc(problem.createdAt), desc(problem.id)); + const hasNextPage = problemsResult.length > input.limit; + const problems = hasNextPage ? problemsResult.slice(0, input.limit) : problemsResult; + let nextCursor = null; + if (hasNextPage && problems.length > 0) { + const lastProblem = problems[problems.length - 1]; + const time3 = lastProblem.createdAt.getTime(); + nextCursor = Buffer.from(`${time3}:${lastProblem.id}`).toString("base64"); + } + if (problems.length === 0) { + return { problems: [], nextCursor: null }; + } + const problemIds = problems.map((p2) => p2.id); + const tagsResult = await db.select({ + problemId: problemTag.problemId, + tagName: tag.name + }).from(problemTag).innerJoin(tag, eq(problemTag.tagId, tag.id)).where(inArray(problemTag.problemId, problemIds)); + const assembledProblems = problems.map((p2) => { + const pTags = tagsResult.filter((t9) => t9.problemId === p2.id).map((t9) => t9.tagName); + return { + ...p2, + tags: pTags + }; + }); + return { + problems: assembledProblems, + nextCursor + }; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error fetching problems:", error); + throw new ApiError_default("Failed to fetch problems", E.INTERNAL_SERVER_ERROR); + } +}; +var handleGetProblemById = async (problemId) => { + try { + const problemResult = await db.select().from(problem).where(and(eq(problem.id, problemId), eq(problem.status, "DONE"))).limit(1); + if (problemResult.length === 0) { + throw new ApiError_default("Problem not found", E.NOT_FOUND); + } + const p2 = problemResult[0]; + const tagsResult = await db.select({ + tagName: tag.name + }).from(problemTag).innerJoin(tag, eq(problemTag.tagId, tag.id)).where(eq(problemTag.problemId, problemId)); + const testcasesResult = await db.select({ + id: testcase.id, + order: testcase.order, + s3Key: testcase.s3Key + }).from(testcase).where(and(eq(testcase.problemId, problemId), eq(testcase.isSample, true))); + const sampleTestcases = await Promise.all(testcasesResult.map(async (tc) => { + const response = await fetchTestcasesFromS3(tc.s3Key); + if (!response) { + throw new ApiError_default("Testcase file not found: " + tc.s3Key, E.INTERNAL_SERVER_ERROR); + } + return { + id: tc.id, + order: tc.order, + input: response.input, + output: response.output + }; + })); + return { + ...p2, + difficulty: p2.difficulty, + tags: tagsResult.map((t9) => t9.tagName), + sampleTestcases + }; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error fetching problem by id:", error); + throw new ApiError_default("Failed to fetch problem details", E.INTERNAL_SERVER_ERROR); + } +}; +var handleGetEditorialSolution = async (problemId) => { + try { + const editorialResult = await db.select().from(editorial).where(eq(editorial.problemId, problemId)).limit(1); + if (editorialResult.length === 0) { + throw new ApiError_default("Editorial not found", E.NOT_FOUND); + } + const editorials = editorialResult[0]; + const solutionResponse = await fetchFileFromS3(editorials.solutionS3Key); + if (!solutionResponse) { + throw new ApiError_default("Solution file not found in storage: " + editorials.solutionS3Key, E.INTERNAL_SERVER_ERROR); + } + return solutionResponse; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error fetching editorial solution:", error); + throw new ApiError_default("Failed to fetch editorial solution", E.INTERNAL_SERVER_ERROR); + } +}; +var handleGetEditorialContent = async (problemId) => { + try { + const editorialResult = await db.select({ + contentS3Key: editorial.contentS3Key, + editorialLink: editorial.editorialLink + }).from(editorial).where(eq(editorial.problemId, problemId)).limit(1); + if (editorialResult.length === 0) { + throw new ApiError_default("Editorial not found", E.NOT_FOUND); + } + const editorials = editorialResult[0]; + const editorialContentResponse = await fetchFileFromS3(editorials.contentS3Key); + if (!editorialContentResponse) { + throw new ApiError_default("Editorial content not found in storage: " + editorials.contentS3Key, E.INTERNAL_SERVER_ERROR); + } + return { + editorialContent: editorialContentResponse, + editorialLink: editorials.editorialLink + }; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error fetching editorial content:", error); + throw new ApiError_default("Failed to fetch editorial content", E.INTERNAL_SERVER_ERROR); + } +}; +var handleGetHints = async (problemId) => { + try { + const result = await db.select({ + difficulty: problem.difficulty, + description: problem.description, + inputFormat: problem.inputFormat, + outputFormat: problem.outputFormat, + constraints: problem.constraints + }).from(problem).innerJoin(problemTag, eq(problem.id, problemTag.problemId)).innerJoin(tag, eq(problemTag.tagId, tag.id)).innerJoin(testcase, eq(problem.id, testcase.problemId)).where(eq(problem.id, problemId)); + if (!result) { + throw new ApiError_default("Problem not found", E.NOT_FOUND); + } + const hintResults = await db.select({ + title: hint.title, + content: hint.content, + order: hint.order + }).from(hint).where(eq(hint.problemId, problemId)); + if (hintResults.length > 0) { + const hints2 = hintResults.map((h2) => { + return { + title: h2.title, + content: h2.content, + order: h2.order + }; + }); + return hints2; + } + const hints = await generateHintsWithAI(result[0]); + const hintsToInsert = hints.map((h2) => ({ + ...h2, + problemId + })); + await db.insert(hint).values(hintsToInsert); + return hints; + } catch (error) { + if (error instanceof ApiError_default) { + throw error; + } + console.error("Error fetching hints:", error); + throw new ApiError_default("Failed to fetch hints", E.INTERNAL_SERVER_ERROR); + } +}; + +// src/api/problem/problem-controller.ts +var createProblem = asyncHandler_default(async (req, res) => { + const response = await handleCreateProblem(req.user.id, req.body); + return res.status(200).json({ + status: "success", + message: "Problem created successfully", + data: response + }); +}); +var finalizeProblem = asyncHandler_default(async (req, res) => { + const problemId = req.query.problemId; + await handleFinalizeProblem(req.user.id, problemId); + return res.status(200).json({ + status: "success", + message: "Problem finalized successfully" + }); +}); +var getProblems = asyncHandler_default(async (req, res) => { + const limit = parseInt(req.query.limit) || 10; + const cursor = req.query.cursor; + const response = await handleGetProblems({ limit, cursor }); + return res.status(200).json({ + status: "success", + message: "Problems fetched successfully", + data: response + }); +}); +var getProblemById = asyncHandler_default(async (req, res) => { + const problemId = req.params.problemId; + const response = await handleGetProblemById(problemId); + return res.status(200).json({ + status: "success", + message: "Problem fetched successfully", + data: response + }); +}); +var getEditorialSolution = asyncHandler_default(async (req, res) => { + const problemId = req.params.problemId; + const response = await handleGetEditorialSolution(problemId); + return res.status(200).json({ + status: "success", + message: "Editorial solution fetched successfully", + data: response + }); +}); +var getEditorialContent = asyncHandler_default(async (req, res) => { + const problemId = req.params.problemId; + const response = await handleGetEditorialContent(problemId); + return res.status(200).json({ + status: "success", + message: "Editorial solution fetched successfully", + data: response + }); +}); +var getHints = asyncHandler_default(async (req, res) => { + const problemId = req.params.problemId; + const response = await handleGetHints(problemId); + if (response.length > 0) { + return res.status(200).json({ + status: "success", + message: "Hints are generated successfully", + data: response + }); + } else { + return res.status(200).json({ + status: "success", + message: "Hints are not generated yet", + data: [] + }); + } +}); + +// src/api/problem/problem-route.ts +var router2 = import_express2.Router(); +router2.post("/create", validate("body", createProblemSchema), verifyJWT, createProblem); +router2.post("/finalize", verifyJWT, finalizeProblem); +router2.get("/", validate("query", getProblemsSchema), getProblems); +router2.get("/:problemId", getProblemById); +router2.get("/:problemId/editorial-solution", getEditorialSolution); +router2.get("/:problemId/editorial-content", getEditorialContent); +router2.get("/:problemId/hints", getHints); +var problem_route_default = router2; + +// src/api/submission/submission-route.ts +var import_express3 = __toESM(require_express(), 1); + +// src/api/submission/submission-schema.ts +var createSubmissionSchema = create$3({ + code: create$6().required("Code is required"), + language: create$6().required("Language is required") +}); +var problemIdSchema = create$3({ + problemId: create$6().required("Problem ID is required") +}); + +// src/loaders/redis.ts +var import_ioredis = __toESM(require_built3(), 1); +var import_dotenv3 = __toESM(require_main(), 1); +import_dotenv3.default.config(); +var redisUrl = process.env.REDIS_URL; +if (!redisUrl) { + throw new Error("REDIS_URL is not set"); +} +var redis = new import_ioredis.default(redisUrl); +var redis_default = redis; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/backoffs.js +class Backoffs { + static normalize(backoff) { + if (Number.isFinite(backoff)) { + return { + type: "fixed", + delay: backoff + }; + } else if (backoff) { + return backoff; + } + } + static calculate(backoff, attemptsMade, err, job, customStrategy) { + if (backoff) { + const strategy = lookupStrategy(backoff, customStrategy); + return strategy(attemptsMade, backoff.type, err, job); + } + } +} +Backoffs.builtinStrategies = { + fixed: function(delay, jitter = 0) { + return function() { + if (jitter > 0) { + const minDelay = delay * (1 - jitter); + return Math.floor(Math.random() * delay * jitter + minDelay); + } else { + return delay; + } + }; + }, + exponential: function(delay, jitter = 0) { + return function(attemptsMade) { + if (jitter > 0) { + const maxDelay = Math.round(Math.pow(2, attemptsMade - 1) * delay); + const minDelay = maxDelay * (1 - jitter); + return Math.floor(Math.random() * maxDelay * jitter + minDelay); + } else { + return Math.round(Math.pow(2, attemptsMade - 1) * delay); + } + }; + } +}; +function lookupStrategy(backoff, customStrategy) { + if (backoff.type in Backoffs.builtinStrategies) { + return Backoffs.builtinStrategies[backoff.type](backoff.delay, backoff.jitter); + } else if (customStrategy) { + return customStrategy; + } else { + throw new Error(`Unknown backoff strategy ${backoff.type}. + If a custom backoff strategy is used, specify it when the queue is created.`); + } +} +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/enums/child-command.js +var ChildCommand; +(function(ChildCommand2) { + ChildCommand2[ChildCommand2["Init"] = 0] = "Init"; + ChildCommand2[ChildCommand2["Start"] = 1] = "Start"; + ChildCommand2[ChildCommand2["Stop"] = 2] = "Stop"; + ChildCommand2[ChildCommand2["GetChildrenValuesResponse"] = 3] = "GetChildrenValuesResponse"; + ChildCommand2[ChildCommand2["GetIgnoredChildrenFailuresResponse"] = 4] = "GetIgnoredChildrenFailuresResponse"; + ChildCommand2[ChildCommand2["GetDependenciesCountResponse"] = 5] = "GetDependenciesCountResponse"; + ChildCommand2[ChildCommand2["MoveToWaitingChildrenResponse"] = 6] = "MoveToWaitingChildrenResponse"; + ChildCommand2[ChildCommand2["Cancel"] = 7] = "Cancel"; + ChildCommand2[ChildCommand2["GetDependenciesResponse"] = 8] = "GetDependenciesResponse"; +})(ChildCommand || (ChildCommand = {})); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/enums/error-code.js +var ErrorCode; +(function(ErrorCode2) { + ErrorCode2[ErrorCode2["JobNotExist"] = -1] = "JobNotExist"; + ErrorCode2[ErrorCode2["JobLockNotExist"] = -2] = "JobLockNotExist"; + ErrorCode2[ErrorCode2["JobNotInState"] = -3] = "JobNotInState"; + ErrorCode2[ErrorCode2["JobPendingChildren"] = -4] = "JobPendingChildren"; + ErrorCode2[ErrorCode2["ParentJobNotExist"] = -5] = "ParentJobNotExist"; + ErrorCode2[ErrorCode2["JobLockMismatch"] = -6] = "JobLockMismatch"; + ErrorCode2[ErrorCode2["ParentJobCannotBeReplaced"] = -7] = "ParentJobCannotBeReplaced"; + ErrorCode2[ErrorCode2["JobBelongsToJobScheduler"] = -8] = "JobBelongsToJobScheduler"; + ErrorCode2[ErrorCode2["JobHasFailedChildren"] = -9] = "JobHasFailedChildren"; + ErrorCode2[ErrorCode2["SchedulerJobIdCollision"] = -10] = "SchedulerJobIdCollision"; + ErrorCode2[ErrorCode2["SchedulerJobSlotsBusy"] = -11] = "SchedulerJobSlotsBusy"; +})(ErrorCode || (ErrorCode = {})); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/enums/parent-command.js +var ParentCommand; +(function(ParentCommand2) { + ParentCommand2[ParentCommand2["Completed"] = 0] = "Completed"; + ParentCommand2[ParentCommand2["Error"] = 1] = "Error"; + ParentCommand2[ParentCommand2["Failed"] = 2] = "Failed"; + ParentCommand2[ParentCommand2["InitFailed"] = 3] = "InitFailed"; + ParentCommand2[ParentCommand2["InitCompleted"] = 4] = "InitCompleted"; + ParentCommand2[ParentCommand2["Log"] = 5] = "Log"; + ParentCommand2[ParentCommand2["MoveToDelayed"] = 6] = "MoveToDelayed"; + ParentCommand2[ParentCommand2["MoveToWait"] = 7] = "MoveToWait"; + ParentCommand2[ParentCommand2["Progress"] = 8] = "Progress"; + ParentCommand2[ParentCommand2["Update"] = 9] = "Update"; + ParentCommand2[ParentCommand2["GetChildrenValues"] = 10] = "GetChildrenValues"; + ParentCommand2[ParentCommand2["GetIgnoredChildrenFailures"] = 11] = "GetIgnoredChildrenFailures"; + ParentCommand2[ParentCommand2["GetDependenciesCount"] = 12] = "GetDependenciesCount"; + ParentCommand2[ParentCommand2["MoveToWaitingChildren"] = 13] = "MoveToWaitingChildren"; + ParentCommand2[ParentCommand2["GetDependencies"] = 14] = "GetDependencies"; +})(ParentCommand || (ParentCommand = {})); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/enums/metrics-time.js +var MetricsTime; +(function(MetricsTime2) { + MetricsTime2[MetricsTime2["ONE_MINUTE"] = 1] = "ONE_MINUTE"; + MetricsTime2[MetricsTime2["FIVE_MINUTES"] = 5] = "FIVE_MINUTES"; + MetricsTime2[MetricsTime2["FIFTEEN_MINUTES"] = 15] = "FIFTEEN_MINUTES"; + MetricsTime2[MetricsTime2["THIRTY_MINUTES"] = 30] = "THIRTY_MINUTES"; + MetricsTime2[MetricsTime2["ONE_HOUR"] = 60] = "ONE_HOUR"; + MetricsTime2[MetricsTime2["ONE_WEEK"] = 10080] = "ONE_WEEK"; + MetricsTime2[MetricsTime2["TWO_WEEKS"] = 20160] = "TWO_WEEKS"; + MetricsTime2[MetricsTime2["ONE_MONTH"] = 80640] = "ONE_MONTH"; +})(MetricsTime || (MetricsTime = {})); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/enums/telemetry-attributes.js +var TelemetryAttributes; +(function(TelemetryAttributes2) { + TelemetryAttributes2["QueueName"] = "bullmq.queue.name"; + TelemetryAttributes2["QueueOperation"] = "bullmq.queue.operation"; + TelemetryAttributes2["BulkCount"] = "bullmq.job.bulk.count"; + TelemetryAttributes2["BulkNames"] = "bullmq.job.bulk.names"; + TelemetryAttributes2["JobName"] = "bullmq.job.name"; + TelemetryAttributes2["JobId"] = "bullmq.job.id"; + TelemetryAttributes2["JobKey"] = "bullmq.job.key"; + TelemetryAttributes2["JobIds"] = "bullmq.job.ids"; + TelemetryAttributes2["JobAttemptsMade"] = "bullmq.job.attempts.made"; + TelemetryAttributes2["DeduplicationKey"] = "bullmq.job.deduplication.key"; + TelemetryAttributes2["JobOptions"] = "bullmq.job.options"; + TelemetryAttributes2["JobProgress"] = "bullmq.job.progress"; + TelemetryAttributes2["QueueDrainDelay"] = "bullmq.queue.drain.delay"; + TelemetryAttributes2["QueueGrace"] = "bullmq.queue.grace"; + TelemetryAttributes2["QueueCleanLimit"] = "bullmq.queue.clean.limit"; + TelemetryAttributes2["QueueRateLimit"] = "bullmq.queue.rate.limit"; + TelemetryAttributes2["JobType"] = "bullmq.job.type"; + TelemetryAttributes2["QueueOptions"] = "bullmq.queue.options"; + TelemetryAttributes2["QueueEventMaxLength"] = "bullmq.queue.event.max.length"; + TelemetryAttributes2["QueueJobsState"] = "bullmq.queue.jobs.state"; + TelemetryAttributes2["WorkerOptions"] = "bullmq.worker.options"; + TelemetryAttributes2["WorkerName"] = "bullmq.worker.name"; + TelemetryAttributes2["WorkerId"] = "bullmq.worker.id"; + TelemetryAttributes2["WorkerRateLimit"] = "bullmq.worker.rate.limit"; + TelemetryAttributes2["WorkerDoNotWaitActive"] = "bullmq.worker.do.not.wait.active"; + TelemetryAttributes2["WorkerForceClose"] = "bullmq.worker.force.close"; + TelemetryAttributes2["WorkerStalledJobs"] = "bullmq.worker.stalled.jobs"; + TelemetryAttributes2["WorkerFailedJobs"] = "bullmq.worker.failed.jobs"; + TelemetryAttributes2["WorkerJobsToExtendLocks"] = "bullmq.worker.jobs.to.extend.locks"; + TelemetryAttributes2["JobFinishedTimestamp"] = "bullmq.job.finished.timestamp"; + TelemetryAttributes2["JobAttemptFinishedTimestamp"] = "bullmq.job.attempt_finished_timestamp"; + TelemetryAttributes2["JobProcessedTimestamp"] = "bullmq.job.processed.timestamp"; + TelemetryAttributes2["JobResult"] = "bullmq.job.result"; + TelemetryAttributes2["JobFailedReason"] = "bullmq.job.failed.reason"; + TelemetryAttributes2["FlowName"] = "bullmq.flow.name"; + TelemetryAttributes2["JobSchedulerId"] = "bullmq.job.scheduler.id"; + TelemetryAttributes2["JobStatus"] = "bullmq.job.status"; +})(TelemetryAttributes || (TelemetryAttributes = {})); +var MetricNames; +(function(MetricNames2) { + MetricNames2["QueueJobsCount"] = "bullmq.queue.jobs"; + MetricNames2["JobsCompleted"] = "bullmq.jobs.completed"; + MetricNames2["JobsFailed"] = "bullmq.jobs.failed"; + MetricNames2["JobsDelayed"] = "bullmq.jobs.delayed"; + MetricNames2["JobsRetried"] = "bullmq.jobs.retried"; + MetricNames2["JobsWaiting"] = "bullmq.jobs.waiting"; + MetricNames2["JobsWaitingChildren"] = "bullmq.jobs.waiting_children"; + MetricNames2["JobDuration"] = "bullmq.job.duration"; +})(MetricNames || (MetricNames = {})); +var SpanKind; +(function(SpanKind2) { + SpanKind2[SpanKind2["INTERNAL"] = 0] = "INTERNAL"; + SpanKind2[SpanKind2["SERVER"] = 1] = "SERVER"; + SpanKind2[SpanKind2["CLIENT"] = 2] = "CLIENT"; + SpanKind2[SpanKind2["PRODUCER"] = 3] = "PRODUCER"; + SpanKind2[SpanKind2["CONSUMER"] = 4] = "CONSUMER"; +})(SpanKind || (SpanKind = {})); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/abort-controller.js +var import_node_abort_controller = __toESM(require_node_abort_controller(), 1); +var AbortControllerImpl; +if (globalThis.AbortController) { + AbortControllerImpl = globalThis.AbortController; +} else { + AbortControllerImpl = import_node_abort_controller.AbortController; +} + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/utils/index.js +var import_ioredis2 = __toESM(require_built3(), 1); +var import_utils54 = __toESM(require_utils7(), 1); +var semver = __toESM(require_semver2(), 1); +var errorObject = { value: null }; +function tryCatch(fn, ctx, args) { + try { + return fn.apply(ctx, args); + } catch (e3) { + errorObject.value = e3; + return errorObject; + } +} +function lengthInUtf8Bytes(str) { + return Buffer.byteLength(str, "utf8"); +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} +function array2obj(arr) { + const obj = {}; + for (let i2 = 0;i2 < arr.length; i2 += 2) { + obj[arr[i2]] = arr[i2 + 1]; + } + return obj; +} +function objectToFlatArray(obj) { + const arr = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key) && obj[key] !== undefined) { + arr[arr.length] = key; + arr[arr.length] = obj[key]; + } + } + return arr; +} +function delay(ms, abortController) { + return new Promise((resolve) => { + let timeout; + const callback = () => { + abortController === null || abortController === undefined || abortController.signal.removeEventListener("abort", callback); + clearTimeout(timeout); + resolve(); + }; + timeout = setTimeout(callback, ms); + abortController === null || abortController === undefined || abortController.signal.addEventListener("abort", callback); + }); +} +function increaseMaxListeners(emitter, count2) { + const maxListeners = emitter.getMaxListeners(); + emitter.setMaxListeners(maxListeners + count2); +} +function invertObject(obj) { + return Object.entries(obj).reduce((result, [key, value]) => { + result[value] = key; + return result; + }, {}); +} +var optsDecodeMap = { + de: "deduplication", + fpof: "failParentOnFailure", + cpof: "continueParentOnFailure", + idof: "ignoreDependencyOnFailure", + kl: "keepLogs", + rdof: "removeDependencyOnFailure" +}; +var optsEncodeMap = Object.assign(Object.assign({}, invertObject(optsDecodeMap)), { + debounce: "de" +}); +function isRedisInstance(obj) { + if (!obj) { + return false; + } + const redisApi = ["connect", "disconnect", "duplicate"]; + return redisApi.every((name) => typeof obj[name] === "function"); +} +function isRedisCluster(obj) { + return isRedisInstance(obj) && obj.isCluster; +} +function decreaseMaxListeners(emitter, count2) { + increaseMaxListeners(emitter, -count2); +} +function getParentKey(opts) { + if (opts) { + return `${opts.queue}:${opts.id}`; + } +} +var clientCommandMessageReg = /ERR unknown command ['`]\s*client\s*['`]/; +var DELAY_TIME_5 = 5000; +function isNotConnectionError(error) { + const { code, message: errorMessage } = error; + return errorMessage !== import_utils54.CONNECTION_CLOSED_ERROR_MSG && !errorMessage.includes("ECONNREFUSED") && code !== "ECONNREFUSED"; +} +var isRedisVersionLowerThan = (currentVersion, minimumVersion, currentDatabaseType, desiredDatabaseType = "redis") => { + if (currentDatabaseType === desiredDatabaseType) { + const version3 = semver.valid(semver.coerce(currentVersion)); + return semver.lt(version3, minimumVersion); + } + return false; +}; +var parseObjectValues = (obj) => { + const accumulator = {}; + for (const value of Object.entries(obj)) { + accumulator[value[0]] = JSON.parse(value[1]); + } + return accumulator; +}; +var INFINITY = 1 / 0; +var QUEUE_EVENT_SUFFIX = ":qe"; +function removeUndefinedFields(obj) { + const newObj = {}; + for (const key in obj) { + if (obj[key] !== undefined) { + newObj[key] = obj[key]; + } + } + return newObj; +} +async function trace(telemetry, spanKind, queueName, operation, destination, callback, srcPropagationMetadata) { + if (!telemetry) { + return callback(); + } else { + const { tracer: tracer3, contextManager } = telemetry; + const currentContext = contextManager.active(); + let parentContext; + if (srcPropagationMetadata) { + parentContext = contextManager.fromMetadata(currentContext, srcPropagationMetadata); + } + const spanName = destination ? `${operation} ${destination}` : operation; + const span = tracer3.startSpan(spanName, { + kind: spanKind + }, parentContext); + try { + span.setAttributes({ + [TelemetryAttributes.QueueName]: queueName, + [TelemetryAttributes.QueueOperation]: operation + }); + let messageContext; + let dstPropagationMetadata; + if (spanKind === SpanKind.CONSUMER && parentContext) { + messageContext = span.setSpanOnContext(parentContext); + } else { + messageContext = span.setSpanOnContext(currentContext); + } + if (callback.length == 2) { + dstPropagationMetadata = contextManager.getMetadata(messageContext); + } + return await contextManager.with(messageContext, () => callback(span, dstPropagationMetadata)); + } catch (err) { + span.recordException(err); + throw err; + } finally { + span.end(); + } + } +} + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/child-processor.js +var ChildStatus; +(function(ChildStatus2) { + ChildStatus2[ChildStatus2["Idle"] = 0] = "Idle"; + ChildStatus2[ChildStatus2["Started"] = 1] = "Started"; + ChildStatus2[ChildStatus2["Terminating"] = 2] = "Terminating"; + ChildStatus2[ChildStatus2["Errored"] = 3] = "Errored"; +})(ChildStatus || (ChildStatus = {})); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/errors/unrecoverable-error.js +var UNRECOVERABLE_ERROR = "bullmq:unrecoverable"; + +class UnrecoverableError extends Error { + constructor(message = UNRECOVERABLE_ERROR) { + super(message); + this.name = this.constructor.name; + Object.setPrototypeOf(this, new.target.prototype); + } +} +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/job.js +import { debuglog } from "util"; + +// node_modules/.pnpm/msgpackr@1.11.5/node_modules/msgpackr/unpack.js +var decoder; +try { + decoder = new TextDecoder; +} catch (error) {} +var src; +var srcEnd; +var position = 0; +var EMPTY_ARRAY = []; +var strings = EMPTY_ARRAY; +var stringPosition = 0; +var currentUnpackr = {}; +var currentStructures; +var srcString; +var srcStringStart = 0; +var srcStringEnd = 0; +var bundledStrings; +var referenceMap; +var currentExtensions = []; +var dataView; +var defaultOptions = { + useRecords: false, + mapsAsObjects: true +}; + +class C1Type { +} +var C1 = new C1Type; +C1.name = "MessagePack 0xC1"; +var sequentialMode = false; +var inlineObjectReadThreshold = 2; +var readStruct; +var onLoadedStructures; +var onSaveState; +try { + new Function(""); +} catch (error) { + inlineObjectReadThreshold = Infinity; +} + +class Unpackr { + constructor(options) { + if (options) { + if (options.useRecords === false && options.mapsAsObjects === undefined) + options.mapsAsObjects = true; + if (options.sequential && options.trusted !== false) { + options.trusted = true; + if (!options.structures && options.useRecords != false) { + options.structures = []; + if (!options.maxSharedStructures) + options.maxSharedStructures = 0; + } + } + if (options.structures) + options.structures.sharedLength = options.structures.length; + else if (options.getStructures) { + (options.structures = []).uninitialized = true; + options.structures.sharedLength = 0; + } + if (options.int64AsNumber) { + options.int64AsType = "number"; + } + } + Object.assign(this, options); + } + unpack(source, options) { + if (src) { + return saveState(() => { + clearSource(); + return this ? this.unpack(source, options) : Unpackr.prototype.unpack.call(defaultOptions, source, options); + }); + } + if (!source.buffer && source.constructor === ArrayBuffer) + source = typeof Buffer !== "undefined" ? Buffer.from(source) : new Uint8Array(source); + if (typeof options === "object") { + srcEnd = options.end || source.length; + position = options.start || 0; + } else { + position = 0; + srcEnd = options > -1 ? options : source.length; + } + stringPosition = 0; + srcStringEnd = 0; + srcString = null; + strings = EMPTY_ARRAY; + bundledStrings = null; + src = source; + try { + dataView = source.dataView || (source.dataView = new DataView(source.buffer, source.byteOffset, source.byteLength)); + } catch (error) { + src = null; + if (source instanceof Uint8Array) + throw error; + throw new Error("Source must be a Uint8Array or Buffer but was a " + (source && typeof source == "object" ? source.constructor.name : typeof source)); + } + if (this instanceof Unpackr) { + currentUnpackr = this; + if (this.structures) { + currentStructures = this.structures; + return checkedRead(options); + } else if (!currentStructures || currentStructures.length > 0) { + currentStructures = []; + } + } else { + currentUnpackr = defaultOptions; + if (!currentStructures || currentStructures.length > 0) + currentStructures = []; + } + return checkedRead(options); + } + unpackMultiple(source, forEach2) { + let values, lastPosition = 0; + try { + sequentialMode = true; + let size = source.length; + let value = this ? this.unpack(source, size) : defaultUnpackr.unpack(source, size); + if (forEach2) { + if (forEach2(value, lastPosition, position) === false) + return; + while (position < size) { + lastPosition = position; + if (forEach2(checkedRead(), lastPosition, position) === false) { + return; + } + } + } else { + values = [value]; + while (position < size) { + lastPosition = position; + values.push(checkedRead()); + } + return values; + } + } catch (error) { + error.lastPosition = lastPosition; + error.values = values; + throw error; + } finally { + sequentialMode = false; + clearSource(); + } + } + _mergeStructures(loadedStructures, existingStructures) { + if (onLoadedStructures) + loadedStructures = onLoadedStructures.call(this, loadedStructures); + loadedStructures = loadedStructures || []; + if (Object.isFrozen(loadedStructures)) + loadedStructures = loadedStructures.map((structure) => structure.slice(0)); + for (let i2 = 0, l2 = loadedStructures.length;i2 < l2; i2++) { + let structure = loadedStructures[i2]; + if (structure) { + structure.isShared = true; + if (i2 >= 32) + structure.highByte = i2 - 32 >> 5; + } + } + loadedStructures.sharedLength = loadedStructures.length; + for (let id in existingStructures || []) { + if (id >= 0) { + let structure = loadedStructures[id]; + let existing = existingStructures[id]; + if (existing) { + if (structure) + (loadedStructures.restoreStructures || (loadedStructures.restoreStructures = []))[id] = structure; + loadedStructures[id] = existing; + } + } + } + return this.structures = loadedStructures; + } + decode(source, options) { + return this.unpack(source, options); + } +} +function checkedRead(options) { + try { + if (!currentUnpackr.trusted && !sequentialMode) { + let sharedLength = currentStructures.sharedLength || 0; + if (sharedLength < currentStructures.length) + currentStructures.length = sharedLength; + } + let result; + if (currentUnpackr.randomAccessStructure && src[position] < 64 && src[position] >= 32 && readStruct) { + result = readStruct(src, position, srcEnd, currentUnpackr); + src = null; + if (!(options && options.lazy) && result) + result = result.toJSON(); + position = srcEnd; + } else + result = read(); + if (bundledStrings) { + position = bundledStrings.postBundlePosition; + bundledStrings = null; + } + if (sequentialMode) + currentStructures.restoreStructures = null; + if (position == srcEnd) { + if (currentStructures && currentStructures.restoreStructures) + restoreStructures(); + currentStructures = null; + src = null; + if (referenceMap) + referenceMap = null; + } else if (position > srcEnd) { + throw new Error("Unexpected end of MessagePack data"); + } else if (!sequentialMode) { + let jsonView; + try { + jsonView = JSON.stringify(result, (_, value) => typeof value === "bigint" ? `${value}n` : value).slice(0, 100); + } catch (error) { + jsonView = "(JSON view not available " + error + ")"; + } + throw new Error("Data read, but end of buffer not reached " + jsonView); + } + return result; + } catch (error) { + if (currentStructures && currentStructures.restoreStructures) + restoreStructures(); + clearSource(); + if (error instanceof RangeError || error.message.startsWith("Unexpected end of buffer") || position > srcEnd) { + error.incomplete = true; + } + throw error; + } +} +function restoreStructures() { + for (let id in currentStructures.restoreStructures) { + currentStructures[id] = currentStructures.restoreStructures[id]; + } + currentStructures.restoreStructures = null; +} +function read() { + let token = src[position++]; + if (token < 160) { + if (token < 128) { + if (token < 64) + return token; + else { + let structure = currentStructures[token & 63] || currentUnpackr.getStructures && loadStructures()[token & 63]; + if (structure) { + if (!structure.read) { + structure.read = createStructureReader(structure, token & 63); + } + return structure.read(); + } else + return token; + } + } else if (token < 144) { + token -= 128; + if (currentUnpackr.mapsAsObjects) { + let object2 = {}; + for (let i2 = 0;i2 < token; i2++) { + let key = readKey(); + if (key === "__proto__") + key = "__proto_"; + object2[key] = read(); + } + return object2; + } else { + let map = new Map; + for (let i2 = 0;i2 < token; i2++) { + map.set(read(), read()); + } + return map; + } + } else { + token -= 144; + let array2 = new Array(token); + for (let i2 = 0;i2 < token; i2++) { + array2[i2] = read(); + } + if (currentUnpackr.freezeData) + return Object.freeze(array2); + return array2; + } + } else if (token < 192) { + let length = token - 160; + if (srcStringEnd >= position) { + return srcString.slice(position - srcStringStart, (position += length) - srcStringStart); + } + if (srcStringEnd == 0 && srcEnd < 140) { + let string2 = length < 16 ? shortStringInJS(length) : longStringInJS(length); + if (string2 != null) + return string2; + } + return readFixedString(length); + } else { + let value; + switch (token) { + case 192: + return null; + case 193: + if (bundledStrings) { + value = read(); + if (value > 0) + return bundledStrings[1].slice(bundledStrings.position1, bundledStrings.position1 += value); + else + return bundledStrings[0].slice(bundledStrings.position0, bundledStrings.position0 -= value); + } + return C1; + case 194: + return false; + case 195: + return true; + case 196: + value = src[position++]; + if (value === undefined) + throw new Error("Unexpected end of buffer"); + return readBin(value); + case 197: + value = dataView.getUint16(position); + position += 2; + return readBin(value); + case 198: + value = dataView.getUint32(position); + position += 4; + return readBin(value); + case 199: + return readExt(src[position++]); + case 200: + value = dataView.getUint16(position); + position += 2; + return readExt(value); + case 201: + value = dataView.getUint32(position); + position += 4; + return readExt(value); + case 202: + value = dataView.getFloat32(position); + if (currentUnpackr.useFloat32 > 2) { + let multiplier = mult10[(src[position] & 127) << 1 | src[position + 1] >> 7]; + position += 4; + return (multiplier * value + (value > 0 ? 0.5 : -0.5) >> 0) / multiplier; + } + position += 4; + return value; + case 203: + value = dataView.getFloat64(position); + position += 8; + return value; + case 204: + return src[position++]; + case 205: + value = dataView.getUint16(position); + position += 2; + return value; + case 206: + value = dataView.getUint32(position); + position += 4; + return value; + case 207: + if (currentUnpackr.int64AsType === "number") { + value = dataView.getUint32(position) * 4294967296; + value += dataView.getUint32(position + 4); + } else if (currentUnpackr.int64AsType === "string") { + value = dataView.getBigUint64(position).toString(); + } else if (currentUnpackr.int64AsType === "auto") { + value = dataView.getBigUint64(position); + if (value <= BigInt(2) << BigInt(52)) + value = Number(value); + } else + value = dataView.getBigUint64(position); + position += 8; + return value; + case 208: + return dataView.getInt8(position++); + case 209: + value = dataView.getInt16(position); + position += 2; + return value; + case 210: + value = dataView.getInt32(position); + position += 4; + return value; + case 211: + if (currentUnpackr.int64AsType === "number") { + value = dataView.getInt32(position) * 4294967296; + value += dataView.getUint32(position + 4); + } else if (currentUnpackr.int64AsType === "string") { + value = dataView.getBigInt64(position).toString(); + } else if (currentUnpackr.int64AsType === "auto") { + value = dataView.getBigInt64(position); + if (value >= BigInt(-2) << BigInt(52) && value <= BigInt(2) << BigInt(52)) + value = Number(value); + } else + value = dataView.getBigInt64(position); + position += 8; + return value; + case 212: + value = src[position++]; + if (value == 114) { + return recordDefinition(src[position++] & 63); + } else { + let extension = currentExtensions[value]; + if (extension) { + if (extension.read) { + position++; + return extension.read(read()); + } else if (extension.noBuffer) { + position++; + return extension(); + } else + return extension(src.subarray(position, ++position)); + } else + throw new Error("Unknown extension " + value); + } + case 213: + value = src[position]; + if (value == 114) { + position++; + return recordDefinition(src[position++] & 63, src[position++]); + } else + return readExt(2); + case 214: + return readExt(4); + case 215: + return readExt(8); + case 216: + return readExt(16); + case 217: + value = src[position++]; + if (srcStringEnd >= position) { + return srcString.slice(position - srcStringStart, (position += value) - srcStringStart); + } + return readString8(value); + case 218: + value = dataView.getUint16(position); + position += 2; + if (srcStringEnd >= position) { + return srcString.slice(position - srcStringStart, (position += value) - srcStringStart); + } + return readString16(value); + case 219: + value = dataView.getUint32(position); + position += 4; + if (srcStringEnd >= position) { + return srcString.slice(position - srcStringStart, (position += value) - srcStringStart); + } + return readString32(value); + case 220: + value = dataView.getUint16(position); + position += 2; + return readArray(value); + case 221: + value = dataView.getUint32(position); + position += 4; + return readArray(value); + case 222: + value = dataView.getUint16(position); + position += 2; + return readMap(value); + case 223: + value = dataView.getUint32(position); + position += 4; + return readMap(value); + default: + if (token >= 224) + return token - 256; + if (token === undefined) { + let error = new Error("Unexpected end of MessagePack data"); + error.incomplete = true; + throw error; + } + throw new Error("Unknown MessagePack token " + token); + } + } +} +var validName = /^[a-zA-Z_$][a-zA-Z\d_$]*$/; +function createStructureReader(structure, firstId) { + function readObject() { + if (readObject.count++ > inlineObjectReadThreshold) { + let readObject2 = structure.read = new Function("r", "return function(){return " + (currentUnpackr.freezeData ? "Object.freeze" : "") + "({" + structure.map((key) => key === "__proto__" ? "__proto_:r()" : validName.test(key) ? key + ":r()" : "[" + JSON.stringify(key) + "]:r()").join(",") + "})}")(read); + if (structure.highByte === 0) + structure.read = createSecondByteReader(firstId, structure.read); + return readObject2(); + } + let object2 = {}; + for (let i2 = 0, l2 = structure.length;i2 < l2; i2++) { + let key = structure[i2]; + if (key === "__proto__") + key = "__proto_"; + object2[key] = read(); + } + if (currentUnpackr.freezeData) + return Object.freeze(object2); + return object2; + } + readObject.count = 0; + if (structure.highByte === 0) { + return createSecondByteReader(firstId, readObject); + } + return readObject; +} +var createSecondByteReader = (firstId, read0) => { + return function() { + let highByte = src[position++]; + if (highByte === 0) + return read0(); + let id = firstId < 32 ? -(firstId + (highByte << 5)) : firstId + (highByte << 5); + let structure = currentStructures[id] || loadStructures()[id]; + if (!structure) { + throw new Error("Record id is not defined for " + id); + } + if (!structure.read) + structure.read = createStructureReader(structure, firstId); + return structure.read(); + }; +}; +function loadStructures() { + let loadedStructures = saveState(() => { + src = null; + return currentUnpackr.getStructures(); + }); + return currentStructures = currentUnpackr._mergeStructures(loadedStructures, currentStructures); +} +var readFixedString = readStringJS; +var readString8 = readStringJS; +var readString16 = readStringJS; +var readString32 = readStringJS; +var isNativeAccelerationEnabled = false; +function setExtractor(extractStrings) { + isNativeAccelerationEnabled = true; + readFixedString = readString(1); + readString8 = readString(2); + readString16 = readString(3); + readString32 = readString(5); + function readString(headerLength) { + return function readString2(length) { + let string2 = strings[stringPosition++]; + if (string2 == null) { + if (bundledStrings) + return readStringJS(length); + let byteOffset = src.byteOffset; + let extraction = extractStrings(position - headerLength + byteOffset, srcEnd + byteOffset, src.buffer); + if (typeof extraction == "string") { + string2 = extraction; + strings = EMPTY_ARRAY; + } else { + strings = extraction; + stringPosition = 1; + srcStringEnd = 1; + string2 = strings[0]; + if (string2 === undefined) + throw new Error("Unexpected end of buffer"); + } + } + let srcStringLength = string2.length; + if (srcStringLength <= length) { + position += length; + return string2; + } + srcString = string2; + srcStringStart = position; + srcStringEnd = position + srcStringLength; + position += length; + return string2.slice(0, length); + }; + } +} +function readStringJS(length) { + let result; + if (length < 16) { + if (result = shortStringInJS(length)) + return result; + } + if (length > 64 && decoder) + return decoder.decode(src.subarray(position, position += length)); + const end = position + length; + const units = []; + result = ""; + while (position < end) { + const byte1 = src[position++]; + if ((byte1 & 128) === 0) { + units.push(byte1); + } else if ((byte1 & 224) === 192) { + const byte2 = src[position++] & 63; + units.push((byte1 & 31) << 6 | byte2); + } else if ((byte1 & 240) === 224) { + const byte2 = src[position++] & 63; + const byte3 = src[position++] & 63; + units.push((byte1 & 31) << 12 | byte2 << 6 | byte3); + } else if ((byte1 & 248) === 240) { + const byte2 = src[position++] & 63; + const byte3 = src[position++] & 63; + const byte4 = src[position++] & 63; + let unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4; + if (unit > 65535) { + unit -= 65536; + units.push(unit >>> 10 & 1023 | 55296); + unit = 56320 | unit & 1023; + } + units.push(unit); + } else { + units.push(byte1); + } + if (units.length >= 4096) { + result += fromCharCode.apply(String, units); + units.length = 0; + } + } + if (units.length > 0) { + result += fromCharCode.apply(String, units); + } + return result; +} +function readString(source, start, length) { + let existingSrc = src; + src = source; + position = start; + try { + return readStringJS(length); + } finally { + src = existingSrc; + } +} +function readArray(length) { + let array2 = new Array(length); + for (let i2 = 0;i2 < length; i2++) { + array2[i2] = read(); + } + if (currentUnpackr.freezeData) + return Object.freeze(array2); + return array2; +} +function readMap(length) { + if (currentUnpackr.mapsAsObjects) { + let object2 = {}; + for (let i2 = 0;i2 < length; i2++) { + let key = readKey(); + if (key === "__proto__") + key = "__proto_"; + object2[key] = read(); + } + return object2; + } else { + let map = new Map; + for (let i2 = 0;i2 < length; i2++) { + map.set(read(), read()); + } + return map; + } +} +var fromCharCode = String.fromCharCode; +function longStringInJS(length) { + let start = position; + let bytes = new Array(length); + for (let i2 = 0;i2 < length; i2++) { + const byte = src[position++]; + if ((byte & 128) > 0) { + position = start; + return; + } + bytes[i2] = byte; + } + return fromCharCode.apply(String, bytes); +} +function shortStringInJS(length) { + if (length < 4) { + if (length < 2) { + if (length === 0) + return ""; + else { + let a2 = src[position++]; + if ((a2 & 128) > 1) { + position -= 1; + return; + } + return fromCharCode(a2); + } + } else { + let a2 = src[position++]; + let b2 = src[position++]; + if ((a2 & 128) > 0 || (b2 & 128) > 0) { + position -= 2; + return; + } + if (length < 3) + return fromCharCode(a2, b2); + let c2 = src[position++]; + if ((c2 & 128) > 0) { + position -= 3; + return; + } + return fromCharCode(a2, b2, c2); + } + } else { + let a2 = src[position++]; + let b2 = src[position++]; + let c2 = src[position++]; + let d2 = src[position++]; + if ((a2 & 128) > 0 || (b2 & 128) > 0 || (c2 & 128) > 0 || (d2 & 128) > 0) { + position -= 4; + return; + } + if (length < 6) { + if (length === 4) + return fromCharCode(a2, b2, c2, d2); + else { + let e3 = src[position++]; + if ((e3 & 128) > 0) { + position -= 5; + return; + } + return fromCharCode(a2, b2, c2, d2, e3); + } + } else if (length < 8) { + let e3 = src[position++]; + let f2 = src[position++]; + if ((e3 & 128) > 0 || (f2 & 128) > 0) { + position -= 6; + return; + } + if (length < 7) + return fromCharCode(a2, b2, c2, d2, e3, f2); + let g2 = src[position++]; + if ((g2 & 128) > 0) { + position -= 7; + return; + } + return fromCharCode(a2, b2, c2, d2, e3, f2, g2); + } else { + let e3 = src[position++]; + let f2 = src[position++]; + let g2 = src[position++]; + let h2 = src[position++]; + if ((e3 & 128) > 0 || (f2 & 128) > 0 || (g2 & 128) > 0 || (h2 & 128) > 0) { + position -= 8; + return; + } + if (length < 10) { + if (length === 8) + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2); + else { + let i2 = src[position++]; + if ((i2 & 128) > 0) { + position -= 9; + return; + } + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2); + } + } else if (length < 12) { + let i2 = src[position++]; + let j2 = src[position++]; + if ((i2 & 128) > 0 || (j2 & 128) > 0) { + position -= 10; + return; + } + if (length < 11) + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2); + let k2 = src[position++]; + if ((k2 & 128) > 0) { + position -= 11; + return; + } + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2); + } else { + let i2 = src[position++]; + let j2 = src[position++]; + let k2 = src[position++]; + let l2 = src[position++]; + if ((i2 & 128) > 0 || (j2 & 128) > 0 || (k2 & 128) > 0 || (l2 & 128) > 0) { + position -= 12; + return; + } + if (length < 14) { + if (length === 12) + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2); + else { + let m2 = src[position++]; + if ((m2 & 128) > 0) { + position -= 13; + return; + } + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2, m2); + } + } else { + let m2 = src[position++]; + let n2 = src[position++]; + if ((m2 & 128) > 0 || (n2 & 128) > 0) { + position -= 14; + return; + } + if (length < 15) + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2, m2, n2); + let o2 = src[position++]; + if ((o2 & 128) > 0) { + position -= 15; + return; + } + return fromCharCode(a2, b2, c2, d2, e3, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2); + } + } + } + } +} +function readOnlyJSString() { + let token = src[position++]; + let length; + if (token < 192) { + length = token - 160; + } else { + switch (token) { + case 217: + length = src[position++]; + break; + case 218: + length = dataView.getUint16(position); + position += 2; + break; + case 219: + length = dataView.getUint32(position); + position += 4; + break; + default: + throw new Error("Expected string"); + } + } + return readStringJS(length); +} +function readBin(length) { + return currentUnpackr.copyBuffers ? Uint8Array.prototype.slice.call(src, position, position += length) : src.subarray(position, position += length); +} +function readExt(length) { + let type = src[position++]; + if (currentExtensions[type]) { + let end; + return currentExtensions[type](src.subarray(position, end = position += length), (readPosition) => { + position = readPosition; + try { + return read(); + } finally { + position = end; + } + }); + } else + throw new Error("Unknown extension type " + type); +} +var keyCache = new Array(4096); +function readKey() { + let length = src[position++]; + if (length >= 160 && length < 192) { + length = length - 160; + if (srcStringEnd >= position) + return srcString.slice(position - srcStringStart, (position += length) - srcStringStart); + else if (!(srcStringEnd == 0 && srcEnd < 180)) + return readFixedString(length); + } else { + position--; + return asSafeString(read()); + } + let key = (length << 5 ^ (length > 1 ? dataView.getUint16(position) : length > 0 ? src[position] : 0)) & 4095; + let entry = keyCache[key]; + let checkPosition = position; + let end = position + length - 3; + let chunk; + let i2 = 0; + if (entry && entry.bytes == length) { + while (checkPosition < end) { + chunk = dataView.getUint32(checkPosition); + if (chunk != entry[i2++]) { + checkPosition = 1879048192; + break; + } + checkPosition += 4; + } + end += 3; + while (checkPosition < end) { + chunk = src[checkPosition++]; + if (chunk != entry[i2++]) { + checkPosition = 1879048192; + break; + } + } + if (checkPosition === end) { + position = checkPosition; + return entry.string; + } + end -= 3; + checkPosition = position; + } + entry = []; + keyCache[key] = entry; + entry.bytes = length; + while (checkPosition < end) { + chunk = dataView.getUint32(checkPosition); + entry.push(chunk); + checkPosition += 4; + } + end += 3; + while (checkPosition < end) { + chunk = src[checkPosition++]; + entry.push(chunk); + } + let string2 = length < 16 ? shortStringInJS(length) : longStringInJS(length); + if (string2 != null) + return entry.string = string2; + return entry.string = readFixedString(length); +} +function asSafeString(property) { + if (typeof property === "string") + return property; + if (typeof property === "number" || typeof property === "boolean" || typeof property === "bigint") + return property.toString(); + if (property == null) + return property + ""; + if (currentUnpackr.allowArraysInMapKeys && Array.isArray(property) && property.flat().every((item) => ["string", "number", "boolean", "bigint"].includes(typeof item))) { + return property.flat().toString(); + } + throw new Error(`Invalid property type for record: ${typeof property}`); +} +var recordDefinition = (id, highByte) => { + let structure = read().map(asSafeString); + let firstByte = id; + if (highByte !== undefined) { + id = id < 32 ? -((highByte << 5) + id) : (highByte << 5) + id; + structure.highByte = highByte; + } + let existingStructure = currentStructures[id]; + if (existingStructure && (existingStructure.isShared || sequentialMode)) { + (currentStructures.restoreStructures || (currentStructures.restoreStructures = []))[id] = existingStructure; + } + currentStructures[id] = structure; + structure.read = createStructureReader(structure, firstByte); + return structure.read(); +}; +currentExtensions[0] = () => {}; +currentExtensions[0].noBuffer = true; +currentExtensions[66] = (data) => { + let headLength = data.byteLength % 8 || 8; + let head = BigInt(data[0] & 128 ? data[0] - 256 : data[0]); + for (let i2 = 1;i2 < headLength; i2++) { + head <<= BigInt(8); + head += BigInt(data[i2]); + } + if (data.byteLength !== headLength) { + let view = new DataView(data.buffer, data.byteOffset, data.byteLength); + let decode = (start, end) => { + let length = end - start; + if (length <= 40) { + let out = view.getBigUint64(start); + for (let i2 = start + 8;i2 < end; i2 += 8) { + out <<= BigInt(64n); + out |= view.getBigUint64(i2); + } + return out; + } + let middle = start + (length >> 4 << 3); + let left = decode(start, middle); + let right = decode(middle, end); + return left << BigInt((end - middle) * 8) | right; + }; + head = head << BigInt((view.byteLength - headLength) * 8) | decode(headLength, view.byteLength); + } + return head; +}; +var errors = { + Error, + EvalError, + RangeError, + ReferenceError, + SyntaxError, + TypeError, + URIError, + AggregateError: typeof AggregateError === "function" ? AggregateError : null +}; +currentExtensions[101] = () => { + let data = read(); + if (!errors[data[0]]) { + let error = Error(data[1], { cause: data[2] }); + error.name = data[0]; + return error; + } + return errors[data[0]](data[1], { cause: data[2] }); +}; +currentExtensions[105] = (data) => { + if (currentUnpackr.structuredClone === false) + throw new Error("Structured clone extension is disabled"); + let id = dataView.getUint32(position - 4); + if (!referenceMap) + referenceMap = new Map; + let token = src[position]; + let target; + if (token >= 144 && token < 160 || token == 220 || token == 221) + target = []; + else if (token >= 128 && token < 144 || token == 222 || token == 223) + target = new Map; + else if ((token >= 199 && token <= 201 || token >= 212 && token <= 216) && src[position + 1] === 115) + target = new Set; + else + target = {}; + let refEntry = { target }; + referenceMap.set(id, refEntry); + let targetProperties = read(); + if (!refEntry.used) { + return refEntry.target = targetProperties; + } else { + Object.assign(target, targetProperties); + } + if (target instanceof Map) + for (let [k2, v2] of targetProperties.entries()) + target.set(k2, v2); + if (target instanceof Set) + for (let i2 of Array.from(targetProperties)) + target.add(i2); + return target; +}; +currentExtensions[112] = (data) => { + if (currentUnpackr.structuredClone === false) + throw new Error("Structured clone extension is disabled"); + let id = dataView.getUint32(position - 4); + let refEntry = referenceMap.get(id); + refEntry.used = true; + return refEntry.target; +}; +currentExtensions[115] = () => new Set(read()); +var typedArrays = ["Int8", "Uint8", "Uint8Clamped", "Int16", "Uint16", "Int32", "Uint32", "Float32", "Float64", "BigInt64", "BigUint64"].map((type) => type + "Array"); +var glbl = typeof globalThis === "object" ? globalThis : window; +currentExtensions[116] = (data) => { + let typeCode = data[0]; + let buffer = Uint8Array.prototype.slice.call(data, 1).buffer; + let typedArrayName = typedArrays[typeCode]; + if (!typedArrayName) { + if (typeCode === 16) + return buffer; + if (typeCode === 17) + return new DataView(buffer); + throw new Error("Could not find typed array for code " + typeCode); + } + return new glbl[typedArrayName](buffer); +}; +currentExtensions[120] = () => { + let data = read(); + return new RegExp(data[0], data[1]); +}; +var TEMP_BUNDLE = []; +currentExtensions[98] = (data) => { + let dataSize = (data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]; + let dataPosition = position; + position += dataSize - data.length; + bundledStrings = TEMP_BUNDLE; + bundledStrings = [readOnlyJSString(), readOnlyJSString()]; + bundledStrings.position0 = 0; + bundledStrings.position1 = 0; + bundledStrings.postBundlePosition = position; + position = dataPosition; + return read(); +}; +currentExtensions[255] = (data) => { + if (data.length == 4) + return new Date((data[0] * 16777216 + (data[1] << 16) + (data[2] << 8) + data[3]) * 1000); + else if (data.length == 8) + return new Date(((data[0] << 22) + (data[1] << 14) + (data[2] << 6) + (data[3] >> 2)) / 1e6 + ((data[3] & 3) * 4294967296 + data[4] * 16777216 + (data[5] << 16) + (data[6] << 8) + data[7]) * 1000); + else if (data.length == 12) + return new Date(((data[0] << 24) + (data[1] << 16) + (data[2] << 8) + data[3]) / 1e6 + ((data[4] & 128 ? -281474976710656 : 0) + data[6] * 1099511627776 + data[7] * 4294967296 + data[8] * 16777216 + (data[9] << 16) + (data[10] << 8) + data[11]) * 1000); + else + return new Date("invalid"); +}; +function saveState(callback) { + if (onSaveState) + onSaveState(); + let savedSrcEnd = srcEnd; + let savedPosition = position; + let savedStringPosition = stringPosition; + let savedSrcStringStart = srcStringStart; + let savedSrcStringEnd = srcStringEnd; + let savedSrcString = srcString; + let savedStrings = strings; + let savedReferenceMap = referenceMap; + let savedBundledStrings = bundledStrings; + let savedSrc = new Uint8Array(src.slice(0, srcEnd)); + let savedStructures = currentStructures; + let savedStructuresContents = currentStructures.slice(0, currentStructures.length); + let savedPackr = currentUnpackr; + let savedSequentialMode = sequentialMode; + let value = callback(); + srcEnd = savedSrcEnd; + position = savedPosition; + stringPosition = savedStringPosition; + srcStringStart = savedSrcStringStart; + srcStringEnd = savedSrcStringEnd; + srcString = savedSrcString; + strings = savedStrings; + referenceMap = savedReferenceMap; + bundledStrings = savedBundledStrings; + src = savedSrc; + sequentialMode = savedSequentialMode; + currentStructures = savedStructures; + currentStructures.splice(0, currentStructures.length, ...savedStructuresContents); + currentUnpackr = savedPackr; + dataView = new DataView(src.buffer, src.byteOffset, src.byteLength); + return value; +} +function clearSource() { + src = null; + referenceMap = null; + currentStructures = null; +} +var mult10 = new Array(147); +for (let i2 = 0;i2 < 256; i2++) { + mult10[i2] = +("1e" + Math.floor(45.15 - i2 * 0.30103)); +} +var defaultUnpackr = new Unpackr({ useRecords: false }); +var unpack = defaultUnpackr.unpack; +var unpackMultiple = defaultUnpackr.unpackMultiple; +var decode = defaultUnpackr.unpack; +var f32Array = new Float32Array(1); +var u8Array = new Uint8Array(f32Array.buffer, 0, 4); +function setReadStruct(updatedReadStruct, loadedStructs, saveState2) { + readStruct = updatedReadStruct; + onLoadedStructures = loadedStructs; + onSaveState = saveState2; +} +// node_modules/.pnpm/msgpackr@1.11.5/node_modules/msgpackr/pack.js +var textEncoder; +try { + textEncoder = new TextEncoder; +} catch (error) {} +var extensions; +var extensionClasses; +var hasNodeBuffer = typeof Buffer !== "undefined"; +var ByteArrayAllocate = hasNodeBuffer ? function(length) { + return Buffer.allocUnsafeSlow(length); +} : Uint8Array; +var ByteArray = hasNodeBuffer ? Buffer : Uint8Array; +var MAX_BUFFER_SIZE = hasNodeBuffer ? 4294967296 : 2144337920; +var target; +var keysTarget; +var targetView; +var position2 = 0; +var safeEnd; +var bundledStrings2 = null; +var writeStructSlots; +var MAX_BUNDLE_SIZE = 21760; +var hasNonLatin = /[\u0080-\uFFFF]/; +var RECORD_SYMBOL = Symbol("record-id"); + +class Packr extends Unpackr { + constructor(options) { + super(options); + this.offset = 0; + let typeBuffer; + let start; + let hasSharedUpdate; + let structures; + let referenceMap2; + let encodeUtf8 = ByteArray.prototype.utf8Write ? function(string2, position3) { + return target.utf8Write(string2, position3, target.byteLength - position3); + } : textEncoder && textEncoder.encodeInto ? function(string2, position3) { + return textEncoder.encodeInto(string2, target.subarray(position3)).written; + } : false; + let packr = this; + if (!options) + options = {}; + let isSequential = options && options.sequential; + let hasSharedStructures = options.structures || options.saveStructures; + let maxSharedStructures = options.maxSharedStructures; + if (maxSharedStructures == null) + maxSharedStructures = hasSharedStructures ? 32 : 0; + if (maxSharedStructures > 8160) + throw new Error("Maximum maxSharedStructure is 8160"); + if (options.structuredClone && options.moreTypes == undefined) { + this.moreTypes = true; + } + let maxOwnStructures = options.maxOwnStructures; + if (maxOwnStructures == null) + maxOwnStructures = hasSharedStructures ? 32 : 64; + if (!this.structures && options.useRecords != false) + this.structures = []; + let useTwoByteRecords = maxSharedStructures > 32 || maxOwnStructures + maxSharedStructures > 64; + let sharedLimitId = maxSharedStructures + 64; + let maxStructureId = maxSharedStructures + maxOwnStructures + 64; + if (maxStructureId > 8256) { + throw new Error("Maximum maxSharedStructure + maxOwnStructure is 8192"); + } + let recordIdsToRemove = []; + let transitionsCount = 0; + let serializationsSinceTransitionRebuild = 0; + this.pack = this.encode = function(value, encodeOptions) { + if (!target) { + target = new ByteArrayAllocate(8192); + targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, 8192)); + position2 = 0; + } + safeEnd = target.length - 10; + if (safeEnd - position2 < 2048) { + target = new ByteArrayAllocate(target.length); + targetView = target.dataView || (target.dataView = new DataView(target.buffer, 0, target.length)); + safeEnd = target.length - 10; + position2 = 0; + } else + position2 = position2 + 7 & 2147483640; + start = position2; + if (encodeOptions & RESERVE_START_SPACE) + position2 += encodeOptions & 255; + referenceMap2 = packr.structuredClone ? new Map : null; + if (packr.bundleStrings && typeof value !== "string") { + bundledStrings2 = []; + bundledStrings2.size = Infinity; + } else + bundledStrings2 = null; + structures = packr.structures; + if (structures) { + if (structures.uninitialized) + structures = packr._mergeStructures(packr.getStructures()); + let sharedLength = structures.sharedLength || 0; + if (sharedLength > maxSharedStructures) { + throw new Error("Shared structures is larger than maximum shared structures, try increasing maxSharedStructures to " + structures.sharedLength); + } + if (!structures.transitions) { + structures.transitions = Object.create(null); + for (let i2 = 0;i2 < sharedLength; i2++) { + let keys = structures[i2]; + if (!keys) + continue; + let nextTransition, transition = structures.transitions; + for (let j2 = 0, l2 = keys.length;j2 < l2; j2++) { + let key = keys[j2]; + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + } + transition = nextTransition; + } + transition[RECORD_SYMBOL] = i2 + 64; + } + this.lastNamedStructuresLength = sharedLength; + } + if (!isSequential) { + structures.nextId = sharedLength + 64; + } + } + if (hasSharedUpdate) + hasSharedUpdate = false; + let encodingError; + try { + if (packr.randomAccessStructure && value && value.constructor && value.constructor === Object) + writeStruct(value); + else + pack(value); + let lastBundle = bundledStrings2; + if (bundledStrings2) + writeBundles(start, pack, 0); + if (referenceMap2 && referenceMap2.idsToInsert) { + let idsToInsert = referenceMap2.idsToInsert.sort((a2, b2) => a2.offset > b2.offset ? 1 : -1); + let i2 = idsToInsert.length; + let incrementPosition = -1; + while (lastBundle && i2 > 0) { + let insertionPoint = idsToInsert[--i2].offset + start; + if (insertionPoint < lastBundle.stringsPosition + start && incrementPosition === -1) + incrementPosition = 0; + if (insertionPoint > lastBundle.position + start) { + if (incrementPosition >= 0) + incrementPosition += 6; + } else { + if (incrementPosition >= 0) { + targetView.setUint32(lastBundle.position + start, targetView.getUint32(lastBundle.position + start) + incrementPosition); + incrementPosition = -1; + } + lastBundle = lastBundle.previous; + i2++; + } + } + if (incrementPosition >= 0 && lastBundle) { + targetView.setUint32(lastBundle.position + start, targetView.getUint32(lastBundle.position + start) + incrementPosition); + } + position2 += idsToInsert.length * 6; + if (position2 > safeEnd) + makeRoom(position2); + packr.offset = position2; + let serialized = insertIds(target.subarray(start, position2), idsToInsert); + referenceMap2 = null; + return serialized; + } + packr.offset = position2; + if (encodeOptions & REUSE_BUFFER_MODE) { + target.start = start; + target.end = position2; + return target; + } + return target.subarray(start, position2); + } catch (error) { + encodingError = error; + throw error; + } finally { + if (structures) { + resetStructures(); + if (hasSharedUpdate && packr.saveStructures) { + let sharedLength = structures.sharedLength || 0; + let returnBuffer = target.subarray(start, position2); + let newSharedData = prepareStructures(structures, packr); + if (!encodingError) { + if (packr.saveStructures(newSharedData, newSharedData.isCompatible) === false) { + return packr.pack(value, encodeOptions); + } + packr.lastNamedStructuresLength = sharedLength; + if (target.length > 1073741824) + target = null; + return returnBuffer; + } + } + } + if (target.length > 1073741824) + target = null; + if (encodeOptions & RESET_BUFFER_MODE) + position2 = start; + } + }; + const resetStructures = () => { + if (serializationsSinceTransitionRebuild < 10) + serializationsSinceTransitionRebuild++; + let sharedLength = structures.sharedLength || 0; + if (structures.length > sharedLength && !isSequential) + structures.length = sharedLength; + if (transitionsCount > 1e4) { + structures.transitions = null; + serializationsSinceTransitionRebuild = 0; + transitionsCount = 0; + if (recordIdsToRemove.length > 0) + recordIdsToRemove = []; + } else if (recordIdsToRemove.length > 0 && !isSequential) { + for (let i2 = 0, l2 = recordIdsToRemove.length;i2 < l2; i2++) { + recordIdsToRemove[i2][RECORD_SYMBOL] = 0; + } + recordIdsToRemove = []; + } + }; + const packArray = (value) => { + var length = value.length; + if (length < 16) { + target[position2++] = 144 | length; + } else if (length < 65536) { + target[position2++] = 220; + target[position2++] = length >> 8; + target[position2++] = length & 255; + } else { + target[position2++] = 221; + targetView.setUint32(position2, length); + position2 += 4; + } + for (let i2 = 0;i2 < length; i2++) { + pack(value[i2]); + } + }; + const pack = (value) => { + if (position2 > safeEnd) + target = makeRoom(position2); + var type = typeof value; + var length; + if (type === "string") { + let strLength = value.length; + if (bundledStrings2 && strLength >= 4 && strLength < 4096) { + if ((bundledStrings2.size += strLength) > MAX_BUNDLE_SIZE) { + let extStart; + let maxBytes2 = (bundledStrings2[0] ? bundledStrings2[0].length * 3 + bundledStrings2[1].length : 0) + 10; + if (position2 + maxBytes2 > safeEnd) + target = makeRoom(position2 + maxBytes2); + let lastBundle; + if (bundledStrings2.position) { + lastBundle = bundledStrings2; + target[position2] = 200; + position2 += 3; + target[position2++] = 98; + extStart = position2 - start; + position2 += 4; + writeBundles(start, pack, 0); + targetView.setUint16(extStart + start - 3, position2 - start - extStart); + } else { + target[position2++] = 214; + target[position2++] = 98; + extStart = position2 - start; + position2 += 4; + } + bundledStrings2 = ["", ""]; + bundledStrings2.previous = lastBundle; + bundledStrings2.size = 0; + bundledStrings2.position = extStart; + } + let twoByte = hasNonLatin.test(value); + bundledStrings2[twoByte ? 0 : 1] += value; + target[position2++] = 193; + pack(twoByte ? -strLength : strLength); + return; + } + let headerSize; + if (strLength < 32) { + headerSize = 1; + } else if (strLength < 256) { + headerSize = 2; + } else if (strLength < 65536) { + headerSize = 3; + } else { + headerSize = 5; + } + let maxBytes = strLength * 3; + if (position2 + maxBytes > safeEnd) + target = makeRoom(position2 + maxBytes); + if (strLength < 64 || !encodeUtf8) { + let i2, c1, c2, strPosition = position2 + headerSize; + for (i2 = 0;i2 < strLength; i2++) { + c1 = value.charCodeAt(i2); + if (c1 < 128) { + target[strPosition++] = c1; + } else if (c1 < 2048) { + target[strPosition++] = c1 >> 6 | 192; + target[strPosition++] = c1 & 63 | 128; + } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i2 + 1)) & 64512) === 56320) { + c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); + i2++; + target[strPosition++] = c1 >> 18 | 240; + target[strPosition++] = c1 >> 12 & 63 | 128; + target[strPosition++] = c1 >> 6 & 63 | 128; + target[strPosition++] = c1 & 63 | 128; + } else { + target[strPosition++] = c1 >> 12 | 224; + target[strPosition++] = c1 >> 6 & 63 | 128; + target[strPosition++] = c1 & 63 | 128; + } + } + length = strPosition - position2 - headerSize; + } else { + length = encodeUtf8(value, position2 + headerSize); + } + if (length < 32) { + target[position2++] = 160 | length; + } else if (length < 256) { + if (headerSize < 2) { + target.copyWithin(position2 + 2, position2 + 1, position2 + 1 + length); + } + target[position2++] = 217; + target[position2++] = length; + } else if (length < 65536) { + if (headerSize < 3) { + target.copyWithin(position2 + 3, position2 + 2, position2 + 2 + length); + } + target[position2++] = 218; + target[position2++] = length >> 8; + target[position2++] = length & 255; + } else { + if (headerSize < 5) { + target.copyWithin(position2 + 5, position2 + 3, position2 + 3 + length); + } + target[position2++] = 219; + targetView.setUint32(position2, length); + position2 += 4; + } + position2 += length; + } else if (type === "number") { + if (value >>> 0 === value) { + if (value < 32 || value < 128 && this.useRecords === false || value < 64 && !this.randomAccessStructure) { + target[position2++] = value; + } else if (value < 256) { + target[position2++] = 204; + target[position2++] = value; + } else if (value < 65536) { + target[position2++] = 205; + target[position2++] = value >> 8; + target[position2++] = value & 255; + } else { + target[position2++] = 206; + targetView.setUint32(position2, value); + position2 += 4; + } + } else if (value >> 0 === value) { + if (value >= -32) { + target[position2++] = 256 + value; + } else if (value >= -128) { + target[position2++] = 208; + target[position2++] = value + 256; + } else if (value >= -32768) { + target[position2++] = 209; + targetView.setInt16(position2, value); + position2 += 2; + } else { + target[position2++] = 210; + targetView.setInt32(position2, value); + position2 += 4; + } + } else { + let useFloat32; + if ((useFloat32 = this.useFloat32) > 0 && value < 4294967296 && value >= -2147483648) { + target[position2++] = 202; + targetView.setFloat32(position2, value); + let xShifted; + if (useFloat32 < 4 || (xShifted = value * mult10[(target[position2] & 127) << 1 | target[position2 + 1] >> 7]) >> 0 === xShifted) { + position2 += 4; + return; + } else + position2--; + } + target[position2++] = 203; + targetView.setFloat64(position2, value); + position2 += 8; + } + } else if (type === "object" || type === "function") { + if (!value) + target[position2++] = 192; + else { + if (referenceMap2) { + let referee = referenceMap2.get(value); + if (referee) { + if (!referee.id) { + let idsToInsert = referenceMap2.idsToInsert || (referenceMap2.idsToInsert = []); + referee.id = idsToInsert.push(referee); + } + target[position2++] = 214; + target[position2++] = 112; + targetView.setUint32(position2, referee.id); + position2 += 4; + return; + } else + referenceMap2.set(value, { offset: position2 - start }); + } + let constructor = value.constructor; + if (constructor === Object) { + writeObject(value); + } else if (constructor === Array) { + packArray(value); + } else if (constructor === Map) { + if (this.mapAsEmptyObject) + target[position2++] = 128; + else { + length = value.size; + if (length < 16) { + target[position2++] = 128 | length; + } else if (length < 65536) { + target[position2++] = 222; + target[position2++] = length >> 8; + target[position2++] = length & 255; + } else { + target[position2++] = 223; + targetView.setUint32(position2, length); + position2 += 4; + } + for (let [key, entryValue] of value) { + pack(key); + pack(entryValue); + } + } + } else { + for (let i2 = 0, l2 = extensions.length;i2 < l2; i2++) { + let extensionClass = extensionClasses[i2]; + if (value instanceof extensionClass) { + let extension = extensions[i2]; + if (extension.write) { + if (extension.type) { + target[position2++] = 212; + target[position2++] = extension.type; + target[position2++] = 0; + } + let writeResult = extension.write.call(this, value); + if (writeResult === value) { + if (Array.isArray(value)) { + packArray(value); + } else { + writeObject(value); + } + } else { + pack(writeResult); + } + return; + } + let currentTarget = target; + let currentTargetView = targetView; + let currentPosition = position2; + target = null; + let result; + try { + result = extension.pack.call(this, value, (size) => { + target = currentTarget; + currentTarget = null; + position2 += size; + if (position2 > safeEnd) + makeRoom(position2); + return { + target, + targetView, + position: position2 - size + }; + }, pack); + } finally { + if (currentTarget) { + target = currentTarget; + targetView = currentTargetView; + position2 = currentPosition; + safeEnd = target.length - 10; + } + } + if (result) { + if (result.length + position2 > safeEnd) + makeRoom(result.length + position2); + position2 = writeExtensionData(result, target, position2, extension.type); + } + return; + } + } + if (Array.isArray(value)) { + packArray(value); + } else { + if (value.toJSON) { + const json3 = value.toJSON(); + if (json3 !== value) + return pack(json3); + } + if (type === "function") + return pack(this.writeFunction && this.writeFunction(value)); + writeObject(value); + } + } + } + } else if (type === "boolean") { + target[position2++] = value ? 195 : 194; + } else if (type === "bigint") { + if (value < 9223372036854776000 && value >= -9223372036854776000) { + target[position2++] = 211; + targetView.setBigInt64(position2, value); + } else if (value < 18446744073709552000 && value > 0) { + target[position2++] = 207; + targetView.setBigUint64(position2, value); + } else { + if (this.largeBigIntToFloat) { + target[position2++] = 203; + targetView.setFloat64(position2, Number(value)); + } else if (this.largeBigIntToString) { + return pack(value.toString()); + } else if (this.useBigIntExtension || this.moreTypes) { + let empty = value < 0 ? BigInt(-1) : BigInt(0); + let array2; + if (value >> BigInt(65536) === empty) { + let mask = BigInt(18446744073709552000) - BigInt(1); + let chunks = []; + while (true) { + chunks.push(value & mask); + if (value >> BigInt(63) === empty) + break; + value >>= BigInt(64); + } + array2 = new Uint8Array(new BigUint64Array(chunks).buffer); + array2.reverse(); + } else { + let invert = value < 0; + let string2 = (invert ? ~value : value).toString(16); + if (string2.length % 2) { + string2 = "0" + string2; + } else if (parseInt(string2.charAt(0), 16) >= 8) { + string2 = "00" + string2; + } + if (hasNodeBuffer) { + array2 = Buffer.from(string2, "hex"); + } else { + array2 = new Uint8Array(string2.length / 2); + for (let i2 = 0;i2 < array2.length; i2++) { + array2[i2] = parseInt(string2.slice(i2 * 2, i2 * 2 + 2), 16); + } + } + if (invert) { + for (let i2 = 0;i2 < array2.length; i2++) + array2[i2] = ~array2[i2]; + } + } + if (array2.length + position2 > safeEnd) + makeRoom(array2.length + position2); + position2 = writeExtensionData(array2, target, position2, 66); + return; + } else { + throw new RangeError(value + " was too large to fit in MessagePack 64-bit integer format, use" + " useBigIntExtension, or set largeBigIntToFloat to convert to float-64, or set" + " largeBigIntToString to convert to string"); + } + } + position2 += 8; + } else if (type === "undefined") { + if (this.encodeUndefinedAsNil) + target[position2++] = 192; + else { + target[position2++] = 212; + target[position2++] = 0; + target[position2++] = 0; + } + } else { + throw new Error("Unknown type: " + type); + } + }; + const writePlainObject = this.variableMapSize || this.coercibleKeyAsNumber || this.skipValues ? (object2) => { + let keys; + if (this.skipValues) { + keys = []; + for (let key2 in object2) { + if ((typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key2)) && !this.skipValues.includes(object2[key2])) + keys.push(key2); + } + } else { + keys = Object.keys(object2); + } + let length = keys.length; + if (length < 16) { + target[position2++] = 128 | length; + } else if (length < 65536) { + target[position2++] = 222; + target[position2++] = length >> 8; + target[position2++] = length & 255; + } else { + target[position2++] = 223; + targetView.setUint32(position2, length); + position2 += 4; + } + let key; + if (this.coercibleKeyAsNumber) { + for (let i2 = 0;i2 < length; i2++) { + key = keys[i2]; + let num = Number(key); + pack(isNaN(num) ? key : num); + pack(object2[key]); + } + } else { + for (let i2 = 0;i2 < length; i2++) { + pack(key = keys[i2]); + pack(object2[key]); + } + } + } : (object2) => { + target[position2++] = 222; + let objectOffset = position2 - start; + position2 += 2; + let size = 0; + for (let key in object2) { + if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { + pack(key); + pack(object2[key]); + size++; + } + } + if (size > 65535) { + throw new Error("Object is too large to serialize with fast 16-bit map size," + ' use the "variableMapSize" option to serialize this object'); + } + target[objectOffset++ + start] = size >> 8; + target[objectOffset + start] = size & 255; + }; + const writeRecord = this.useRecords === false ? writePlainObject : options.progressiveRecords && !useTwoByteRecords ? (object2) => { + let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); + let objectOffset = position2++ - start; + let wroteKeys; + for (let key in object2) { + if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { + nextTransition = transition[key]; + if (nextTransition) + transition = nextTransition; + else { + let keys = Object.keys(object2); + let lastTransition = transition; + transition = structures.transitions; + let newTransitions = 0; + for (let i2 = 0, l2 = keys.length;i2 < l2; i2++) { + let key2 = keys[i2]; + nextTransition = transition[key2]; + if (!nextTransition) { + nextTransition = transition[key2] = Object.create(null); + newTransitions++; + } + transition = nextTransition; + } + if (objectOffset + start + 1 == position2) { + position2--; + newRecord(transition, keys, newTransitions); + } else + insertNewRecord(transition, keys, objectOffset, newTransitions); + wroteKeys = true; + transition = lastTransition[key]; + } + pack(object2[key]); + } + } + if (!wroteKeys) { + let recordId = transition[RECORD_SYMBOL]; + if (recordId) + target[objectOffset + start] = recordId; + else + insertNewRecord(transition, Object.keys(object2), objectOffset, 0); + } + } : (object2) => { + let nextTransition, transition = structures.transitions || (structures.transitions = Object.create(null)); + let newTransitions = 0; + for (let key in object2) + if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { + nextTransition = transition[key]; + if (!nextTransition) { + nextTransition = transition[key] = Object.create(null); + newTransitions++; + } + transition = nextTransition; + } + let recordId = transition[RECORD_SYMBOL]; + if (recordId) { + if (recordId >= 96 && useTwoByteRecords) { + target[position2++] = ((recordId -= 96) & 31) + 96; + target[position2++] = recordId >> 5; + } else + target[position2++] = recordId; + } else { + newRecord(transition, transition.__keys__ || Object.keys(object2), newTransitions); + } + for (let key in object2) + if (typeof object2.hasOwnProperty !== "function" || object2.hasOwnProperty(key)) { + pack(object2[key]); + } + }; + const checkUseRecords = typeof this.useRecords == "function" && this.useRecords; + const writeObject = checkUseRecords ? (object2) => { + checkUseRecords(object2) ? writeRecord(object2) : writePlainObject(object2); + } : writeRecord; + const makeRoom = (end) => { + let newSize; + if (end > 16777216) { + if (end - start > MAX_BUFFER_SIZE) + throw new Error("Packed buffer would be larger than maximum buffer size"); + newSize = Math.min(MAX_BUFFER_SIZE, Math.round(Math.max((end - start) * (end > 67108864 ? 1.25 : 2), 4194304) / 4096) * 4096); + } else + newSize = (Math.max(end - start << 2, target.length - 1) >> 12) + 1 << 12; + let newBuffer = new ByteArrayAllocate(newSize); + targetView = newBuffer.dataView || (newBuffer.dataView = new DataView(newBuffer.buffer, 0, newSize)); + end = Math.min(end, target.length); + if (target.copy) + target.copy(newBuffer, 0, start, end); + else + newBuffer.set(target.slice(start, end)); + position2 -= start; + start = 0; + safeEnd = newBuffer.length - 10; + return target = newBuffer; + }; + const newRecord = (transition, keys, newTransitions) => { + let recordId = structures.nextId; + if (!recordId) + recordId = 64; + if (recordId < sharedLimitId && this.shouldShareStructure && !this.shouldShareStructure(keys)) { + recordId = structures.nextOwnId; + if (!(recordId < maxStructureId)) + recordId = sharedLimitId; + structures.nextOwnId = recordId + 1; + } else { + if (recordId >= maxStructureId) + recordId = sharedLimitId; + structures.nextId = recordId + 1; + } + let highByte = keys.highByte = recordId >= 96 && useTwoByteRecords ? recordId - 96 >> 5 : -1; + transition[RECORD_SYMBOL] = recordId; + transition.__keys__ = keys; + structures[recordId - 64] = keys; + if (recordId < sharedLimitId) { + keys.isShared = true; + structures.sharedLength = recordId - 63; + hasSharedUpdate = true; + if (highByte >= 0) { + target[position2++] = (recordId & 31) + 96; + target[position2++] = highByte; + } else { + target[position2++] = recordId; + } + } else { + if (highByte >= 0) { + target[position2++] = 213; + target[position2++] = 114; + target[position2++] = (recordId & 31) + 96; + target[position2++] = highByte; + } else { + target[position2++] = 212; + target[position2++] = 114; + target[position2++] = recordId; + } + if (newTransitions) + transitionsCount += serializationsSinceTransitionRebuild * newTransitions; + if (recordIdsToRemove.length >= maxOwnStructures) + recordIdsToRemove.shift()[RECORD_SYMBOL] = 0; + recordIdsToRemove.push(transition); + pack(keys); + } + }; + const insertNewRecord = (transition, keys, insertionOffset, newTransitions) => { + let mainTarget = target; + let mainPosition = position2; + let mainSafeEnd = safeEnd; + let mainStart = start; + target = keysTarget; + position2 = 0; + start = 0; + if (!target) + keysTarget = target = new ByteArrayAllocate(8192); + safeEnd = target.length - 10; + newRecord(transition, keys, newTransitions); + keysTarget = target; + let keysPosition = position2; + target = mainTarget; + position2 = mainPosition; + safeEnd = mainSafeEnd; + start = mainStart; + if (keysPosition > 1) { + let newEnd = position2 + keysPosition - 1; + if (newEnd > safeEnd) + makeRoom(newEnd); + let insertionPosition = insertionOffset + start; + target.copyWithin(insertionPosition + keysPosition, insertionPosition + 1, position2); + target.set(keysTarget.slice(0, keysPosition), insertionPosition); + position2 = newEnd; + } else { + target[insertionOffset + start] = keysTarget[0]; + } + }; + const writeStruct = (object2) => { + let newPosition = writeStructSlots(object2, target, start, position2, structures, makeRoom, (value, newPosition2, notifySharedUpdate) => { + if (notifySharedUpdate) + return hasSharedUpdate = true; + position2 = newPosition2; + let startTarget = target; + pack(value); + resetStructures(); + if (startTarget !== target) { + return { position: position2, targetView, target }; + } + return position2; + }, this); + if (newPosition === 0) + return writeObject(object2); + position2 = newPosition; + }; + } + useBuffer(buffer) { + target = buffer; + target.dataView || (target.dataView = new DataView(target.buffer, target.byteOffset, target.byteLength)); + targetView = target.dataView; + position2 = 0; + } + set position(value) { + position2 = value; + } + get position() { + return position2; + } + clearSharedData() { + if (this.structures) + this.structures = []; + if (this.typedStructs) + this.typedStructs = []; + } +} +extensionClasses = [Date, Set, Error, RegExp, ArrayBuffer, Object.getPrototypeOf(Uint8Array.prototype).constructor, DataView, C1Type]; +extensions = [{ + pack(date4, allocateForWrite, pack) { + let seconds = date4.getTime() / 1000; + if ((this.useTimestamp32 || date4.getMilliseconds() === 0) && seconds >= 0 && seconds < 4294967296) { + let { target: target2, targetView: targetView2, position: position3 } = allocateForWrite(6); + target2[position3++] = 214; + target2[position3++] = 255; + targetView2.setUint32(position3, seconds); + } else if (seconds > 0 && seconds < 4294967296) { + let { target: target2, targetView: targetView2, position: position3 } = allocateForWrite(10); + target2[position3++] = 215; + target2[position3++] = 255; + targetView2.setUint32(position3, date4.getMilliseconds() * 4000000 + (seconds / 1000 / 4294967296 >> 0)); + targetView2.setUint32(position3 + 4, seconds); + } else if (isNaN(seconds)) { + if (this.onInvalidDate) { + allocateForWrite(0); + return pack(this.onInvalidDate()); + } + let { target: target2, targetView: targetView2, position: position3 } = allocateForWrite(3); + target2[position3++] = 212; + target2[position3++] = 255; + target2[position3++] = 255; + } else { + let { target: target2, targetView: targetView2, position: position3 } = allocateForWrite(15); + target2[position3++] = 199; + target2[position3++] = 12; + target2[position3++] = 255; + targetView2.setUint32(position3, date4.getMilliseconds() * 1e6); + targetView2.setBigInt64(position3 + 4, BigInt(Math.floor(seconds))); + } + } +}, { + pack(set, allocateForWrite, pack) { + if (this.setAsEmptyObject) { + allocateForWrite(0); + return pack({}); + } + let array2 = Array.from(set); + let { target: target2, position: position3 } = allocateForWrite(this.moreTypes ? 3 : 0); + if (this.moreTypes) { + target2[position3++] = 212; + target2[position3++] = 115; + target2[position3++] = 0; + } + pack(array2); + } +}, { + pack(error, allocateForWrite, pack) { + let { target: target2, position: position3 } = allocateForWrite(this.moreTypes ? 3 : 0); + if (this.moreTypes) { + target2[position3++] = 212; + target2[position3++] = 101; + target2[position3++] = 0; + } + pack([error.name, error.message, error.cause]); + } +}, { + pack(regex, allocateForWrite, pack) { + let { target: target2, position: position3 } = allocateForWrite(this.moreTypes ? 3 : 0); + if (this.moreTypes) { + target2[position3++] = 212; + target2[position3++] = 120; + target2[position3++] = 0; + } + pack([regex.source, regex.flags]); + } +}, { + pack(arrayBuffer, allocateForWrite) { + if (this.moreTypes) + writeExtBuffer(arrayBuffer, 16, allocateForWrite); + else + writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite); + } +}, { + pack(typedArray, allocateForWrite) { + let constructor = typedArray.constructor; + if (constructor !== ByteArray && this.moreTypes) + writeExtBuffer(typedArray, typedArrays.indexOf(constructor.name), allocateForWrite); + else + writeBuffer(typedArray, allocateForWrite); + } +}, { + pack(arrayBuffer, allocateForWrite) { + if (this.moreTypes) + writeExtBuffer(arrayBuffer, 17, allocateForWrite); + else + writeBuffer(hasNodeBuffer ? Buffer.from(arrayBuffer) : new Uint8Array(arrayBuffer), allocateForWrite); + } +}, { + pack(c1, allocateForWrite) { + let { target: target2, position: position3 } = allocateForWrite(1); + target2[position3] = 193; + } +}]; +function writeExtBuffer(typedArray, type, allocateForWrite, encode) { + let length = typedArray.byteLength; + if (length + 1 < 256) { + var { target: target2, position: position3 } = allocateForWrite(4 + length); + target2[position3++] = 199; + target2[position3++] = length + 1; + } else if (length + 1 < 65536) { + var { target: target2, position: position3 } = allocateForWrite(5 + length); + target2[position3++] = 200; + target2[position3++] = length + 1 >> 8; + target2[position3++] = length + 1 & 255; + } else { + var { target: target2, position: position3, targetView: targetView2 } = allocateForWrite(7 + length); + target2[position3++] = 201; + targetView2.setUint32(position3, length + 1); + position3 += 4; + } + target2[position3++] = 116; + target2[position3++] = type; + if (!typedArray.buffer) + typedArray = new Uint8Array(typedArray); + target2.set(new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength), position3); +} +function writeBuffer(buffer, allocateForWrite) { + let length = buffer.byteLength; + var target2, position3; + if (length < 256) { + var { target: target2, position: position3 } = allocateForWrite(length + 2); + target2[position3++] = 196; + target2[position3++] = length; + } else if (length < 65536) { + var { target: target2, position: position3 } = allocateForWrite(length + 3); + target2[position3++] = 197; + target2[position3++] = length >> 8; + target2[position3++] = length & 255; + } else { + var { target: target2, position: position3, targetView: targetView2 } = allocateForWrite(length + 5); + target2[position3++] = 198; + targetView2.setUint32(position3, length); + position3 += 4; + } + target2.set(buffer, position3); +} +function writeExtensionData(result, target2, position3, type) { + let length = result.length; + switch (length) { + case 1: + target2[position3++] = 212; + break; + case 2: + target2[position3++] = 213; + break; + case 4: + target2[position3++] = 214; + break; + case 8: + target2[position3++] = 215; + break; + case 16: + target2[position3++] = 216; + break; + default: + if (length < 256) { + target2[position3++] = 199; + target2[position3++] = length; + } else if (length < 65536) { + target2[position3++] = 200; + target2[position3++] = length >> 8; + target2[position3++] = length & 255; + } else { + target2[position3++] = 201; + target2[position3++] = length >> 24; + target2[position3++] = length >> 16 & 255; + target2[position3++] = length >> 8 & 255; + target2[position3++] = length & 255; + } + } + target2[position3++] = type; + target2.set(result, position3); + position3 += length; + return position3; +} +function insertIds(serialized, idsToInsert) { + let nextId; + let distanceToMove = idsToInsert.length * 6; + let lastEnd = serialized.length - distanceToMove; + while (nextId = idsToInsert.pop()) { + let offset = nextId.offset; + let id = nextId.id; + serialized.copyWithin(offset + distanceToMove, offset, lastEnd); + distanceToMove -= 6; + let position3 = offset + distanceToMove; + serialized[position3++] = 214; + serialized[position3++] = 105; + serialized[position3++] = id >> 24; + serialized[position3++] = id >> 16 & 255; + serialized[position3++] = id >> 8 & 255; + serialized[position3++] = id & 255; + lastEnd = offset; + } + return serialized; +} +function writeBundles(start, pack, incrementPosition) { + if (bundledStrings2.length > 0) { + targetView.setUint32(bundledStrings2.position + start, position2 + incrementPosition - bundledStrings2.position - start); + bundledStrings2.stringsPosition = position2 - start; + let writeStrings = bundledStrings2; + bundledStrings2 = null; + pack(writeStrings[0]); + pack(writeStrings[1]); + } +} +function prepareStructures(structures, packr) { + structures.isCompatible = (existingStructures) => { + let compatible = !existingStructures || (packr.lastNamedStructuresLength || 0) === existingStructures.length; + if (!compatible) + packr._mergeStructures(existingStructures); + return compatible; + }; + return structures; +} +function setWriteStructSlots(writeSlots, makeStructures) { + writeStructSlots = writeSlots; + prepareStructures = makeStructures; +} +var defaultPackr = new Packr({ useRecords: false }); +var pack = defaultPackr.pack; +var encode = defaultPackr.pack; +var REUSE_BUFFER_MODE = 512; +var RESET_BUFFER_MODE = 1024; +var RESERVE_START_SPACE = 2048; +// node_modules/.pnpm/msgpackr@1.11.5/node_modules/msgpackr/struct.js +var ASCII = 3; +var NUMBER = 0; +var UTF8 = 2; +var OBJECT_DATA = 1; +var DATE = 16; +var TYPE_NAMES = ["num", "object", "string", "ascii"]; +TYPE_NAMES[DATE] = "date"; +var float32Headers = [false, true, true, false, false, true, true, false]; +var evalSupported; +try { + new Function(""); + evalSupported = true; +} catch (error) {} +var updatedPosition; +var hasNodeBuffer2 = typeof Buffer !== "undefined"; +var textEncoder2; +var currentSource; +try { + textEncoder2 = new TextEncoder; +} catch (error) {} +var encodeUtf8 = hasNodeBuffer2 ? function(target2, string2, position3) { + return target2.utf8Write(string2, position3, target2.byteLength - position3); +} : textEncoder2 && textEncoder2.encodeInto ? function(target2, string2, position3) { + return textEncoder2.encodeInto(string2, target2.subarray(position3)).written; +} : false; +var TYPE = Symbol("type"); +var PARENT = Symbol("parent"); +setWriteStructSlots(writeStruct, prepareStructures2); +function writeStruct(object2, target2, encodingStart, position3, structures, makeRoom, pack2, packr) { + let typedStructs = packr.typedStructs || (packr.typedStructs = []); + let targetView2 = target2.dataView; + let refsStartPosition = (typedStructs.lastStringStart || 100) + position3; + let safeEnd2 = target2.length - 10; + let start = position3; + if (position3 > safeEnd2) { + target2 = makeRoom(position3); + targetView2 = target2.dataView; + position3 -= encodingStart; + start -= encodingStart; + refsStartPosition -= encodingStart; + encodingStart = 0; + safeEnd2 = target2.length - 10; + } + let refOffset, refPosition = refsStartPosition; + let transition = typedStructs.transitions || (typedStructs.transitions = Object.create(null)); + let nextId = typedStructs.nextId || typedStructs.length; + let headerSize = nextId < 15 ? 1 : nextId < 240 ? 2 : nextId < 61440 ? 3 : nextId < 15728640 ? 4 : 0; + if (headerSize === 0) + return 0; + position3 += headerSize; + let queuedReferences = []; + let usedAscii0; + let keyIndex = 0; + for (let key in object2) { + let value = object2[key]; + let nextTransition = transition[key]; + if (!nextTransition) { + transition[key] = nextTransition = { + key, + parent: transition, + enumerationOffset: 0, + ascii0: null, + ascii8: null, + num8: null, + string16: null, + object16: null, + num32: null, + float64: null, + date64: null + }; + } + if (position3 > safeEnd2) { + target2 = makeRoom(position3); + targetView2 = target2.dataView; + position3 -= encodingStart; + start -= encodingStart; + refsStartPosition -= encodingStart; + refPosition -= encodingStart; + encodingStart = 0; + safeEnd2 = target2.length - 10; + } + switch (typeof value) { + case "number": + let number2 = value; + if (nextId < 200 || !nextTransition.num64) { + if (number2 >> 0 === number2 && number2 < 536870912 && number2 > -520093696) { + if (number2 < 246 && number2 >= 0 && (nextTransition.num8 && !(nextId > 200 && nextTransition.num32) || number2 < 32 && !nextTransition.num32)) { + transition = nextTransition.num8 || createTypeTransition(nextTransition, NUMBER, 1); + target2[position3++] = number2; + } else { + transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4); + targetView2.setUint32(position3, number2, true); + position3 += 4; + } + break; + } else if (number2 < 4294967296 && number2 >= -2147483648) { + targetView2.setFloat32(position3, number2, true); + if (float32Headers[target2[position3 + 3] >>> 5]) { + let xShifted; + if ((xShifted = number2 * mult10[(target2[position3 + 3] & 127) << 1 | target2[position3 + 2] >> 7]) >> 0 === xShifted) { + transition = nextTransition.num32 || createTypeTransition(nextTransition, NUMBER, 4); + position3 += 4; + break; + } + } + } + } + transition = nextTransition.num64 || createTypeTransition(nextTransition, NUMBER, 8); + targetView2.setFloat64(position3, number2, true); + position3 += 8; + break; + case "string": + let strLength = value.length; + refOffset = refPosition - refsStartPosition; + if ((strLength << 2) + refPosition > safeEnd2) { + target2 = makeRoom((strLength << 2) + refPosition); + targetView2 = target2.dataView; + position3 -= encodingStart; + start -= encodingStart; + refsStartPosition -= encodingStart; + refPosition -= encodingStart; + encodingStart = 0; + safeEnd2 = target2.length - 10; + } + if (strLength > 65280 + refOffset >> 2) { + queuedReferences.push(key, value, position3 - start); + break; + } + let isNotAscii; + let strStart = refPosition; + if (strLength < 64) { + let i2, c1, c2; + for (i2 = 0;i2 < strLength; i2++) { + c1 = value.charCodeAt(i2); + if (c1 < 128) { + target2[refPosition++] = c1; + } else if (c1 < 2048) { + isNotAscii = true; + target2[refPosition++] = c1 >> 6 | 192; + target2[refPosition++] = c1 & 63 | 128; + } else if ((c1 & 64512) === 55296 && ((c2 = value.charCodeAt(i2 + 1)) & 64512) === 56320) { + isNotAscii = true; + c1 = 65536 + ((c1 & 1023) << 10) + (c2 & 1023); + i2++; + target2[refPosition++] = c1 >> 18 | 240; + target2[refPosition++] = c1 >> 12 & 63 | 128; + target2[refPosition++] = c1 >> 6 & 63 | 128; + target2[refPosition++] = c1 & 63 | 128; + } else { + isNotAscii = true; + target2[refPosition++] = c1 >> 12 | 224; + target2[refPosition++] = c1 >> 6 & 63 | 128; + target2[refPosition++] = c1 & 63 | 128; + } + } + } else { + refPosition += encodeUtf8(target2, value, refPosition); + isNotAscii = refPosition - strStart > strLength; + } + if (refOffset < 160 || refOffset < 246 && (nextTransition.ascii8 || nextTransition.string8)) { + if (isNotAscii) { + if (!(transition = nextTransition.string8)) { + if (typedStructs.length > 10 && (transition = nextTransition.ascii8)) { + transition.__type = UTF8; + nextTransition.ascii8 = null; + nextTransition.string8 = transition; + pack2(null, 0, true); + } else { + transition = createTypeTransition(nextTransition, UTF8, 1); + } + } + } else if (refOffset === 0 && !usedAscii0) { + usedAscii0 = true; + transition = nextTransition.ascii0 || createTypeTransition(nextTransition, ASCII, 0); + break; + } else if (!(transition = nextTransition.ascii8) && !(typedStructs.length > 10 && (transition = nextTransition.string8))) + transition = createTypeTransition(nextTransition, ASCII, 1); + target2[position3++] = refOffset; + } else { + transition = nextTransition.string16 || createTypeTransition(nextTransition, UTF8, 2); + targetView2.setUint16(position3, refOffset, true); + position3 += 2; + } + break; + case "object": + if (value) { + if (value.constructor === Date) { + transition = nextTransition.date64 || createTypeTransition(nextTransition, DATE, 8); + targetView2.setFloat64(position3, value.getTime(), true); + position3 += 8; + } else { + queuedReferences.push(key, value, keyIndex); + } + break; + } else { + nextTransition = anyType(nextTransition, position3, targetView2, -10); + if (nextTransition) { + transition = nextTransition; + position3 = updatedPosition; + } else + queuedReferences.push(key, value, keyIndex); + } + break; + case "boolean": + transition = nextTransition.num8 || nextTransition.ascii8 || createTypeTransition(nextTransition, NUMBER, 1); + target2[position3++] = value ? 249 : 248; + break; + case "undefined": + nextTransition = anyType(nextTransition, position3, targetView2, -9); + if (nextTransition) { + transition = nextTransition; + position3 = updatedPosition; + } else + queuedReferences.push(key, value, keyIndex); + break; + default: + queuedReferences.push(key, value, keyIndex); + } + keyIndex++; + } + for (let i2 = 0, l2 = queuedReferences.length;i2 < l2; ) { + let key = queuedReferences[i2++]; + let value = queuedReferences[i2++]; + let propertyIndex = queuedReferences[i2++]; + let nextTransition = transition[key]; + if (!nextTransition) { + transition[key] = nextTransition = { + key, + parent: transition, + enumerationOffset: propertyIndex - keyIndex, + ascii0: null, + ascii8: null, + num8: null, + string16: null, + object16: null, + num32: null, + float64: null + }; + } + let newPosition; + if (value) { + let size; + refOffset = refPosition - refsStartPosition; + if (refOffset < 65280) { + transition = nextTransition.object16; + if (transition) + size = 2; + else if (transition = nextTransition.object32) + size = 4; + else { + transition = createTypeTransition(nextTransition, OBJECT_DATA, 2); + size = 2; + } + } else { + transition = nextTransition.object32 || createTypeTransition(nextTransition, OBJECT_DATA, 4); + size = 4; + } + newPosition = pack2(value, refPosition); + if (typeof newPosition === "object") { + refPosition = newPosition.position; + targetView2 = newPosition.targetView; + target2 = newPosition.target; + refsStartPosition -= encodingStart; + position3 -= encodingStart; + start -= encodingStart; + encodingStart = 0; + } else + refPosition = newPosition; + if (size === 2) { + targetView2.setUint16(position3, refOffset, true); + position3 += 2; + } else { + targetView2.setUint32(position3, refOffset, true); + position3 += 4; + } + } else { + transition = nextTransition.object16 || createTypeTransition(nextTransition, OBJECT_DATA, 2); + targetView2.setInt16(position3, value === null ? -10 : -9, true); + position3 += 2; + } + keyIndex++; + } + let recordId = transition[RECORD_SYMBOL]; + if (recordId == null) { + recordId = packr.typedStructs.length; + let structure = []; + let nextTransition = transition; + let key, type; + while ((type = nextTransition.__type) !== undefined) { + let size = nextTransition.__size; + nextTransition = nextTransition.__parent; + key = nextTransition.key; + let property = [type, size, key]; + if (nextTransition.enumerationOffset) + property.push(nextTransition.enumerationOffset); + structure.push(property); + nextTransition = nextTransition.parent; + } + structure.reverse(); + transition[RECORD_SYMBOL] = recordId; + packr.typedStructs[recordId] = structure; + pack2(null, 0, true); + } + switch (headerSize) { + case 1: + if (recordId >= 16) + return 0; + target2[start] = recordId + 32; + break; + case 2: + if (recordId >= 256) + return 0; + target2[start] = 56; + target2[start + 1] = recordId; + break; + case 3: + if (recordId >= 65536) + return 0; + target2[start] = 57; + targetView2.setUint16(start + 1, recordId, true); + break; + case 4: + if (recordId >= 16777216) + return 0; + targetView2.setUint32(start, (recordId << 8) + 58, true); + break; + } + if (position3 < refsStartPosition) { + if (refsStartPosition === refPosition) + return position3; + target2.copyWithin(position3, refsStartPosition, refPosition); + refPosition += position3 - refsStartPosition; + typedStructs.lastStringStart = position3 - start; + } else if (position3 > refsStartPosition) { + if (refsStartPosition === refPosition) + return position3; + typedStructs.lastStringStart = position3 - start; + return writeStruct(object2, target2, encodingStart, start, structures, makeRoom, pack2, packr); + } + return refPosition; +} +function anyType(transition, position3, targetView2, value) { + let nextTransition; + if (nextTransition = transition.ascii8 || transition.num8) { + targetView2.setInt8(position3, value, true); + updatedPosition = position3 + 1; + return nextTransition; + } + if (nextTransition = transition.string16 || transition.object16) { + targetView2.setInt16(position3, value, true); + updatedPosition = position3 + 2; + return nextTransition; + } + if (nextTransition = transition.num32) { + targetView2.setUint32(position3, 3758096640 + value, true); + updatedPosition = position3 + 4; + return nextTransition; + } + if (nextTransition = transition.num64) { + targetView2.setFloat64(position3, NaN, true); + targetView2.setInt8(position3, value); + updatedPosition = position3 + 8; + return nextTransition; + } + updatedPosition = position3; + return; +} +function createTypeTransition(transition, type, size) { + let typeName = TYPE_NAMES[type] + (size << 3); + let newTransition = transition[typeName] || (transition[typeName] = Object.create(null)); + newTransition.__type = type; + newTransition.__size = size; + newTransition.__parent = transition; + return newTransition; +} +function onLoadedStructures2(sharedData) { + if (!(sharedData instanceof Map)) + return sharedData; + let typed = sharedData.get("typed") || []; + if (Object.isFrozen(typed)) + typed = typed.map((structure) => structure.slice(0)); + let named = sharedData.get("named"); + let transitions = Object.create(null); + for (let i2 = 0, l2 = typed.length;i2 < l2; i2++) { + let structure = typed[i2]; + let transition = transitions; + for (let [type, size, key] of structure) { + let nextTransition = transition[key]; + if (!nextTransition) { + transition[key] = nextTransition = { + key, + parent: transition, + enumerationOffset: 0, + ascii0: null, + ascii8: null, + num8: null, + string16: null, + object16: null, + num32: null, + float64: null, + date64: null + }; + } + transition = createTypeTransition(nextTransition, type, size); + } + transition[RECORD_SYMBOL] = i2; + } + typed.transitions = transitions; + this.typedStructs = typed; + this.lastTypedStructuresLength = typed.length; + return named; +} +var sourceSymbol = Symbol.for("source"); +function readStruct2(src2, position3, srcEnd2, unpackr) { + let recordId = src2[position3++] - 32; + if (recordId >= 24) { + switch (recordId) { + case 24: + recordId = src2[position3++]; + break; + case 25: + recordId = src2[position3++] + (src2[position3++] << 8); + break; + case 26: + recordId = src2[position3++] + (src2[position3++] << 8) + (src2[position3++] << 16); + break; + case 27: + recordId = src2[position3++] + (src2[position3++] << 8) + (src2[position3++] << 16) + (src2[position3++] << 24); + break; + } + } + let structure = unpackr.typedStructs && unpackr.typedStructs[recordId]; + if (!structure) { + src2 = Uint8Array.prototype.slice.call(src2, position3, srcEnd2); + srcEnd2 -= position3; + position3 = 0; + if (!unpackr.getStructures) + throw new Error(`Reference to shared structure ${recordId} without getStructures method`); + unpackr._mergeStructures(unpackr.getStructures()); + if (!unpackr.typedStructs) + throw new Error("Could not find any shared typed structures"); + unpackr.lastTypedStructuresLength = unpackr.typedStructs.length; + structure = unpackr.typedStructs[recordId]; + if (!structure) + throw new Error("Could not find typed structure " + recordId); + } + var construct2 = structure.construct; + var fullConstruct = structure.fullConstruct; + if (!construct2) { + construct2 = structure.construct = function LazyObject() {}; + fullConstruct = structure.fullConstruct = function LoadedObject() {}; + fullConstruct.prototype = unpackr.structPrototype || {}; + var prototype = construct2.prototype = unpackr.structPrototype ? Object.create(unpackr.structPrototype) : {}; + let properties = []; + let currentOffset = 0; + let lastRefProperty; + for (let i2 = 0, l2 = structure.length;i2 < l2; i2++) { + let definition = structure[i2]; + let [type, size, key, enumerationOffset] = definition; + if (key === "__proto__") + key = "__proto_"; + let property = { + key, + offset: currentOffset + }; + if (enumerationOffset) + properties.splice(i2 + enumerationOffset, 0, property); + else + properties.push(property); + let getRef; + switch (size) { + case 0: + getRef = () => 0; + break; + case 1: + getRef = (source, position4) => { + let ref = source.bytes[position4 + property.offset]; + return ref >= 246 ? toConstant(ref) : ref; + }; + break; + case 2: + getRef = (source, position4) => { + let src3 = source.bytes; + let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); + let ref = dataView2.getUint16(position4 + property.offset, true); + return ref >= 65280 ? toConstant(ref & 255) : ref; + }; + break; + case 4: + getRef = (source, position4) => { + let src3 = source.bytes; + let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); + let ref = dataView2.getUint32(position4 + property.offset, true); + return ref >= 4294967040 ? toConstant(ref & 255) : ref; + }; + break; + } + property.getRef = getRef; + currentOffset += size; + let get; + switch (type) { + case ASCII: + if (lastRefProperty && !lastRefProperty.next) + lastRefProperty.next = property; + lastRefProperty = property; + property.multiGetCount = 0; + get = function(source) { + let src3 = source.bytes; + let position4 = source.position; + let refStart = currentOffset + position4; + let ref = getRef(source, position4); + if (typeof ref !== "number") + return ref; + let end, next = property.next; + while (next) { + end = next.getRef(source, position4); + if (typeof end === "number") + break; + else + end = null; + next = next.next; + } + if (end == null) + end = source.bytesEnd - refStart; + if (source.srcString) { + return source.srcString.slice(ref, end); + } + return readString(src3, ref + refStart, end - ref); + }; + break; + case UTF8: + case OBJECT_DATA: + if (lastRefProperty && !lastRefProperty.next) + lastRefProperty.next = property; + lastRefProperty = property; + get = function(source) { + let position4 = source.position; + let refStart = currentOffset + position4; + let ref = getRef(source, position4); + if (typeof ref !== "number") + return ref; + let src3 = source.bytes; + let end, next = property.next; + while (next) { + end = next.getRef(source, position4); + if (typeof end === "number") + break; + else + end = null; + next = next.next; + } + if (end == null) + end = source.bytesEnd - refStart; + if (type === UTF8) { + return src3.toString("utf8", ref + refStart, end + refStart); + } else { + currentSource = source; + try { + return unpackr.unpack(src3, { start: ref + refStart, end: end + refStart }); + } finally { + currentSource = null; + } + } + }; + break; + case NUMBER: + switch (size) { + case 4: + get = function(source) { + let src3 = source.bytes; + let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); + let position4 = source.position + property.offset; + let value = dataView2.getInt32(position4, true); + if (value < 536870912) { + if (value > -520093696) + return value; + if (value > -536870912) + return toConstant(value & 255); + } + let fValue = dataView2.getFloat32(position4, true); + let multiplier = mult10[(src3[position4 + 3] & 127) << 1 | src3[position4 + 2] >> 7]; + return (multiplier * fValue + (fValue > 0 ? 0.5 : -0.5) >> 0) / multiplier; + }; + break; + case 8: + get = function(source) { + let src3 = source.bytes; + let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); + let value = dataView2.getFloat64(source.position + property.offset, true); + if (isNaN(value)) { + let byte = src3[source.position + property.offset]; + if (byte >= 246) + return toConstant(byte); + } + return value; + }; + break; + case 1: + get = function(source) { + let src3 = source.bytes; + let value = src3[source.position + property.offset]; + return value < 246 ? value : toConstant(value); + }; + break; + } + break; + case DATE: + get = function(source) { + let src3 = source.bytes; + let dataView2 = src3.dataView || (src3.dataView = new DataView(src3.buffer, src3.byteOffset, src3.byteLength)); + return new Date(dataView2.getFloat64(source.position + property.offset, true)); + }; + break; + } + property.get = get; + } + if (evalSupported) { + let objectLiteralProperties = []; + let args = []; + let i2 = 0; + let hasInheritedProperties; + for (let property of properties) { + if (unpackr.alwaysLazyProperty && unpackr.alwaysLazyProperty(property.key)) { + hasInheritedProperties = true; + continue; + } + Object.defineProperty(prototype, property.key, { get: withSource(property.get), enumerable: true }); + let valueFunction = "v" + i2++; + args.push(valueFunction); + objectLiteralProperties.push("o[" + JSON.stringify(property.key) + "]=" + valueFunction + "(s)"); + } + if (hasInheritedProperties) { + objectLiteralProperties.push("__proto__:this"); + } + let toObject = new Function(...args, "var c=this;return function(s){var o=new c();" + objectLiteralProperties.join(";") + ";return o;}").apply(fullConstruct, properties.map((prop) => prop.get)); + Object.defineProperty(prototype, "toJSON", { + value(omitUnderscoredProperties) { + return toObject.call(this, this[sourceSymbol]); + } + }); + } else { + Object.defineProperty(prototype, "toJSON", { + value(omitUnderscoredProperties) { + let resolved = {}; + for (let i2 = 0, l2 = properties.length;i2 < l2; i2++) { + let key = properties[i2].key; + resolved[key] = this[key]; + } + return resolved; + } + }); + } + } + var instance = new construct2; + instance[sourceSymbol] = { + bytes: src2, + position: position3, + srcString: "", + bytesEnd: srcEnd2 + }; + return instance; +} +function toConstant(code) { + switch (code) { + case 246: + return null; + case 247: + return; + case 248: + return false; + case 249: + return true; + } + throw new Error("Unknown constant"); +} +function withSource(get) { + return function() { + return get(this[sourceSymbol]); + }; +} +function saveState2() { + if (currentSource) { + currentSource.bytes = Uint8Array.prototype.slice.call(currentSource.bytes, currentSource.position, currentSource.bytesEnd); + currentSource.position = 0; + currentSource.bytesEnd = currentSource.bytes.length; + } +} +function prepareStructures2(structures, packr) { + if (packr.typedStructs) { + let structMap = new Map; + structMap.set("named", structures); + structMap.set("typed", packr.typedStructs); + structures = structMap; + } + let lastTypedStructuresLength = packr.lastTypedStructuresLength || 0; + structures.isCompatible = (existing) => { + let compatible = true; + if (existing instanceof Map) { + let named = existing.get("named") || []; + if (named.length !== (packr.lastNamedStructuresLength || 0)) + compatible = false; + let typed = existing.get("typed") || []; + if (typed.length !== lastTypedStructuresLength) + compatible = false; + } else if (existing instanceof Array || Array.isArray(existing)) { + if (existing.length !== (packr.lastNamedStructuresLength || 0)) + compatible = false; + } + if (!compatible) + packr._mergeStructures(existing); + return compatible; + }; + packr.lastTypedStructuresLength = packr.typedStructs && packr.typedStructs.length; + return structures; +} +setReadStruct(readStruct2, onLoadedStructures2, saveState2); +// node_modules/.pnpm/msgpackr@1.11.5/node_modules/msgpackr/node-index.js +var nativeAccelerationDisabled = process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED !== undefined && process.env.MSGPACKR_NATIVE_ACCELERATION_DISABLED.toLowerCase() === "true"; +if (!nativeAccelerationDisabled) { + let extractor; + try { + if (true) + extractor = require_msgpackr_extract(); + else + ; + if (extractor) + setExtractor(extractor.extractStrings); + } catch (error) {} +} + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/version.js +var version3 = "5.76.1"; + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/scripts.js +var packer = new Packr({ + useRecords: false, + encodeUndefinedAsNil: true +}); +var pack2 = packer.pack; + +class Scripts { + constructor(queue) { + this.queue = queue; + this.version = version3; + const queueKeys = this.queue.keys; + this.moveToFinishedKeys = [ + queueKeys.wait, + queueKeys.active, + queueKeys.prioritized, + queueKeys.events, + queueKeys.stalled, + queueKeys.limiter, + queueKeys.delayed, + queueKeys.paused, + queueKeys.meta, + queueKeys.pc, + undefined, + undefined, + undefined, + undefined + ]; + } + execCommand(client, commandName, args) { + const commandNameWithVersion = `${commandName}:${this.version}`; + return client[commandNameWithVersion](args); + } + async isJobInList(listKey, jobId) { + const client = await this.queue.client; + let result; + if (isRedisVersionLowerThan(this.queue.redisVersion, "6.0.6", this.queue.databaseType)) { + result = await this.execCommand(client, "isJobInList", [listKey, jobId]); + } else { + result = await client.lpos(listKey, jobId); + } + return Number.isInteger(result); + } + addDelayedJobArgs(job, encodedOpts, args) { + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.marker, + queueKeys.meta, + queueKeys.id, + queueKeys.delayed, + queueKeys.completed, + queueKeys.events + ]; + keys.push(pack2(args), job.data, encodedOpts); + return keys; + } + addDelayedJob(client, job, encodedOpts, args) { + const argsList = this.addDelayedJobArgs(job, encodedOpts, args); + return this.execCommand(client, "addDelayedJob", argsList); + } + addPrioritizedJobArgs(job, encodedOpts, args) { + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.marker, + queueKeys.meta, + queueKeys.id, + queueKeys.prioritized, + queueKeys.delayed, + queueKeys.completed, + queueKeys.active, + queueKeys.events, + queueKeys.pc + ]; + keys.push(pack2(args), job.data, encodedOpts); + return keys; + } + addPrioritizedJob(client, job, encodedOpts, args) { + const argsList = this.addPrioritizedJobArgs(job, encodedOpts, args); + return this.execCommand(client, "addPrioritizedJob", argsList); + } + addParentJobArgs(job, encodedOpts, args) { + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.meta, + queueKeys.id, + queueKeys.delayed, + queueKeys["waiting-children"], + queueKeys.completed, + queueKeys.events + ]; + keys.push(pack2(args), job.data, encodedOpts); + return keys; + } + addParentJob(client, job, encodedOpts, args) { + const argsList = this.addParentJobArgs(job, encodedOpts, args); + return this.execCommand(client, "addParentJob", argsList); + } + addStandardJobArgs(job, encodedOpts, args) { + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.wait, + queueKeys.paused, + queueKeys.meta, + queueKeys.id, + queueKeys.completed, + queueKeys.delayed, + queueKeys.active, + queueKeys.events, + queueKeys.marker + ]; + keys.push(pack2(args), job.data, encodedOpts); + return keys; + } + addStandardJob(client, job, encodedOpts, args) { + const argsList = this.addStandardJobArgs(job, encodedOpts, args); + return this.execCommand(client, "addStandardJob", argsList); + } + async addJob(client, job, opts, jobId, parentKeyOpts = {}) { + const queueKeys = this.queue.keys; + const parent = job.parent; + const args = [ + queueKeys[""], + typeof jobId !== "undefined" ? jobId : "", + job.name, + job.timestamp, + job.parentKey || null, + parentKeyOpts.parentDependenciesKey || null, + parent, + job.repeatJobKey, + job.deduplicationId ? `${queueKeys.de}:${job.deduplicationId}` : null + ]; + let encodedOpts; + if (opts.repeat) { + const repeat = Object.assign({}, opts.repeat); + if (repeat.startDate) { + repeat.startDate = +new Date(repeat.startDate); + } + if (repeat.endDate) { + repeat.endDate = +new Date(repeat.endDate); + } + encodedOpts = pack2(Object.assign(Object.assign({}, opts), { repeat })); + } else { + encodedOpts = pack2(opts); + } + let result; + if (parentKeyOpts.addToWaitingChildren) { + result = await this.addParentJob(client, job, encodedOpts, args); + } else if (typeof opts.delay == "number" && opts.delay > 0) { + result = await this.addDelayedJob(client, job, encodedOpts, args); + } else if (opts.priority) { + result = await this.addPrioritizedJob(client, job, encodedOpts, args); + } else { + result = await this.addStandardJob(client, job, encodedOpts, args); + } + if (result < 0) { + throw this.finishedErrors({ + code: result, + parentKey: parentKeyOpts.parentKey, + command: "addJob" + }); + } + return result; + } + pauseArgs(pause) { + let src2 = "wait", dst = "paused"; + if (!pause) { + src2 = "paused"; + dst = "wait"; + } + const keys = [src2, dst, "meta", "prioritized"].map((name) => this.queue.toKey(name)); + keys.push(this.queue.keys.events, this.queue.keys.delayed, this.queue.keys.marker); + const args = [pause ? "paused" : "resumed"]; + return keys.concat(args); + } + async pause(pause) { + const client = await this.queue.client; + const args = this.pauseArgs(pause); + return this.execCommand(client, "pause", args); + } + addRepeatableJobArgs(customKey, nextMillis, opts, legacyCustomKey) { + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.repeat, + queueKeys.delayed + ]; + const args = [ + nextMillis, + pack2(opts), + legacyCustomKey, + customKey, + queueKeys[""] + ]; + return keys.concat(args); + } + async addRepeatableJob(customKey, nextMillis, opts, legacyCustomKey) { + const client = await this.queue.client; + const args = this.addRepeatableJobArgs(customKey, nextMillis, opts, legacyCustomKey); + return this.execCommand(client, "addRepeatableJob", args); + } + async removeDeduplicationKey(deduplicationId, jobId) { + const client = await this.queue.client; + const queueKeys = this.queue.keys; + const keys = [`${queueKeys.de}:${deduplicationId}`]; + const args = [jobId]; + return this.execCommand(client, "removeDeduplicationKey", keys.concat(args)); + } + async addJobScheduler(jobSchedulerId, nextMillis, templateData, templateOpts, opts, delayedJobOpts, producerId) { + const client = await this.queue.client; + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.repeat, + queueKeys.delayed, + queueKeys.wait, + queueKeys.paused, + queueKeys.meta, + queueKeys.prioritized, + queueKeys.marker, + queueKeys.id, + queueKeys.events, + queueKeys.pc, + queueKeys.active + ]; + const args = [ + nextMillis, + pack2(opts), + jobSchedulerId, + templateData, + pack2(templateOpts), + pack2(delayedJobOpts), + Date.now(), + queueKeys[""], + producerId ? this.queue.toKey(producerId) : "" + ]; + const result = await this.execCommand(client, "addJobScheduler", keys.concat(args)); + if (typeof result === "number" && result < 0) { + throw this.finishedErrors({ + code: result, + command: "addJobScheduler" + }); + } + return result; + } + async updateRepeatableJobMillis(client, customKey, nextMillis, legacyCustomKey) { + const args = [ + this.queue.keys.repeat, + nextMillis, + customKey, + legacyCustomKey + ]; + return this.execCommand(client, "updateRepeatableJobMillis", args); + } + async updateJobSchedulerNextMillis(jobSchedulerId, nextMillis, templateData, delayedJobOpts, producerId) { + const client = await this.queue.client; + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.repeat, + queueKeys.delayed, + queueKeys.wait, + queueKeys.paused, + queueKeys.meta, + queueKeys.prioritized, + queueKeys.marker, + queueKeys.id, + queueKeys.events, + queueKeys.pc, + producerId ? this.queue.toKey(producerId) : "", + queueKeys.active + ]; + const args = [ + nextMillis, + jobSchedulerId, + templateData, + pack2(delayedJobOpts), + Date.now(), + queueKeys[""], + producerId + ]; + return this.execCommand(client, "updateJobScheduler", keys.concat(args)); + } + removeRepeatableArgs(legacyRepeatJobId, repeatConcatOptions, repeatJobKey) { + const queueKeys = this.queue.keys; + const keys = [queueKeys.repeat, queueKeys.delayed, queueKeys.events]; + const args = [ + legacyRepeatJobId, + this.getRepeatConcatOptions(repeatConcatOptions, repeatJobKey), + repeatJobKey, + queueKeys[""] + ]; + return keys.concat(args); + } + getRepeatConcatOptions(repeatConcatOptions, repeatJobKey) { + if (repeatJobKey && repeatJobKey.split(":").length > 2) { + return repeatJobKey; + } + return repeatConcatOptions; + } + async removeRepeatable(legacyRepeatJobId, repeatConcatOptions, repeatJobKey) { + const client = await this.queue.client; + const args = this.removeRepeatableArgs(legacyRepeatJobId, repeatConcatOptions, repeatJobKey); + return this.execCommand(client, "removeRepeatable", args); + } + async removeJobScheduler(jobSchedulerId) { + const client = await this.queue.client; + const queueKeys = this.queue.keys; + const keys = [queueKeys.repeat, queueKeys.delayed, queueKeys.events]; + const args = [jobSchedulerId, queueKeys[""]]; + return this.execCommand(client, "removeJobScheduler", keys.concat(args)); + } + removeArgs(jobId, removeChildren) { + const keys = [jobId, "repeat"].map((name) => this.queue.toKey(name)); + const args = [jobId, removeChildren ? 1 : 0, this.queue.toKey("")]; + return keys.concat(args); + } + async remove(jobId, removeChildren) { + const client = await this.queue.client; + const args = this.removeArgs(jobId, removeChildren); + const result = await this.execCommand(client, "removeJob", args); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "removeJob" + }); + } + return result; + } + async removeUnprocessedChildren(jobId) { + const client = await this.queue.client; + const args = [ + this.queue.toKey(jobId), + this.queue.keys.meta, + this.queue.toKey(""), + jobId + ]; + await this.execCommand(client, "removeUnprocessedChildren", args); + } + async extendLock(jobId, token, duration, client) { + client = client || await this.queue.client; + const args = [ + this.queue.toKey(jobId) + ":lock", + this.queue.keys.stalled, + token, + duration, + jobId + ]; + return this.execCommand(client, "extendLock", args); + } + async extendLocks(jobIds, tokens, duration) { + const client = await this.queue.client; + const args = [ + this.queue.keys.stalled, + this.queue.toKey(""), + pack2(tokens), + pack2(jobIds), + duration + ]; + return this.execCommand(client, "extendLocks", args); + } + async updateData(job, data) { + const client = await this.queue.client; + const keys = [this.queue.toKey(job.id)]; + const dataJson = JSON.stringify(data); + const result = await this.execCommand(client, "updateData", keys.concat([dataJson])); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId: job.id, + command: "updateData" + }); + } + } + async updateProgress(jobId, progress) { + const client = await this.queue.client; + const keys = [ + this.queue.toKey(jobId), + this.queue.keys.events, + this.queue.keys.meta + ]; + const progressJson = JSON.stringify(progress); + const result = await this.execCommand(client, "updateProgress", keys.concat([jobId, progressJson])); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "updateProgress" + }); + } + } + async addLog(jobId, logRow, keepLogs) { + const client = await this.queue.client; + const keys = [ + this.queue.toKey(jobId), + this.queue.toKey(jobId) + ":logs" + ]; + const result = await this.execCommand(client, "addLog", keys.concat([jobId, logRow, keepLogs ? keepLogs : ""])); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "addLog" + }); + } + return result; + } + moveToFinishedArgs(job, val, propVal, shouldRemove, target2, token, timestamp3, fetchNext = true, fieldsToUpdate) { + var _a, _b, _c2, _d2, _e2, _f, _g; + const queueKeys = this.queue.keys; + const opts = this.queue.opts; + const workerKeepJobs = target2 === "completed" ? opts.removeOnComplete : opts.removeOnFail; + const metricsKey = this.queue.toKey(`metrics:${target2}`); + const keys = this.moveToFinishedKeys; + keys[10] = queueKeys[target2]; + keys[11] = this.queue.toKey((_a = job.id) !== null && _a !== undefined ? _a : ""); + keys[12] = metricsKey; + keys[13] = this.queue.keys.marker; + const keepJobs = this.getKeepJobs(shouldRemove, workerKeepJobs); + const args = [ + job.id, + timestamp3, + propVal, + typeof val === "undefined" ? "null" : val, + target2, + !fetchNext || this.queue.closing ? 0 : 1, + queueKeys[""], + pack2({ + token, + name: opts.name, + keepJobs, + limiter: opts.limiter, + lockDuration: opts.lockDuration, + attempts: job.opts.attempts, + maxMetricsSize: ((_b = opts.metrics) === null || _b === undefined ? undefined : _b.maxDataPoints) ? (_c2 = opts.metrics) === null || _c2 === undefined ? undefined : _c2.maxDataPoints : "", + fpof: !!((_d2 = job.opts) === null || _d2 === undefined ? undefined : _d2.failParentOnFailure), + cpof: !!((_e2 = job.opts) === null || _e2 === undefined ? undefined : _e2.continueParentOnFailure), + idof: !!((_f = job.opts) === null || _f === undefined ? undefined : _f.ignoreDependencyOnFailure), + rdof: !!((_g = job.opts) === null || _g === undefined ? undefined : _g.removeDependencyOnFailure) + }), + fieldsToUpdate ? pack2(objectToFlatArray(fieldsToUpdate)) : undefined + ]; + return keys.concat(args); + } + getKeepJobs(shouldRemove, workerKeepJobs) { + if (typeof shouldRemove === "undefined") { + return workerKeepJobs || { count: shouldRemove ? 0 : -1 }; + } + return typeof shouldRemove === "object" ? shouldRemove : typeof shouldRemove === "number" ? { count: shouldRemove } : { count: shouldRemove ? 0 : -1 }; + } + async moveToFinished(jobId, args) { + const client = await this.queue.client; + const result = await this.execCommand(client, "moveToFinished", args); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "moveToFinished", + state: "active" + }); + } else { + if (typeof result !== "undefined") { + return raw2NextJobData(result); + } + } + } + drainArgs(delayed) { + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.wait, + queueKeys.paused, + queueKeys.delayed, + queueKeys.prioritized, + queueKeys.repeat + ]; + const args = [queueKeys[""], delayed ? "1" : "0"]; + return keys.concat(args); + } + async drain(delayed) { + const client = await this.queue.client; + const args = this.drainArgs(delayed); + return this.execCommand(client, "drain", args); + } + removeChildDependencyArgs(jobId, parentKey) { + const queueKeys = this.queue.keys; + const keys = [queueKeys[""]]; + const args = [this.queue.toKey(jobId), parentKey]; + return keys.concat(args); + } + async removeChildDependency(jobId, parentKey) { + const client = await this.queue.client; + const args = this.removeChildDependencyArgs(jobId, parentKey); + const result = await this.execCommand(client, "removeChildDependency", args); + switch (result) { + case 0: + return true; + case 1: + return false; + default: + throw this.finishedErrors({ + code: result, + jobId, + parentKey, + command: "removeChildDependency" + }); + } + } + getRangesArgs(types6, start, end, asc2) { + const queueKeys = this.queue.keys; + const transformedTypes = types6.map((type) => { + return type === "waiting" ? "wait" : type; + }); + const keys = [queueKeys[""]]; + const args = [start, end, asc2 ? "1" : "0", ...transformedTypes]; + return keys.concat(args); + } + async getRanges(types6, start = 0, end = 1, asc2 = false) { + const client = await this.queue.client; + const args = this.getRangesArgs(types6, start, end, asc2); + return await this.execCommand(client, "getRanges", args); + } + getCountsArgs(types6) { + const queueKeys = this.queue.keys; + const transformedTypes = types6.map((type) => { + return type === "waiting" ? "wait" : type; + }); + const keys = [queueKeys[""]]; + const args = [...transformedTypes]; + return keys.concat(args); + } + async getCounts(types6) { + const client = await this.queue.client; + const args = this.getCountsArgs(types6); + return await this.execCommand(client, "getCounts", args); + } + getCountsPerPriorityArgs(priorities) { + const keys = [ + this.queue.keys.wait, + this.queue.keys.paused, + this.queue.keys.meta, + this.queue.keys.prioritized + ]; + const args = priorities; + return keys.concat(args); + } + async getCountsPerPriority(priorities) { + const client = await this.queue.client; + const args = this.getCountsPerPriorityArgs(priorities); + return await this.execCommand(client, "getCountsPerPriority", args); + } + getDependencyCountsArgs(jobId, types6) { + const keys = [ + `${jobId}:processed`, + `${jobId}:dependencies`, + `${jobId}:failed`, + `${jobId}:unsuccessful` + ].map((name) => { + return this.queue.toKey(name); + }); + const args = types6; + return keys.concat(args); + } + async getDependencyCounts(jobId, types6) { + const client = await this.queue.client; + const args = this.getDependencyCountsArgs(jobId, types6); + return await this.execCommand(client, "getDependencyCounts", args); + } + moveToCompletedArgs(job, returnvalue, removeOnComplete, token, fetchNext = false) { + const timestamp3 = Date.now(); + return this.moveToFinishedArgs(job, returnvalue, "returnvalue", removeOnComplete, "completed", token, timestamp3, fetchNext); + } + moveToFailedArgs(job, failedReason, removeOnFailed, token, fetchNext = false, fieldsToUpdate) { + const timestamp3 = Date.now(); + return this.moveToFinishedArgs(job, failedReason, "failedReason", removeOnFailed, "failed", token, timestamp3, fetchNext, fieldsToUpdate); + } + async isFinished(jobId, returnValue = false) { + const client = await this.queue.client; + const keys = ["completed", "failed", jobId].map((key) => { + return this.queue.toKey(key); + }); + return this.execCommand(client, "isFinished", keys.concat([jobId, returnValue ? "1" : ""])); + } + async getState(jobId) { + const client = await this.queue.client; + const keys = [ + "completed", + "failed", + "delayed", + "active", + "wait", + "paused", + "waiting-children", + "prioritized" + ].map((key) => { + return this.queue.toKey(key); + }); + if (isRedisVersionLowerThan(this.queue.redisVersion, "6.0.6", this.queue.databaseType)) { + return this.execCommand(client, "getState", keys.concat([jobId])); + } + return this.execCommand(client, "getStateV2", keys.concat([jobId])); + } + async changeDelay(jobId, delay2) { + const client = await this.queue.client; + const args = this.changeDelayArgs(jobId, delay2); + const result = await this.execCommand(client, "changeDelay", args); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "changeDelay", + state: "delayed" + }); + } + } + changeDelayArgs(jobId, delay2) { + const timestamp3 = Date.now(); + const keys = [ + this.queue.keys.delayed, + this.queue.keys.meta, + this.queue.keys.marker, + this.queue.keys.events + ]; + return keys.concat([ + delay2, + JSON.stringify(timestamp3), + jobId, + this.queue.toKey(jobId) + ]); + } + async changePriority(jobId, priority = 0, lifo = false) { + const client = await this.queue.client; + const args = this.changePriorityArgs(jobId, priority, lifo); + const result = await this.execCommand(client, "changePriority", args); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "changePriority" + }); + } + } + changePriorityArgs(jobId, priority = 0, lifo = false) { + const keys = [ + this.queue.keys.wait, + this.queue.keys.paused, + this.queue.keys.meta, + this.queue.keys.prioritized, + this.queue.keys.active, + this.queue.keys.pc, + this.queue.keys.marker + ]; + return keys.concat([priority, this.queue.toKey(""), jobId, lifo ? 1 : 0]); + } + moveToDelayedArgs(jobId, timestamp3, token, delay2, opts = {}) { + const queueKeys = this.queue.keys; + const workerOpts = this.queue.opts; + const keys = [ + queueKeys.marker, + queueKeys.active, + queueKeys.prioritized, + queueKeys.delayed, + this.queue.toKey(jobId), + queueKeys.events, + queueKeys.meta, + queueKeys.stalled, + queueKeys.wait, + queueKeys.limiter, + queueKeys.paused, + queueKeys.pc + ]; + const fetchNext = opts.fetchNext && !this.queue.closing ? 1 : 0; + return keys.concat([ + this.queue.keys[""], + timestamp3, + jobId, + token, + delay2, + opts.skipAttempt ? "1" : "0", + opts.fieldsToUpdate ? pack2(objectToFlatArray(opts.fieldsToUpdate)) : undefined, + fetchNext, + fetchNext ? pack2({ + token, + lockDuration: workerOpts.lockDuration, + limiter: workerOpts.limiter, + name: workerOpts.name + }) : undefined + ]); + } + moveToWaitingChildrenArgs(jobId, token, opts) { + const timestamp3 = Date.now(); + const childKey = getParentKey(opts.child); + const keys = [ + "active", + "waiting-children", + jobId, + `${jobId}:dependencies`, + `${jobId}:unsuccessful`, + "stalled", + "events" + ].map((name) => { + return this.queue.toKey(name); + }); + return keys.concat([ + token, + childKey !== null && childKey !== undefined ? childKey : "", + JSON.stringify(timestamp3), + jobId, + this.queue.toKey("") + ]); + } + isMaxedArgs() { + const queueKeys = this.queue.keys; + const keys = [queueKeys.meta, queueKeys.active]; + return keys; + } + async isMaxed() { + const client = await this.queue.client; + const args = this.isMaxedArgs(); + return !!await this.execCommand(client, "isMaxed", args); + } + async moveToDelayed(jobId, timestamp3, delay2, token = "0", opts = {}) { + const client = await this.queue.client; + const args = this.moveToDelayedArgs(jobId, timestamp3, token, delay2, opts); + const result = await this.execCommand(client, "moveToDelayed", args); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "moveToDelayed", + state: "active" + }); + } else if (typeof result !== "undefined") { + return raw2NextJobData(result); + } + } + async moveToWaitingChildren(jobId, token, opts = {}) { + const client = await this.queue.client; + const args = this.moveToWaitingChildrenArgs(jobId, token, opts); + const result = await this.execCommand(client, "moveToWaitingChildren", args); + switch (result) { + case 0: + return true; + case 1: + return false; + default: + throw this.finishedErrors({ + code: result, + jobId, + command: "moveToWaitingChildren", + state: "active" + }); + } + } + getRateLimitTtlArgs(maxJobs) { + const keys = [ + this.queue.keys.limiter, + this.queue.keys.meta + ]; + return keys.concat([maxJobs !== null && maxJobs !== undefined ? maxJobs : "0"]); + } + async getRateLimitTtl(maxJobs) { + const client = await this.queue.client; + const args = this.getRateLimitTtlArgs(maxJobs); + return this.execCommand(client, "getRateLimitTtl", args); + } + async cleanJobsInSet(set, timestamp3, limit = 0) { + const client = await this.queue.client; + return this.execCommand(client, "cleanJobsInSet", [ + this.queue.toKey(set), + this.queue.toKey("events"), + this.queue.toKey("repeat"), + this.queue.toKey(""), + timestamp3, + limit, + set + ]); + } + getJobSchedulerArgs(id) { + const keys = [this.queue.keys.repeat]; + return keys.concat([id]); + } + async getJobScheduler(id) { + const client = await this.queue.client; + const args = this.getJobSchedulerArgs(id); + return this.execCommand(client, "getJobScheduler", args); + } + retryJobArgs(jobId, lifo, token, opts = {}) { + const keys = [ + this.queue.keys.active, + this.queue.keys.wait, + this.queue.keys.paused, + this.queue.toKey(jobId), + this.queue.keys.meta, + this.queue.keys.events, + this.queue.keys.delayed, + this.queue.keys.prioritized, + this.queue.keys.pc, + this.queue.keys.marker, + this.queue.keys.stalled + ]; + const pushCmd = (lifo ? "R" : "L") + "PUSH"; + return keys.concat([ + this.queue.toKey(""), + Date.now(), + pushCmd, + jobId, + token, + opts.fieldsToUpdate ? pack2(objectToFlatArray(opts.fieldsToUpdate)) : undefined + ]); + } + async retryJob(jobId, lifo, token = "0", opts = {}) { + const client = await this.queue.client; + const args = this.retryJobArgs(jobId, lifo, token, opts); + const result = await this.execCommand(client, "retryJob", args); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "retryJob", + state: "active" + }); + } + } + moveJobsToWaitArgs(state, count2, timestamp3) { + const keys = [ + this.queue.toKey(""), + this.queue.keys.events, + this.queue.toKey(state), + this.queue.toKey("wait"), + this.queue.toKey("paused"), + this.queue.keys.meta, + this.queue.keys.active, + this.queue.keys.marker + ]; + const args = [count2, timestamp3, state]; + return keys.concat(args); + } + async retryJobs(state = "failed", count2 = 1000, timestamp3 = new Date().getTime()) { + const client = await this.queue.client; + const args = this.moveJobsToWaitArgs(state, count2, timestamp3); + return this.execCommand(client, "moveJobsToWait", args); + } + async promoteJobs(count2 = 1000) { + const client = await this.queue.client; + const args = this.moveJobsToWaitArgs("delayed", count2, Number.MAX_VALUE); + return this.execCommand(client, "moveJobsToWait", args); + } + async reprocessJob(job, state, opts = {}) { + const client = await this.queue.client; + const keys = [ + this.queue.toKey(job.id), + this.queue.keys.events, + this.queue.toKey(state), + this.queue.keys.wait, + this.queue.keys.meta, + this.queue.keys.paused, + this.queue.keys.active, + this.queue.keys.marker + ]; + const args = [ + job.id, + (job.opts.lifo ? "R" : "L") + "PUSH", + state === "failed" ? "failedReason" : "returnvalue", + state, + opts.resetAttemptsMade ? "1" : "0", + opts.resetAttemptsStarted ? "1" : "0" + ]; + const result = await this.execCommand(client, "reprocessJob", keys.concat(args)); + switch (result) { + case 1: + return; + default: + throw this.finishedErrors({ + code: result, + jobId: job.id, + command: "reprocessJob", + state + }); + } + } + async getMetrics(type, start = 0, end = -1) { + const client = await this.queue.client; + const keys = [ + this.queue.toKey(`metrics:${type}`), + this.queue.toKey(`metrics:${type}:data`) + ]; + const args = [start, end]; + const result = await this.execCommand(client, "getMetrics", keys.concat(args)); + return result; + } + async moveToActive(client, token, name) { + const opts = this.queue.opts; + const queueKeys = this.queue.keys; + const keys = [ + queueKeys.wait, + queueKeys.active, + queueKeys.prioritized, + queueKeys.events, + queueKeys.stalled, + queueKeys.limiter, + queueKeys.delayed, + queueKeys.paused, + queueKeys.meta, + queueKeys.pc, + queueKeys.marker + ]; + const args = [ + queueKeys[""], + Date.now(), + pack2({ + token, + lockDuration: opts.lockDuration, + limiter: opts.limiter, + name + }) + ]; + const result = await this.execCommand(client, "moveToActive", keys.concat(args)); + return raw2NextJobData(result); + } + async promote(jobId) { + const client = await this.queue.client; + const keys = [ + this.queue.keys.delayed, + this.queue.keys.wait, + this.queue.keys.paused, + this.queue.keys.meta, + this.queue.keys.prioritized, + this.queue.keys.active, + this.queue.keys.pc, + this.queue.keys.events, + this.queue.keys.marker + ]; + const args = [this.queue.toKey(""), jobId]; + const code = await this.execCommand(client, "promote", keys.concat(args)); + if (code < 0) { + throw this.finishedErrors({ + code, + jobId, + command: "promote", + state: "delayed" + }); + } + } + moveStalledJobsToWaitArgs() { + const opts = this.queue.opts; + const keys = [ + this.queue.keys.stalled, + this.queue.keys.wait, + this.queue.keys.active, + this.queue.keys["stalled-check"], + this.queue.keys.meta, + this.queue.keys.paused, + this.queue.keys.marker, + this.queue.keys.events + ]; + const args = [ + opts.maxStalledCount, + this.queue.toKey(""), + Date.now(), + opts.stalledInterval + ]; + return keys.concat(args); + } + async moveStalledJobsToWait() { + const client = await this.queue.client; + const args = this.moveStalledJobsToWaitArgs(); + return this.execCommand(client, "moveStalledJobsToWait", args); + } + async moveJobFromActiveToWait(jobId, token = "0") { + const client = await this.queue.client; + const keys = [ + this.queue.keys.active, + this.queue.keys.wait, + this.queue.keys.stalled, + this.queue.keys.paused, + this.queue.keys.meta, + this.queue.keys.limiter, + this.queue.keys.prioritized, + this.queue.keys.marker, + this.queue.keys.events + ]; + const args = [jobId, token, this.queue.toKey(jobId)]; + const result = await this.execCommand(client, "moveJobFromActiveToWait", keys.concat(args)); + if (result < 0) { + throw this.finishedErrors({ + code: result, + jobId, + command: "moveJobFromActiveToWait", + state: "active" + }); + } + return result; + } + async obliterate(opts) { + const client = await this.queue.client; + const keys = [ + this.queue.keys.meta, + this.queue.toKey("") + ]; + const args = [opts.count, opts.force ? "force" : null]; + const result = await this.execCommand(client, "obliterate", keys.concat(args)); + if (result < 0) { + switch (result) { + case -1: + throw new Error("Cannot obliterate non-paused queue"); + case -2: + throw new Error("Cannot obliterate queue with active jobs"); + } + } + return result; + } + async paginate(key, opts) { + const client = await this.queue.client; + const keys = [key]; + const maxIterations = 5; + const pageSize = opts.end >= 0 ? opts.end - opts.start + 1 : Infinity; + let cursor = "0", offset = 0, items, total, rawJobs, page = [], jobs = []; + do { + const args = [ + opts.start + page.length, + opts.end, + cursor, + offset, + maxIterations + ]; + if (opts.fetchJobs) { + args.push(1); + } + [cursor, offset, items, total, rawJobs] = await this.execCommand(client, "paginate", keys.concat(args)); + page = page.concat(items); + if (rawJobs && rawJobs.length) { + jobs = jobs.concat(rawJobs.map(array2obj)); + } + } while (cursor != "0" && page.length < pageSize); + if (page.length && Array.isArray(page[0])) { + const result = []; + for (let index3 = 0;index3 < page.length; index3++) { + const [id, value] = page[index3]; + try { + result.push({ id, v: JSON.parse(value) }); + } catch (err) { + result.push({ id, err: err.message }); + } + } + return { + cursor, + items: result, + total, + jobs + }; + } else { + return { + cursor, + items: page.map((item) => ({ id: item })), + total, + jobs + }; + } + } + finishedErrors({ code, jobId, parentKey, command, state }) { + let error; + switch (code) { + case ErrorCode.JobNotExist: + error = new Error(`Missing key for job ${jobId}. ${command}`); + break; + case ErrorCode.JobLockNotExist: + error = new Error(`Missing lock for job ${jobId}. ${command}`); + break; + case ErrorCode.JobNotInState: + error = new Error(`Job ${jobId} is not in the ${state} state. ${command}`); + break; + case ErrorCode.JobPendingChildren: + error = new Error(`Job ${jobId} has pending dependencies. ${command}`); + break; + case ErrorCode.ParentJobNotExist: + error = new Error(`Missing key for parent job ${parentKey}. ${command}`); + break; + case ErrorCode.JobLockMismatch: + error = new Error(`Lock mismatch for job ${jobId}. Cmd ${command} from ${state}`); + break; + case ErrorCode.ParentJobCannotBeReplaced: + error = new Error(`The parent job ${parentKey} cannot be replaced. ${command}`); + break; + case ErrorCode.JobBelongsToJobScheduler: + error = new Error(`Job ${jobId} belongs to a job scheduler and cannot be removed directly. ${command}`); + break; + case ErrorCode.JobHasFailedChildren: + error = new UnrecoverableError(`Cannot complete job ${jobId} because it has at least one failed child. ${command}`); + break; + case ErrorCode.SchedulerJobIdCollision: + error = new Error(`Cannot create job scheduler iteration - job ID already exists. ${command}`); + break; + case ErrorCode.SchedulerJobSlotsBusy: + error = new Error(`Cannot create job scheduler iteration - current and next time slots already have jobs. ${command}`); + break; + default: + error = new Error(`Unknown code ${code} error for ${jobId}. ${command}`); + } + error.code = code; + return error; + } + async removeOrphanedJobs(candidateJobIds, stateKeySuffixes, jobSubKeySuffixes) { + const client = await this.queue.client; + const args = [ + this.queue.toKey(""), + stateKeySuffixes.length, + ...stateKeySuffixes, + jobSubKeySuffixes.length, + ...jobSubKeySuffixes, + ...candidateJobIds + ]; + return this.execCommand(client, "removeOrphanedJobs", args); + } } -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/package.json -var package_default = { - name: "@aws-sdk/client-s3", - description: "AWS SDK for JavaScript S3 Client for Node.js, Browser and React Native", - version: "3.1032.0", - scripts: { - build: "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs", - "build:cjs": "node ../../scripts/compilation/inline client-s3", - "build:es": "tsc -p tsconfig.es.json", - "build:include:deps": 'yarn g:turbo run build -F="$npm_package_name"', - "build:types": "tsc -p tsconfig.types.json", - "build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4", - clean: "premove dist-cjs dist-es dist-types tsconfig.cjs.tsbuildinfo tsconfig.es.tsbuildinfo tsconfig.types.tsbuildinfo", - "extract:docs": "api-extractor run --local", - "generate:client": "node ../../scripts/generate-clients/single-service --solo s3", - test: "yarn g:vitest run", - "test:browser": "node ./test/browser-build/esbuild && yarn g:vitest run -c vitest.config.browser.mts", - "test:browser:watch": "node ./test/browser-build/esbuild && yarn g:vitest watch -c vitest.config.browser.mts", - "test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts && yarn test:browser", - "test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts", - "test:index": "tsc --noEmit ./test/index-types.ts && node ./test/index-objects.spec.mjs", - "test:integration": "yarn g:vitest run -c vitest.config.integ.mts", - "test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.mts", - "test:watch": "yarn g:vitest watch" - }, - main: "./dist-cjs/index.js", - types: "./dist-types/index.d.ts", - module: "./dist-es/index.js", - sideEffects: false, - dependencies: { - "@aws-crypto/sha1-browser": "5.2.0", - "@aws-crypto/sha256-browser": "5.2.0", - "@aws-crypto/sha256-js": "5.2.0", - "@aws-sdk/core": "^3.974.1", - "@aws-sdk/credential-provider-node": "^3.972.32", - "@aws-sdk/middleware-bucket-endpoint": "^3.972.10", - "@aws-sdk/middleware-expect-continue": "^3.972.10", - "@aws-sdk/middleware-flexible-checksums": "^3.974.9", - "@aws-sdk/middleware-host-header": "^3.972.10", - "@aws-sdk/middleware-location-constraint": "^3.972.10", - "@aws-sdk/middleware-logger": "^3.972.10", - "@aws-sdk/middleware-recursion-detection": "^3.972.11", - "@aws-sdk/middleware-sdk-s3": "^3.972.30", - "@aws-sdk/middleware-ssec": "^3.972.10", - "@aws-sdk/middleware-user-agent": "^3.972.31", - "@aws-sdk/region-config-resolver": "^3.972.12", - "@aws-sdk/signature-v4-multi-region": "^3.996.18", - "@aws-sdk/types": "^3.973.8", - "@aws-sdk/util-endpoints": "^3.996.7", - "@aws-sdk/util-user-agent-browser": "^3.972.10", - "@aws-sdk/util-user-agent-node": "^3.973.17", - "@smithy/config-resolver": "^4.4.16", - "@smithy/core": "^3.23.15", - "@smithy/eventstream-serde-browser": "^4.2.14", - "@smithy/eventstream-serde-config-resolver": "^4.3.14", - "@smithy/eventstream-serde-node": "^4.2.14", - "@smithy/fetch-http-handler": "^5.3.17", - "@smithy/hash-blob-browser": "^4.2.15", - "@smithy/hash-node": "^4.2.14", - "@smithy/hash-stream-node": "^4.2.14", - "@smithy/invalid-dependency": "^4.2.14", - "@smithy/md5-js": "^4.2.14", - "@smithy/middleware-content-length": "^4.2.14", - "@smithy/middleware-endpoint": "^4.4.30", - "@smithy/middleware-retry": "^4.5.3", - "@smithy/middleware-serde": "^4.2.18", - "@smithy/middleware-stack": "^4.2.14", - "@smithy/node-config-provider": "^4.3.14", - "@smithy/node-http-handler": "^4.5.3", - "@smithy/protocol-http": "^5.3.14", - "@smithy/smithy-client": "^4.12.11", - "@smithy/types": "^4.14.1", - "@smithy/url-parser": "^4.2.14", - "@smithy/util-base64": "^4.3.2", - "@smithy/util-body-length-browser": "^4.2.2", - "@smithy/util-body-length-node": "^4.2.3", - "@smithy/util-defaults-mode-browser": "^4.3.47", - "@smithy/util-defaults-mode-node": "^4.2.52", - "@smithy/util-endpoints": "^3.4.1", - "@smithy/util-middleware": "^4.2.14", - "@smithy/util-retry": "^4.3.2", - "@smithy/util-stream": "^4.5.23", - "@smithy/util-utf8": "^4.2.2", - "@smithy/util-waiter": "^4.2.16", - tslib: "^2.6.2" - }, - devDependencies: { - "@aws-sdk/signature-v4-crt": "3.1032.0", - "@smithy/snapshot-testing": "^2.0.6", - "@tsconfig/node20": "20.1.8", - "@types/node": "^20.14.8", - concurrently: "7.0.0", - "downlevel-dts": "0.10.1", - premove: "4.0.0", - typescript: "~5.8.3", - vitest: "^4.0.17" - }, - engines: { - node: ">=20.0.0" - }, - typesVersions: { - "<4.5": { - "dist-types/*": [ - "dist-types/ts3.4/*" - ] +function raw2NextJobData(raw) { + if (raw) { + const result = [null, raw[1], raw[2], raw[3]]; + if (raw[0]) { + result[0] = array2obj(raw[0]); + } + return result; + } + return []; +} + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/utils/create-scripts.js +var createScripts = (queue) => { + return new Scripts({ + keys: queue.keys, + client: queue.client, + get redisVersion() { + return queue.redisVersion; + }, + toKey: queue.toKey, + opts: queue.opts, + closing: queue.closing, + databaseType: queue.databaseType + }); +}; + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/job.js +var logger = debuglog("bull"); +var PRIORITY_LIMIT = 2 ** 21; + +class Job { + constructor(queue, name, data, opts = {}, id) { + this.queue = queue; + this.name = name; + this.data = data; + this.opts = opts; + this.id = id; + this.progress = 0; + this.returnvalue = null; + this.stacktrace = null; + this.delay = 0; + this.priority = 0; + this.attemptsStarted = 0; + this.attemptsMade = 0; + this.stalledCounter = 0; + const _a = this.opts, { repeatJobKey } = _a, restOpts = __rest(_a, ["repeatJobKey"]); + this.opts = Object.assign({ + attempts: 0 + }, restOpts); + this.delay = this.opts.delay; + this.priority = this.opts.priority || 0; + this.repeatJobKey = repeatJobKey; + this.timestamp = opts.timestamp ? opts.timestamp : Date.now(); + this.opts.backoff = Backoffs.normalize(opts.backoff); + this.parentKey = getParentKey(opts.parent); + if (opts.parent) { + this.parent = { id: opts.parent.id, queueKey: opts.parent.queue }; + if (opts.failParentOnFailure) { + this.parent.fpof = true; + } + if (opts.removeDependencyOnFailure) { + this.parent.rdof = true; + } + if (opts.ignoreDependencyOnFailure) { + this.parent.idof = true; + } + if (opts.continueParentOnFailure) { + this.parent.cpof = true; + } + } + this.debounceId = opts.debounce ? opts.debounce.id : undefined; + this.deduplicationId = opts.deduplication ? opts.deduplication.id : this.debounceId; + this.toKey = queue.toKey.bind(queue); + this.createScripts(); + this.queueQualifiedName = queue.qualifiedName; + } + static async create(queue, name, data, opts) { + const client = await queue.client; + const job = new this(queue, name, data, opts, opts && opts.jobId); + job.id = await job.addJob(client, { + parentKey: job.parentKey, + parentDependenciesKey: job.parentKey ? `${job.parentKey}:dependencies` : "" + }); + return job; + } + static async createBulk(queue, jobs) { + const client = await queue.client; + const jobInstances = jobs.map((job) => { + var _a; + return new this(queue, job.name, job.data, job.opts, (_a = job.opts) === null || _a === undefined ? undefined : _a.jobId); + }); + const pipeline = client.pipeline(); + for (const job of jobInstances) { + job.addJob(pipeline, { + parentKey: job.parentKey, + parentDependenciesKey: job.parentKey ? `${job.parentKey}:dependencies` : "" + }); + } + const results = await pipeline.exec(); + for (let index3 = 0;index3 < results.length; ++index3) { + const [err, id] = results[index3]; + if (err) { + throw err; + } + jobInstances[index3].id = id; + } + return jobInstances; + } + static fromJSON(queue, json3, jobId) { + const data = JSON.parse(json3.data || "{}"); + const opts = Job.optsFromJSON(json3.opts); + const job = new this(queue, json3.name, data, opts, json3.id || jobId); + job.progress = JSON.parse(json3.progress || "0"); + job.delay = parseInt(json3.delay); + job.priority = parseInt(json3.priority); + job.timestamp = parseInt(json3.timestamp); + if (json3.finishedOn) { + job.finishedOn = parseInt(json3.finishedOn); + } + if (json3.processedOn) { + job.processedOn = parseInt(json3.processedOn); + } + if (json3.rjk) { + job.repeatJobKey = json3.rjk; + } + if (json3.deid) { + job.debounceId = json3.deid; + job.deduplicationId = json3.deid; + } + if (json3.failedReason) { + job.failedReason = json3.failedReason; + } + job.attemptsStarted = parseInt(json3.ats || "0"); + job.attemptsMade = parseInt(json3.attemptsMade || json3.atm || "0"); + job.stalledCounter = parseInt(json3.stc || "0"); + if (json3.defa) { + job.deferredFailure = json3.defa; + } + job.stacktrace = getTraces(json3.stacktrace); + if (typeof json3.returnvalue === "string") { + job.returnvalue = getReturnValue(json3.returnvalue); + } + if (json3.parentKey) { + job.parentKey = json3.parentKey; + } + if (json3.parent) { + job.parent = JSON.parse(json3.parent); + } + if (json3.pb) { + job.processedBy = json3.pb; + } + if (json3.nrjid) { + job.nextRepeatableJobId = json3.nrjid; + } + return job; + } + createScripts() { + this.scripts = createScripts(this.queue); + } + static optsFromJSON(rawOpts, optsDecode = optsDecodeMap) { + const opts = JSON.parse(rawOpts || "{}"); + const optionEntries = Object.entries(opts); + const options = {}; + for (const item of optionEntries) { + const [attributeName, value] = item; + if (optsDecode[attributeName]) { + options[optsDecode[attributeName]] = value; + } else { + if (attributeName === "tm") { + options.telemetry = Object.assign(Object.assign({}, options.telemetry), { metadata: value }); + } else if (attributeName === "omc") { + options.telemetry = Object.assign(Object.assign({}, options.telemetry), { omitContext: value }); + } else { + options[attributeName] = value; + } + } + } + return options; + } + static async fromId(queue, jobId) { + if (jobId) { + const client = await queue.client; + const jobData = await client.hgetall(queue.toKey(jobId)); + return isEmpty(jobData) ? undefined : this.fromJSON(queue, jobData, jobId); + } + } + static addJobLog(queue, jobId, logRow, keepLogs) { + const scripts = queue.scripts; + return scripts.addLog(jobId, logRow, keepLogs); + } + toJSON() { + const _a = this, { queue, scripts } = _a, withoutQueueAndScripts = __rest(_a, ["queue", "scripts"]); + return withoutQueueAndScripts; + } + asJSON() { + return removeUndefinedFields({ + id: this.id, + name: this.name, + data: JSON.stringify(typeof this.data === "undefined" ? {} : this.data), + opts: Job.optsAsJSON(this.opts), + parent: this.parent ? Object.assign({}, this.parent) : undefined, + parentKey: this.parentKey, + progress: this.progress, + attemptsMade: this.attemptsMade, + attemptsStarted: this.attemptsStarted, + stalledCounter: this.stalledCounter, + finishedOn: this.finishedOn, + processedOn: this.processedOn, + timestamp: this.timestamp, + failedReason: JSON.stringify(this.failedReason), + stacktrace: JSON.stringify(this.stacktrace), + debounceId: this.debounceId, + deduplicationId: this.deduplicationId, + repeatJobKey: this.repeatJobKey, + returnvalue: JSON.stringify(this.returnvalue), + nrjid: this.nextRepeatableJobId + }); + } + static optsAsJSON(opts = {}, optsEncode = optsEncodeMap) { + const optionEntries = Object.entries(opts); + const options = {}; + for (const [attributeName, value] of optionEntries) { + if (typeof value === "undefined") { + continue; + } + if (attributeName in optsEncode) { + const compressableAttribute = attributeName; + const key = optsEncode[compressableAttribute]; + options[key] = value; + } else { + if (attributeName === "telemetry") { + if (value.metadata !== undefined) { + options.tm = value.metadata; + } + if (value.omitContext !== undefined) { + options.omc = value.omitContext; + } + } else { + options[attributeName] = value; + } + } + } + return options; + } + asJSONSandbox() { + return Object.assign(Object.assign({}, this.asJSON()), { queueName: this.queueName, queueQualifiedName: this.queueQualifiedName, prefix: this.prefix }); + } + updateData(data) { + this.data = data; + return this.scripts.updateData(this, data); + } + async updateProgress(progress) { + this.progress = progress; + await this.scripts.updateProgress(this.id, progress); + this.queue.emit("progress", this, progress); + } + async log(logRow) { + return Job.addJobLog(this.queue, this.id, logRow, this.opts.keepLogs); + } + async removeChildDependency() { + const childDependencyIsRemoved = await this.scripts.removeChildDependency(this.id, this.parentKey); + if (childDependencyIsRemoved) { + this.parent = undefined; + this.parentKey = undefined; + return true; + } + return false; + } + async clearLogs(keepLogs) { + const client = await this.queue.client; + const logsKey = this.toKey(this.id) + ":logs"; + if (keepLogs) { + await client.ltrim(logsKey, -keepLogs, -1); + } else { + await client.del(logsKey); + } + } + async remove({ removeChildren = true } = {}) { + await this.queue.waitUntilReady(); + const queue = this.queue; + const job = this; + const removed = await this.scripts.remove(job.id, removeChildren); + if (removed) { + queue.emit("removed", job); + } else { + throw new Error(`Job ${this.id} could not be removed because it is locked by another worker`); + } + } + async removeUnprocessedChildren() { + const jobId = this.id; + await this.scripts.removeUnprocessedChildren(jobId); + } + extendLock(token, duration) { + return this.scripts.extendLock(this.id, token, duration); + } + async moveToCompleted(returnValue, token, fetchNext = true) { + return this.queue.trace(SpanKind.INTERNAL, "complete", this.queue.name, async (span) => { + this.setSpanJobAttributes(span); + await this.queue.waitUntilReady(); + this.returnvalue = returnValue || undefined; + const stringifiedReturnValue = tryCatch(JSON.stringify, JSON, [ + returnValue + ]); + if (stringifiedReturnValue === errorObject) { + throw errorObject.value; + } + const args = this.scripts.moveToCompletedArgs(this, stringifiedReturnValue, this.opts.removeOnComplete, token, fetchNext); + const result = await this.scripts.moveToFinished(this.id, args); + this.finishedOn = args[this.scripts.moveToFinishedKeys.length + 1]; + this.attemptsMade += 1; + this.recordJobMetrics("completed"); + return result; + }); + } + async moveToWait(token) { + const result = await this.scripts.moveJobFromActiveToWait(this.id, token); + this.recordJobMetrics("waiting"); + return result; + } + async shouldRetryJob(err) { + if (this.attemptsMade + 1 < this.opts.attempts && !this.discarded && !(err instanceof UnrecoverableError || err.name == "UnrecoverableError")) { + const opts = this.queue.opts; + const delay2 = await Backoffs.calculate(this.opts.backoff, this.attemptsMade + 1, err, this, opts.settings && opts.settings.backoffStrategy); + return [delay2 == -1 ? false : true, delay2 == -1 ? 0 : delay2]; + } else { + return [false, 0]; + } + } + async moveToFailed(err, token, fetchNext = false) { + this.failedReason = err === null || err === undefined ? undefined : err.message; + const [shouldRetry, retryDelay] = await this.shouldRetryJob(err); + return this.queue.trace(SpanKind.INTERNAL, this.getSpanOperation(shouldRetry, retryDelay), this.queue.name, async (span, dstPropagationMetadata) => { + var _a, _b; + this.setSpanJobAttributes(span); + let tm; + if (!((_b = (_a = this.opts) === null || _a === undefined ? undefined : _a.telemetry) === null || _b === undefined ? undefined : _b.omitContext) && dstPropagationMetadata) { + tm = dstPropagationMetadata; + } + let result; + this.updateStacktrace(err); + const fieldsToUpdate = { + failedReason: this.failedReason, + stacktrace: JSON.stringify(this.stacktrace), + tm + }; + let finishedOn; + if (shouldRetry) { + if (retryDelay) { + result = await this.scripts.moveToDelayed(this.id, Date.now(), retryDelay, token, { fieldsToUpdate, fetchNext }); + this.recordJobMetrics("delayed"); + } else { + result = await this.scripts.retryJob(this.id, this.opts.lifo, token, { + fieldsToUpdate + }); + this.recordJobMetrics("retried"); + } + } else { + const args = this.scripts.moveToFailedArgs(this, this.failedReason, this.opts.removeOnFail, token, fetchNext, fieldsToUpdate); + result = await this.scripts.moveToFinished(this.id, args); + finishedOn = args[this.scripts.moveToFinishedKeys.length + 1]; + this.recordJobMetrics("failed"); + } + if (finishedOn && typeof finishedOn === "number") { + this.finishedOn = finishedOn; + } + if (retryDelay && typeof retryDelay === "number") { + this.delay = retryDelay; + } + this.attemptsMade += 1; + return result; + }); + } + getSpanOperation(shouldRetry, retryDelay) { + if (shouldRetry) { + if (retryDelay) { + return "delay"; + } + return "retry"; + } + return "fail"; + } + recordJobMetrics(status) { + var _a, _b; + const meter = (_b = (_a = this.queue.opts) === null || _a === undefined ? undefined : _a.telemetry) === null || _b === undefined ? undefined : _b.meter; + if (!meter) { + return; + } + const attributes = { + [TelemetryAttributes.QueueName]: this.queue.name, + [TelemetryAttributes.JobName]: this.name, + [TelemetryAttributes.JobStatus]: status + }; + const statusToCounterName = { + completed: MetricNames.JobsCompleted, + failed: MetricNames.JobsFailed, + delayed: MetricNames.JobsDelayed, + retried: MetricNames.JobsRetried, + waiting: MetricNames.JobsWaiting, + "waiting-children": MetricNames.JobsWaitingChildren + }; + const counterName = statusToCounterName[status]; + const counter = meter.createCounter(counterName, { + description: `Number of jobs ${status}`, + unit: "1" + }); + counter.add(1, attributes); + if (this.processedOn) { + const duration = Date.now() - this.processedOn; + const histogram = meter.createHistogram(MetricNames.JobDuration, { + description: "Job processing duration", + unit: "ms" + }); + histogram.record(duration, attributes); + } + } + isCompleted() { + return this.isInZSet("completed"); + } + isFailed() { + return this.isInZSet("failed"); + } + isDelayed() { + return this.isInZSet("delayed"); + } + isWaitingChildren() { + return this.isInZSet("waiting-children"); + } + isActive() { + return this.isInList("active"); + } + async isWaiting() { + return await this.isInList("wait") || await this.isInList("paused"); + } + get queueName() { + return this.queue.name; + } + get prefix() { + return this.queue.opts.prefix; + } + getState() { + return this.scripts.getState(this.id); + } + async changeDelay(delay2) { + await this.scripts.changeDelay(this.id, delay2); + this.delay = delay2; + } + async changePriority(opts) { + await this.scripts.changePriority(this.id, opts.priority, opts.lifo); + this.priority = opts.priority || 0; + } + async getChildrenValues() { + const client = await this.queue.client; + const result = await client.hgetall(this.toKey(`${this.id}:processed`)); + if (result) { + return parseObjectValues(result); + } + } + async getIgnoredChildrenFailures() { + const client = await this.queue.client; + return client.hgetall(this.toKey(`${this.id}:failed`)); + } + async getFailedChildrenValues() { + const client = await this.queue.client; + return client.hgetall(this.toKey(`${this.id}:failed`)); + } + async getDependencies(opts = {}) { + const client = await this.queue.client; + const multi = client.multi(); + if (!opts.processed && !opts.unprocessed && !opts.ignored && !opts.failed) { + multi.hgetall(this.toKey(`${this.id}:processed`)); + multi.smembers(this.toKey(`${this.id}:dependencies`)); + multi.hgetall(this.toKey(`${this.id}:failed`)); + multi.zrange(this.toKey(`${this.id}:unsuccessful`), 0, -1); + const [[err1, processed], [err2, unprocessed], [err3, ignored], [err4, failed]] = await multi.exec(); + return { + processed: parseObjectValues(processed), + unprocessed, + failed, + ignored + }; + } else { + const defaultOpts = { + cursor: 0, + count: 20 + }; + const childrenResultOrder = []; + if (opts.processed) { + childrenResultOrder.push("processed"); + const processedOpts = Object.assign(Object.assign({}, defaultOpts), opts.processed); + multi.hscan(this.toKey(`${this.id}:processed`), processedOpts.cursor, "COUNT", processedOpts.count); + } + if (opts.unprocessed) { + childrenResultOrder.push("unprocessed"); + const unprocessedOpts = Object.assign(Object.assign({}, defaultOpts), opts.unprocessed); + multi.sscan(this.toKey(`${this.id}:dependencies`), unprocessedOpts.cursor, "COUNT", unprocessedOpts.count); + } + if (opts.ignored) { + childrenResultOrder.push("ignored"); + const ignoredOpts = Object.assign(Object.assign({}, defaultOpts), opts.ignored); + multi.hscan(this.toKey(`${this.id}:failed`), ignoredOpts.cursor, "COUNT", ignoredOpts.count); + } + let failedCursor; + if (opts.failed) { + childrenResultOrder.push("failed"); + const failedOpts = Object.assign(Object.assign({}, defaultOpts), opts.failed); + failedCursor = failedOpts.cursor + failedOpts.count; + multi.zrange(this.toKey(`${this.id}:unsuccessful`), failedOpts.cursor, failedOpts.count - 1); + } + const results = await multi.exec(); + let processedCursor, processed, unprocessedCursor, unprocessed, failed, ignoredCursor, ignored; + childrenResultOrder.forEach((key, index3) => { + switch (key) { + case "processed": { + processedCursor = results[index3][1][0]; + const rawProcessed = results[index3][1][1]; + const transformedProcessed = {}; + for (let ind = 0;ind < rawProcessed.length; ++ind) { + if (ind % 2) { + transformedProcessed[rawProcessed[ind - 1]] = JSON.parse(rawProcessed[ind]); + } + } + processed = transformedProcessed; + break; + } + case "failed": { + failed = results[index3][1]; + break; + } + case "ignored": { + ignoredCursor = results[index3][1][0]; + const rawIgnored = results[index3][1][1]; + const transformedIgnored = {}; + for (let ind = 0;ind < rawIgnored.length; ++ind) { + if (ind % 2) { + transformedIgnored[rawIgnored[ind - 1]] = rawIgnored[ind]; + } + } + ignored = transformedIgnored; + break; + } + case "unprocessed": { + unprocessedCursor = results[index3][1][0]; + unprocessed = results[index3][1][1]; + break; + } + } + }); + return Object.assign(Object.assign(Object.assign(Object.assign({}, processedCursor ? { + processed, + nextProcessedCursor: Number(processedCursor) + } : {}), ignoredCursor ? { + ignored, + nextIgnoredCursor: Number(ignoredCursor) + } : {}), failedCursor ? { + failed, + nextFailedCursor: failedCursor + } : {}), unprocessedCursor ? { unprocessed, nextUnprocessedCursor: Number(unprocessedCursor) } : {}); + } + } + async getDependenciesCount(opts = {}) { + const types6 = []; + Object.entries(opts).forEach(([key, value]) => { + if (value) { + types6.push(key); + } + }); + const finalTypes = types6.length ? types6 : ["processed", "unprocessed", "ignored", "failed"]; + const responses = await this.scripts.getDependencyCounts(this.id, finalTypes); + const counts = {}; + responses.forEach((res, index3) => { + counts[`${finalTypes[index3]}`] = res || 0; + }); + return counts; + } + async waitUntilFinished(queueEvents, ttl) { + await this.queue.waitUntilReady(); + const jobId = this.id; + return new Promise(async (resolve, reject) => { + let timeout; + if (ttl) { + timeout = setTimeout(() => onFailed(`Job wait ${this.name} timed out before finishing, no finish notification arrived after ${ttl}ms (id=${jobId})`), ttl); + } + function onCompleted(args) { + removeListeners(); + resolve(args.returnvalue); + } + function onFailed(args) { + removeListeners(); + reject(new Error(args.failedReason || args)); + } + const completedEvent = `completed:${jobId}`; + const failedEvent = `failed:${jobId}`; + queueEvents.on(completedEvent, onCompleted); + queueEvents.on(failedEvent, onFailed); + this.queue.on("closing", onFailed); + const removeListeners = () => { + clearInterval(timeout); + queueEvents.removeListener(completedEvent, onCompleted); + queueEvents.removeListener(failedEvent, onFailed); + this.queue.removeListener("closing", onFailed); + }; + await queueEvents.waitUntilReady(); + const [status, result] = await this.scripts.isFinished(jobId, true); + const finished = status != 0; + if (finished) { + if (status == -1 || status == 2) { + onFailed({ failedReason: result }); + } else { + onCompleted({ returnvalue: getReturnValue(result) }); + } + } + }); + } + async moveToDelayed(timestamp3, token) { + const now = Date.now(); + const delay2 = timestamp3 - now; + const finalDelay = delay2 > 0 ? delay2 : 0; + await this.scripts.moveToDelayed(this.id, now, finalDelay, token, { + skipAttempt: true + }); + this.delay = finalDelay; + this.recordJobMetrics("delayed"); + } + async moveToWaitingChildren(token, opts = {}) { + const movedToWaitingChildren = await this.scripts.moveToWaitingChildren(this.id, token, opts); + if (movedToWaitingChildren) { + this.recordJobMetrics("waiting-children"); + } + return movedToWaitingChildren; + } + async promote() { + const jobId = this.id; + await this.scripts.promote(jobId); + this.delay = 0; + } + async retry(state = "failed", opts = {}) { + await this.scripts.reprocessJob(this, state, opts); + this.failedReason = null; + this.finishedOn = null; + this.processedOn = null; + this.returnvalue = null; + if (opts.resetAttemptsMade) { + this.attemptsMade = 0; + } + if (opts.resetAttemptsStarted) { + this.attemptsStarted = 0; + } + } + discard() { + this.discarded = true; + } + async isInZSet(set) { + const client = await this.queue.client; + const score = await client.zscore(this.queue.toKey(set), this.id); + return score !== null; + } + async isInList(list) { + return this.scripts.isJobInList(this.queue.toKey(list), this.id); + } + addJob(client, parentOpts) { + const jobData = this.asJSON(); + this.validateOptions(jobData); + return this.scripts.addJob(client, jobData, jobData.opts, this.id, parentOpts); + } + async removeDeduplicationKey() { + if (this.deduplicationId) { + const result = await this.scripts.removeDeduplicationKey(this.deduplicationId, this.id); + return result > 0; + } + return false; + } + validateOptions(jobData) { + var _a, _b, _c2, _d2, _e2, _f, _g, _h2; + const exclusiveOptions = [ + "removeDependencyOnFailure", + "failParentOnFailure", + "continueParentOnFailure", + "ignoreDependencyOnFailure" + ]; + const exceedLimit = this.opts.sizeLimit && lengthInUtf8Bytes(jobData.data) > this.opts.sizeLimit; + if (exceedLimit) { + throw new Error(`The size of job ${this.name} exceeds the limit ${this.opts.sizeLimit} bytes`); + } + if (this.opts.delay && this.opts.repeat && !((_a = this.opts.repeat) === null || _a === undefined ? undefined : _a.count)) { + throw new Error(`Delay and repeat options cannot be used together`); + } + const enabledExclusiveOptions = exclusiveOptions.filter((opt) => this.opts[opt]); + if (enabledExclusiveOptions.length > 1) { + const optionsList = enabledExclusiveOptions.join(", "); + throw new Error(`The following options cannot be used together: ${optionsList}`); + } + if ((_b = this.opts) === null || _b === undefined ? undefined : _b.jobId) { + if (`${parseInt(this.opts.jobId, 10)}` === ((_c2 = this.opts) === null || _c2 === undefined ? undefined : _c2.jobId)) { + throw new Error("Custom Id cannot be integers"); + } + if (((_d2 = this.opts) === null || _d2 === undefined ? undefined : _d2.jobId.includes(":")) && ((_f = (_e2 = this.opts) === null || _e2 === undefined ? undefined : _e2.jobId) === null || _f === undefined ? undefined : _f.split(":").length) !== 3) { + throw new Error("Custom Id cannot contain :"); + } + } + if (this.opts.priority) { + if (Math.trunc(this.opts.priority) !== this.opts.priority) { + throw new Error(`Priority should not be float`); + } + if (this.opts.priority > PRIORITY_LIMIT) { + throw new Error(`Priority should be between 0 and ${PRIORITY_LIMIT}`); + } + } + if (this.opts.deduplication) { + if (!((_g = this.opts.deduplication) === null || _g === undefined ? undefined : _g.id)) { + throw new Error("Deduplication id must be provided"); + } + if (this.parentKey) { + throw new Error("Deduplication and parent options cannot be used together"); + } + } + if (this.opts.debounce) { + if (!((_h2 = this.opts.debounce) === null || _h2 === undefined ? undefined : _h2.id)) { + throw new Error("Debounce id must be provided"); + } + if (this.parentKey) { + throw new Error("Debounce and parent options cannot be used together"); + } + } + if (typeof this.opts.backoff === "object" && typeof this.opts.backoff.jitter === "number") { + if (this.opts.backoff.jitter < 0 || this.opts.backoff.jitter > 1) { + throw new Error(`Jitter should be between 0 and 1`); + } + } + } + updateStacktrace(err) { + this.stacktrace = this.stacktrace || []; + if (err === null || err === undefined ? undefined : err.stack) { + this.stacktrace.push(err.stack); + if (this.opts.stackTraceLimit === 0) { + this.stacktrace = []; + } else if (this.opts.stackTraceLimit) { + this.stacktrace = this.stacktrace.slice(-this.opts.stackTraceLimit); + } + } + } + setSpanJobAttributes(span) { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobName]: this.name, + [TelemetryAttributes.JobId]: this.id + }); + } +} +function getTraces(stacktrace) { + if (!stacktrace) { + return []; + } + const traces = tryCatch(JSON.parse, JSON, [stacktrace]); + if (traces === errorObject || !(traces instanceof Array)) { + return []; + } else { + return traces; + } +} +function getReturnValue(_value) { + const value = tryCatch(JSON.parse, JSON, [_value]); + if (value !== errorObject) { + return value; + } else { + logger("corrupted returnvalue: " + _value, value); + } +} + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/queue-keys.js +class QueueKeys { + constructor(prefix = "bull") { + this.prefix = prefix; + } + getKeys(name) { + const keys = {}; + [ + "", + "active", + "wait", + "waiting-children", + "paused", + "id", + "delayed", + "prioritized", + "stalled-check", + "completed", + "failed", + "stalled", + "repeat", + "limiter", + "meta", + "events", + "pc", + "marker", + "de" + ].forEach((key) => { + keys[key] = this.toKey(name, key); + }); + return keys; + } + toKey(name, type) { + return `${this.getQueueQualifiedName(name)}:${type}`; + } + getQueueQualifiedName(name) { + return `${this.prefix}:${name}`; + } +} + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/redis-connection.js +var import_ioredis3 = __toESM(require_built3(), 1); +var import_utils58 = __toESM(require_utils7(), 1); +import { EventEmitter } from "events"; + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/index.js +var exports_scripts = {}; +__export(exports_scripts, { + updateRepeatableJobMillis: () => updateRepeatableJobMillis, + updateProgress: () => updateProgress, + updateJobScheduler: () => updateJobScheduler, + updateData: () => updateData, + saveStacktrace: () => saveStacktrace, + retryJob: () => retryJob, + reprocessJob: () => reprocessJob, + removeUnprocessedChildren: () => removeUnprocessedChildren, + removeRepeatable: () => removeRepeatable, + removeOrphanedJobs: () => removeOrphanedJobs, + removeJobScheduler: () => removeJobScheduler, + removeJob: () => removeJob, + removeDeduplicationKey: () => removeDeduplicationKey, + removeChildDependency: () => removeChildDependency, + releaseLock: () => releaseLock, + promote: () => promote, + pause: () => pause, + paginate: () => paginate, + obliterate: () => obliterate, + moveToWaitingChildren: () => moveToWaitingChildren, + moveToFinished: () => moveToFinished, + moveToDelayed: () => moveToDelayed, + moveToActive: () => moveToActive, + moveStalledJobsToWait: () => moveStalledJobsToWait, + moveJobsToWait: () => moveJobsToWait, + moveJobFromActiveToWait: () => moveJobFromActiveToWait, + isMaxed: () => isMaxed, + isJobInList: () => isJobInList, + isFinished: () => isFinished, + getStateV2: () => getStateV2, + getState: () => getState, + getRateLimitTtl: () => getRateLimitTtl, + getRanges: () => getRanges, + getMetrics: () => getMetrics, + getJobScheduler: () => getJobScheduler, + getDependencyCounts: () => getDependencyCounts, + getCountsPerPriority: () => getCountsPerPriority, + getCounts: () => getCounts, + extendLocks: () => extendLocks, + extendLock: () => extendLock, + drain: () => drain, + cleanJobsInSet: () => cleanJobsInSet, + changePriority: () => changePriority, + changeDelay: () => changeDelay, + addStandardJob: () => addStandardJob, + addRepeatableJob: () => addRepeatableJob, + addPrioritizedJob: () => addPrioritizedJob, + addParentJob: () => addParentJob, + addLog: () => addLog, + addJobScheduler: () => addJobScheduler, + addDelayedJob: () => addDelayedJob +}); + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addDelayedJob-6.js +var content = `--[[ + Adds a delayed job to the queue by doing the following: + - Increases the job counter if needed. + - Creates a new job key with the job data. + - computes timestamp. + - adds to delayed zset. + - Emits a global event 'delayed' if the job is delayed. + Input: + KEYS[1] 'marker', + KEYS[2] 'meta' + KEYS[3] 'id' + KEYS[4] 'delayed' + KEYS[5] 'completed' + KEYS[6] events stream key + ARGV[1] msgpacked arguments array + [1] key prefix, + [2] custom id (use custom instead of one generated automatically) + [3] name + [4] timestamp + [5] parentKey? + [6] parent dependencies key. + [7] parent? {id, queueKey} + [8] repeat job key + [9] deduplication key + ARGV[2] Json stringified job data + ARGV[3] msgpacked options + Output: + jobId - OK + -5 - Missing parent key +]] +local metaKey = KEYS[2] +local idKey = KEYS[3] +local delayedKey = KEYS[4] +local completedKey = KEYS[5] +local eventsKey = KEYS[6] +local jobId +local jobIdKey +local rcall = redis.call +local args = cmsgpack.unpack(ARGV[1]) +local data = ARGV[2] +local parentKey = args[5] +local parent = args[7] +local repeatJobKey = args[8] +local deduplicationKey = args[9] +local parentData +-- Includes +--[[ + Adds a delayed job to the queue by doing the following: + - Creates a new job key with the job data. + - adds to delayed zset. + - Emits a global event 'delayed' if the job is delayed. +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Bake in the job id first 12 bits into the timestamp + to guarantee correct execution order of delayed jobs + (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp) + WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail +]] +local function getDelayedScore(delayedKey, timestamp, delay) + local delayedTimestamp = (delay > 0 and (tonumber(timestamp) + delay)) or tonumber(timestamp) + local minScore = delayedTimestamp * 0x1000 + local maxScore = (delayedTimestamp + 1 ) * 0x1000 - 1 + local result = rcall("ZREVRANGEBYSCORE", delayedKey, maxScore, + minScore, "WITHSCORES","LIMIT", 0, 1) + if #result then + local currentMaxScore = tonumber(result[2]) + if currentMaxScore ~= nil then + if currentMaxScore >= maxScore then + return maxScore, delayedTimestamp + else + return currentMaxScore + 1, delayedTimestamp + end + end + end + return minScore, delayedTimestamp +end +local function addDelayedJob(jobId, delayedKey, eventsKey, timestamp, + maxEvents, markerKey, delay) + local score, delayedTimestamp = getDelayedScore(delayedKey, timestamp, tonumber(delay)) + rcall("ZADD", delayedKey, score, jobId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "delayed", + "jobId", jobId, "delay", delayedTimestamp) + -- mark that a delayed job is available + addDelayMarkerIfNeeded(markerKey, delayedKey) +end +--[[ + Function to debounce a job. +]] +-- Includes +--[[ + Function to deduplicate a job. +]] +--[[ + Function to set the deduplication key for a job. + Uses TTL from deduplication opts if provided. +]] +local function setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + local ttl = deduplicationOpts and deduplicationOpts['ttl'] + if ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'PX', ttl) + else + rcall('SET', deduplicationKey, jobId) + end +end +--[[ + Function to store a deduplicated next job if the existing job is active + and keepLastIfActive is set. When the active job finishes, the stored + proto-job is used to create a real job in the queue. + Returns true if the proto-job was stored, false otherwise. +]] +--[[ + Function to check if an item belongs to a list. +]] +local function checkItemInList(list, item) + for _, v in pairs(list) do + if v == item then + return 1 + end + end + return nil +end +local function storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + if deduplicationOpts['keepLastIfActive'] and currentDebounceJobId then + local activeKey = prefix .. "active" + local activeItems = rcall('LRANGE', activeKey, 0, -1) + if checkItemInList(activeItems, currentDebounceJobId) then + local deduplicationNextKey = prefix .. "dn:" .. deduplicationId + local fields = {'name', jobName, 'data', jobData, 'opts', cjson.encode(fullOpts)} + if parentKey then + fields[#fields+1] = 'pk' + fields[#fields+1] = parentKey + end + if parentData then + fields[#fields+1] = 'pd' + fields[#fields+1] = parentData + end + if parentDependenciesKey then + fields[#fields+1] = 'pdk' + fields[#fields+1] = parentDependenciesKey + end + if repeatJobKey then + fields[#fields+1] = 'rjk' + fields[#fields+1] = repeatJobKey + end + rcall('HSET', deduplicationNextKey, unpack(fields)) + -- Ensure the dedup key does not expire while the job is active, + -- so subsequent adds always hit the dedup path and never bypass + -- the active-check because of a TTL expiry. + local deduplicationKey = prefix .. "de:" .. deduplicationId + rcall('PERSIST', deduplicationKey) + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return true + end + end + return false +end +local function deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, jobId, deduplicationKey, + eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + local ttl = deduplicationOpts['ttl'] + local deduplicationKeyExists + if ttl and ttl > 0 then + if deduplicationOpts['extend'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, currentDebounceJobId) + else + setDeduplicationKey(deduplicationKey, currentDebounceJobId, deduplicationOpts) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", + "jobId", currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + if deduplicationOpts['keepLastIfActive'] then + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'PX', ttl, 'NX') + end + end + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + end + if deduplicationKeyExists then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +local function removeDelayedJob(delayedKey, deduplicationKey, eventsKey, maxEvents, currentDeduplicatedJobId, + jobId, deduplicationId, prefix) + if rcall("ZREM", delayedKey, currentDeduplicatedJobId) > 0 then + removeJobKeys(prefix .. currentDeduplicatedJobId) + rcall("XADD", eventsKey, "*", "event", "removed", "jobId", currentDeduplicatedJobId, + "prev", "delayed") + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + jobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + jobId, "deduplicationId", deduplicationId, "deduplicatedJobId", currentDeduplicatedJobId) + return true + end + return false +end +local function deduplicateJob(deduplicationOpts, jobId, delayedKey, deduplicationKey, eventsKey, maxEvents, + prefix, jobName, jobData, fullOpts, parentKey, parentData, parentDependenciesKey, repeatJobKey) + local deduplicationId = deduplicationOpts and deduplicationOpts['id'] + if deduplicationId then + if deduplicationOpts['replace'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + local isRemoved = removeDelayedJob(delayedKey, deduplicationKey, eventsKey, maxEvents, + currentDebounceJobId, jobId, deduplicationId, prefix) + if isRemoved then + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + local ttl = deduplicationOpts['ttl'] + if not deduplicationOpts['extend'] and ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'KEEPTTL') + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + end + return + else + storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + return currentDebounceJobId + end + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + return deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, + jobId, deduplicationKey, eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + end + end +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to handle the case when job is duplicated. +]] +-- Includes +--[[ + This function is used to update the parent's dependencies if the job + is already completed and about to be ignored. The parent must get its + dependencies updated to avoid the parent job being stuck forever in + the waiting-children state. +]] +-- Includes +--[[ + Validate and move or add dependencies to parent. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) + if no pending dependencies. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) if needed. +]] +-- Includes +--[[ + Move parent to a wait status (wait, prioritized or delayed) +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check if queue is paused or maxed + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePausedOrMaxed(queueMetaKey, activeKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency") + if queueAttributes[1] then + return true + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + return activeCount >= tonumber(queueAttributes[2]) + end + end + return false +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + local parentWaitKey = parentQueueKey .. ":wait" + local parentPausedKey = parentQueueKey .. ":paused" + local parentActiveKey = parentQueueKey .. ":active" + local parentMetaKey = parentQueueKey .. ":meta" + local parentMarkerKey = parentQueueKey .. ":marker" + local jobAttributes = rcall("HMGET", parentKey, "priority", "delay") + local priority = tonumber(jobAttributes[1]) or 0 + local delay = tonumber(jobAttributes[2]) or 0 + if delay > 0 then + local delayedTimestamp = tonumber(timestamp) + delay + local score = delayedTimestamp * 0x1000 + local parentDelayedKey = parentQueueKey .. ":delayed" + rcall("ZADD", parentDelayedKey, score, parentId) + rcall("XADD", parentQueueKey .. ":events", "*", "event", "delayed", "jobId", parentId, "delay", + delayedTimestamp) + addDelayMarkerIfNeeded(parentMarkerKey, parentDelayedKey) + else + if priority == 0 then + local parentTarget, isParentPausedOrMaxed = getTargetQueueList(parentMetaKey, parentActiveKey, + parentWaitKey, parentPausedKey) + addJobInTargetList(parentTarget, parentMarkerKey, "RPUSH", isParentPausedOrMaxed, parentId) + else + local isPausedOrMaxed = isQueuePausedOrMaxed(parentMetaKey, parentActiveKey) + addJobWithPriority(parentMarkerKey, parentQueueKey .. ":prioritized", priority, parentId, + parentQueueKey .. ":pc", isPausedOrMaxed) + end + rcall("XADD", parentQueueKey .. ":events", "*", "event", "waiting", "jobId", parentId, "prev", + "waiting-children") + end +end +local function moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + if rcall("EXISTS", parentKey) == 1 then + local parentWaitingChildrenKey = parentQueueKey .. ":waiting-children" + if rcall("ZSCORE", parentWaitingChildrenKey, parentId) then + rcall("ZREM", parentWaitingChildrenKey, parentId) + moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + end + end +end +local function moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, + parentId, timestamp) + local doNotHavePendingDependencies = rcall("SCARD", parentDependenciesKey) == 0 + if doNotHavePendingDependencies then + moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + end +end +local function updateParentDepsIfNeeded(parentKey, parentQueueKey, parentDependenciesKey, + parentId, jobIdKey, returnvalue, timestamp ) + local processedSet = parentKey .. ":processed" + rcall("HSET", processedSet, jobIdKey, returnvalue) + moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, parentId, timestamp) +end +local function updateExistingJobsParent(parentKey, parent, parentData, + parentDependenciesKey, completedKey, + jobIdKey, jobId, timestamp) + if parentKey ~= nil then + if rcall("ZSCORE", completedKey, jobId) then + local returnvalue = rcall("HGET", jobIdKey, "returnvalue") + updateParentDepsIfNeeded(parentKey, parent['queueKey'], + parentDependenciesKey, parent['id'], + jobIdKey, returnvalue, timestamp) + else + if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) + end + end + rcall("HMSET", jobIdKey, "parentKey", parentKey, "parent", parentData) + end +end +local function handleDuplicatedJob(jobKey, jobId, currentParentKey, currentParent, + parentData, parentDependenciesKey, completedKey, eventsKey, maxEvents, timestamp) + local existedParentKey = rcall("HGET", jobKey, "parentKey") + if not existedParentKey or existedParentKey == currentParentKey then + updateExistingJobsParent(currentParentKey, currentParent, parentData, + parentDependenciesKey, completedKey, jobKey, + jobId, timestamp) + else + if currentParentKey ~= nil and currentParentKey ~= existedParentKey + and (rcall("EXISTS", existedParentKey) == 1) then + return -7 + end + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", + "duplicated", "jobId", jobId) + return jobId .. "" -- convert to string +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +if parentKey ~= nil then + if rcall("EXISTS", parentKey) ~= 1 then return -5 end + parentData = cjson.encode(parent) +end +local jobCounter = rcall("INCR", idKey) +local maxEvents = getOrSetMaxEvents(metaKey) +local opts = cmsgpack.unpack(ARGV[3]) +local parentDependenciesKey = args[6] +local timestamp = args[4] +if args[2] == "" then + jobId = jobCounter + jobIdKey = args[1] .. jobId +else + jobId = args[2] + jobIdKey = args[1] .. jobId + if rcall("EXISTS", jobIdKey) == 1 then + return handleDuplicatedJob(jobIdKey, jobId, parentKey, parent, + parentData, parentDependenciesKey, completedKey, eventsKey, + maxEvents, timestamp) + end +end +local deduplicationJobId = deduplicateJob(opts['de'], jobId, delayedKey, deduplicationKey, + eventsKey, maxEvents, args[1], args[3], ARGV[2], opts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) +if deduplicationJobId then + return deduplicationJobId +end +local delay, priority = storeJob(eventsKey, jobIdKey, jobId, args[3], ARGV[2], + opts, timestamp, parentKey, parentData, repeatJobKey) +addDelayedJob(jobId, delayedKey, eventsKey, timestamp, maxEvents, KEYS[1], delay) +-- Check if this job is a child of another job, if so add it to the parents dependencies +if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) +end +return jobId .. "" -- convert to string +`; +var addDelayedJob = { + name: "addDelayedJob", + content, + keys: 6 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addJobScheduler-11.js +var content2 = `--[[ + Adds a job scheduler, i.e. a job factory that creates jobs based on a given schedule (repeat options). + Input: + KEYS[1] 'repeat' key + KEYS[2] 'delayed' key + KEYS[3] 'wait' key + KEYS[4] 'paused' key + KEYS[5] 'meta' key + KEYS[6] 'prioritized' key + KEYS[7] 'marker' key + KEYS[8] 'id' key + KEYS[9] 'events' key + KEYS[10] 'pc' priority counter + KEYS[11] 'active' key + ARGV[1] next milliseconds + ARGV[2] msgpacked options + [1] name + [2] tz? + [3] pattern? + [4] endDate? + [5] every? + ARGV[3] jobs scheduler id + ARGV[4] Json stringified template data + ARGV[5] mspacked template opts + ARGV[6] msgpacked delayed opts + ARGV[7] timestamp + ARGV[8] prefix key + ARGV[9] producer key + Output: + repeatableKey - OK +]] local rcall = redis.call +local repeatKey = KEYS[1] +local delayedKey = KEYS[2] +local waitKey = KEYS[3] +local pausedKey = KEYS[4] +local metaKey = KEYS[5] +local prioritizedKey = KEYS[6] +local eventsKey = KEYS[9] +local nextMillis = ARGV[1] +local jobSchedulerId = ARGV[3] +local templateOpts = cmsgpack.unpack(ARGV[5]) +local now = tonumber(ARGV[7]) +local prefixKey = ARGV[8] +local jobOpts = cmsgpack.unpack(ARGV[6]) +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Shared helper to store a job and enqueue it into the appropriate list/set. + Handles delayed, prioritized, and standard (LIFO/FIFO) jobs. + Emits the appropriate event after enqueuing ("delayed" or "waiting"). + Returns delay, priority from storeJob. +]] +-- Includes +--[[ + Adds a delayed job to the queue by doing the following: + - Creates a new job key with the job data. + - adds to delayed zset. + - Emits a global event 'delayed' if the job is delayed. +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Bake in the job id first 12 bits into the timestamp + to guarantee correct execution order of delayed jobs + (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp) + WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail +]] +local function getDelayedScore(delayedKey, timestamp, delay) + local delayedTimestamp = (delay > 0 and (tonumber(timestamp) + delay)) or tonumber(timestamp) + local minScore = delayedTimestamp * 0x1000 + local maxScore = (delayedTimestamp + 1 ) * 0x1000 - 1 + local result = rcall("ZREVRANGEBYSCORE", delayedKey, maxScore, + minScore, "WITHSCORES","LIMIT", 0, 1) + if #result then + local currentMaxScore = tonumber(result[2]) + if currentMaxScore ~= nil then + if currentMaxScore >= maxScore then + return maxScore, delayedTimestamp + else + return currentMaxScore + 1, delayedTimestamp + end + end + end + return minScore, delayedTimestamp +end +local function addDelayedJob(jobId, delayedKey, eventsKey, timestamp, + maxEvents, markerKey, delay) + local score, delayedTimestamp = getDelayedScore(delayedKey, timestamp, tonumber(delay)) + rcall("ZADD", delayedKey, score, jobId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "delayed", + "jobId", jobId, "delay", delayedTimestamp) + -- mark that a delayed job is available + addDelayMarkerIfNeeded(markerKey, delayedKey) +end +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +local function storeAndEnqueueJob(eventsKey, jobIdKey, jobId, name, data, opts, + timestamp, parentKey, parentData, repeatJobKey, maxEvents, + waitKey, pausedKey, activeKey, metaKey, prioritizedKey, + priorityCounterKey, delayedKey, markerKey) + local delay, priority = storeJob(eventsKey, jobIdKey, jobId, name, data, + opts, timestamp, parentKey, parentData, repeatJobKey) + if delay ~= 0 and delayedKey then + addDelayedJob(jobId, delayedKey, eventsKey, timestamp, maxEvents, markerKey, delay) + else + local target, isPausedOrMaxed = getTargetQueueList(metaKey, activeKey, waitKey, pausedKey) + if priority > 0 then + addJobWithPriority(markerKey, prioritizedKey, priority, jobId, + priorityCounterKey, isPausedOrMaxed) + else + local pushCmd = opts['lifo'] and 'RPUSH' or 'LPUSH' + addJobInTargetList(target, markerKey, pushCmd, isPausedOrMaxed, jobId) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId) + end + return delay, priority +end +local function addJobFromScheduler(jobKey, jobId, opts, waitKey, pausedKey, activeKey, metaKey, + prioritizedKey, priorityCounter, delayedKey, markerKey, eventsKey, name, maxEvents, timestamp, + data, jobSchedulerId, repeatDelay) + opts['delay'] = repeatDelay + opts['jobId'] = jobId + storeAndEnqueueJob(eventsKey, jobKey, jobId, name, data, opts, + timestamp, nil, nil, jobSchedulerId, maxEvents, + waitKey, pausedKey, activeKey, metaKey, prioritizedKey, + priorityCounter, delayedKey, markerKey) +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePaused(queueMetaKey) + return rcall("HEXISTS", queueMetaKey, "paused") == 1 +end +--[[ + Function to remove job. +]] +-- Includes +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local function removeJob(jobId, hard, baseKey, shouldRemoveDeduplicationKey) + local jobKey = baseKey .. jobId + removeParentDependencyKey(jobKey, hard, nil, baseKey) + if shouldRemoveDeduplicationKey then + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(baseKey, jobId, deduplicationId) + end + removeJobKeys(jobKey) +end +--[[ + Function to store a job scheduler +]] +local function storeJobScheduler(schedulerId, schedulerKey, repeatKey, nextMillis, opts, + templateData, templateOpts) + rcall("ZADD", repeatKey, nextMillis, schedulerId) + local optionalValues = {} + if opts['tz'] then + table.insert(optionalValues, "tz") + table.insert(optionalValues, opts['tz']) + end + if opts['limit'] then + table.insert(optionalValues, "limit") + table.insert(optionalValues, opts['limit']) + end + if opts['pattern'] then + table.insert(optionalValues, "pattern") + table.insert(optionalValues, opts['pattern']) + end + if opts['startDate'] then + table.insert(optionalValues, "startDate") + table.insert(optionalValues, opts['startDate']) + end + if opts['endDate'] then + table.insert(optionalValues, "endDate") + table.insert(optionalValues, opts['endDate']) + end + if opts['every'] then + table.insert(optionalValues, "every") + table.insert(optionalValues, opts['every']) + end + if opts['offset'] then + table.insert(optionalValues, "offset") + table.insert(optionalValues, opts['offset']) + else + local offset = rcall("HGET", schedulerKey, "offset") + if offset then + table.insert(optionalValues, "offset") + table.insert(optionalValues, tonumber(offset)) + end + end + local jsonTemplateOpts = cjson.encode(templateOpts) + if jsonTemplateOpts and jsonTemplateOpts ~= '{}' then + table.insert(optionalValues, "opts") + table.insert(optionalValues, jsonTemplateOpts) + end + if templateData and templateData ~= '{}' then + table.insert(optionalValues, "data") + table.insert(optionalValues, templateData) + end + table.insert(optionalValues, "ic") + table.insert(optionalValues, rcall("HGET", schedulerKey, "ic") or 1) + rcall("DEL", schedulerKey) -- remove all attributes and then re-insert new ones + rcall("HMSET", schedulerKey, "name", opts['name'], unpack(optionalValues)) +end +local function getJobSchedulerEveryNextMillis(prevMillis, every, now, offset, startDate) + local nextMillis + if not prevMillis then + if startDate then + -- Assuming startDate is passed as milliseconds from JavaScript + nextMillis = tonumber(startDate) + nextMillis = nextMillis > now and nextMillis or now + else + nextMillis = now + end + else + nextMillis = prevMillis + every + -- check if we may have missed some iterations + if nextMillis < now then + nextMillis = math.floor(now / every) * every + every + (offset or 0) + end + end + if not offset or offset == 0 then + local timeSlot = math.floor(nextMillis / every) * every; + offset = nextMillis - timeSlot; + end + -- Return a tuple nextMillis, offset + return math.floor(nextMillis), math.floor(offset) +end +-- If we are overriding a repeatable job we must delete the delayed job for +-- the next iteration. +local schedulerKey = repeatKey .. ":" .. jobSchedulerId +local maxEvents = getOrSetMaxEvents(metaKey) +local templateData = ARGV[4] +local prevMillis = rcall("ZSCORE", repeatKey, jobSchedulerId) +if prevMillis then + prevMillis = tonumber(prevMillis) +end +local schedulerOpts = cmsgpack.unpack(ARGV[2]) +local every = schedulerOpts['every'] +-- For backwards compatibility we also check the offset from the job itself. +-- could be removed in future major versions. +local jobOffset = jobOpts['repeat'] and jobOpts['repeat']['offset'] or 0 +local offset = schedulerOpts['offset'] or jobOffset or 0 +local newOffset = offset +local updatedEvery = false +if every then + -- if we changed the 'every' value we need to reset millis to nil + local millis = prevMillis + if prevMillis then + local prevEvery = tonumber(rcall("HGET", schedulerKey, "every")) + if prevEvery ~= every then + millis = nil + updatedEvery = true + end + end + local startDate = schedulerOpts['startDate'] + nextMillis, newOffset = getJobSchedulerEveryNextMillis(millis, every, now, offset, startDate) +end +local function removeJobFromScheduler(prefixKey, delayedKey, prioritizedKey, waitKey, pausedKey, jobId, metaKey, + eventsKey) + if rcall("ZSCORE", delayedKey, jobId) then + removeJob(jobId, true, prefixKey, true --[[remove debounce key]] ) + rcall("ZREM", delayedKey, jobId) + return true + elseif rcall("ZSCORE", prioritizedKey, jobId) then + removeJob(jobId, true, prefixKey, true --[[remove debounce key]] ) + rcall("ZREM", prioritizedKey, jobId) + return true + else + local pausedOrWaitKey = waitKey + if isQueuePaused(metaKey) then + pausedOrWaitKey = pausedKey + end + if rcall("LREM", pausedOrWaitKey, 1, jobId) > 0 then + removeJob(jobId, true, prefixKey, true --[[remove debounce key]] ) + return true + end + end + return false +end +local removedPrevJob = false +if prevMillis then + local currentJobId = "repeat:" .. jobSchedulerId .. ":" .. prevMillis + local currentJobKey = schedulerKey .. ":" .. prevMillis + -- In theory it should always exist the currentJobKey if there is a prevMillis unless something has + -- gone really wrong. + if rcall("EXISTS", currentJobKey) == 1 then + removedPrevJob = removeJobFromScheduler(prefixKey, delayedKey, prioritizedKey, waitKey, pausedKey, currentJobId, + metaKey, eventsKey) + end +end +if removedPrevJob then + -- The jobs has been removed and we want to replace it, so lets use the same millis. + if every and not updatedEvery then + nextMillis = prevMillis + end +else + -- Special case where no job was removed, and we need to add the next iteration. + schedulerOpts['offset'] = newOffset +end +-- Check for job ID collision with existing jobs (in any state) +local jobId = "repeat:" .. jobSchedulerId .. ":" .. nextMillis +local jobKey = prefixKey .. jobId +-- If there's already a job with this ID, in a state +-- that is not updatable (active, completed, failed) we must +-- handle the collision +local hasCollision = false +if rcall("EXISTS", jobKey) == 1 then + if every then + -- For 'every' case: try next time slot to avoid collision + local nextSlotMillis = nextMillis + every + local nextSlotJobId = "repeat:" .. jobSchedulerId .. ":" .. nextSlotMillis + local nextSlotJobKey = prefixKey .. nextSlotJobId + if rcall("EXISTS", nextSlotJobKey) == 0 then + -- Next slot is free, use it + nextMillis = nextSlotMillis + jobId = nextSlotJobId + else + -- Next slot also has a job, return error code + return -11 -- SchedulerJobSlotsBusy + end + else + hasCollision = true + end +end +local delay = nextMillis - now +-- Fast Clamp delay to minimum of 0 +if delay < 0 then + delay = 0 +end +local nextJobKey = schedulerKey .. ":" .. nextMillis +if not hasCollision or removedPrevJob then + -- jobId already calculated above during collision check + storeJobScheduler(jobSchedulerId, schedulerKey, repeatKey, nextMillis, schedulerOpts, templateData, templateOpts) + rcall("INCR", KEYS[8]) + addJobFromScheduler(nextJobKey, jobId, jobOpts, waitKey, pausedKey, KEYS[11], metaKey, prioritizedKey, KEYS[10], + delayedKey, KEYS[7], eventsKey, schedulerOpts['name'], maxEvents, now, templateData, jobSchedulerId, delay) +elseif hasCollision then + -- For 'pattern' case: return error code + return -10 -- SchedulerJobIdCollision +end +if ARGV[9] ~= "" then + rcall("HSET", ARGV[9], "nrjid", jobId) +end +return {jobId .. "", delay} +`; +var addJobScheduler = { + name: "addJobScheduler", + content: content2, + keys: 11 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addLog-2.js +var content3 = `--[[ + Add job log + Input: + KEYS[1] job id key + KEYS[2] job logs key + ARGV[1] id + ARGV[2] log + ARGV[3] keepLogs + Output: + -1 - Missing job. +]] +local rcall = redis.call +if rcall("EXISTS", KEYS[1]) == 1 then -- // Make sure job exists + local logCount = rcall("RPUSH", KEYS[2], ARGV[2]) + if ARGV[3] ~= '' then + local keepLogs = tonumber(ARGV[3]) + rcall("LTRIM", KEYS[2], -keepLogs, -1) + return math.min(keepLogs, logCount) + end + return logCount +else + return -1 +end +`; +var addLog = { + name: "addLog", + content: content3, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addParentJob-6.js +var content4 = `--[[ + Adds a parent job to the queue by doing the following: + - Increases the job counter if needed. + - Creates a new job key with the job data. + - adds the job to the waiting-children zset + Input: + KEYS[1] 'meta' + KEYS[2] 'id' + KEYS[3] 'delayed' + KEYS[4] 'waiting-children' + KEYS[5] 'completed' + KEYS[6] events stream key + ARGV[1] msgpacked arguments array + [1] key prefix, + [2] custom id (will not generate one automatically) + [3] name + [4] timestamp + [5] parentKey? + [6] parent dependencies key. + [7] parent? {id, queueKey} + [8] repeat job key + [9] deduplication key + ARGV[2] Json stringified job data + ARGV[3] msgpacked options + Output: + jobId - OK + -5 - Missing parent key +]] +local metaKey = KEYS[1] +local idKey = KEYS[2] +local delayedKey = KEYS[3] +local completedKey = KEYS[5] +local eventsKey = KEYS[6] +local jobId +local jobIdKey +local rcall = redis.call +local args = cmsgpack.unpack(ARGV[1]) +local data = ARGV[2] +local opts = cmsgpack.unpack(ARGV[3]) +local parentKey = args[5] +local parent = args[7] +local repeatJobKey = args[8] +local deduplicationKey = args[9] +local parentData +-- Includes +--[[ + Function to deduplicate a job. +]] +--[[ + Function to set the deduplication key for a job. + Uses TTL from deduplication opts if provided. +]] +local function setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + local ttl = deduplicationOpts and deduplicationOpts['ttl'] + if ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'PX', ttl) + else + rcall('SET', deduplicationKey, jobId) + end +end +--[[ + Function to store a deduplicated next job if the existing job is active + and keepLastIfActive is set. When the active job finishes, the stored + proto-job is used to create a real job in the queue. + Returns true if the proto-job was stored, false otherwise. +]] +--[[ + Function to check if an item belongs to a list. +]] +local function checkItemInList(list, item) + for _, v in pairs(list) do + if v == item then + return 1 + end + end + return nil +end +local function storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + if deduplicationOpts['keepLastIfActive'] and currentDebounceJobId then + local activeKey = prefix .. "active" + local activeItems = rcall('LRANGE', activeKey, 0, -1) + if checkItemInList(activeItems, currentDebounceJobId) then + local deduplicationNextKey = prefix .. "dn:" .. deduplicationId + local fields = {'name', jobName, 'data', jobData, 'opts', cjson.encode(fullOpts)} + if parentKey then + fields[#fields+1] = 'pk' + fields[#fields+1] = parentKey + end + if parentData then + fields[#fields+1] = 'pd' + fields[#fields+1] = parentData + end + if parentDependenciesKey then + fields[#fields+1] = 'pdk' + fields[#fields+1] = parentDependenciesKey + end + if repeatJobKey then + fields[#fields+1] = 'rjk' + fields[#fields+1] = repeatJobKey + end + rcall('HSET', deduplicationNextKey, unpack(fields)) + -- Ensure the dedup key does not expire while the job is active, + -- so subsequent adds always hit the dedup path and never bypass + -- the active-check because of a TTL expiry. + local deduplicationKey = prefix .. "de:" .. deduplicationId + rcall('PERSIST', deduplicationKey) + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return true + end + end + return false +end +local function deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, jobId, deduplicationKey, + eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + local ttl = deduplicationOpts['ttl'] + local deduplicationKeyExists + if ttl and ttl > 0 then + if deduplicationOpts['extend'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, currentDebounceJobId) + else + setDeduplicationKey(deduplicationKey, currentDebounceJobId, deduplicationOpts) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", + "jobId", currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + if deduplicationOpts['keepLastIfActive'] then + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'PX', ttl, 'NX') + end + end + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + end + if deduplicationKeyExists then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + end +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to handle the case when job is duplicated. +]] +-- Includes +--[[ + This function is used to update the parent's dependencies if the job + is already completed and about to be ignored. The parent must get its + dependencies updated to avoid the parent job being stuck forever in + the waiting-children state. +]] +-- Includes +--[[ + Validate and move or add dependencies to parent. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) + if no pending dependencies. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) if needed. +]] +-- Includes +--[[ + Move parent to a wait status (wait, prioritized or delayed) +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check if queue is paused or maxed + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePausedOrMaxed(queueMetaKey, activeKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency") + if queueAttributes[1] then + return true + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + return activeCount >= tonumber(queueAttributes[2]) + end + end + return false +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + local parentWaitKey = parentQueueKey .. ":wait" + local parentPausedKey = parentQueueKey .. ":paused" + local parentActiveKey = parentQueueKey .. ":active" + local parentMetaKey = parentQueueKey .. ":meta" + local parentMarkerKey = parentQueueKey .. ":marker" + local jobAttributes = rcall("HMGET", parentKey, "priority", "delay") + local priority = tonumber(jobAttributes[1]) or 0 + local delay = tonumber(jobAttributes[2]) or 0 + if delay > 0 then + local delayedTimestamp = tonumber(timestamp) + delay + local score = delayedTimestamp * 0x1000 + local parentDelayedKey = parentQueueKey .. ":delayed" + rcall("ZADD", parentDelayedKey, score, parentId) + rcall("XADD", parentQueueKey .. ":events", "*", "event", "delayed", "jobId", parentId, "delay", + delayedTimestamp) + addDelayMarkerIfNeeded(parentMarkerKey, parentDelayedKey) + else + if priority == 0 then + local parentTarget, isParentPausedOrMaxed = getTargetQueueList(parentMetaKey, parentActiveKey, + parentWaitKey, parentPausedKey) + addJobInTargetList(parentTarget, parentMarkerKey, "RPUSH", isParentPausedOrMaxed, parentId) + else + local isPausedOrMaxed = isQueuePausedOrMaxed(parentMetaKey, parentActiveKey) + addJobWithPriority(parentMarkerKey, parentQueueKey .. ":prioritized", priority, parentId, + parentQueueKey .. ":pc", isPausedOrMaxed) + end + rcall("XADD", parentQueueKey .. ":events", "*", "event", "waiting", "jobId", parentId, "prev", + "waiting-children") + end +end +local function moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + if rcall("EXISTS", parentKey) == 1 then + local parentWaitingChildrenKey = parentQueueKey .. ":waiting-children" + if rcall("ZSCORE", parentWaitingChildrenKey, parentId) then + rcall("ZREM", parentWaitingChildrenKey, parentId) + moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + end + end +end +local function moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, + parentId, timestamp) + local doNotHavePendingDependencies = rcall("SCARD", parentDependenciesKey) == 0 + if doNotHavePendingDependencies then + moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + end +end +local function updateParentDepsIfNeeded(parentKey, parentQueueKey, parentDependenciesKey, + parentId, jobIdKey, returnvalue, timestamp ) + local processedSet = parentKey .. ":processed" + rcall("HSET", processedSet, jobIdKey, returnvalue) + moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, parentId, timestamp) +end +local function updateExistingJobsParent(parentKey, parent, parentData, + parentDependenciesKey, completedKey, + jobIdKey, jobId, timestamp) + if parentKey ~= nil then + if rcall("ZSCORE", completedKey, jobId) then + local returnvalue = rcall("HGET", jobIdKey, "returnvalue") + updateParentDepsIfNeeded(parentKey, parent['queueKey'], + parentDependenciesKey, parent['id'], + jobIdKey, returnvalue, timestamp) + else + if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) + end + end + rcall("HMSET", jobIdKey, "parentKey", parentKey, "parent", parentData) + end +end +local function handleDuplicatedJob(jobKey, jobId, currentParentKey, currentParent, + parentData, parentDependenciesKey, completedKey, eventsKey, maxEvents, timestamp) + local existedParentKey = rcall("HGET", jobKey, "parentKey") + if not existedParentKey or existedParentKey == currentParentKey then + updateExistingJobsParent(currentParentKey, currentParent, parentData, + parentDependenciesKey, completedKey, jobKey, + jobId, timestamp) + else + if currentParentKey ~= nil and currentParentKey ~= existedParentKey + and (rcall("EXISTS", existedParentKey) == 1) then + return -7 + end + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", + "duplicated", "jobId", jobId) + return jobId .. "" -- convert to string +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +if parentKey ~= nil then + if rcall("EXISTS", parentKey) ~= 1 then return -5 end + parentData = cjson.encode(parent) +end +local jobCounter = rcall("INCR", idKey) +local maxEvents = getOrSetMaxEvents(metaKey) +local parentDependenciesKey = args[6] +local timestamp = args[4] +if args[2] == "" then + jobId = jobCounter + jobIdKey = args[1] .. jobId +else + jobId = args[2] + jobIdKey = args[1] .. jobId + if rcall("EXISTS", jobIdKey) == 1 then + return handleDuplicatedJob(jobIdKey, jobId, parentKey, parent, + parentData, parentDependenciesKey, completedKey, eventsKey, + maxEvents, timestamp) + end +end +local deduplicationId = opts['de'] and opts['de']['id'] +if deduplicationId then + local deduplicationJobId = deduplicateJobWithoutReplace(deduplicationId, opts['de'], + jobId, deduplicationKey, eventsKey, maxEvents, args[1], args[3], ARGV[2], opts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + if deduplicationJobId then + return deduplicationJobId + end +end +-- Store the job. +storeJob(eventsKey, jobIdKey, jobId, args[3], ARGV[2], opts, timestamp, + parentKey, parentData, repeatJobKey) +local waitChildrenKey = KEYS[4] +rcall("ZADD", waitChildrenKey, timestamp, jobId) +rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", + "waiting-children", "jobId", jobId) +-- Check if this job is a child of another job, if so add it to the parents dependencies +if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) +end +return jobId .. "" -- convert to string +`; +var addParentJob = { + name: "addParentJob", + content: content4, + keys: 6 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addPrioritizedJob-9.js +var content5 = `--[[ + Adds a priotitized job to the queue by doing the following: + - Increases the job counter if needed. + - Creates a new job key with the job data. + - Adds the job to the "added" list so that workers gets notified. + Input: + KEYS[1] 'marker', + KEYS[2] 'meta' + KEYS[3] 'id' + KEYS[4] 'prioritized' + KEYS[5] 'delayed' + KEYS[6] 'completed' + KEYS[7] 'active' + KEYS[8] events stream key + KEYS[9] 'pc' priority counter + ARGV[1] msgpacked arguments array + [1] key prefix, + [2] custom id (will not generate one automatically) + [3] name + [4] timestamp + [5] parentKey? + [6] parent dependencies key. + [7] parent? {id, queueKey} + [8] repeat job key + [9] deduplication key + ARGV[2] Json stringified job data + ARGV[3] msgpacked options + Output: + jobId - OK + -5 - Missing parent key +]] +local metaKey = KEYS[2] +local idKey = KEYS[3] +local priorityKey = KEYS[4] +local completedKey = KEYS[6] +local activeKey = KEYS[7] +local eventsKey = KEYS[8] +local priorityCounterKey = KEYS[9] +local jobId +local jobIdKey +local rcall = redis.call +local args = cmsgpack.unpack(ARGV[1]) +local data = ARGV[2] +local opts = cmsgpack.unpack(ARGV[3]) +local parentKey = args[5] +local parent = args[7] +local repeatJobKey = args[8] +local deduplicationKey = args[9] +local parentData +-- Includes +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to debounce a job. +]] +-- Includes +--[[ + Function to deduplicate a job. +]] +--[[ + Function to set the deduplication key for a job. + Uses TTL from deduplication opts if provided. +]] +local function setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + local ttl = deduplicationOpts and deduplicationOpts['ttl'] + if ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'PX', ttl) + else + rcall('SET', deduplicationKey, jobId) + end +end +--[[ + Function to store a deduplicated next job if the existing job is active + and keepLastIfActive is set. When the active job finishes, the stored + proto-job is used to create a real job in the queue. + Returns true if the proto-job was stored, false otherwise. +]] +--[[ + Function to check if an item belongs to a list. +]] +local function checkItemInList(list, item) + for _, v in pairs(list) do + if v == item then + return 1 + end + end + return nil +end +local function storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + if deduplicationOpts['keepLastIfActive'] and currentDebounceJobId then + local activeKey = prefix .. "active" + local activeItems = rcall('LRANGE', activeKey, 0, -1) + if checkItemInList(activeItems, currentDebounceJobId) then + local deduplicationNextKey = prefix .. "dn:" .. deduplicationId + local fields = {'name', jobName, 'data', jobData, 'opts', cjson.encode(fullOpts)} + if parentKey then + fields[#fields+1] = 'pk' + fields[#fields+1] = parentKey + end + if parentData then + fields[#fields+1] = 'pd' + fields[#fields+1] = parentData + end + if parentDependenciesKey then + fields[#fields+1] = 'pdk' + fields[#fields+1] = parentDependenciesKey + end + if repeatJobKey then + fields[#fields+1] = 'rjk' + fields[#fields+1] = repeatJobKey + end + rcall('HSET', deduplicationNextKey, unpack(fields)) + -- Ensure the dedup key does not expire while the job is active, + -- so subsequent adds always hit the dedup path and never bypass + -- the active-check because of a TTL expiry. + local deduplicationKey = prefix .. "de:" .. deduplicationId + rcall('PERSIST', deduplicationKey) + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return true + end + end + return false +end +local function deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, jobId, deduplicationKey, + eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + local ttl = deduplicationOpts['ttl'] + local deduplicationKeyExists + if ttl and ttl > 0 then + if deduplicationOpts['extend'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, currentDebounceJobId) + else + setDeduplicationKey(deduplicationKey, currentDebounceJobId, deduplicationOpts) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", + "jobId", currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + if deduplicationOpts['keepLastIfActive'] then + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'PX', ttl, 'NX') + end + end + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + end + if deduplicationKeyExists then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +local function removeDelayedJob(delayedKey, deduplicationKey, eventsKey, maxEvents, currentDeduplicatedJobId, + jobId, deduplicationId, prefix) + if rcall("ZREM", delayedKey, currentDeduplicatedJobId) > 0 then + removeJobKeys(prefix .. currentDeduplicatedJobId) + rcall("XADD", eventsKey, "*", "event", "removed", "jobId", currentDeduplicatedJobId, + "prev", "delayed") + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + jobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + jobId, "deduplicationId", deduplicationId, "deduplicatedJobId", currentDeduplicatedJobId) + return true + end + return false +end +local function deduplicateJob(deduplicationOpts, jobId, delayedKey, deduplicationKey, eventsKey, maxEvents, + prefix, jobName, jobData, fullOpts, parentKey, parentData, parentDependenciesKey, repeatJobKey) + local deduplicationId = deduplicationOpts and deduplicationOpts['id'] + if deduplicationId then + if deduplicationOpts['replace'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + local isRemoved = removeDelayedJob(delayedKey, deduplicationKey, eventsKey, maxEvents, + currentDebounceJobId, jobId, deduplicationId, prefix) + if isRemoved then + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + local ttl = deduplicationOpts['ttl'] + if not deduplicationOpts['extend'] and ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'KEEPTTL') + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + end + return + else + storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + return currentDebounceJobId + end + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + return deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, + jobId, deduplicationKey, eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + end + end +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to handle the case when job is duplicated. +]] +-- Includes +--[[ + This function is used to update the parent's dependencies if the job + is already completed and about to be ignored. The parent must get its + dependencies updated to avoid the parent job being stuck forever in + the waiting-children state. +]] +-- Includes +--[[ + Validate and move or add dependencies to parent. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) + if no pending dependencies. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) if needed. +]] +-- Includes +--[[ + Move parent to a wait status (wait, prioritized or delayed) +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check if queue is paused or maxed + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePausedOrMaxed(queueMetaKey, activeKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency") + if queueAttributes[1] then + return true + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + return activeCount >= tonumber(queueAttributes[2]) + end + end + return false +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + local parentWaitKey = parentQueueKey .. ":wait" + local parentPausedKey = parentQueueKey .. ":paused" + local parentActiveKey = parentQueueKey .. ":active" + local parentMetaKey = parentQueueKey .. ":meta" + local parentMarkerKey = parentQueueKey .. ":marker" + local jobAttributes = rcall("HMGET", parentKey, "priority", "delay") + local priority = tonumber(jobAttributes[1]) or 0 + local delay = tonumber(jobAttributes[2]) or 0 + if delay > 0 then + local delayedTimestamp = tonumber(timestamp) + delay + local score = delayedTimestamp * 0x1000 + local parentDelayedKey = parentQueueKey .. ":delayed" + rcall("ZADD", parentDelayedKey, score, parentId) + rcall("XADD", parentQueueKey .. ":events", "*", "event", "delayed", "jobId", parentId, "delay", + delayedTimestamp) + addDelayMarkerIfNeeded(parentMarkerKey, parentDelayedKey) + else + if priority == 0 then + local parentTarget, isParentPausedOrMaxed = getTargetQueueList(parentMetaKey, parentActiveKey, + parentWaitKey, parentPausedKey) + addJobInTargetList(parentTarget, parentMarkerKey, "RPUSH", isParentPausedOrMaxed, parentId) + else + local isPausedOrMaxed = isQueuePausedOrMaxed(parentMetaKey, parentActiveKey) + addJobWithPriority(parentMarkerKey, parentQueueKey .. ":prioritized", priority, parentId, + parentQueueKey .. ":pc", isPausedOrMaxed) + end + rcall("XADD", parentQueueKey .. ":events", "*", "event", "waiting", "jobId", parentId, "prev", + "waiting-children") + end +end +local function moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + if rcall("EXISTS", parentKey) == 1 then + local parentWaitingChildrenKey = parentQueueKey .. ":waiting-children" + if rcall("ZSCORE", parentWaitingChildrenKey, parentId) then + rcall("ZREM", parentWaitingChildrenKey, parentId) + moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + end + end +end +local function moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, + parentId, timestamp) + local doNotHavePendingDependencies = rcall("SCARD", parentDependenciesKey) == 0 + if doNotHavePendingDependencies then + moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + end +end +local function updateParentDepsIfNeeded(parentKey, parentQueueKey, parentDependenciesKey, + parentId, jobIdKey, returnvalue, timestamp ) + local processedSet = parentKey .. ":processed" + rcall("HSET", processedSet, jobIdKey, returnvalue) + moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, parentId, timestamp) +end +local function updateExistingJobsParent(parentKey, parent, parentData, + parentDependenciesKey, completedKey, + jobIdKey, jobId, timestamp) + if parentKey ~= nil then + if rcall("ZSCORE", completedKey, jobId) then + local returnvalue = rcall("HGET", jobIdKey, "returnvalue") + updateParentDepsIfNeeded(parentKey, parent['queueKey'], + parentDependenciesKey, parent['id'], + jobIdKey, returnvalue, timestamp) + else + if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) + end + end + rcall("HMSET", jobIdKey, "parentKey", parentKey, "parent", parentData) + end +end +local function handleDuplicatedJob(jobKey, jobId, currentParentKey, currentParent, + parentData, parentDependenciesKey, completedKey, eventsKey, maxEvents, timestamp) + local existedParentKey = rcall("HGET", jobKey, "parentKey") + if not existedParentKey or existedParentKey == currentParentKey then + updateExistingJobsParent(currentParentKey, currentParent, parentData, + parentDependenciesKey, completedKey, jobKey, + jobId, timestamp) + else + if currentParentKey ~= nil and currentParentKey ~= existedParentKey + and (rcall("EXISTS", existedParentKey) == 1) then + return -7 + end + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", + "duplicated", "jobId", jobId) + return jobId .. "" -- convert to string +end +if parentKey ~= nil then + if rcall("EXISTS", parentKey) ~= 1 then return -5 end + parentData = cjson.encode(parent) +end +local jobCounter = rcall("INCR", idKey) +local maxEvents = getOrSetMaxEvents(metaKey) +local parentDependenciesKey = args[6] +local timestamp = args[4] +if args[2] == "" then + jobId = jobCounter + jobIdKey = args[1] .. jobId +else + jobId = args[2] + jobIdKey = args[1] .. jobId + if rcall("EXISTS", jobIdKey) == 1 then + return handleDuplicatedJob(jobIdKey, jobId, parentKey, parent, + parentData, parentDependenciesKey, completedKey, eventsKey, + maxEvents, timestamp) + end +end +local deduplicationJobId = deduplicateJob(opts['de'], jobId, KEYS[5], + deduplicationKey, eventsKey, maxEvents, args[1], args[3], ARGV[2], opts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) +if deduplicationJobId then + return deduplicationJobId +end +-- Store the job. +local delay, priority = storeJob(eventsKey, jobIdKey, jobId, args[3], ARGV[2], + opts, timestamp, parentKey, parentData, + repeatJobKey) +-- Add the job to the prioritized set +local isPausedOrMaxed = isQueuePausedOrMaxed(metaKey, activeKey) +addJobWithPriority( KEYS[1], priorityKey, priority, jobId, priorityCounterKey, isPausedOrMaxed) +-- Emit waiting event +rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId) +-- Check if this job is a child of another job, if so add it to the parents dependencies +if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) +end +return jobId .. "" -- convert to string +`; +var addPrioritizedJob = { + name: "addPrioritizedJob", + content: content5, + keys: 9 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addRepeatableJob-2.js +var content6 = `--[[ + Adds a repeatable job + Input: + KEYS[1] 'repeat' key + KEYS[2] 'delayed' key + ARGV[1] next milliseconds + ARGV[2] msgpacked options + [1] name + [2] tz? + [3] pattern? + [4] endDate? + [5] every? + ARGV[3] legacy custom key TODO: remove this logic in next breaking change + ARGV[4] custom key + ARGV[5] prefix key + Output: + repeatableKey - OK +]] +local rcall = redis.call +local repeatKey = KEYS[1] +local delayedKey = KEYS[2] +local nextMillis = ARGV[1] +local legacyCustomKey = ARGV[3] +local customKey = ARGV[4] +local prefixKey = ARGV[5] +-- Includes +--[[ + Function to remove job. +]] +-- Includes +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local function removeJob(jobId, hard, baseKey, shouldRemoveDeduplicationKey) + local jobKey = baseKey .. jobId + removeParentDependencyKey(jobKey, hard, nil, baseKey) + if shouldRemoveDeduplicationKey then + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(baseKey, jobId, deduplicationId) + end + removeJobKeys(jobKey) +end +local function storeRepeatableJob(repeatKey, customKey, nextMillis, rawOpts) + rcall("ZADD", repeatKey, nextMillis, customKey) + local opts = cmsgpack.unpack(rawOpts) + local optionalValues = {} + if opts['tz'] then + table.insert(optionalValues, "tz") + table.insert(optionalValues, opts['tz']) + end + if opts['pattern'] then + table.insert(optionalValues, "pattern") + table.insert(optionalValues, opts['pattern']) + end + if opts['endDate'] then + table.insert(optionalValues, "endDate") + table.insert(optionalValues, opts['endDate']) + end + if opts['every'] then + table.insert(optionalValues, "every") + table.insert(optionalValues, opts['every']) + end + rcall("HMSET", repeatKey .. ":" .. customKey, "name", opts['name'], + unpack(optionalValues)) + return customKey +end +-- If we are overriding a repeatable job we must delete the delayed job for +-- the next iteration. +local prevMillis = rcall("ZSCORE", repeatKey, customKey) +if prevMillis then + local delayedJobId = "repeat:" .. customKey .. ":" .. prevMillis + local nextDelayedJobId = repeatKey .. ":" .. customKey .. ":" .. nextMillis + if rcall("ZSCORE", delayedKey, delayedJobId) + and rcall("EXISTS", nextDelayedJobId) ~= 1 then + removeJob(delayedJobId, true, prefixKey, true --[[remove debounce key]]) + rcall("ZREM", delayedKey, delayedJobId) + end +end +-- Keep backwards compatibility with old repeatable jobs (<= 3.0.0) +if rcall("ZSCORE", repeatKey, legacyCustomKey) ~= false then + return storeRepeatableJob(repeatKey, legacyCustomKey, nextMillis, ARGV[2]) +end +return storeRepeatableJob(repeatKey, customKey, nextMillis, ARGV[2]) +`; +var addRepeatableJob = { + name: "addRepeatableJob", + content: content6, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/addStandardJob-9.js +var content7 = `--[[ + Adds a job to the queue by doing the following: + - Increases the job counter if needed. + - Creates a new job key with the job data. + - if delayed: + - computes timestamp. + - adds to delayed zset. + - Emits a global event 'delayed' if the job is delayed. + - if not delayed + - Adds the jobId to the wait/paused list in one of three ways: + - LIFO + - FIFO + - prioritized. + - Adds the job to the "added" list so that workers gets notified. + Input: + KEYS[1] 'wait', + KEYS[2] 'paused' + KEYS[3] 'meta' + KEYS[4] 'id' + KEYS[5] 'completed' + KEYS[6] 'delayed' + KEYS[7] 'active' + KEYS[8] events stream key + KEYS[9] marker key + ARGV[1] msgpacked arguments array + [1] key prefix, + [2] custom id (will not generate one automatically) + [3] name + [4] timestamp + [5] parentKey? + [6] parent dependencies key. + [7] parent? {id, queueKey} + [8] repeat job key + [9] deduplication key + ARGV[2] Json stringified job data + ARGV[3] msgpacked options + Output: + jobId - OK + -5 - Missing parent key +]] +local eventsKey = KEYS[8] +local jobId +local jobIdKey +local rcall = redis.call +local args = cmsgpack.unpack(ARGV[1]) +local data = ARGV[2] +local opts = cmsgpack.unpack(ARGV[3]) +local parentKey = args[5] +local parent = args[7] +local repeatJobKey = args[8] +local deduplicationKey = args[9] +local parentData +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to debounce a job. +]] +-- Includes +--[[ + Function to deduplicate a job. +]] +--[[ + Function to set the deduplication key for a job. + Uses TTL from deduplication opts if provided. +]] +local function setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + local ttl = deduplicationOpts and deduplicationOpts['ttl'] + if ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'PX', ttl) + else + rcall('SET', deduplicationKey, jobId) + end +end +--[[ + Function to store a deduplicated next job if the existing job is active + and keepLastIfActive is set. When the active job finishes, the stored + proto-job is used to create a real job in the queue. + Returns true if the proto-job was stored, false otherwise. +]] +--[[ + Function to check if an item belongs to a list. +]] +local function checkItemInList(list, item) + for _, v in pairs(list) do + if v == item then + return 1 + end + end + return nil +end +local function storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + if deduplicationOpts['keepLastIfActive'] and currentDebounceJobId then + local activeKey = prefix .. "active" + local activeItems = rcall('LRANGE', activeKey, 0, -1) + if checkItemInList(activeItems, currentDebounceJobId) then + local deduplicationNextKey = prefix .. "dn:" .. deduplicationId + local fields = {'name', jobName, 'data', jobData, 'opts', cjson.encode(fullOpts)} + if parentKey then + fields[#fields+1] = 'pk' + fields[#fields+1] = parentKey + end + if parentData then + fields[#fields+1] = 'pd' + fields[#fields+1] = parentData + end + if parentDependenciesKey then + fields[#fields+1] = 'pdk' + fields[#fields+1] = parentDependenciesKey + end + if repeatJobKey then + fields[#fields+1] = 'rjk' + fields[#fields+1] = repeatJobKey + end + rcall('HSET', deduplicationNextKey, unpack(fields)) + -- Ensure the dedup key does not expire while the job is active, + -- so subsequent adds always hit the dedup path and never bypass + -- the active-check because of a TTL expiry. + local deduplicationKey = prefix .. "de:" .. deduplicationId + rcall('PERSIST', deduplicationKey) + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return true + end + end + return false +end +local function deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, jobId, deduplicationKey, + eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + local ttl = deduplicationOpts['ttl'] + local deduplicationKeyExists + if ttl and ttl > 0 then + if deduplicationOpts['extend'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, currentDebounceJobId) + else + setDeduplicationKey(deduplicationKey, currentDebounceJobId, deduplicationOpts) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", + "jobId", currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + if deduplicationOpts['keepLastIfActive'] then + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'PX', ttl, 'NX') + end + end + else + deduplicationKeyExists = not rcall('SET', deduplicationKey, jobId, 'NX') + end + if deduplicationKeyExists then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) then + return currentDebounceJobId + end + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + currentDebounceJobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + currentDebounceJobId, "deduplicationId", deduplicationId, "deduplicatedJobId", jobId) + return currentDebounceJobId + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +local function removeDelayedJob(delayedKey, deduplicationKey, eventsKey, maxEvents, currentDeduplicatedJobId, + jobId, deduplicationId, prefix) + if rcall("ZREM", delayedKey, currentDeduplicatedJobId) > 0 then + removeJobKeys(prefix .. currentDeduplicatedJobId) + rcall("XADD", eventsKey, "*", "event", "removed", "jobId", currentDeduplicatedJobId, + "prev", "delayed") + -- TODO remove debounced event in next breaking change + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "debounced", "jobId", + jobId, "debounceId", deduplicationId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "deduplicated", "jobId", + jobId, "deduplicationId", deduplicationId, "deduplicatedJobId", currentDeduplicatedJobId) + return true + end + return false +end +local function deduplicateJob(deduplicationOpts, jobId, delayedKey, deduplicationKey, eventsKey, maxEvents, + prefix, jobName, jobData, fullOpts, parentKey, parentData, parentDependenciesKey, repeatJobKey) + local deduplicationId = deduplicationOpts and deduplicationOpts['id'] + if deduplicationId then + if deduplicationOpts['replace'] then + local currentDebounceJobId = rcall('GET', deduplicationKey) + if currentDebounceJobId then + local isRemoved = removeDelayedJob(delayedKey, deduplicationKey, eventsKey, maxEvents, + currentDebounceJobId, jobId, deduplicationId, prefix) + if isRemoved then + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + local ttl = deduplicationOpts['ttl'] + if not deduplicationOpts['extend'] and ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'KEEPTTL') + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + end + return + else + storeDeduplicatedNextJob(deduplicationOpts, currentDebounceJobId, prefix, + deduplicationId, jobName, jobData, fullOpts, eventsKey, maxEvents, jobId, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + return currentDebounceJobId + end + else + if deduplicationOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, jobId) + else + setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + end + return + end + else + return deduplicateJobWithoutReplace(deduplicationId, deduplicationOpts, + jobId, deduplicationKey, eventsKey, maxEvents, prefix, jobName, jobData, fullOpts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) + end + end +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to handle the case when job is duplicated. +]] +-- Includes +--[[ + This function is used to update the parent's dependencies if the job + is already completed and about to be ignored. The parent must get its + dependencies updated to avoid the parent job being stuck forever in + the waiting-children state. +]] +-- Includes +--[[ + Validate and move or add dependencies to parent. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) + if no pending dependencies. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) if needed. +]] +-- Includes +--[[ + Move parent to a wait status (wait, prioritized or delayed) +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check if queue is paused or maxed + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePausedOrMaxed(queueMetaKey, activeKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency") + if queueAttributes[1] then + return true + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + return activeCount >= tonumber(queueAttributes[2]) + end + end + return false +end +local function moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + local parentWaitKey = parentQueueKey .. ":wait" + local parentPausedKey = parentQueueKey .. ":paused" + local parentActiveKey = parentQueueKey .. ":active" + local parentMetaKey = parentQueueKey .. ":meta" + local parentMarkerKey = parentQueueKey .. ":marker" + local jobAttributes = rcall("HMGET", parentKey, "priority", "delay") + local priority = tonumber(jobAttributes[1]) or 0 + local delay = tonumber(jobAttributes[2]) or 0 + if delay > 0 then + local delayedTimestamp = tonumber(timestamp) + delay + local score = delayedTimestamp * 0x1000 + local parentDelayedKey = parentQueueKey .. ":delayed" + rcall("ZADD", parentDelayedKey, score, parentId) + rcall("XADD", parentQueueKey .. ":events", "*", "event", "delayed", "jobId", parentId, "delay", + delayedTimestamp) + addDelayMarkerIfNeeded(parentMarkerKey, parentDelayedKey) + else + if priority == 0 then + local parentTarget, isParentPausedOrMaxed = getTargetQueueList(parentMetaKey, parentActiveKey, + parentWaitKey, parentPausedKey) + addJobInTargetList(parentTarget, parentMarkerKey, "RPUSH", isParentPausedOrMaxed, parentId) + else + local isPausedOrMaxed = isQueuePausedOrMaxed(parentMetaKey, parentActiveKey) + addJobWithPriority(parentMarkerKey, parentQueueKey .. ":prioritized", priority, parentId, + parentQueueKey .. ":pc", isPausedOrMaxed) + end + rcall("XADD", parentQueueKey .. ":events", "*", "event", "waiting", "jobId", parentId, "prev", + "waiting-children") + end +end +local function moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + if rcall("EXISTS", parentKey) == 1 then + local parentWaitingChildrenKey = parentQueueKey .. ":waiting-children" + if rcall("ZSCORE", parentWaitingChildrenKey, parentId) then + rcall("ZREM", parentWaitingChildrenKey, parentId) + moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + end + end +end +local function moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, + parentId, timestamp) + local doNotHavePendingDependencies = rcall("SCARD", parentDependenciesKey) == 0 + if doNotHavePendingDependencies then + moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + end +end +local function updateParentDepsIfNeeded(parentKey, parentQueueKey, parentDependenciesKey, + parentId, jobIdKey, returnvalue, timestamp ) + local processedSet = parentKey .. ":processed" + rcall("HSET", processedSet, jobIdKey, returnvalue) + moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, parentId, timestamp) +end +local function updateExistingJobsParent(parentKey, parent, parentData, + parentDependenciesKey, completedKey, + jobIdKey, jobId, timestamp) + if parentKey ~= nil then + if rcall("ZSCORE", completedKey, jobId) then + local returnvalue = rcall("HGET", jobIdKey, "returnvalue") + updateParentDepsIfNeeded(parentKey, parent['queueKey'], + parentDependenciesKey, parent['id'], + jobIdKey, returnvalue, timestamp) + else + if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) + end + end + rcall("HMSET", jobIdKey, "parentKey", parentKey, "parent", parentData) + end +end +local function handleDuplicatedJob(jobKey, jobId, currentParentKey, currentParent, + parentData, parentDependenciesKey, completedKey, eventsKey, maxEvents, timestamp) + local existedParentKey = rcall("HGET", jobKey, "parentKey") + if not existedParentKey or existedParentKey == currentParentKey then + updateExistingJobsParent(currentParentKey, currentParent, parentData, + parentDependenciesKey, completedKey, jobKey, + jobId, timestamp) + else + if currentParentKey ~= nil and currentParentKey ~= existedParentKey + and (rcall("EXISTS", existedParentKey) == 1) then + return -7 + end + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", + "duplicated", "jobId", jobId) + return jobId .. "" -- convert to string +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +if parentKey ~= nil then + if rcall("EXISTS", parentKey) ~= 1 then return -5 end + parentData = cjson.encode(parent) +end +local jobCounter = rcall("INCR", KEYS[4]) +local metaKey = KEYS[3] +local maxEvents = getOrSetMaxEvents(metaKey) +local parentDependenciesKey = args[6] +local timestamp = args[4] +if args[2] == "" then + jobId = jobCounter + jobIdKey = args[1] .. jobId +else + jobId = args[2] + jobIdKey = args[1] .. jobId + if rcall("EXISTS", jobIdKey) == 1 then + return handleDuplicatedJob(jobIdKey, jobId, parentKey, parent, + parentData, parentDependenciesKey, KEYS[5], eventsKey, + maxEvents, timestamp) + end +end +local deduplicationJobId = deduplicateJob(opts['de'], jobId, KEYS[6], + deduplicationKey, eventsKey, maxEvents, args[1], args[3], ARGV[2], opts, + parentKey, parentData, parentDependenciesKey, repeatJobKey) +if deduplicationJobId then + return deduplicationJobId +end +-- Store the job. +storeJob(eventsKey, jobIdKey, jobId, args[3], ARGV[2], opts, timestamp, + parentKey, parentData, repeatJobKey) +local target, isPausedOrMaxed = getTargetQueueList(metaKey, KEYS[7], KEYS[1], KEYS[2]) +-- LIFO or FIFO +local pushCmd = opts['lifo'] and 'RPUSH' or 'LPUSH' +addJobInTargetList(target, KEYS[9], pushCmd, isPausedOrMaxed, jobId) +-- Emit waiting event +rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId) +-- Check if this job is a child of another job, if so add it to the parents dependencies +if parentDependenciesKey ~= nil then + rcall("SADD", parentDependenciesKey, jobIdKey) +end +return jobId .. "" -- convert to string +`; +var addStandardJob = { + name: "addStandardJob", + content: content7, + keys: 9 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/changeDelay-4.js +var content8 = `--[[ + Change job delay when it is in delayed set. + Input: + KEYS[1] delayed key + KEYS[2] meta key + KEYS[3] marker key + KEYS[4] events stream + ARGV[1] delay + ARGV[2] timestamp + ARGV[3] the id of the job + ARGV[4] job key + Output: + 0 - OK + -1 - Missing job. + -3 - Job not in delayed set. + Events: + - delayed key. +]] +local rcall = redis.call +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Bake in the job id first 12 bits into the timestamp + to guarantee correct execution order of delayed jobs + (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp) + WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail +]] +local function getDelayedScore(delayedKey, timestamp, delay) + local delayedTimestamp = (delay > 0 and (tonumber(timestamp) + delay)) or tonumber(timestamp) + local minScore = delayedTimestamp * 0x1000 + local maxScore = (delayedTimestamp + 1 ) * 0x1000 - 1 + local result = rcall("ZREVRANGEBYSCORE", delayedKey, maxScore, + minScore, "WITHSCORES","LIMIT", 0, 1) + if #result then + local currentMaxScore = tonumber(result[2]) + if currentMaxScore ~= nil then + if currentMaxScore >= maxScore then + return maxScore, delayedTimestamp + else + return currentMaxScore + 1, delayedTimestamp + end + end + end + return minScore, delayedTimestamp +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +if rcall("EXISTS", ARGV[4]) == 1 then + local jobId = ARGV[3] + local delay = tonumber(ARGV[1]) + local score, delayedTimestamp = getDelayedScore(KEYS[1], ARGV[2], delay) + local numRemovedElements = rcall("ZREM", KEYS[1], jobId) + if numRemovedElements < 1 then + return -3 + end + rcall("HSET", ARGV[4], "delay", delay) + rcall("ZADD", KEYS[1], score, jobId) + local maxEvents = getOrSetMaxEvents(KEYS[2]) + rcall("XADD", KEYS[4], "MAXLEN", "~", maxEvents, "*", "event", "delayed", + "jobId", jobId, "delay", delayedTimestamp) + -- mark that a delayed job is available + addDelayMarkerIfNeeded(KEYS[3], KEYS[1]) + return 0 +else + return -1 +end`; +var changeDelay = { + name: "changeDelay", + content: content8, + keys: 4 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/changePriority-7.js +var content9 = `--[[ + Change job priority + Input: + KEYS[1] 'wait', + KEYS[2] 'paused' + KEYS[3] 'meta' + KEYS[4] 'prioritized' + KEYS[5] 'active' + KEYS[6] 'pc' priority counter + KEYS[7] 'marker' + ARGV[1] priority value + ARGV[2] prefix key + ARGV[3] job id + ARGV[4] lifo + Output: + 0 - OK + -1 - Missing job +]] +local jobId = ARGV[3] +local jobKey = ARGV[2] .. jobId +local priority = tonumber(ARGV[1]) +local rcall = redis.call +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to push back job considering priority in front of same prioritized jobs. +]] +local function pushBackJobWithPriority(prioritizedKey, priority, jobId) + -- in order to put it at front of same prioritized jobs + -- we consider prioritized counter as 0 + local score = priority * 0x100000000 + rcall("ZADD", prioritizedKey, score, jobId) +end +local function reAddJobWithNewPriority( prioritizedKey, markerKey, targetKey, + priorityCounter, lifo, priority, jobId, isPausedOrMaxed) + if priority == 0 then + local pushCmd = lifo and 'RPUSH' or 'LPUSH' + addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + else + if lifo then + pushBackJobWithPriority(prioritizedKey, priority, jobId) + else + addJobWithPriority(markerKey, prioritizedKey, priority, jobId, + priorityCounter, isPausedOrMaxed) + end + end +end +if rcall("EXISTS", jobKey) == 1 then + local metaKey = KEYS[3] + local target, isPausedOrMaxed = getTargetQueueList(metaKey, KEYS[5], KEYS[1], KEYS[2]) + local prioritizedKey = KEYS[4] + local priorityCounterKey = KEYS[6] + local markerKey = KEYS[7] + -- Re-add with the new priority + if rcall("ZREM", prioritizedKey, jobId) > 0 then + reAddJobWithNewPriority( prioritizedKey, markerKey, target, + priorityCounterKey, ARGV[4] == '1', priority, jobId, isPausedOrMaxed) + elseif rcall("LREM", target, -1, jobId) > 0 then + reAddJobWithNewPriority( prioritizedKey, markerKey, target, + priorityCounterKey, ARGV[4] == '1', priority, jobId, isPausedOrMaxed) + end + rcall("HSET", jobKey, "priority", priority) + return 0 +else + return -1 +end +`; +var changePriority = { + name: "changePriority", + content: content9, + keys: 7 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/cleanJobsInSet-3.js +var content10 = `--[[ + Remove jobs from the specific set. + Input: + KEYS[1] set key, + KEYS[2] events stream key + KEYS[3] repeat key + ARGV[1] jobKey prefix + ARGV[2] timestamp + ARGV[3] limit the number of jobs to be removed. 0 is unlimited + ARGV[4] set name, can be any of 'wait', 'active', 'paused', 'delayed', 'completed', or 'failed' +]] +local rcall = redis.call +local repeatKey = KEYS[3] +local rangeStart = 0 +local rangeEnd = -1 +local limit = tonumber(ARGV[3]) +-- If we're only deleting _n_ items, avoid retrieving all items +-- for faster performance +-- +-- Start from the tail of the list, since that's where oldest elements +-- are generally added for FIFO lists +if limit > 0 then + rangeStart = -1 - limit + 1 + rangeEnd = -1 +end +-- Includes +--[[ + Function to clean job list. + Returns jobIds and deleted count number. +]] +-- Includes +--[[ + Function to get the latest saved timestamp. +]] +local function getTimestamp(jobKey, attributes) + if #attributes == 1 then + return rcall("HGET", jobKey, attributes[1]) + end + local jobTs + for _, ts in ipairs(rcall("HMGET", jobKey, unpack(attributes))) do + if (ts) then + jobTs = ts + break + end + end + return jobTs +end +--[[ + Function to check if the job belongs to a job scheduler and + current delayed job matches with jobId +]] +local function isJobSchedulerJob(jobId, jobKey, jobSchedulersKey) + local repeatJobKey = rcall("HGET", jobKey, "rjk") + if repeatJobKey then + local prevMillis = rcall("ZSCORE", jobSchedulersKey, repeatJobKey) + if prevMillis then + local currentDelayedJobId = "repeat:" .. repeatJobKey .. ":" .. prevMillis + return jobId == currentDelayedJobId + end + end + return false +end +--[[ + Function to remove job. +]] +-- Includes +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local function removeJob(jobId, hard, baseKey, shouldRemoveDeduplicationKey) + local jobKey = baseKey .. jobId + removeParentDependencyKey(jobKey, hard, nil, baseKey) + if shouldRemoveDeduplicationKey then + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(baseKey, jobId, deduplicationId) + end + removeJobKeys(jobKey) +end +local function cleanList(listKey, jobKeyPrefix, rangeStart, rangeEnd, + timestamp, isWaiting, jobSchedulersKey) + local jobs = rcall("LRANGE", listKey, rangeStart, rangeEnd) + local deleted = {} + local deletedCount = 0 + local jobTS + local deletionMarker = '' + local jobIdsLen = #jobs + for i, job in ipairs(jobs) do + if limit > 0 and deletedCount >= limit then + break + end + local jobKey = jobKeyPrefix .. job + if (isWaiting or rcall("EXISTS", jobKey .. ":lock") == 0) and + not isJobSchedulerJob(job, jobKey, jobSchedulersKey) then + -- Find the right timestamp of the job to compare to maxTimestamp: + -- * finishedOn says when the job was completed, but it isn't set unless the job has actually completed + -- * processedOn represents when the job was last attempted, but it doesn't get populated until + -- the job is first tried + -- * timestamp is the original job submission time + -- Fetch all three of these (in that order) and use the first one that is set so that we'll leave jobs + -- that have been active within the grace period: + jobTS = getTimestamp(jobKey, {"finishedOn", "processedOn", "timestamp"}) + if (not jobTS or jobTS <= timestamp) then + -- replace the entry with a deletion marker; the actual deletion will + -- occur at the end of the script + rcall("LSET", listKey, rangeEnd - jobIdsLen + i, deletionMarker) + removeJob(job, true, jobKeyPrefix, true --[[remove debounce key]]) + deletedCount = deletedCount + 1 + table.insert(deleted, job) + end + end + end + rcall("LREM", listKey, 0, deletionMarker) + return {deleted, deletedCount} +end +--[[ + Function to clean job set. + Returns jobIds and deleted count number. +]] +-- Includes +--[[ + Function to loop in batches. + Just a bit of warning, some commands as ZREM + could receive a maximum of 7000 parameters per call. +]] +local function batches(n, batchSize) + local i = 0 + return function() + local from = i * batchSize + 1 + i = i + 1 + if (from <= n) then + local to = math.min(from + batchSize - 1, n) + return from, to + end + end +end +--[[ + We use ZRANGEBYSCORE to make the case where we're deleting a limited number + of items in a sorted set only run a single iteration. If we simply used + ZRANGE, we may take a long time traversing through jobs that are within the + grace period. +]] +local function getJobsInZset(zsetKey, rangeEnd, limit) + if limit > 0 then + return rcall("ZRANGEBYSCORE", zsetKey, 0, rangeEnd, "LIMIT", 0, limit) + else + return rcall("ZRANGEBYSCORE", zsetKey, 0, rangeEnd) + end +end +local function cleanSet( + setKey, + jobKeyPrefix, + rangeEnd, + timestamp, + limit, + attributes, + isFinished, + jobSchedulersKey) + local jobs = getJobsInZset(setKey, rangeEnd, limit) + local deleted = {} + local deletedCount = 0 + local jobTS + for i, job in ipairs(jobs) do + if limit > 0 and deletedCount >= limit then + break + end + local jobKey = jobKeyPrefix .. job + -- Extract a Job Scheduler Id from jobId ("repeat:job-scheduler-id:millis") + -- and check if it is in the scheduled jobs + if not (jobSchedulersKey and isJobSchedulerJob(job, jobKey, jobSchedulersKey)) then + if isFinished then + removeJob(job, true, jobKeyPrefix, true --[[remove debounce key]] ) + deletedCount = deletedCount + 1 + table.insert(deleted, job) + else + -- * finishedOn says when the job was completed, but it isn't set unless the job has actually completed + jobTS = getTimestamp(jobKey, attributes) + if (not jobTS or jobTS <= timestamp) then + removeJob(job, true, jobKeyPrefix, true --[[remove debounce key]] ) + deletedCount = deletedCount + 1 + table.insert(deleted, job) + end + end + end + end + if (#deleted > 0) then + for from, to in batches(#deleted, 7000) do + rcall("ZREM", setKey, unpack(deleted, from, to)) + end + end + return {deleted, deletedCount} +end +local result +if ARGV[4] == "active" then + result = cleanList(KEYS[1], ARGV[1], rangeStart, rangeEnd, ARGV[2], false --[[ hasFinished ]], + repeatKey) +elseif ARGV[4] == "delayed" then + rangeEnd = "+inf" + result = cleanSet(KEYS[1], ARGV[1], rangeEnd, ARGV[2], limit, + {"processedOn", "timestamp"}, false --[[ hasFinished ]], repeatKey) +elseif ARGV[4] == "prioritized" then + rangeEnd = "+inf" + result = cleanSet(KEYS[1], ARGV[1], rangeEnd, ARGV[2], limit, + {"timestamp"}, false --[[ hasFinished ]], repeatKey) +elseif ARGV[4] == "wait" or ARGV[4] == "paused" then + result = cleanList(KEYS[1], ARGV[1], rangeStart, rangeEnd, ARGV[2], true --[[ hasFinished ]], + repeatKey) +else + rangeEnd = ARGV[2] + -- No need to pass repeat key as in that moment job won't be related to a job scheduler + result = cleanSet(KEYS[1], ARGV[1], rangeEnd, ARGV[2], limit, + {"finishedOn"}, true --[[ hasFinished ]]) +end +rcall("XADD", KEYS[2], "*", "event", "cleaned", "count", result[2]) +return result[1] +`; +var cleanJobsInSet = { + name: "cleanJobsInSet", + content: content10, + keys: 3 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/drain-5.js +var content11 = `--[[ + Drains the queue, removes all jobs that are waiting + or delayed, but not active, completed or failed + Input: + KEYS[1] 'wait', + KEYS[2] 'paused' + KEYS[3] 'delayed' + KEYS[4] 'prioritized' + KEYS[5] 'jobschedulers' (repeat) + ARGV[1] queue key prefix + ARGV[2] should clean delayed jobs +]] +local rcall = redis.call +local queueBaseKey = ARGV[1] +--[[ + Functions to remove jobs. +]] +-- Includes +--[[ + Function to filter out jobs to ignore from a table. +]] +local function filterOutJobsToIgnore(jobs, jobsToIgnore) + local filteredJobs = {} + for i = 1, #jobs do + if not jobsToIgnore[jobs[i]] then + table.insert(filteredJobs, jobs[i]) + end + end + return filteredJobs +end +--[[ + Functions to remove jobs. +]] +-- Includes +--[[ + Function to remove job. +]] +-- Includes +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local function removeJob(jobId, hard, baseKey, shouldRemoveDeduplicationKey) + local jobKey = baseKey .. jobId + removeParentDependencyKey(jobKey, hard, nil, baseKey) + if shouldRemoveDeduplicationKey then + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(baseKey, jobId, deduplicationId) + end + removeJobKeys(jobKey) +end +local function removeJobs(keys, hard, baseKey, max) + for i, key in ipairs(keys) do + removeJob(key, hard, baseKey, true --[[remove debounce key]]) + end + return max - #keys +end +local function getListItems(keyName, max) + return rcall('LRANGE', keyName, 0, max - 1) +end +local function removeListJobs(keyName, hard, baseKey, max, jobsToIgnore) + local jobs = getListItems(keyName, max) + if jobsToIgnore then + jobs = filterOutJobsToIgnore(jobs, jobsToIgnore) + end + local count = removeJobs(jobs, hard, baseKey, max) + rcall("LTRIM", keyName, #jobs, -1) + return count +end +-- Includes +--[[ + Function to loop in batches. + Just a bit of warning, some commands as ZREM + could receive a maximum of 7000 parameters per call. +]] +local function batches(n, batchSize) + local i = 0 + return function() + local from = i * batchSize + 1 + i = i + 1 + if (from <= n) then + local to = math.min(from + batchSize - 1, n) + return from, to + end + end +end +--[[ + Function to get ZSet items. +]] +local function getZSetItems(keyName, max) + return rcall('ZRANGE', keyName, 0, max - 1) +end +local function removeZSetJobs(keyName, hard, baseKey, max, jobsToIgnore) + local jobs = getZSetItems(keyName, max) + if jobsToIgnore then + jobs = filterOutJobsToIgnore(jobs, jobsToIgnore) + end + local count = removeJobs(jobs, hard, baseKey, max) + if(#jobs > 0) then + for from, to in batches(#jobs, 7000) do + rcall("ZREM", keyName, unpack(jobs, from, to)) + end + end + return count +end +-- We must not remove delayed jobs if they are associated to a job scheduler. +local scheduledJobs = {} +local jobSchedulers = rcall("ZRANGE", KEYS[5], 0, -1, "WITHSCORES") +-- For every job scheduler, get the current delayed job id. +for i = 1, #jobSchedulers, 2 do + local jobSchedulerId = jobSchedulers[i] + local jobSchedulerMillis = jobSchedulers[i + 1] + local delayedJobId = "repeat:" .. jobSchedulerId .. ":" .. jobSchedulerMillis + scheduledJobs[delayedJobId] = true +end +removeListJobs(KEYS[1], true, queueBaseKey, 0, scheduledJobs) -- wait +removeListJobs(KEYS[2], true, queueBaseKey, 0, scheduledJobs) -- paused +if ARGV[2] == "1" then + removeZSetJobs(KEYS[3], true, queueBaseKey, 0, scheduledJobs) -- delayed +end +removeZSetJobs(KEYS[4], true, queueBaseKey, 0, scheduledJobs) -- prioritized +`; +var drain = { + name: "drain", + content: content11, + keys: 5 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/extendLock-2.js +var content12 = `--[[ + Extend lock and removes the job from the stalled set. + Input: + KEYS[1] 'lock', + KEYS[2] 'stalled' + ARGV[1] token + ARGV[2] lock duration in milliseconds + ARGV[3] jobid + Output: + "1" if lock extented succesfully. +]] +local rcall = redis.call +if rcall("GET", KEYS[1]) == ARGV[1] then + -- if rcall("SET", KEYS[1], ARGV[1], "PX", ARGV[2], "XX") then + if rcall("SET", KEYS[1], ARGV[1], "PX", ARGV[2]) then + rcall("SREM", KEYS[2], ARGV[3]) + return 1 + end +end +return 0 +`; +var extendLock = { + name: "extendLock", + content: content12, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/extendLocks-1.js +var content13 = `--[[ + Extend locks for multiple jobs and remove them from the stalled set if successful. + Return the list of job IDs for which the operation failed. + KEYS[1] = stalled key + ARGV[1] = baseKey + ARGV[2] = tokens + ARGV[3] = jobIds + ARGV[4] = lockDuration (ms) + Output: + An array of failed job IDs. If empty, all succeeded. +]] +local rcall = redis.call +local stalledKey = KEYS[1] +local baseKey = ARGV[1] +local tokens = cmsgpack.unpack(ARGV[2]) +local jobIds = cmsgpack.unpack(ARGV[3]) +local lockDuration = ARGV[4] +local jobCount = #jobIds +local failedJobs = {} +for i = 1, jobCount, 1 do + local lockKey = baseKey .. jobIds[i] .. ':lock' + local jobId = jobIds[i] + local token = tokens[i] + local currentToken = rcall("GET", lockKey) + if currentToken then + if currentToken == token then + local setResult = rcall("SET", lockKey, token, "PX", lockDuration) + if setResult then + rcall("SREM", stalledKey, jobId) + else + table.insert(failedJobs, jobId) + end + else + table.insert(failedJobs, jobId) + end + else + table.insert(failedJobs, jobId) + end +end +return failedJobs +`; +var extendLocks = { + name: "extendLocks", + content: content13, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getCounts-1.js +var content14 = `--[[ + Get counts per provided states + Input: + KEYS[1] 'prefix' + ARGV[1...] types +]] +local rcall = redis.call; +local prefix = KEYS[1] +local results = {} +for i = 1, #ARGV do + local stateKey = prefix .. ARGV[i] + if ARGV[i] == "wait" or ARGV[i] == "paused" then + -- Markers in waitlist DEPRECATED in v5: Remove in v6. + local marker = rcall("LINDEX", stateKey, -1) + if marker and string.sub(marker, 1, 2) == "0:" then + local count = rcall("LLEN", stateKey) + if count > 1 then + rcall("RPOP", stateKey) + results[#results+1] = count-1 + else + results[#results+1] = 0 + end + else + results[#results+1] = rcall("LLEN", stateKey) + end + elseif ARGV[i] == "active" then + results[#results+1] = rcall("LLEN", stateKey) + else + results[#results+1] = rcall("ZCARD", stateKey) + end +end +return results +`; +var getCounts = { + name: "getCounts", + content: content14, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getCountsPerPriority-4.js +var content15 = `--[[ + Get counts per provided states + Input: + KEYS[1] wait key + KEYS[2] paused key + KEYS[3] meta key + KEYS[4] prioritized key + ARGV[1...] priorities +]] +local rcall = redis.call +local results = {} +local waitKey = KEYS[1] +local pausedKey = KEYS[2] +local prioritizedKey = KEYS[4] +-- Includes +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePaused(queueMetaKey) + return rcall("HEXISTS", queueMetaKey, "paused") == 1 +end +for i = 1, #ARGV do + local priority = tonumber(ARGV[i]) + if priority == 0 then + if isQueuePaused(KEYS[3]) then + results[#results+1] = rcall("LLEN", pausedKey) + else + results[#results+1] = rcall("LLEN", waitKey) + end + else + results[#results+1] = rcall("ZCOUNT", prioritizedKey, + priority * 0x100000000, (priority + 1) * 0x100000000 - 1) + end +end +return results +`; +var getCountsPerPriority = { + name: "getCountsPerPriority", + content: content15, + keys: 4 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getDependencyCounts-4.js +var content16 = `--[[ + Get counts per child states + Input: + KEYS[1] processed key + KEYS[2] unprocessed key + KEYS[3] ignored key + KEYS[4] failed key + ARGV[1...] types +]] +local rcall = redis.call; +local processedKey = KEYS[1] +local unprocessedKey = KEYS[2] +local ignoredKey = KEYS[3] +local failedKey = KEYS[4] +local results = {} +for i = 1, #ARGV do + if ARGV[i] == "processed" then + results[#results+1] = rcall("HLEN", processedKey) + elseif ARGV[i] == "unprocessed" then + results[#results+1] = rcall("SCARD", unprocessedKey) + elseif ARGV[i] == "ignored" then + results[#results+1] = rcall("HLEN", ignoredKey) + else + results[#results+1] = rcall("ZCARD", failedKey) + end +end +return results +`; +var getDependencyCounts = { + name: "getDependencyCounts", + content: content16, + keys: 4 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getJobScheduler-1.js +var content17 = `--[[ + Get job scheduler record. + Input: + KEYS[1] 'repeat' key + ARGV[1] id +]] +local rcall = redis.call +local jobSchedulerKey = KEYS[1] .. ":" .. ARGV[1] +local score = rcall("ZSCORE", KEYS[1], ARGV[1]) +if score then + return {rcall("HGETALL", jobSchedulerKey), score} -- get job data +end +return {nil, nil} +`; +var getJobScheduler = { + name: "getJobScheduler", + content: content17, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getMetrics-2.js +var content18 = `--[[ + Get metrics + Input: + KEYS[1] 'metrics' key + KEYS[2] 'metrics data' key + ARGV[1] start index + ARGV[2] end index +]] +local rcall = redis.call; +local metricsKey = KEYS[1] +local dataKey = KEYS[2] +local metrics = rcall("HMGET", metricsKey, "count", "prevTS", "prevCount") +local data = rcall("LRANGE", dataKey, tonumber(ARGV[1]), tonumber(ARGV[2])) +local numPoints = rcall("LLEN", dataKey) +return {metrics, data, numPoints} +`; +var getMetrics = { + name: "getMetrics", + content: content18, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getRanges-1.js +var content19 = `--[[ + Get job ids per provided states + Input: + KEYS[1] 'prefix' + ARGV[1] start + ARGV[2] end + ARGV[3] asc + ARGV[4...] types +]] +local rcall = redis.call +local prefix = KEYS[1] +local rangeStart = tonumber(ARGV[1]) +local rangeEnd = tonumber(ARGV[2]) +local asc = ARGV[3] +local results = {} +local function getRangeInList(listKey, asc, rangeStart, rangeEnd, results) + if asc == "1" then + local modifiedRangeStart + local modifiedRangeEnd + if rangeStart == -1 then + modifiedRangeStart = 0 + else + modifiedRangeStart = -(rangeStart + 1) + end + if rangeEnd == -1 then + modifiedRangeEnd = 0 + else + modifiedRangeEnd = -(rangeEnd + 1) + end + results[#results+1] = rcall("LRANGE", listKey, + modifiedRangeEnd, + modifiedRangeStart) + else + results[#results+1] = rcall("LRANGE", listKey, rangeStart, rangeEnd) + end +end +for i = 4, #ARGV do + local stateKey = prefix .. ARGV[i] + if ARGV[i] == "wait" or ARGV[i] == "paused" then + -- Markers in waitlist DEPRECATED in v5: Remove in v6. + local marker = rcall("LINDEX", stateKey, -1) + if marker and string.sub(marker, 1, 2) == "0:" then + local count = rcall("LLEN", stateKey) + if count > 1 then + rcall("RPOP", stateKey) + getRangeInList(stateKey, asc, rangeStart, rangeEnd, results) + else + results[#results+1] = {} + end + else + getRangeInList(stateKey, asc, rangeStart, rangeEnd, results) + end + elseif ARGV[i] == "active" then + getRangeInList(stateKey, asc, rangeStart, rangeEnd, results) + else + if asc == "1" then + results[#results+1] = rcall("ZRANGE", stateKey, rangeStart, rangeEnd) + else + results[#results+1] = rcall("ZREVRANGE", stateKey, rangeStart, rangeEnd) + end + end +end +return results +`; +var getRanges = { + name: "getRanges", + content: content19, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getRateLimitTtl-2.js +var content20 = `--[[ + Get rate limit ttl + Input: + KEYS[1] 'limiter' + KEYS[2] 'meta' + ARGV[1] maxJobs +]] +local rcall = redis.call +-- Includes +--[[ + Function to get current rate limit ttl. +]] +local function getRateLimitTTL(maxJobs, rateLimiterKey) + if maxJobs and maxJobs <= tonumber(rcall("GET", rateLimiterKey) or 0) then + local pttl = rcall("PTTL", rateLimiterKey) + if pttl == 0 then + rcall("DEL", rateLimiterKey) + end + if pttl > 0 then + return pttl + end + end + return 0 +end +local rateLimiterKey = KEYS[1] +if ARGV[1] ~= "0" then + return getRateLimitTTL(tonumber(ARGV[1]), rateLimiterKey) +else + local rateLimitMax = rcall("HGET", KEYS[2], "max") + if rateLimitMax then + return getRateLimitTTL(tonumber(rateLimitMax), rateLimiterKey) + end + return rcall("PTTL", rateLimiterKey) +end +`; +var getRateLimitTtl = { + name: "getRateLimitTtl", + content: content20, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getState-8.js +var content21 = `--[[ + Get a job state + Input: + KEYS[1] 'completed' key, + KEYS[2] 'failed' key + KEYS[3] 'delayed' key + KEYS[4] 'active' key + KEYS[5] 'wait' key + KEYS[6] 'paused' key + KEYS[7] 'waiting-children' key + KEYS[8] 'prioritized' key + ARGV[1] job id + Output: + 'completed' + 'failed' + 'delayed' + 'active' + 'prioritized' + 'waiting' + 'waiting-children' + 'unknown' +]] +local rcall = redis.call +if rcall("ZSCORE", KEYS[1], ARGV[1]) then + return "completed" +end +if rcall("ZSCORE", KEYS[2], ARGV[1]) then + return "failed" +end +if rcall("ZSCORE", KEYS[3], ARGV[1]) then + return "delayed" +end +if rcall("ZSCORE", KEYS[8], ARGV[1]) then + return "prioritized" +end +-- Includes +--[[ + Function to check if an item belongs to a list. +]] +local function checkItemInList(list, item) + for _, v in pairs(list) do + if v == item then + return 1 + end + end + return nil +end +local active_items = rcall("LRANGE", KEYS[4] , 0, -1) +if checkItemInList(active_items, ARGV[1]) ~= nil then + return "active" +end +local wait_items = rcall("LRANGE", KEYS[5] , 0, -1) +if checkItemInList(wait_items, ARGV[1]) ~= nil then + return "waiting" +end +local paused_items = rcall("LRANGE", KEYS[6] , 0, -1) +if checkItemInList(paused_items, ARGV[1]) ~= nil then + return "waiting" +end +if rcall("ZSCORE", KEYS[7], ARGV[1]) then + return "waiting-children" +end +return "unknown" +`; +var getState = { + name: "getState", + content: content21, + keys: 8 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/getStateV2-8.js +var content22 = `--[[ + Get a job state + Input: + KEYS[1] 'completed' key, + KEYS[2] 'failed' key + KEYS[3] 'delayed' key + KEYS[4] 'active' key + KEYS[5] 'wait' key + KEYS[6] 'paused' key + KEYS[7] 'waiting-children' key + KEYS[8] 'prioritized' key + ARGV[1] job id + Output: + 'completed' + 'failed' + 'delayed' + 'active' + 'waiting' + 'waiting-children' + 'unknown' +]] +local rcall = redis.call +if rcall("ZSCORE", KEYS[1], ARGV[1]) then + return "completed" +end +if rcall("ZSCORE", KEYS[2], ARGV[1]) then + return "failed" +end +if rcall("ZSCORE", KEYS[3], ARGV[1]) then + return "delayed" +end +if rcall("ZSCORE", KEYS[8], ARGV[1]) then + return "prioritized" +end +if rcall("LPOS", KEYS[4] , ARGV[1]) then + return "active" +end +if rcall("LPOS", KEYS[5] , ARGV[1]) then + return "waiting" +end +if rcall("LPOS", KEYS[6] , ARGV[1]) then + return "waiting" +end +if rcall("ZSCORE", KEYS[7] , ARGV[1]) then + return "waiting-children" +end +return "unknown" +`; +var getStateV2 = { + name: "getStateV2", + content: content22, + keys: 8 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/isFinished-3.js +var content23 = `--[[ + Checks if a job is finished (.i.e. is in the completed or failed set) + Input: + KEYS[1] completed key + KEYS[2] failed key + KEYS[3] job key + ARGV[1] job id + ARGV[2] return value? + Output: + 0 - Not finished. + 1 - Completed. + 2 - Failed. + -1 - Missing job. +]] +local rcall = redis.call +if rcall("EXISTS", KEYS[3]) ~= 1 then + if ARGV[2] == "1" then + return {-1,"Missing key for job " .. KEYS[3] .. ". isFinished"} + end + return -1 +end +if rcall("ZSCORE", KEYS[1], ARGV[1]) then + if ARGV[2] == "1" then + local returnValue = rcall("HGET", KEYS[3], "returnvalue") + return {1,returnValue} + end + return 1 +end +if rcall("ZSCORE", KEYS[2], ARGV[1]) then + if ARGV[2] == "1" then + local failedReason = rcall("HGET", KEYS[3], "failedReason") + return {2,failedReason} + end + return 2 +end +if ARGV[2] == "1" then + return {0} +end +return 0 +`; +var isFinished = { + name: "isFinished", + content: content23, + keys: 3 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/isJobInList-1.js +var content24 = `--[[ + Checks if job is in a given list. + Input: + KEYS[1] + ARGV[1] + Output: + 1 if element found in the list. +]] +-- Includes +--[[ + Function to check if an item belongs to a list. +]] +local function checkItemInList(list, item) + for _, v in pairs(list) do + if v == item then + return 1 + end + end + return nil +end +local items = redis.call("LRANGE", KEYS[1] , 0, -1) +return checkItemInList(items, ARGV[1]) +`; +var isJobInList = { + name: "isJobInList", + content: content24, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/isMaxed-2.js +var content25 = `--[[ + Checks if queue is maxed. + Input: + KEYS[1] meta key + KEYS[2] active key + Output: + 1 if element found in the list. +]] +local rcall = redis.call +-- Includes +--[[ + Function to check if queue is maxed or not. +]] +local function isQueueMaxed(queueMetaKey, activeKey) + local maxConcurrency = rcall("HGET", queueMetaKey, "concurrency") + if maxConcurrency then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(maxConcurrency) then + return true + end + end + return false +end +return isQueueMaxed(KEYS[1], KEYS[2]) +`; +var isMaxed = { + name: "isMaxed", + content: content25, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveJobFromActiveToWait-9.js +var content26 = `--[[ + Function to move job from active state to wait. + Input: + KEYS[1] active key + KEYS[2] wait key + KEYS[3] stalled key + KEYS[4] paused key + KEYS[5] meta key + KEYS[6] limiter key + KEYS[7] prioritized key + KEYS[8] marker key + KEYS[9] event key + ARGV[1] job id + ARGV[2] lock token + ARGV[3] job id key +]] +local rcall = redis.call +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to push back job considering priority in front of same prioritized jobs. +]] +local function pushBackJobWithPriority(prioritizedKey, priority, jobId) + -- in order to put it at front of same prioritized jobs + -- we consider prioritized counter as 0 + local score = priority * 0x100000000 + rcall("ZADD", prioritizedKey, score, jobId) +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function removeLock(jobKey, stalledKey, token, jobId) + if token ~= "0" then + local lockKey = jobKey .. ':lock' + local lockToken = rcall("GET", lockKey) + if lockToken == token then + rcall("DEL", lockKey) + rcall("SREM", stalledKey, jobId) + else + if lockToken then + -- Lock exists but token does not match + return -6 + else + -- Lock is missing completely + return -2 + end + end + end + return 0 +end +local jobId = ARGV[1] +local token = ARGV[2] +local jobKey = ARGV[3] +if rcall("EXISTS", jobKey) == 0 then + return -1 +end +local errorCode = removeLock(jobKey, KEYS[3], token, jobId) +if errorCode < 0 then + return errorCode +end +local metaKey = KEYS[5] +local removed = rcall("LREM", KEYS[1], 1, jobId) +if removed > 0 then + local target, isPausedOrMaxed = getTargetQueueList(metaKey, KEYS[1], KEYS[2], KEYS[4]) + local priority = tonumber(rcall("HGET", ARGV[3], "priority")) or 0 + if priority > 0 then + pushBackJobWithPriority(KEYS[7], priority, jobId) + else + addJobInTargetList(target, KEYS[8], "RPUSH", isPausedOrMaxed, jobId) + end + local maxEvents = getOrSetMaxEvents(metaKey) + -- Emit waiting event + rcall("XADD", KEYS[9], "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId, "prev", "active") +end +local pttl = rcall("PTTL", KEYS[6]) +if pttl > 0 then + return pttl +else + return 0 +end +`; +var moveJobFromActiveToWait = { + name: "moveJobFromActiveToWait", + content: content26, + keys: 9 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveJobsToWait-8.js +var content27 = `--[[ + Move completed, failed or delayed jobs to wait. + Note: Does not support jobs with priorities. + Input: + KEYS[1] base key + KEYS[2] events stream + KEYS[3] state key (failed, completed, delayed) + KEYS[4] 'wait' + KEYS[5] 'paused' + KEYS[6] 'meta' + KEYS[7] 'active' + KEYS[8] 'marker' + ARGV[1] count + ARGV[2] timestamp + ARGV[3] prev state + Output: + 1 means the operation is not completed + 0 means the operation is completed +]] +local maxCount = tonumber(ARGV[1]) +local timestamp = tonumber(ARGV[2]) +local rcall = redis.call; +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +--[[ + Function to loop in batches. + Just a bit of warning, some commands as ZREM + could receive a maximum of 7000 parameters per call. +]] +local function batches(n, batchSize) + local i = 0 + return function() + local from = i * batchSize + 1 + i = i + 1 + if (from <= n) then + local to = math.min(from + batchSize - 1, n) + return from, to + end + end +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local metaKey = KEYS[6] +local target, isPausedOrMaxed = getTargetQueueList(metaKey, KEYS[7], KEYS[4], KEYS[5]) +local jobs = rcall('ZRANGEBYSCORE', KEYS[3], 0, timestamp, 'LIMIT', 0, maxCount) +if (#jobs > 0) then + if ARGV[3] == "failed" then + for i, key in ipairs(jobs) do + local jobKey = KEYS[1] .. key + rcall("HDEL", jobKey, "finishedOn", "processedOn", "failedReason") + end + elseif ARGV[3] == "completed" then + for i, key in ipairs(jobs) do + local jobKey = KEYS[1] .. key + rcall("HDEL", jobKey, "finishedOn", "processedOn", "returnvalue") + end + end + local maxEvents = getOrSetMaxEvents(metaKey) + for i, key in ipairs(jobs) do + -- Emit waiting event + rcall("XADD", KEYS[2], "MAXLEN", "~", maxEvents, "*", "event", + "waiting", "jobId", key, "prev", ARGV[3]); + end + for from, to in batches(#jobs, 7000) do + rcall("ZREM", KEYS[3], unpack(jobs, from, to)) + rcall("LPUSH", target, unpack(jobs, from, to)) + end + addBaseMarkerIfNeeded(KEYS[8], isPausedOrMaxed) +end +maxCount = maxCount - #jobs +if (maxCount <= 0) then return 1 end +return 0 +`; +var moveJobsToWait = { + name: "moveJobsToWait", + content: content27, + keys: 8 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveStalledJobsToWait-8.js +var content28 = `--[[ + Move stalled jobs to wait. + Input: + KEYS[1] 'stalled' (SET) + KEYS[2] 'wait', (LIST) + KEYS[3] 'active', (LIST) + KEYS[4] 'stalled-check', (KEY) + KEYS[5] 'meta', (KEY) + KEYS[6] 'paused', (LIST) + KEYS[7] 'marker' + KEYS[8] 'event stream' (STREAM) + ARGV[1] Max stalled job count + ARGV[2] queue.toKey('') + ARGV[3] timestamp + ARGV[4] max check time + Events: + 'stalled' with stalled job id. +]] +local rcall = redis.call +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to loop in batches. + Just a bit of warning, some commands as ZREM + could receive a maximum of 7000 parameters per call. +]] +local function batches(n, batchSize) + local i = 0 + return function() + local from = i * batchSize + 1 + i = i + 1 + if (from <= n) then + local to = math.min(from + batchSize - 1, n) + return from, to + end + end +end +--[[ + Function to move job to wait to be picked up by a waiting worker. +]] +-- Includes +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function moveJobToWait(metaKey, activeKey, waitKey, pausedKey, markerKey, eventStreamKey, + jobId, pushCmd) + local target, isPausedOrMaxed = getTargetQueueList(metaKey, activeKey, waitKey, pausedKey) + addJobInTargetList(target, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall("XADD", eventStreamKey, "*", "event", "waiting", "jobId", jobId, 'prev', 'active') +end +--[[ + Function to trim events, default 10000. +]] +-- Includes +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +local function trimEvents(metaKey, eventStreamKey) + local maxEvents = getOrSetMaxEvents(metaKey) + if maxEvents then + rcall("XTRIM", eventStreamKey, "MAXLEN", "~", maxEvents) + else + rcall("XTRIM", eventStreamKey, "MAXLEN", "~", 10000) + end +end +local stalledKey = KEYS[1] +local waitKey = KEYS[2] +local activeKey = KEYS[3] +local stalledCheckKey = KEYS[4] +local metaKey = KEYS[5] +local pausedKey = KEYS[6] +local markerKey = KEYS[7] +local eventStreamKey = KEYS[8] +local maxStalledJobCount = tonumber(ARGV[1]) +local queueKeyPrefix = ARGV[2] +local timestamp = ARGV[3] +local maxCheckTime = ARGV[4] +if rcall("EXISTS", stalledCheckKey) == 1 then + return {} +end +rcall("SET", stalledCheckKey, timestamp, "PX", maxCheckTime) +-- Trim events before emiting them to avoid trimming events emitted in this script +trimEvents(metaKey, eventStreamKey) +-- Move all stalled jobs to wait +local stalling = rcall('SMEMBERS', stalledKey) +local stalled = {} +if (#stalling > 0) then + rcall('DEL', stalledKey) + -- Remove from active list + for i, jobId in ipairs(stalling) do + -- Markers in waitlist DEPRECATED in v5: Remove in v6. + if string.sub(jobId, 1, 2) == "0:" then + -- If the jobId is a delay marker ID we just remove it. + rcall("LREM", activeKey, 1, jobId) + else + local jobKey = queueKeyPrefix .. jobId + -- Check that the lock is also missing, then we can handle this job as really stalled. + if (rcall("EXISTS", jobKey .. ":lock") == 0) then + -- Remove from the active queue. + local removed = rcall("LREM", activeKey, 1, jobId) + if (removed > 0) then + -- If this job has been stalled too many times, such as if it crashes the worker, then fail it. + local stalledCount = rcall("HINCRBY", jobKey, "stc", 1) + -- Check if this is a repeatable job by looking at job options + local jobOpts = rcall("HGET", jobKey, "opts") + local isRepeatableJob = false + if jobOpts then + local opts = cjson.decode(jobOpts) + if opts and opts["repeat"] then + isRepeatableJob = true + end + end + -- Only fail job if it exceeds stall limit AND is not a repeatable job + if stalledCount > maxStalledJobCount and not isRepeatableJob then + local failedReason = "job stalled more than allowable limit" + rcall("HSET", jobKey, "defa", failedReason) + end + moveJobToWait(metaKey, activeKey, waitKey, pausedKey, markerKey, eventStreamKey, jobId, + "RPUSH") + -- Emit the stalled event + rcall("XADD", eventStreamKey, "*", "event", "stalled", "jobId", jobId) + table.insert(stalled, jobId) + end + end + end + end +end +-- Mark potentially stalled jobs +local active = rcall('LRANGE', activeKey, 0, -1) +if (#active > 0) then + for from, to in batches(#active, 7000) do + rcall('SADD', stalledKey, unpack(active, from, to)) + end +end +return stalled +`; +var moveStalledJobsToWait = { + name: "moveStalledJobsToWait", + content: content28, + keys: 8 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveToActive-11.js +var content29 = `--[[ + Move next job to be processed to active, lock it and fetch its data. The job + may be delayed, in that case we need to move it to the delayed set instead. + This operation guarantees that the worker owns the job during the lock + expiration time. The worker is responsible of keeping the lock fresh + so that no other worker picks this job again. + Input: + KEYS[1] wait key + KEYS[2] active key + KEYS[3] prioritized key + KEYS[4] stream events key + KEYS[5] stalled key + -- Rate limiting + KEYS[6] rate limiter key + KEYS[7] delayed key + -- Delayed jobs + KEYS[8] paused key + KEYS[9] meta key + KEYS[10] pc priority counter + -- Marker + KEYS[11] marker key + -- Arguments + ARGV[1] key prefix + ARGV[2] timestamp + ARGV[3] opts + opts - token - lock token + opts - lockDuration + opts - limiter + opts - name - worker name +]] +local rcall = redis.call +local waitKey = KEYS[1] +local activeKey = KEYS[2] +local eventStreamKey = KEYS[4] +local rateLimiterKey = KEYS[6] +local delayedKey = KEYS[7] +local opts = cmsgpack.unpack(ARGV[3]) +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +--[[ + Function to get current rate limit ttl. +]] +local function getRateLimitTTL(maxJobs, rateLimiterKey) + if maxJobs and maxJobs <= tonumber(rcall("GET", rateLimiterKey) or 0) then + local pttl = rcall("PTTL", rateLimiterKey) + if pttl == 0 then + rcall("DEL", rateLimiterKey) + end + if pttl > 0 then + return pttl + end + end + return 0 +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to move job from prioritized state to active. +]] +local function moveJobFromPrioritizedToActive(priorityKey, activeKey, priorityCounterKey) + local prioritizedJob = rcall("ZPOPMIN", priorityKey) + if #prioritizedJob > 0 then + rcall("LPUSH", activeKey, prioritizedJob[1]) + return prioritizedJob[1] + else + rcall("DEL", priorityCounterKey) + end +end +--[[ + Function to move job from wait state to active. + Input: + opts - token - lock token + opts - lockDuration + opts - limiter +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function prepareJobForProcessing(keyPrefix, rateLimiterKey, eventStreamKey, + jobId, processedOn, maxJobs, limiterDuration, markerKey, opts) + local jobKey = keyPrefix .. jobId + -- Check if we need to perform rate limiting. + if maxJobs then + local jobCounter = tonumber(rcall("INCR", rateLimiterKey)) + if jobCounter == 1 then + local integerDuration = math.floor(math.abs(limiterDuration)) + rcall("PEXPIRE", rateLimiterKey, integerDuration) + end + end + -- get a lock + if opts['token'] ~= "0" then + local lockKey = jobKey .. ':lock' + rcall("SET", lockKey, opts['token'], "PX", opts['lockDuration']) + end + local optionalValues = {} + if opts['name'] then + -- Set "processedBy" field to the worker name + table.insert(optionalValues, "pb") + table.insert(optionalValues, opts['name']) + end + rcall("XADD", eventStreamKey, "*", "event", "active", "jobId", jobId, "prev", "waiting") + rcall("HMSET", jobKey, "processedOn", processedOn, unpack(optionalValues)) + rcall("HINCRBY", jobKey, "ats", 1) + addBaseMarkerIfNeeded(markerKey, false) + -- rate limit delay must be 0 in this case to prevent adding more delay + -- when job that is moved to active needs to be processed + return {rcall("HGETALL", jobKey), jobId, 0, 0} -- get job data +end +--[[ + Updates the delay set, by moving delayed jobs that should + be processed now to "wait". + Events: + 'waiting' +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +-- Try to get as much as 1000 jobs at once +local function promoteDelayedJobs(delayedKey, markerKey, targetKey, prioritizedKey, + eventStreamKey, prefix, timestamp, priorityCounterKey, isPaused) + local jobs = rcall("ZRANGEBYSCORE", delayedKey, 0, (timestamp + 1) * 0x1000 - 1, "LIMIT", 0, 1000) + if (#jobs > 0) then + rcall("ZREM", delayedKey, unpack(jobs)) + for _, jobId in ipairs(jobs) do + local jobKey = prefix .. jobId + local priority = + tonumber(rcall("HGET", jobKey, "priority")) or 0 + if priority == 0 then + -- LIFO or FIFO + rcall("LPUSH", targetKey, jobId) + else + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + end + -- Emit waiting event + rcall("XADD", eventStreamKey, "*", "event", "waiting", "jobId", + jobId, "prev", "delayed") + rcall("HSET", jobKey, "delay", 0) + end + addBaseMarkerIfNeeded(markerKey, isPaused) + end +end +local target, isPausedOrMaxed, rateLimitMax, rateLimitDuration = getTargetQueueList(KEYS[9], + activeKey, waitKey, KEYS[8]) +-- Check if there are delayed jobs that we can move to wait. +local markerKey = KEYS[11] +promoteDelayedJobs(delayedKey, markerKey, target, KEYS[3], eventStreamKey, ARGV[1], + ARGV[2], KEYS[10], isPausedOrMaxed) +local maxJobs = tonumber(rateLimitMax or (opts['limiter'] and opts['limiter']['max'])) +local expireTime = getRateLimitTTL(maxJobs, rateLimiterKey) +-- Check if we are rate limited first. +if expireTime > 0 then return {0, 0, expireTime, 0} end +-- paused or maxed queue +if isPausedOrMaxed then return {0, 0, 0, 0} end +local limiterDuration = (opts['limiter'] and opts['limiter']['duration']) or rateLimitDuration +-- no job ID, try non-blocking move from wait to active +local jobId = rcall("RPOPLPUSH", waitKey, activeKey) +-- Markers in waitlist DEPRECATED in v5: Will be completely removed in v6. +if jobId and string.sub(jobId, 1, 2) == "0:" then + rcall("LREM", activeKey, 1, jobId) + jobId = rcall("RPOPLPUSH", waitKey, activeKey) +end +if jobId then + return prepareJobForProcessing(ARGV[1], rateLimiterKey, eventStreamKey, jobId, ARGV[2], + maxJobs, limiterDuration, markerKey, opts) +else + jobId = moveJobFromPrioritizedToActive(KEYS[3], activeKey, KEYS[10]) + if jobId then + return prepareJobForProcessing(ARGV[1], rateLimiterKey, eventStreamKey, jobId, ARGV[2], + maxJobs, limiterDuration, markerKey, opts) + end +end +-- Return the timestamp for the next delayed job if any. +local nextTimestamp = getNextDelayedTimestamp(delayedKey) +if nextTimestamp ~= nil then return {0, 0, 0, nextTimestamp} end +return {0, 0, 0, 0} +`; +var moveToActive = { + name: "moveToActive", + content: content29, + keys: 11 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveToDelayed-12.js +var content30 = `--[[ + Moves job from active to delayed set. + Input: + KEYS[1] marker key + KEYS[2] active key + KEYS[3] prioritized key + KEYS[4] delayed key + KEYS[5] job key + KEYS[6] events stream + KEYS[7] meta key + KEYS[8] stalled key + KEYS[9] wait key + KEYS[10] rate limiter key + KEYS[11] paused key + KEYS[12] pc priority counter + ARGV[1] key prefix + ARGV[2] timestamp + ARGV[3] the id of the job + ARGV[4] queue token + ARGV[5] delay value + ARGV[6] skip attempt + ARGV[7] optional job fields to update + ARGV[8] fetch next? + ARGV[9] opts + Output: + 0 - OK + -1 - Missing job. + -3 - Job not in active set. + Events: + - delayed key. +]] +local rcall = redis.call +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Function to fetch the next job to process. + Tries to get the next job to avoid an extra roundtrip if the queue is + not closing and not rate limited. + Input: + waitKey - wait list key + activeKey - active list key + prioritizedKey - prioritized sorted set key + eventStreamKey - event stream key + rateLimiterKey - rate limiter key + delayedKey - delayed sorted set key + pausedKey - paused list key + metaKey - meta hash key + pcKey - priority counter key + markerKey - marker key + prefix - keys prefix + timestamp - current timestamp + opts - options table: + token (required) - lock token used when locking jobs + lockDuration (required) - lock duration for acquired jobs + limiter (optional) - rate limiter options table (e.g. { max = number }) +]] +-- Includes +--[[ + Function to get current rate limit ttl. +]] +local function getRateLimitTTL(maxJobs, rateLimiterKey) + if maxJobs and maxJobs <= tonumber(rcall("GET", rateLimiterKey) or 0) then + local pttl = rcall("PTTL", rateLimiterKey) + if pttl == 0 then + rcall("DEL", rateLimiterKey) + end + if pttl > 0 then + return pttl + end + end + return 0 +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to move job from prioritized state to active. +]] +local function moveJobFromPrioritizedToActive(priorityKey, activeKey, priorityCounterKey) + local prioritizedJob = rcall("ZPOPMIN", priorityKey) + if #prioritizedJob > 0 then + rcall("LPUSH", activeKey, prioritizedJob[1]) + return prioritizedJob[1] + else + rcall("DEL", priorityCounterKey) + end +end +--[[ + Function to move job from wait state to active. + Input: + opts - token - lock token + opts - lockDuration + opts - limiter +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function prepareJobForProcessing(keyPrefix, rateLimiterKey, eventStreamKey, + jobId, processedOn, maxJobs, limiterDuration, markerKey, opts) + local jobKey = keyPrefix .. jobId + -- Check if we need to perform rate limiting. + if maxJobs then + local jobCounter = tonumber(rcall("INCR", rateLimiterKey)) + if jobCounter == 1 then + local integerDuration = math.floor(math.abs(limiterDuration)) + rcall("PEXPIRE", rateLimiterKey, integerDuration) + end + end + -- get a lock + if opts['token'] ~= "0" then + local lockKey = jobKey .. ':lock' + rcall("SET", lockKey, opts['token'], "PX", opts['lockDuration']) + end + local optionalValues = {} + if opts['name'] then + -- Set "processedBy" field to the worker name + table.insert(optionalValues, "pb") + table.insert(optionalValues, opts['name']) + end + rcall("XADD", eventStreamKey, "*", "event", "active", "jobId", jobId, "prev", "waiting") + rcall("HMSET", jobKey, "processedOn", processedOn, unpack(optionalValues)) + rcall("HINCRBY", jobKey, "ats", 1) + addBaseMarkerIfNeeded(markerKey, false) + -- rate limit delay must be 0 in this case to prevent adding more delay + -- when job that is moved to active needs to be processed + return {rcall("HGETALL", jobKey), jobId, 0, 0} -- get job data +end +--[[ + Updates the delay set, by moving delayed jobs that should + be processed now to "wait". + Events: + 'waiting' +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +-- Try to get as much as 1000 jobs at once +local function promoteDelayedJobs(delayedKey, markerKey, targetKey, prioritizedKey, + eventStreamKey, prefix, timestamp, priorityCounterKey, isPaused) + local jobs = rcall("ZRANGEBYSCORE", delayedKey, 0, (timestamp + 1) * 0x1000 - 1, "LIMIT", 0, 1000) + if (#jobs > 0) then + rcall("ZREM", delayedKey, unpack(jobs)) + for _, jobId in ipairs(jobs) do + local jobKey = prefix .. jobId + local priority = + tonumber(rcall("HGET", jobKey, "priority")) or 0 + if priority == 0 then + -- LIFO or FIFO + rcall("LPUSH", targetKey, jobId) + else + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + end + -- Emit waiting event + rcall("XADD", eventStreamKey, "*", "event", "waiting", "jobId", + jobId, "prev", "delayed") + rcall("HSET", jobKey, "delay", 0) + end + addBaseMarkerIfNeeded(markerKey, isPaused) + end +end +local function fetchNextJob(waitKey, activeKey, prioritizedKey, eventStreamKey, + rateLimiterKey, delayedKey, pausedKey, metaKey, pcKey, markerKey, prefix, + timestamp, opts) + local target, isPausedOrMaxed, rateLimitMax, rateLimitDuration = + getTargetQueueList(metaKey, activeKey, waitKey, pausedKey) + -- Check if there are delayed jobs that can be promoted + promoteDelayedJobs(delayedKey, markerKey, target, prioritizedKey, + eventStreamKey, prefix, timestamp, pcKey, isPausedOrMaxed) + local maxJobs = tonumber(rateLimitMax or (opts['limiter'] and opts['limiter']['max'])) + -- Check if we are rate limited first. + local expireTime = getRateLimitTTL(maxJobs, rateLimiterKey) + if expireTime > 0 then + return {0, 0, expireTime, 0} + end + -- paused or maxed queue + if isPausedOrMaxed then + return {0, 0, 0, 0} + end + local limiterDuration = (opts['limiter'] and opts['limiter']['duration']) or rateLimitDuration + local jobId = rcall("RPOPLPUSH", waitKey, activeKey) + if jobId then + -- Markers in waitlist DEPRECATED in v5: Remove in v6. + if string.sub(jobId, 1, 2) == "0:" then + rcall("LREM", activeKey, 1, jobId) + -- If jobId is special ID 0:delay (delay greater than 0), then there is no job to process + -- but if ID is 0:0, then there is at least 1 prioritized job to process + if jobId == "0:0" then + jobId = moveJobFromPrioritizedToActive(prioritizedKey, activeKey, pcKey) + return prepareJobForProcessing(prefix, rateLimiterKey, + eventStreamKey, jobId, timestamp, maxJobs, + limiterDuration, markerKey, opts) + end + else + return prepareJobForProcessing(prefix, rateLimiterKey, + eventStreamKey, jobId, timestamp, maxJobs, + limiterDuration, markerKey, opts) + end + else + jobId = moveJobFromPrioritizedToActive(prioritizedKey, activeKey, pcKey) + if jobId then + return prepareJobForProcessing(prefix, rateLimiterKey, + eventStreamKey, jobId, timestamp, maxJobs, + limiterDuration, markerKey, opts) + end + end + -- Return the timestamp for the next delayed job if any. + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- The result is guaranteed to be positive, since the + -- ZRANGEBYSCORE command would have return a job otherwise. + return {0, 0, 0, nextTimestamp} + end +end +--[[ + Bake in the job id first 12 bits into the timestamp + to guarantee correct execution order of delayed jobs + (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp) + WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail +]] +local function getDelayedScore(delayedKey, timestamp, delay) + local delayedTimestamp = (delay > 0 and (tonumber(timestamp) + delay)) or tonumber(timestamp) + local minScore = delayedTimestamp * 0x1000 + local maxScore = (delayedTimestamp + 1 ) * 0x1000 - 1 + local result = rcall("ZREVRANGEBYSCORE", delayedKey, maxScore, + minScore, "WITHSCORES","LIMIT", 0, 1) + if #result then + local currentMaxScore = tonumber(result[2]) + if currentMaxScore ~= nil then + if currentMaxScore >= maxScore then + return maxScore, delayedTimestamp + else + return currentMaxScore + 1, delayedTimestamp + end + end + end + return minScore, delayedTimestamp +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +local function removeLock(jobKey, stalledKey, token, jobId) + if token ~= "0" then + local lockKey = jobKey .. ':lock' + local lockToken = rcall("GET", lockKey) + if lockToken == token then + rcall("DEL", lockKey) + rcall("SREM", stalledKey, jobId) + else + if lockToken then + -- Lock exists but token does not match + return -6 + else + -- Lock is missing completely + return -2 + end + end + end + return 0 +end +--[[ + Function to update a bunch of fields in a job. +]] +local function updateJobFields(jobKey, msgpackedFields) + if msgpackedFields and #msgpackedFields > 0 then + local fieldsToUpdate = cmsgpack.unpack(msgpackedFields) + if fieldsToUpdate then + rcall("HMSET", jobKey, unpack(fieldsToUpdate)) + end + end +end +local jobKey = KEYS[5] +local markerKey = KEYS[1] +local metaKey = KEYS[7] +local token = ARGV[4] +if rcall("EXISTS", jobKey) == 1 then + local errorCode = removeLock(jobKey, KEYS[8], token, ARGV[3]) + if errorCode < 0 then + return errorCode + end + updateJobFields(jobKey, ARGV[7]) + local delayedKey = KEYS[4] + local jobId = ARGV[3] + local delay = tonumber(ARGV[5]) + local numRemovedElements = rcall("LREM", KEYS[2], -1, jobId) + if numRemovedElements < 1 then return -3 end + local score, delayedTimestamp = getDelayedScore(delayedKey, ARGV[2], delay) + if ARGV[6] == "0" then + rcall("HINCRBY", jobKey, "atm", 1) + end + rcall("HSET", jobKey, "delay", ARGV[5]) + local maxEvents = getOrSetMaxEvents(metaKey) + rcall("ZADD", delayedKey, score, jobId) + rcall("XADD", KEYS[6], "MAXLEN", "~", maxEvents, "*", "event", "delayed", + "jobId", jobId, "delay", delayedTimestamp) + -- Try to get next job to avoid an extra roundtrip if the queue is not closing, + -- and not rate limited. + if (ARGV[8] == "1") then + local opts = cmsgpack.unpack(ARGV[9]) + local result = fetchNextJob(KEYS[9], KEYS[2], KEYS[3], KEYS[6], + KEYS[10], KEYS[4], KEYS[11], metaKey, KEYS[12], markerKey, + ARGV[1], ARGV[2], opts) + if result and type(result[1]) == "table" then + return result + end + end + -- Check if we need to push a marker job to wake up sleeping workers. + addDelayMarkerIfNeeded(markerKey, delayedKey) + return 0 +else + return -1 +end +`; +var moveToDelayed = { + name: "moveToDelayed", + content: content30, + keys: 12 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveToFinished-14.js +var content31 = `--[[ + Move job from active to a finished status (completed o failed) + A job can only be moved to completed if it was active. + The job must be locked before it can be moved to a finished status, + and the lock must be released in this script. + Input: + KEYS[1] wait key + KEYS[2] active key + KEYS[3] prioritized key + KEYS[4] event stream key + KEYS[5] stalled key + -- Rate limiting + KEYS[6] rate limiter key + KEYS[7] delayed key + KEYS[8] paused key + KEYS[9] meta key + KEYS[10] pc priority counter + KEYS[11] completed/failed key + KEYS[12] jobId key + KEYS[13] metrics key + KEYS[14] marker key + ARGV[1] jobId + ARGV[2] timestamp + ARGV[3] msg property returnvalue / failedReason + ARGV[4] return value / failed reason + ARGV[5] target (completed/failed) + ARGV[6] fetch next? + ARGV[7] keys prefix + ARGV[8] opts + ARGV[9] job fields to update + opts - token - lock token + opts - keepJobs + opts - lockDuration - lock duration in milliseconds + opts - attempts max attempts + opts - maxMetricsSize + opts - fpof - fail parent on fail + opts - cpof - continue parent on fail + opts - idof - ignore dependency on fail + opts - rdof - remove dependency on fail + opts - name - worker name + Output: + 0 OK + -1 Missing key. + -2 Missing lock. + -3 Job not in active set + -4 Job has pending children + -6 Lock is not owned by this client + -9 Job has failed children + Events: + 'completed/failed' +]] +local rcall = redis.call +--- Includes +--[[ + Functions to collect metrics based on a current and previous count of jobs. + Granualarity is fixed at 1 minute. +]] +--[[ + Function to loop in batches. + Just a bit of warning, some commands as ZREM + could receive a maximum of 7000 parameters per call. +]] +local function batches(n, batchSize) + local i = 0 + return function() + local from = i * batchSize + 1 + i = i + 1 + if (from <= n) then + local to = math.min(from + batchSize - 1, n) + return from, to + end + end +end +local function collectMetrics(metaKey, dataPointsList, maxDataPoints, + timestamp) + -- Increment current count + local count = rcall("HINCRBY", metaKey, "count", 1) - 1 + -- Compute how many data points we need to add to the list, N. + local prevTS = rcall("HGET", metaKey, "prevTS") + if not prevTS then + -- If prevTS is nil, set it to the current timestamp + rcall("HSET", metaKey, "prevTS", timestamp, "prevCount", 0) + return + end + local N = math.min(math.floor(timestamp / 60000) - math.floor(prevTS / 60000), tonumber(maxDataPoints)) + if N > 0 then + local delta = count - rcall("HGET", metaKey, "prevCount") + -- If N > 1, add N-1 zeros to the list + if N > 1 then + local points = {} + points[1] = delta + for i = 2, N do + points[i] = 0 + end + for from, to in batches(#points, 7000) do + rcall("LPUSH", dataPointsList, unpack(points, from, to)) + end + else + -- LPUSH delta to the list + rcall("LPUSH", dataPointsList, delta) + end + -- LTRIM to keep list to its max size + rcall("LTRIM", dataPointsList, 0, maxDataPoints - 1) + -- update prev count with current count + rcall("HSET", metaKey, "prevCount", count, "prevTS", timestamp) + end +end +--[[ + Function to fetch the next job to process. + Tries to get the next job to avoid an extra roundtrip if the queue is + not closing and not rate limited. + Input: + waitKey - wait list key + activeKey - active list key + prioritizedKey - prioritized sorted set key + eventStreamKey - event stream key + rateLimiterKey - rate limiter key + delayedKey - delayed sorted set key + pausedKey - paused list key + metaKey - meta hash key + pcKey - priority counter key + markerKey - marker key + prefix - keys prefix + timestamp - current timestamp + opts - options table: + token (required) - lock token used when locking jobs + lockDuration (required) - lock duration for acquired jobs + limiter (optional) - rate limiter options table (e.g. { max = number }) +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +--[[ + Function to get current rate limit ttl. +]] +local function getRateLimitTTL(maxJobs, rateLimiterKey) + if maxJobs and maxJobs <= tonumber(rcall("GET", rateLimiterKey) or 0) then + local pttl = rcall("PTTL", rateLimiterKey) + if pttl == 0 then + rcall("DEL", rateLimiterKey) + end + if pttl > 0 then + return pttl + end + end + return 0 +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to move job from prioritized state to active. +]] +local function moveJobFromPrioritizedToActive(priorityKey, activeKey, priorityCounterKey) + local prioritizedJob = rcall("ZPOPMIN", priorityKey) + if #prioritizedJob > 0 then + rcall("LPUSH", activeKey, prioritizedJob[1]) + return prioritizedJob[1] + else + rcall("DEL", priorityCounterKey) + end +end +--[[ + Function to move job from wait state to active. + Input: + opts - token - lock token + opts - lockDuration + opts - limiter +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function prepareJobForProcessing(keyPrefix, rateLimiterKey, eventStreamKey, + jobId, processedOn, maxJobs, limiterDuration, markerKey, opts) + local jobKey = keyPrefix .. jobId + -- Check if we need to perform rate limiting. + if maxJobs then + local jobCounter = tonumber(rcall("INCR", rateLimiterKey)) + if jobCounter == 1 then + local integerDuration = math.floor(math.abs(limiterDuration)) + rcall("PEXPIRE", rateLimiterKey, integerDuration) + end + end + -- get a lock + if opts['token'] ~= "0" then + local lockKey = jobKey .. ':lock' + rcall("SET", lockKey, opts['token'], "PX", opts['lockDuration']) + end + local optionalValues = {} + if opts['name'] then + -- Set "processedBy" field to the worker name + table.insert(optionalValues, "pb") + table.insert(optionalValues, opts['name']) + end + rcall("XADD", eventStreamKey, "*", "event", "active", "jobId", jobId, "prev", "waiting") + rcall("HMSET", jobKey, "processedOn", processedOn, unpack(optionalValues)) + rcall("HINCRBY", jobKey, "ats", 1) + addBaseMarkerIfNeeded(markerKey, false) + -- rate limit delay must be 0 in this case to prevent adding more delay + -- when job that is moved to active needs to be processed + return {rcall("HGETALL", jobKey), jobId, 0, 0} -- get job data +end +--[[ + Updates the delay set, by moving delayed jobs that should + be processed now to "wait". + Events: + 'waiting' +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +-- Try to get as much as 1000 jobs at once +local function promoteDelayedJobs(delayedKey, markerKey, targetKey, prioritizedKey, + eventStreamKey, prefix, timestamp, priorityCounterKey, isPaused) + local jobs = rcall("ZRANGEBYSCORE", delayedKey, 0, (timestamp + 1) * 0x1000 - 1, "LIMIT", 0, 1000) + if (#jobs > 0) then + rcall("ZREM", delayedKey, unpack(jobs)) + for _, jobId in ipairs(jobs) do + local jobKey = prefix .. jobId + local priority = + tonumber(rcall("HGET", jobKey, "priority")) or 0 + if priority == 0 then + -- LIFO or FIFO + rcall("LPUSH", targetKey, jobId) + else + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + end + -- Emit waiting event + rcall("XADD", eventStreamKey, "*", "event", "waiting", "jobId", + jobId, "prev", "delayed") + rcall("HSET", jobKey, "delay", 0) + end + addBaseMarkerIfNeeded(markerKey, isPaused) + end +end +local function fetchNextJob(waitKey, activeKey, prioritizedKey, eventStreamKey, + rateLimiterKey, delayedKey, pausedKey, metaKey, pcKey, markerKey, prefix, + timestamp, opts) + local target, isPausedOrMaxed, rateLimitMax, rateLimitDuration = + getTargetQueueList(metaKey, activeKey, waitKey, pausedKey) + -- Check if there are delayed jobs that can be promoted + promoteDelayedJobs(delayedKey, markerKey, target, prioritizedKey, + eventStreamKey, prefix, timestamp, pcKey, isPausedOrMaxed) + local maxJobs = tonumber(rateLimitMax or (opts['limiter'] and opts['limiter']['max'])) + -- Check if we are rate limited first. + local expireTime = getRateLimitTTL(maxJobs, rateLimiterKey) + if expireTime > 0 then + return {0, 0, expireTime, 0} + end + -- paused or maxed queue + if isPausedOrMaxed then + return {0, 0, 0, 0} + end + local limiterDuration = (opts['limiter'] and opts['limiter']['duration']) or rateLimitDuration + local jobId = rcall("RPOPLPUSH", waitKey, activeKey) + if jobId then + -- Markers in waitlist DEPRECATED in v5: Remove in v6. + if string.sub(jobId, 1, 2) == "0:" then + rcall("LREM", activeKey, 1, jobId) + -- If jobId is special ID 0:delay (delay greater than 0), then there is no job to process + -- but if ID is 0:0, then there is at least 1 prioritized job to process + if jobId == "0:0" then + jobId = moveJobFromPrioritizedToActive(prioritizedKey, activeKey, pcKey) + return prepareJobForProcessing(prefix, rateLimiterKey, + eventStreamKey, jobId, timestamp, maxJobs, + limiterDuration, markerKey, opts) + end + else + return prepareJobForProcessing(prefix, rateLimiterKey, + eventStreamKey, jobId, timestamp, maxJobs, + limiterDuration, markerKey, opts) + end + else + jobId = moveJobFromPrioritizedToActive(prioritizedKey, activeKey, pcKey) + if jobId then + return prepareJobForProcessing(prefix, rateLimiterKey, + eventStreamKey, jobId, timestamp, maxJobs, + limiterDuration, markerKey, opts) + end + end + -- Return the timestamp for the next delayed job if any. + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- The result is guaranteed to be positive, since the + -- ZRANGEBYSCORE command would have return a job otherwise. + return {0, 0, 0, nextTimestamp} + end +end +--[[ + Function to recursively move from waitingChildren to failed. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) + if no pending dependencies. +]] +-- Includes +--[[ + Validate and move parent to a wait status (waiting, delayed or prioritized) if needed. +]] +-- Includes +--[[ + Move parent to a wait status (wait, prioritized or delayed) +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Function to check if queue is paused or maxed + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePausedOrMaxed(queueMetaKey, activeKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency") + if queueAttributes[1] then + return true + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + return activeCount >= tonumber(queueAttributes[2]) + end + end + return false +end +local function moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + local parentWaitKey = parentQueueKey .. ":wait" + local parentPausedKey = parentQueueKey .. ":paused" + local parentActiveKey = parentQueueKey .. ":active" + local parentMetaKey = parentQueueKey .. ":meta" + local parentMarkerKey = parentQueueKey .. ":marker" + local jobAttributes = rcall("HMGET", parentKey, "priority", "delay") + local priority = tonumber(jobAttributes[1]) or 0 + local delay = tonumber(jobAttributes[2]) or 0 + if delay > 0 then + local delayedTimestamp = tonumber(timestamp) + delay + local score = delayedTimestamp * 0x1000 + local parentDelayedKey = parentQueueKey .. ":delayed" + rcall("ZADD", parentDelayedKey, score, parentId) + rcall("XADD", parentQueueKey .. ":events", "*", "event", "delayed", "jobId", parentId, "delay", + delayedTimestamp) + addDelayMarkerIfNeeded(parentMarkerKey, parentDelayedKey) + else + if priority == 0 then + local parentTarget, isParentPausedOrMaxed = getTargetQueueList(parentMetaKey, parentActiveKey, + parentWaitKey, parentPausedKey) + addJobInTargetList(parentTarget, parentMarkerKey, "RPUSH", isParentPausedOrMaxed, parentId) + else + local isPausedOrMaxed = isQueuePausedOrMaxed(parentMetaKey, parentActiveKey) + addJobWithPriority(parentMarkerKey, parentQueueKey .. ":prioritized", priority, parentId, + parentQueueKey .. ":pc", isPausedOrMaxed) + end + rcall("XADD", parentQueueKey .. ":events", "*", "event", "waiting", "jobId", parentId, "prev", + "waiting-children") + end +end +local function moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + if rcall("EXISTS", parentKey) == 1 then + local parentWaitingChildrenKey = parentQueueKey .. ":waiting-children" + if rcall("ZSCORE", parentWaitingChildrenKey, parentId) then + rcall("ZREM", parentWaitingChildrenKey, parentId) + moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + end + end +end +local function moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, + parentId, timestamp) + local doNotHavePendingDependencies = rcall("SCARD", parentDependenciesKey) == 0 + if doNotHavePendingDependencies then + moveParentToWaitIfNeeded(parentQueueKey, parentKey, parentId, timestamp) + end +end +local handleChildFailureAndMoveParentToWait = function (parentQueueKey, parentKey, parentId, jobIdKey, timestamp) + if rcall("EXISTS", parentKey) == 1 then + local parentWaitingChildrenKey = parentQueueKey .. ":waiting-children" + local parentDelayedKey = parentQueueKey .. ":delayed" + local parentWaitingChildrenOrDelayedKey + if rcall("ZSCORE", parentWaitingChildrenKey, parentId) then + parentWaitingChildrenOrDelayedKey = parentWaitingChildrenKey + elseif rcall("ZSCORE", parentDelayedKey, parentId) then + parentWaitingChildrenOrDelayedKey = parentDelayedKey + rcall("HSET", parentKey, "delay", 0) + end + if parentWaitingChildrenOrDelayedKey then + rcall("ZREM", parentWaitingChildrenOrDelayedKey, parentId) + local deferredFailure = "child " .. jobIdKey .. " failed" + rcall("HSET", parentKey, "defa", deferredFailure) + moveParentToWait(parentQueueKey, parentKey, parentId, timestamp) + else + if not rcall("ZSCORE", parentQueueKey .. ":failed", parentId) then + local deferredFailure = "child " .. jobIdKey .. " failed" + rcall("HSET", parentKey, "defa", deferredFailure) + end + end + end +end +local moveChildFromDependenciesIfNeeded = function (rawParentData, childKey, failedReason, timestamp) + if rawParentData then + local parentData = cjson.decode(rawParentData) + local parentKey = parentData['queueKey'] .. ':' .. parentData['id'] + local parentDependenciesChildrenKey = parentKey .. ":dependencies" + if parentData['fpof'] then + if rcall("SREM", parentDependenciesChildrenKey, childKey) == 1 then + local parentUnsuccessfulChildrenKey = parentKey .. ":unsuccessful" + rcall("ZADD", parentUnsuccessfulChildrenKey, timestamp, childKey) + handleChildFailureAndMoveParentToWait( + parentData['queueKey'], + parentKey, + parentData['id'], + childKey, + timestamp + ) + end + elseif parentData['cpof'] then + if rcall("SREM", parentDependenciesChildrenKey, childKey) == 1 then + local parentFailedChildrenKey = parentKey .. ":failed" + rcall("HSET", parentFailedChildrenKey, childKey, failedReason) + moveParentToWaitIfNeeded(parentData['queueKey'], parentKey, parentData['id'], timestamp) + end + elseif parentData['idof'] or parentData['rdof'] then + if rcall("SREM", parentDependenciesChildrenKey, childKey) == 1 then + moveParentToWaitIfNoPendingDependencies(parentData['queueKey'], parentDependenciesChildrenKey, + parentKey, parentData['id'], timestamp) + if parentData['idof'] then + local parentFailedChildrenKey = parentKey .. ":failed" + rcall("HSET", parentFailedChildrenKey, childKey, failedReason) + end + end + end + end +end +--[[ + Function to remove deduplication key if needed + when a job is moved to completed or failed states. +]] +local function removeDeduplicationKeyIfNeededOnFinalization(prefixKey, + deduplicationId, jobId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local pttl = rcall("PTTL", deduplicationKey) + if pttl == 0 then + return rcall("DEL", deduplicationKey) + end + if pttl == -1 then + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + return rcall("DEL", deduplicationKey) + end + end + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Functions to remove jobs by max age. +]] +-- Includes +--[[ + Function to remove job. +]] +-- Includes +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local function removeJob(jobId, hard, baseKey, shouldRemoveDeduplicationKey) + local jobKey = baseKey .. jobId + removeParentDependencyKey(jobKey, hard, nil, baseKey) + if shouldRemoveDeduplicationKey then + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(baseKey, jobId, deduplicationId) + end + removeJobKeys(jobKey) +end +local function removeJobsByMaxAge(timestamp, maxAge, targetSet, prefix, maxLimit) + local start = timestamp - maxAge * 1000 + local jobIds = rcall("ZREVRANGEBYSCORE", targetSet, start, "-inf", "LIMIT", 0, maxLimit) + for i, jobId in ipairs(jobIds) do + removeJob(jobId, false, prefix, false --[[remove debounce key]]) + end + if #jobIds > 0 then + if #jobIds < maxLimit then + rcall("ZREMRANGEBYSCORE", targetSet, "-inf", start) + else + for from, to in batches(#jobIds, 7000) do + rcall("ZREM", targetSet, unpack(jobIds, from, to)) + end + end + end +end +--[[ + Functions to remove jobs by max count. +]] +-- Includes +local function removeJobsByMaxCount(maxCount, targetSet, prefix) + local start = maxCount + local jobIds = rcall("ZREVRANGE", targetSet, start, -1) + for i, jobId in ipairs(jobIds) do + removeJob(jobId, false, prefix, false --[[remove debounce key]]) + end + rcall("ZREMRANGEBYRANK", targetSet, 0, -(maxCount + 1)) +end +local function removeLock(jobKey, stalledKey, token, jobId) + if token ~= "0" then + local lockKey = jobKey .. ':lock' + local lockToken = rcall("GET", lockKey) + if lockToken == token then + rcall("DEL", lockKey) + rcall("SREM", stalledKey, jobId) + else + if lockToken then + -- Lock exists but token does not match + return -6 + else + -- Lock is missing completely + return -2 + end + end + end + return 0 +end +--[[ + Function to create a new job from stored dedup-next data + when a deduplicated job with keepLastIfActive finishes. + At most one next job is created per deduplication ID. + Multiple triggers while active overwrite the dedup-next data, + so only the latest data is used. +]] +-- Includes +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to set the deduplication key for a job. + Uses TTL from deduplication opts if provided. +]] +local function setDeduplicationKey(deduplicationKey, jobId, deduplicationOpts) + local ttl = deduplicationOpts and deduplicationOpts['ttl'] + if ttl and ttl > 0 then + rcall('SET', deduplicationKey, jobId, 'PX', ttl) + else + rcall('SET', deduplicationKey, jobId) + end +end +--[[ + Shared helper to store a job and enqueue it into the appropriate list/set. + Handles delayed, prioritized, and standard (LIFO/FIFO) jobs. + Emits the appropriate event after enqueuing ("delayed" or "waiting"). + Returns delay, priority from storeJob. +]] +-- Includes +--[[ + Adds a delayed job to the queue by doing the following: + - Creates a new job key with the job data. + - adds to delayed zset. + - Emits a global event 'delayed' if the job is delayed. +]] +-- Includes +--[[ + Bake in the job id first 12 bits into the timestamp + to guarantee correct execution order of delayed jobs + (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp) + WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail +]] +local function getDelayedScore(delayedKey, timestamp, delay) + local delayedTimestamp = (delay > 0 and (tonumber(timestamp) + delay)) or tonumber(timestamp) + local minScore = delayedTimestamp * 0x1000 + local maxScore = (delayedTimestamp + 1 ) * 0x1000 - 1 + local result = rcall("ZREVRANGEBYSCORE", delayedKey, maxScore, + minScore, "WITHSCORES","LIMIT", 0, 1) + if #result then + local currentMaxScore = tonumber(result[2]) + if currentMaxScore ~= nil then + if currentMaxScore >= maxScore then + return maxScore, delayedTimestamp + else + return currentMaxScore + 1, delayedTimestamp + end + end + end + return minScore, delayedTimestamp +end +local function addDelayedJob(jobId, delayedKey, eventsKey, timestamp, + maxEvents, markerKey, delay) + local score, delayedTimestamp = getDelayedScore(delayedKey, timestamp, tonumber(delay)) + rcall("ZADD", delayedKey, score, jobId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "delayed", + "jobId", jobId, "delay", delayedTimestamp) + -- mark that a delayed job is available + addDelayMarkerIfNeeded(markerKey, delayedKey) +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +local function storeAndEnqueueJob(eventsKey, jobIdKey, jobId, name, data, opts, + timestamp, parentKey, parentData, repeatJobKey, maxEvents, + waitKey, pausedKey, activeKey, metaKey, prioritizedKey, + priorityCounterKey, delayedKey, markerKey) + local delay, priority = storeJob(eventsKey, jobIdKey, jobId, name, data, + opts, timestamp, parentKey, parentData, repeatJobKey) + if delay ~= 0 and delayedKey then + addDelayedJob(jobId, delayedKey, eventsKey, timestamp, maxEvents, markerKey, delay) + else + local target, isPausedOrMaxed = getTargetQueueList(metaKey, activeKey, waitKey, pausedKey) + if priority > 0 then + addJobWithPriority(markerKey, prioritizedKey, priority, jobId, + priorityCounterKey, isPausedOrMaxed) + else + local pushCmd = opts['lifo'] and 'RPUSH' or 'LPUSH' + addJobInTargetList(target, markerKey, pushCmd, isPausedOrMaxed, jobId) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId) + end + return delay, priority +end +local function requeueDeduplicatedJob(prefix, deduplicationId, eventStreamKey, + metaKey, activeKey, waitKey, pausedKey, markerKey, prioritizedKey, + priorityCounterKey, delayedKey, timestamp) + local deduplicationNextKey = prefix .. "dn:" .. deduplicationId + if rcall("EXISTS", deduplicationNextKey) == 1 then + local nextData = rcall("HMGET", deduplicationNextKey, + "name", "data", "opts", "pk", "pd", "pdk", "rjk") + local newJobId = rcall("INCR", prefix .. "id") .. "" + local newJobIdKey = prefix .. newJobId + local newOpts = cjson.decode(nextData[3]) + local deduplicationKey = prefix .. "de:" .. deduplicationId + local parentKey = nextData[4] or nil + local parentData = nextData[5] or nil + local parentDependenciesKey = nextData[6] or nil + local repeatJobKey = nextData[7] or nil + -- Set dedup key for the new job (without TTL when keepLastIfActive, + -- so the key outlives the job's active duration) + local deOpts = newOpts['de'] + if deOpts and deOpts['keepLastIfActive'] then + rcall('SET', deduplicationKey, newJobId) + else + setDeduplicationKey(deduplicationKey, newJobId, deOpts) + end + -- Store and enqueue using the shared helper (handles priority/lifo/delayed) + local maxEvents = getOrSetMaxEvents(metaKey) + storeAndEnqueueJob(eventStreamKey, newJobIdKey, newJobId, nextData[1], nextData[2], + newOpts, timestamp, parentKey, parentData, repeatJobKey, maxEvents, + waitKey, pausedKey, activeKey, metaKey, prioritizedKey, + priorityCounterKey, delayedKey, markerKey) + -- Register as child dependency if the job has a parent + if parentDependenciesKey then + rcall("SADD", parentDependenciesKey, newJobIdKey) + end + -- Only delete the dedup-next hash after the job is fully created, + -- so that if any step above errors, the data is not permanently lost. + rcall("DEL", deduplicationNextKey) + end +end +--[[ + Function to trim events, default 10000. +]] +-- Includes +local function trimEvents(metaKey, eventStreamKey) + local maxEvents = getOrSetMaxEvents(metaKey) + if maxEvents then + rcall("XTRIM", eventStreamKey, "MAXLEN", "~", maxEvents) + else + rcall("XTRIM", eventStreamKey, "MAXLEN", "~", 10000) + end +end +--[[ + Validate and move or add dependencies to parent. +]] +-- Includes +local function updateParentDepsIfNeeded(parentKey, parentQueueKey, parentDependenciesKey, + parentId, jobIdKey, returnvalue, timestamp ) + local processedSet = parentKey .. ":processed" + rcall("HSET", processedSet, jobIdKey, returnvalue) + moveParentToWaitIfNoPendingDependencies(parentQueueKey, parentDependenciesKey, parentKey, parentId, timestamp) +end +--[[ + Function to update a bunch of fields in a job. +]] +local function updateJobFields(jobKey, msgpackedFields) + if msgpackedFields and #msgpackedFields > 0 then + local fieldsToUpdate = cmsgpack.unpack(msgpackedFields) + if fieldsToUpdate then + rcall("HMSET", jobKey, unpack(fieldsToUpdate)) + end + end +end +local jobIdKey = KEYS[12] +if rcall("EXISTS", jobIdKey) == 1 then -- Make sure job exists + -- Make sure it does not have pending dependencies + -- It must happen before removing lock + if ARGV[5] == "completed" then + if rcall("SCARD", jobIdKey .. ":dependencies") ~= 0 then + return -4 + end + if rcall("ZCARD", jobIdKey .. ":unsuccessful") ~= 0 then + return -9 + end + end + local opts = cmsgpack.unpack(ARGV[8]) + local token = opts['token'] + local errorCode = removeLock(jobIdKey, KEYS[5], token, ARGV[1]) + if errorCode < 0 then + return errorCode + end + updateJobFields(jobIdKey, ARGV[9]); + local attempts = opts['attempts'] + local maxMetricsSize = opts['maxMetricsSize'] + local maxCount = opts['keepJobs']['count'] + local maxAge = opts['keepJobs']['age'] + local maxLimit = opts['keepJobs']['limit'] or 1000 + local jobAttributes = rcall("HMGET", jobIdKey, "parentKey", "parent", "deid") + local parentKey = jobAttributes[1] or "" + local parentId = "" + local parentQueueKey = "" + if jobAttributes[2] then -- TODO: need to revisit this logic if it's still needed + local jsonDecodedParent = cjson.decode(jobAttributes[2]) + parentId = jsonDecodedParent['id'] + parentQueueKey = jsonDecodedParent['queueKey'] + end + local jobId = ARGV[1] + local timestamp = ARGV[2] + -- Remove from active list (if not active we shall return error) + local numRemovedElements = rcall("LREM", KEYS[2], -1, jobId) + if (numRemovedElements < 1) then + return -3 + end + local eventStreamKey = KEYS[4] + local metaKey = KEYS[9] + -- Trim events before emiting them to avoid trimming events emitted in this script + trimEvents(metaKey, eventStreamKey) + local prefix = ARGV[7] + removeDeduplicationKeyIfNeededOnFinalization(prefix, jobAttributes[3], jobId) + -- Check if there is requeue data for this dedup ID (keepLastIfActive mode) + if jobAttributes[3] then + requeueDeduplicatedJob(prefix, jobAttributes[3], eventStreamKey, + metaKey, KEYS[2], KEYS[1], KEYS[8], KEYS[14], KEYS[3], KEYS[10], + KEYS[7], timestamp) + end + -- If job has a parent we need to + -- 1) remove this job id from parents dependencies + -- 2) move the job Id to parent "processed" set + -- 3) push the results into parent "results" list + -- 4) if parent's dependencies is empty, then move parent to "wait/paused". Note it may be a different queue!. + if parentId == "" and parentKey ~= "" then + parentId = getJobIdFromKey(parentKey) + parentQueueKey = getJobKeyPrefix(parentKey, ":" .. parentId) + end + if parentId ~= "" then + if ARGV[5] == "completed" then + local dependenciesSet = parentKey .. ":dependencies" + if rcall("SREM", dependenciesSet, jobIdKey) == 1 then + updateParentDepsIfNeeded(parentKey, parentQueueKey, dependenciesSet, parentId, jobIdKey, ARGV[4], + timestamp) + end + else + moveChildFromDependenciesIfNeeded(jobAttributes[2], jobIdKey, ARGV[4], timestamp) + end + end + local attemptsMade = rcall("HINCRBY", jobIdKey, "atm", 1) + -- Remove job? + if maxCount ~= 0 then + local targetSet = KEYS[11] + -- Add to complete/failed set + rcall("ZADD", targetSet, timestamp, jobId) + rcall("HSET", jobIdKey, ARGV[3], ARGV[4], "finishedOn", timestamp) + -- "returnvalue" / "failedReason" and "finishedOn" + if ARGV[5] == "failed" then + rcall("HDEL", jobIdKey, "defa") + end + -- Remove old jobs? + if maxAge ~= nil then + removeJobsByMaxAge(timestamp, maxAge, targetSet, prefix, maxLimit) + end + if maxCount ~= nil and maxCount > 0 then + removeJobsByMaxCount(maxCount, targetSet, prefix) + end + else + removeJobKeys(jobIdKey) + if parentKey ~= "" then + -- TODO: when a child is removed when finished, result or failure in parent + -- must not be deleted, those value references should be deleted when the parent + -- is deleted + removeParentDependencyKey(jobIdKey, false, parentKey, jobAttributes[3]) + end + end + rcall("XADD", eventStreamKey, "*", "event", ARGV[5], "jobId", jobId, ARGV[3], ARGV[4], "prev", "active") + if ARGV[5] == "failed" then + if tonumber(attemptsMade) >= tonumber(attempts) then + rcall("XADD", eventStreamKey, "*", "event", "retries-exhausted", "jobId", jobId, "attemptsMade", + attemptsMade) + end + end + -- Collect metrics + if maxMetricsSize ~= "" then + collectMetrics(KEYS[13], KEYS[13] .. ':data', maxMetricsSize, timestamp) + end + -- Try to get next job to avoid an extra roundtrip if the queue is not closing, + -- and not rate limited. + if (ARGV[6] == "1") then + local result = fetchNextJob(KEYS[1], KEYS[2], KEYS[3], eventStreamKey, + KEYS[6], KEYS[7], KEYS[8], metaKey, KEYS[10], KEYS[14], prefix, + timestamp, opts) + if result then + return result + end + end + local waitLen = rcall("LLEN", KEYS[1]) + if waitLen == 0 then + local activeLen = rcall("LLEN", KEYS[2]) + if activeLen == 0 then + local prioritizedLen = rcall("ZCARD", KEYS[3]) + if prioritizedLen == 0 then + rcall("XADD", eventStreamKey, "*", "event", "drained") + end + end + end + return 0 +else + return -1 +end +`; +var moveToFinished = { + name: "moveToFinished", + content: content31, + keys: 14 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/moveToWaitingChildren-7.js +var content32 = `--[[ + Moves job from active to waiting children set. + Input: + KEYS[1] active key + KEYS[2] wait-children key + KEYS[3] job key + KEYS[4] job dependencies key + KEYS[5] job unsuccessful key + KEYS[6] stalled key + KEYS[7] events key + ARGV[1] token + ARGV[2] child key + ARGV[3] timestamp + ARGV[4] jobId + ARGV[5] prefix + Output: + 0 - OK + 1 - There are not pending dependencies. + -1 - Missing job. + -2 - Missing lock + -3 - Job not in active set + -9 - Job has failed children +]] +local rcall = redis.call +local activeKey = KEYS[1] +local waitingChildrenKey = KEYS[2] +local jobKey = KEYS[3] +local jobDependenciesKey = KEYS[4] +local jobUnsuccessfulKey = KEYS[5] +local stalledKey = KEYS[6] +local eventStreamKey = KEYS[7] +local token = ARGV[1] +local timestamp = ARGV[3] +local jobId = ARGV[4] +--- Includes +local function removeLock(jobKey, stalledKey, token, jobId) + if token ~= "0" then + local lockKey = jobKey .. ':lock' + local lockToken = rcall("GET", lockKey) + if lockToken == token then + rcall("DEL", lockKey) + rcall("SREM", stalledKey, jobId) + else + if lockToken then + -- Lock exists but token does not match + return -6 + else + -- Lock is missing completely + return -2 + end + end + end + return 0 +end +local function removeJobFromActive(activeKey, stalledKey, jobKey, jobId, + token) + local errorCode = removeLock(jobKey, stalledKey, token, jobId) + if errorCode < 0 then + return errorCode + end + local numRemovedElements = rcall("LREM", activeKey, -1, jobId) + if numRemovedElements < 1 then + return -3 + end + return 0 +end +local function moveToWaitingChildren(activeKey, waitingChildrenKey, stalledKey, eventStreamKey, + jobKey, jobId, timestamp, token) + local errorCode = removeJobFromActive(activeKey, stalledKey, jobKey, jobId, token) + if errorCode < 0 then + return errorCode + end + local score = tonumber(timestamp) + rcall("ZADD", waitingChildrenKey, score, jobId) + rcall("XADD", eventStreamKey, "*", "event", "waiting-children", "jobId", jobId, 'prev', 'active') + return 0 +end +if rcall("EXISTS", jobKey) == 1 then + if rcall("ZCARD", jobUnsuccessfulKey) ~= 0 then + return -9 + else + if ARGV[2] ~= "" then + if rcall("SISMEMBER", jobDependenciesKey, ARGV[2]) ~= 0 then + return moveToWaitingChildren(activeKey, waitingChildrenKey, stalledKey, eventStreamKey, + jobKey, jobId, timestamp, token) + end + return 1 + else + if rcall("SCARD", jobDependenciesKey) ~= 0 then + return moveToWaitingChildren(activeKey, waitingChildrenKey, stalledKey, eventStreamKey, + jobKey, jobId, timestamp, token) + end + return 1 + end + end +end +return -1 +`; +var moveToWaitingChildren = { + name: "moveToWaitingChildren", + content: content32, + keys: 7 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/obliterate-2.js +var content33 = `--[[ + Completely obliterates a queue and all of its contents + This command completely destroys a queue including all of its jobs, current or past + leaving no trace of its existence. Since this script needs to iterate to find all the job + keys, consider that this call may be slow for very large queues. + The queue needs to be "paused" or it will return an error + If the queue has currently active jobs then the script by default will return error, + however this behaviour can be overrided using the 'force' option. + Input: + KEYS[1] meta + KEYS[2] base + ARGV[1] count + ARGV[2] force +]] +local maxCount = tonumber(ARGV[1]) +local baseKey = KEYS[2] +local rcall = redis.call +-- Includes +--[[ + Functions to remove jobs. +]] +-- Includes +--[[ + Function to remove job. +]] +-- Includes +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local function removeJob(jobId, hard, baseKey, shouldRemoveDeduplicationKey) + local jobKey = baseKey .. jobId + removeParentDependencyKey(jobKey, hard, nil, baseKey) + if shouldRemoveDeduplicationKey then + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(baseKey, jobId, deduplicationId) + end + removeJobKeys(jobKey) +end +local function removeJobs(keys, hard, baseKey, max) + for i, key in ipairs(keys) do + removeJob(key, hard, baseKey, true --[[remove debounce key]]) + end + return max - #keys +end +--[[ + Functions to remove jobs. +]] +-- Includes +--[[ + Function to filter out jobs to ignore from a table. +]] +local function filterOutJobsToIgnore(jobs, jobsToIgnore) + local filteredJobs = {} + for i = 1, #jobs do + if not jobsToIgnore[jobs[i]] then + table.insert(filteredJobs, jobs[i]) + end + end + return filteredJobs +end +local function getListItems(keyName, max) + return rcall('LRANGE', keyName, 0, max - 1) +end +local function removeListJobs(keyName, hard, baseKey, max, jobsToIgnore) + local jobs = getListItems(keyName, max) + if jobsToIgnore then + jobs = filterOutJobsToIgnore(jobs, jobsToIgnore) + end + local count = removeJobs(jobs, hard, baseKey, max) + rcall("LTRIM", keyName, #jobs, -1) + return count +end +-- Includes +--[[ + Function to loop in batches. + Just a bit of warning, some commands as ZREM + could receive a maximum of 7000 parameters per call. +]] +local function batches(n, batchSize) + local i = 0 + return function() + local from = i * batchSize + 1 + i = i + 1 + if (from <= n) then + local to = math.min(from + batchSize - 1, n) + return from, to + end + end +end +--[[ + Function to get ZSet items. +]] +local function getZSetItems(keyName, max) + return rcall('ZRANGE', keyName, 0, max - 1) +end +local function removeZSetJobs(keyName, hard, baseKey, max, jobsToIgnore) + local jobs = getZSetItems(keyName, max) + if jobsToIgnore then + jobs = filterOutJobsToIgnore(jobs, jobsToIgnore) + end + local count = removeJobs(jobs, hard, baseKey, max) + if(#jobs > 0) then + for from, to in batches(#jobs, 7000) do + rcall("ZREM", keyName, unpack(jobs, from, to)) + end + end + return count +end +local function removeLockKeys(keys) + for i, key in ipairs(keys) do + rcall("DEL", baseKey .. key .. ':lock') + end +end +-- 1) Check if paused, if not return with error. +if rcall("HEXISTS", KEYS[1], "paused") ~= 1 then + return -1 -- Error, NotPaused +end +-- 2) Check if there are active jobs, if there are and not "force" return error. +local activeKey = baseKey .. 'active' +local activeJobs = getListItems(activeKey, maxCount) +if (#activeJobs > 0) then + if(ARGV[2] == "") then + return -2 -- Error, ExistActiveJobs + end +end +removeLockKeys(activeJobs) +maxCount = removeJobs(activeJobs, true, baseKey, maxCount) +rcall("LTRIM", activeKey, #activeJobs, -1) +if(maxCount <= 0) then + return 1 +end +local delayedKey = baseKey .. 'delayed' +maxCount = removeZSetJobs(delayedKey, true, baseKey, maxCount) +if(maxCount <= 0) then + return 1 +end +local repeatKey = baseKey .. 'repeat' +local repeatJobsIds = getZSetItems(repeatKey, maxCount) +for i, key in ipairs(repeatJobsIds) do + local jobKey = repeatKey .. ":" .. key + rcall("DEL", jobKey) +end +if(#repeatJobsIds > 0) then + for from, to in batches(#repeatJobsIds, 7000) do + rcall("ZREM", repeatKey, unpack(repeatJobsIds, from, to)) + end +end +maxCount = maxCount - #repeatJobsIds +if(maxCount <= 0) then + return 1 +end +local completedKey = baseKey .. 'completed' +maxCount = removeZSetJobs(completedKey, true, baseKey, maxCount) +if(maxCount <= 0) then + return 1 +end +local pausedKey = baseKey .. 'paused' +maxCount = removeListJobs(pausedKey, true, baseKey, maxCount) +if(maxCount <= 0) then + return 1 +end +local prioritizedKey = baseKey .. 'prioritized' +maxCount = removeZSetJobs(prioritizedKey, true, baseKey, maxCount) +if(maxCount <= 0) then + return 1 +end +local failedKey = baseKey .. 'failed' +maxCount = removeZSetJobs(failedKey, true, baseKey, maxCount) +if(maxCount <= 0) then + return 1 +end +if(maxCount > 0) then + rcall("DEL", + baseKey .. 'events', + baseKey .. 'delay', + baseKey .. 'stalled-check', + baseKey .. 'stalled', + baseKey .. 'id', + baseKey .. 'pc', + baseKey .. 'marker', + baseKey .. 'meta', + baseKey .. 'metrics:completed', + baseKey .. 'metrics:completed:data', + baseKey .. 'metrics:failed', + baseKey .. 'metrics:failed:data') + return 0 +else + return 1 +end +`; +var obliterate = { + name: "obliterate", + content: content33, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/paginate-1.js +var content34 = `--[[ + Paginate a set or hash + Input: + KEYS[1] key pointing to the set or hash to be paginated. + ARGV[1] page start offset + ARGV[2] page end offset (-1 for all the elements) + ARGV[3] cursor + ARGV[4] offset + ARGV[5] max iterations + ARGV[6] fetch jobs? + Output: + [cursor, offset, items, numItems] +]] +local rcall = redis.call +-- Includes +--[[ + Function to achieve pagination for a set or hash. + This function simulates pagination in the most efficient way possible + for a set using sscan or hscan. + The main limitation is that sets are not order preserving, so the + pagination is not stable. This means that if the set is modified + between pages, the same element may appear in different pages. +]] -- Maximum number of elements to be returned by sscan per iteration. +local maxCount = 100 +-- Finds the cursor, and returns the first elements available for the requested page. +local function findPage(key, command, pageStart, pageSize, cursor, offset, + maxIterations, fetchJobs) + local items = {} + local jobs = {} + local iterations = 0 + repeat + -- Iterate over the set using sscan/hscan. + local result = rcall(command, key, cursor, "COUNT", maxCount) + cursor = result[1] + local members = result[2] + local step = 1 + if command == "HSCAN" then + step = 2 + end + if #members == 0 then + -- If the result is empty, we can return the result. + return cursor, offset, items, jobs + end + local chunkStart = offset + local chunkEnd = offset + #members / step + local pageEnd = pageStart + pageSize + if chunkEnd < pageStart then + -- If the chunk is before the page, we can skip it. + offset = chunkEnd + elseif chunkStart > pageEnd then + -- If the chunk is after the page, we can return the result. + return cursor, offset, items, jobs + else + -- If the chunk is overlapping the page, we need to add the elements to the result. + for i = 1, #members, step do + if offset >= pageEnd then + return cursor, offset, items, jobs + end + if offset >= pageStart then + local index = #items + 1 + if fetchJobs ~= nil then + jobs[#jobs+1] = rcall("HGETALL", members[i]) + end + if step == 2 then + items[index] = {members[i], members[i + 1]} + else + items[index] = members[i] + end + end + offset = offset + 1 + end + end + iterations = iterations + 1 + until cursor == "0" or iterations >= maxIterations + return cursor, offset, items, jobs +end +local key = KEYS[1] +local scanCommand = "SSCAN" +local countCommand = "SCARD" +local type = rcall("TYPE", key)["ok"] +if type == "none" then + return {0, 0, {}, 0} +elseif type == "hash" then + scanCommand = "HSCAN" + countCommand = "HLEN" +elseif type ~= "set" then + return + redis.error_reply("Pagination is only supported for sets and hashes.") +end +local numItems = rcall(countCommand, key) +local startOffset = tonumber(ARGV[1]) +local endOffset = tonumber(ARGV[2]) +if endOffset == -1 then + endOffset = numItems +end +local pageSize = (endOffset - startOffset) + 1 +local cursor, offset, items, jobs = findPage(key, scanCommand, startOffset, + pageSize, ARGV[3], tonumber(ARGV[4]), + tonumber(ARGV[5]), ARGV[6]) +return {cursor, offset, items, numItems, jobs} +`; +var paginate = { + name: "paginate", + content: content34, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/pause-7.js +var content35 = `--[[ + Pauses or resumes a queue globably. + Input: + KEYS[1] 'wait' or 'paused'' + KEYS[2] 'paused' or 'wait' + KEYS[3] 'meta' + KEYS[4] 'prioritized' + KEYS[5] events stream key + KEYS[6] 'delayed' + KEYS|7] 'marker' + ARGV[1] 'paused' or 'resumed' + Event: + publish paused or resumed event. +]] +local rcall = redis.call +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +local markerKey = KEYS[7] +local hasJobs = rcall("EXISTS", KEYS[1]) == 1 +--TODO: check this logic to be reused when changing a delay +if hasJobs then rcall("RENAME", KEYS[1], KEYS[2]) end +if ARGV[1] == "paused" then + rcall("HSET", KEYS[3], "paused", 1) + rcall("DEL", markerKey) +else + rcall("HDEL", KEYS[3], "paused") + if hasJobs or rcall("ZCARD", KEYS[4]) > 0 then + -- Add marker if there are waiting or priority jobs + rcall("ZADD", markerKey, 0, "0") + else + addDelayMarkerIfNeeded(markerKey, KEYS[6]) + end +end +rcall("XADD", KEYS[5], "*", "event", ARGV[1]); +`; +var pause = { + name: "pause", + content: content35, + keys: 7 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/promote-9.js +var content36 = `--[[ + Promotes a job that is currently "delayed" to the "waiting" state + Input: + KEYS[1] 'delayed' + KEYS[2] 'wait' + KEYS[3] 'paused' + KEYS[4] 'meta' + KEYS[5] 'prioritized' + KEYS[6] 'active' + KEYS[7] 'pc' priority counter + KEYS[8] 'event stream' + KEYS[9] 'marker' + ARGV[1] queue.toKey('') + ARGV[2] jobId + Output: + 0 - OK + -3 - Job not in delayed zset. + Events: + 'waiting' +]] +local rcall = redis.call +local jobId = ARGV[2] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +if rcall("ZREM", KEYS[1], jobId) == 1 then + local jobKey = ARGV[1] .. jobId + local priority = tonumber(rcall("HGET", jobKey, "priority")) or 0 + local metaKey = KEYS[4] + local markerKey = KEYS[9] + -- Remove delayed "marker" from the wait list if there is any. + -- Since we are adding a job we do not need the marker anymore. + -- Markers in waitlist DEPRECATED in v5: Remove in v6. + local target, isPausedOrMaxed = getTargetQueueList(metaKey, KEYS[6], KEYS[2], KEYS[3]) + local marker = rcall("LINDEX", target, 0) + if marker and string.sub(marker, 1, 2) == "0:" then rcall("LPOP", target) end + if priority == 0 then + -- LIFO or FIFO + addJobInTargetList(target, markerKey, "LPUSH", isPausedOrMaxed, jobId) + else + addJobWithPriority(markerKey, KEYS[5], priority, jobId, KEYS[7], isPausedOrMaxed) + end + rcall("XADD", KEYS[8], "*", "event", "waiting", "jobId", jobId, "prev", + "delayed"); + rcall("HSET", jobKey, "delay", 0) + return 0 +else + return -3 +end +`; +var promote = { + name: "promote", + content: content36, + keys: 9 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/releaseLock-1.js +var content37 = `--[[ + Release lock + Input: + KEYS[1] 'lock', + ARGV[1] token + ARGV[2] lock duration in milliseconds + Output: + "OK" if lock extented succesfully. +]] +local rcall = redis.call +if rcall("GET", KEYS[1]) == ARGV[1] then + return rcall("DEL", KEYS[1]) +else + return 0 +end +`; +var releaseLock = { + name: "releaseLock", + content: content37, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeChildDependency-1.js +var content38 = `--[[ + Break parent-child dependency by removing + child reference from parent + Input: + KEYS[1] 'key' prefix, + ARGV[1] job key + ARGV[2] parent key + Output: + 0 - OK + 1 - There is not relationship. + -1 - Missing job key + -5 - Missing parent key +]] +local rcall = redis.call +local jobKey = ARGV[1] +local parentKey = ARGV[2] +-- Includes +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +if rcall("EXISTS", jobKey) ~= 1 then return -1 end +if rcall("EXISTS", parentKey) ~= 1 then return -5 end +if removeParentDependencyKey(jobKey, false, parentKey, KEYS[1], nil) then + rcall("HDEL", jobKey, "parentKey", "parent") + return 0 +else + return 1 +end`; +var removeChildDependency = { + name: "removeChildDependency", + content: content38, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeDeduplicationKey-1.js +var content39 = `--[[ + Remove deduplication key if it matches the job id. + Input: + KEYS[1] deduplication key + ARGV[1] job id + Output: + 0 - false + 1 - true +]] +local rcall = redis.call +local deduplicationKey = KEYS[1] +local jobId = ARGV[1] +local currentJobId = rcall('GET', deduplicationKey) +if currentJobId and currentJobId == jobId then + return rcall("DEL", deduplicationKey) +end +return 0 +`; +var removeDeduplicationKey = { + name: "removeDeduplicationKey", + content: content39, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeJob-2.js +var content40 = `--[[ + Remove a job from all the statuses it may be in as well as all its data. + In order to be able to remove a job, it cannot be active. + Input: + KEYS[1] jobKey + KEYS[2] repeat key + ARGV[1] jobId + ARGV[2] remove children + ARGV[3] queue prefix + Events: + 'removed' +]] +local rcall = redis.call +-- Includes +--[[ + Function to check if the job belongs to a job scheduler and + current delayed job matches with jobId +]] +local function isJobSchedulerJob(jobId, jobKey, jobSchedulersKey) + local repeatJobKey = rcall("HGET", jobKey, "rjk") + if repeatJobKey then + local prevMillis = rcall("ZSCORE", jobSchedulersKey, repeatJobKey) + if prevMillis then + local currentDelayedJobId = "repeat:" .. repeatJobKey .. ":" .. prevMillis + return jobId == currentDelayedJobId + end + end + return false +end +--[[ + Function to recursively check if there are no locks + on the jobs to be removed. + returns: + boolean +]] +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +local function isLocked( prefix, jobId, removeChildren) + local jobKey = prefix .. jobId; + -- Check if this job is locked + local lockKey = jobKey .. ':lock' + local lock = rcall("GET", lockKey) + if not lock then + if removeChildren == "1" then + local dependencies = rcall("SMEMBERS", jobKey .. ":dependencies") + if (#dependencies > 0) then + for i, childJobKey in ipairs(dependencies) do + -- We need to get the jobId for this job. + local childJobId = getJobIdFromKey(childJobKey) + local childJobPrefix = getJobKeyPrefix(childJobKey, childJobId) + local result = isLocked( childJobPrefix, childJobId, removeChildren ) + if result then + return true + end + end + end + end + return false + end + return true +end +--[[ + Remove a job from all the statuses it may be in as well as all its data, + including its children. Active children can be ignored. + Events: + 'removed' +]] +local rcall = redis.call +-- Includes +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove from any state. + returns: + prev state +]] +local function removeJobFromAnyState( prefix, jobId) + -- We start with the ZSCORE checks, since they have O(1) complexity + if rcall("ZSCORE", prefix .. "completed", jobId) then + rcall("ZREM", prefix .. "completed", jobId) + return "completed" + elseif rcall("ZSCORE", prefix .. "waiting-children", jobId) then + rcall("ZREM", prefix .. "waiting-children", jobId) + return "waiting-children" + elseif rcall("ZSCORE", prefix .. "delayed", jobId) then + rcall("ZREM", prefix .. "delayed", jobId) + return "delayed" + elseif rcall("ZSCORE", prefix .. "failed", jobId) then + rcall("ZREM", prefix .. "failed", jobId) + return "failed" + elseif rcall("ZSCORE", prefix .. "prioritized", jobId) then + rcall("ZREM", prefix .. "prioritized", jobId) + return "prioritized" + -- We remove only 1 element from the list, since we assume they are not added multiple times + elseif rcall("LREM", prefix .. "wait", 1, jobId) == 1 then + return "wait" + elseif rcall("LREM", prefix .. "paused", 1, jobId) == 1 then + return "paused" + elseif rcall("LREM", prefix .. "active", 1, jobId) == 1 then + return "active" + end + return "unknown" +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +local removeJobChildren +local removeJobWithChildren +removeJobChildren = function(prefix, jobKey, options) + -- Check if this job has children + -- If so, we are going to try to remove the children recursively in a depth-first way + -- because if some job is locked, we must exit with an error. + if not options.ignoreProcessed then + local processed = rcall("HGETALL", jobKey .. ":processed") + if #processed > 0 then + for i = 1, #processed, 2 do + local childJobId = getJobIdFromKey(processed[i]) + local childJobPrefix = getJobKeyPrefix(processed[i], childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end + local failed = rcall("HGETALL", jobKey .. ":failed") + if #failed > 0 then + for i = 1, #failed, 2 do + local childJobId = getJobIdFromKey(failed[i]) + local childJobPrefix = getJobKeyPrefix(failed[i], childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end + local unsuccessful = rcall("ZRANGE", jobKey .. ":unsuccessful", 0, -1) + if #unsuccessful > 0 then + for i = 1, #unsuccessful, 1 do + local childJobId = getJobIdFromKey(unsuccessful[i]) + local childJobPrefix = getJobKeyPrefix(unsuccessful[i], childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end + end + local dependencies = rcall("SMEMBERS", jobKey .. ":dependencies") + if #dependencies > 0 then + for i, childJobKey in ipairs(dependencies) do + local childJobId = getJobIdFromKey(childJobKey) + local childJobPrefix = getJobKeyPrefix(childJobKey, childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end +end +removeJobWithChildren = function(prefix, jobId, parentKey, options) + local jobKey = prefix .. jobId + if options.ignoreLocked then + if isLocked(prefix, jobId) then + return + end + end + -- Check if job is in the failed zset + local failedSet = prefix .. "failed" + if not (options.ignoreProcessed and rcall("ZSCORE", failedSet, jobId)) then + removeParentDependencyKey(jobKey, false, parentKey, nil) + if options.removeChildren then + removeJobChildren(prefix, jobKey, options) + end + local prev = removeJobFromAnyState(prefix, jobId) + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(prefix, jobId, deduplicationId) + if removeJobKeys(jobKey) > 0 then + local metaKey = prefix .. "meta" + local maxEvents = getOrSetMaxEvents(metaKey) + rcall("XADD", prefix .. "events", "MAXLEN", "~", maxEvents, "*", "event", "removed", + "jobId", jobId, "prev", prev) + end + end +end +local jobId = ARGV[1] +local shouldRemoveChildren = ARGV[2] +local prefix = ARGV[3] +local jobKey = KEYS[1] +local repeatKey = KEYS[2] +if isJobSchedulerJob(jobId, jobKey, repeatKey) then + return -8 +end +if not isLocked(prefix, jobId, shouldRemoveChildren) then + local options = { + removeChildren = shouldRemoveChildren == "1", + ignoreProcessed = false, + ignoreLocked = false } - }, - files: [ - "dist-*/**" - ], - author: { - name: "AWS SDK for JavaScript Team", - url: "https://aws.amazon.com/javascript/" - }, - license: "Apache-2.0", - browser: { - "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.browser" - }, - "react-native": { - "./dist-es/runtimeConfig": "./dist-es/runtimeConfig.native" - }, - homepage: "https://github.com/aws/aws-sdk-js-v3/tree/main/clients/client-s3", - repository: { - type: "git", - url: "https://github.com/aws/aws-sdk-js-v3.git", - directory: "clients/client-s3" - } + removeJobWithChildren(prefix, jobId, nil, options) + return 1 +end +return 0 +`; +var removeJob = { + name: "removeJob", + content: content40, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeJobScheduler-3.js +var content41 = `--[[ + Removes a job scheduler and its next scheduled job. + Input: + KEYS[1] job schedulers key + KEYS[2] delayed jobs key + KEYS[3] events key + ARGV[1] job scheduler id + ARGV[2] prefix key + Output: + 0 - OK + 1 - Missing repeat job + Events: + 'removed' +]] +local rcall = redis.call +-- Includes +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +local jobSchedulerId = ARGV[1] +local prefix = ARGV[2] +local millis = rcall("ZSCORE", KEYS[1], jobSchedulerId) +if millis then + -- Delete next programmed job. + local delayedJobId = "repeat:" .. jobSchedulerId .. ":" .. millis + if(rcall("ZREM", KEYS[2], delayedJobId) == 1) then + removeJobKeys(prefix .. delayedJobId) + rcall("XADD", KEYS[3], "*", "event", "removed", "jobId", delayedJobId, "prev", "delayed") + end +end +if(rcall("ZREM", KEYS[1], jobSchedulerId) == 1) then + rcall("DEL", KEYS[1] .. ":" .. jobSchedulerId) + return 0 +end +return 1 +`; +var removeJobScheduler = { + name: "removeJobScheduler", + content: content41, + keys: 3 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeOrphanedJobs-1.js +var content42 = `--[[ + Removes orphaned job keys that exist in Redis but are not referenced + in any queue state set. Checks each candidate atomically. + Input: + KEYS[1] base prefix key including trailing colon (e.g. bull:queueName:) + ARGV[1] number of state key suffixes + ARGV[2 .. 1+N] state key suffixes (e.g. active, wait, completed, ...) + ARGV[2+N] number of job sub-key suffixes + ARGV[3+N .. 2+N+M] job sub-key suffixes (e.g. logs, dependencies, ...) + ARGV[3+N+M .. end] candidate job IDs to check + Output: + number of removed jobs +]] +local rcall = redis.call +local basePrefix = KEYS[1] +-- Parse state key suffixes and cache their full key names + types. +local stateKeyCount = tonumber(ARGV[1]) +local stateKeys = {} +local stateKeyTypes = {} +for i = 1, stateKeyCount do + local fullKey = basePrefix .. ARGV[1 + i] + stateKeys[i] = fullKey + stateKeyTypes[i] = rcall('TYPE', fullKey)['ok'] +end +-- Parse job sub-key suffixes. +local subKeyCountIdx = 2 + stateKeyCount +local subKeyCount = tonumber(ARGV[subKeyCountIdx]) +local subKeySuffixes = {} +for i = 1, subKeyCount do + subKeySuffixes[i] = ARGV[subKeyCountIdx + i] +end +-- Process candidate job IDs. +local candidateStart = subKeyCountIdx + subKeyCount + 1 +local removedCount = 0 +for c = candidateStart, #ARGV do + local jobId = ARGV[c] + local found = false + for i = 1, stateKeyCount do + local kt = stateKeyTypes[i] + if kt == 'list' then + if rcall('LPOS', stateKeys[i], jobId) then + found = true + break + end + elseif kt == 'zset' then + if rcall('ZSCORE', stateKeys[i], jobId) then + found = true + break + end + elseif kt == 'set' then + if rcall('SISMEMBER', stateKeys[i], jobId) == 1 then + found = true + break + end + end + end + if not found then + local jobKey = basePrefix .. jobId + local keysToDelete = { jobKey } + for _, suffix in ipairs(subKeySuffixes) do + keysToDelete[#keysToDelete + 1] = jobKey .. ':' .. suffix + end + rcall('DEL', unpack(keysToDelete)) + removedCount = removedCount + 1 + end +end +return removedCount +`; +var removeOrphanedJobs = { + name: "removeOrphanedJobs", + content: content42, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeRepeatable-3.js +var content43 = `--[[ + Removes a repeatable job + Input: + KEYS[1] repeat jobs key + KEYS[2] delayed jobs key + KEYS[3] events key + ARGV[1] old repeat job id + ARGV[2] options concat + ARGV[3] repeat job key + ARGV[4] prefix key + Output: + 0 - OK + 1 - Missing repeat job + Events: + 'removed' +]] +local rcall = redis.call +local millis = rcall("ZSCORE", KEYS[1], ARGV[2]) +-- Includes +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +-- legacy removal TODO: remove in next breaking change +if millis then + -- Delete next programmed job. + local repeatJobId = ARGV[1] .. millis + if(rcall("ZREM", KEYS[2], repeatJobId) == 1) then + removeJobKeys(ARGV[4] .. repeatJobId) + rcall("XADD", KEYS[3], "*", "event", "removed", "jobId", repeatJobId, "prev", "delayed"); + end +end +if(rcall("ZREM", KEYS[1], ARGV[2]) == 1) then + return 0 +end +-- new removal +millis = rcall("ZSCORE", KEYS[1], ARGV[3]) +if millis then + -- Delete next programmed job. + local repeatJobId = "repeat:" .. ARGV[3] .. ":" .. millis + if(rcall("ZREM", KEYS[2], repeatJobId) == 1) then + removeJobKeys(ARGV[4] .. repeatJobId) + rcall("XADD", KEYS[3], "*", "event", "removed", "jobId", repeatJobId, "prev", "delayed") + end +end +if(rcall("ZREM", KEYS[1], ARGV[3]) == 1) then + rcall("DEL", KEYS[1] .. ":" .. ARGV[3]) + return 0 +end +return 1 +`; +var removeRepeatable = { + name: "removeRepeatable", + content: content43, + keys: 3 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/removeUnprocessedChildren-2.js +var content44 = `--[[ + Remove a job from all the statuses it may be in as well as all its data. + In order to be able to remove a job, it cannot be active. + Input: + KEYS[1] jobKey + KEYS[2] meta key + ARGV[1] prefix + ARGV[2] jobId + Events: + 'removed' for every children removed +]] +-- Includes +--[[ + Remove a job from all the statuses it may be in as well as all its data, + including its children. Active children can be ignored. + Events: + 'removed' +]] +local rcall = redis.call +-- Includes +--[[ + Functions to destructure job key. + Just a bit of warning, these functions may be a bit slow and affect performance significantly. +]] +local getJobIdFromKey = function (jobKey) + return string.match(jobKey, ".*:(.*)") +end +local getJobKeyPrefix = function (jobKey, jobId) + return string.sub(jobKey, 0, #jobKey - #jobId) +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check if the job belongs to a job scheduler and + current delayed job matches with jobId +]] +local function isJobSchedulerJob(jobId, jobKey, jobSchedulersKey) + local repeatJobKey = rcall("HGET", jobKey, "rjk") + if repeatJobKey then + local prevMillis = rcall("ZSCORE", jobSchedulersKey, repeatJobKey) + if prevMillis then + local currentDelayedJobId = "repeat:" .. repeatJobKey .. ":" .. prevMillis + return jobId == currentDelayedJobId + end + end + return false +end +--[[ + Function to remove deduplication key if needed + when a job is being removed. +]] +local function removeDeduplicationKeyIfNeededOnRemoval(prefixKey, + jobId, deduplicationId) + if deduplicationId then + local deduplicationKey = prefixKey .. "de:" .. deduplicationId + local currentJobId = rcall('GET', deduplicationKey) + if currentJobId and currentJobId == jobId then + rcall("DEL", deduplicationKey) + -- Also clean up any pending dedup-next data for this dedup ID + rcall("DEL", prefixKey .. "dn:" .. deduplicationId) + return 1 + end + end +end +--[[ + Function to remove from any state. + returns: + prev state +]] +local function removeJobFromAnyState( prefix, jobId) + -- We start with the ZSCORE checks, since they have O(1) complexity + if rcall("ZSCORE", prefix .. "completed", jobId) then + rcall("ZREM", prefix .. "completed", jobId) + return "completed" + elseif rcall("ZSCORE", prefix .. "waiting-children", jobId) then + rcall("ZREM", prefix .. "waiting-children", jobId) + return "waiting-children" + elseif rcall("ZSCORE", prefix .. "delayed", jobId) then + rcall("ZREM", prefix .. "delayed", jobId) + return "delayed" + elseif rcall("ZSCORE", prefix .. "failed", jobId) then + rcall("ZREM", prefix .. "failed", jobId) + return "failed" + elseif rcall("ZSCORE", prefix .. "prioritized", jobId) then + rcall("ZREM", prefix .. "prioritized", jobId) + return "prioritized" + -- We remove only 1 element from the list, since we assume they are not added multiple times + elseif rcall("LREM", prefix .. "wait", 1, jobId) == 1 then + return "wait" + elseif rcall("LREM", prefix .. "paused", 1, jobId) == 1 then + return "paused" + elseif rcall("LREM", prefix .. "active", 1, jobId) == 1 then + return "active" + end + return "unknown" +end +--[[ + Function to remove job keys. +]] +local function removeJobKeys(jobKey) + return rcall("DEL", jobKey, jobKey .. ':logs', jobKey .. ':dependencies', + jobKey .. ':processed', jobKey .. ':failed', jobKey .. ':unsuccessful') +end +--[[ + Check if this job has a parent. If so we will just remove it from + the parent child list, but if it is the last child we should move the parent to "wait/paused" + which requires code from "moveToFinished" +]] +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local function _moveParentToWait(parentPrefix, parentId, emitEvent) + local parentTarget, isPausedOrMaxed = getTargetQueueList(parentPrefix .. "meta", parentPrefix .. "active", + parentPrefix .. "wait", parentPrefix .. "paused") + addJobInTargetList(parentTarget, parentPrefix .. "marker", "RPUSH", isPausedOrMaxed, parentId) + if emitEvent then + local parentEventStream = parentPrefix .. "events" + rcall("XADD", parentEventStream, "*", "event", "waiting", "jobId", parentId, "prev", "waiting-children") + end +end +local function removeParentDependencyKey(jobKey, hard, parentKey, baseKey, debounceId) + if parentKey then + local parentDependenciesKey = parentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(parentKey) + local parentPrefix = getJobKeyPrefix(parentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then -- remove parent in same queue + if parentPrefix == baseKey then + removeParentDependencyKey(parentKey, hard, nil, baseKey, nil) + removeJobKeys(parentKey) + if debounceId then + rcall("DEL", parentPrefix .. "de:" .. debounceId) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + else + local parentAttributes = rcall("HMGET", jobKey, "parentKey", "deid") + local missedParentKey = parentAttributes[1] + if( (type(missedParentKey) == "string") and missedParentKey ~= "" + and (rcall("EXISTS", missedParentKey) == 1)) then + local parentDependenciesKey = missedParentKey .. ":dependencies" + local result = rcall("SREM", parentDependenciesKey, jobKey) + if result > 0 then + local pendingDependencies = rcall("SCARD", parentDependenciesKey) + if pendingDependencies == 0 then + local parentId = getJobIdFromKey(missedParentKey) + local parentPrefix = getJobKeyPrefix(missedParentKey, parentId) + local numRemovedElements = rcall("ZREM", parentPrefix .. "waiting-children", parentId) + if numRemovedElements == 1 then + if hard then + if parentPrefix == baseKey then + removeParentDependencyKey(missedParentKey, hard, nil, baseKey, nil) + removeJobKeys(missedParentKey) + if parentAttributes[2] then + rcall("DEL", parentPrefix .. "de:" .. parentAttributes[2]) + end + else + _moveParentToWait(parentPrefix, parentId) + end + else + _moveParentToWait(parentPrefix, parentId, true) + end + end + end + return true + end + end + end + return false +end +--[[ + Function to recursively check if there are no locks + on the jobs to be removed. + returns: + boolean +]] +local function isLocked( prefix, jobId, removeChildren) + local jobKey = prefix .. jobId; + -- Check if this job is locked + local lockKey = jobKey .. ':lock' + local lock = rcall("GET", lockKey) + if not lock then + if removeChildren == "1" then + local dependencies = rcall("SMEMBERS", jobKey .. ":dependencies") + if (#dependencies > 0) then + for i, childJobKey in ipairs(dependencies) do + -- We need to get the jobId for this job. + local childJobId = getJobIdFromKey(childJobKey) + local childJobPrefix = getJobKeyPrefix(childJobKey, childJobId) + local result = isLocked( childJobPrefix, childJobId, removeChildren ) + if result then + return true + end + end + end + end + return false + end + return true +end +local removeJobChildren +local removeJobWithChildren +removeJobChildren = function(prefix, jobKey, options) + -- Check if this job has children + -- If so, we are going to try to remove the children recursively in a depth-first way + -- because if some job is locked, we must exit with an error. + if not options.ignoreProcessed then + local processed = rcall("HGETALL", jobKey .. ":processed") + if #processed > 0 then + for i = 1, #processed, 2 do + local childJobId = getJobIdFromKey(processed[i]) + local childJobPrefix = getJobKeyPrefix(processed[i], childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end + local failed = rcall("HGETALL", jobKey .. ":failed") + if #failed > 0 then + for i = 1, #failed, 2 do + local childJobId = getJobIdFromKey(failed[i]) + local childJobPrefix = getJobKeyPrefix(failed[i], childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end + local unsuccessful = rcall("ZRANGE", jobKey .. ":unsuccessful", 0, -1) + if #unsuccessful > 0 then + for i = 1, #unsuccessful, 1 do + local childJobId = getJobIdFromKey(unsuccessful[i]) + local childJobPrefix = getJobKeyPrefix(unsuccessful[i], childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end + end + local dependencies = rcall("SMEMBERS", jobKey .. ":dependencies") + if #dependencies > 0 then + for i, childJobKey in ipairs(dependencies) do + local childJobId = getJobIdFromKey(childJobKey) + local childJobPrefix = getJobKeyPrefix(childJobKey, childJobId) + removeJobWithChildren(childJobPrefix, childJobId, jobKey, options) + end + end +end +removeJobWithChildren = function(prefix, jobId, parentKey, options) + local jobKey = prefix .. jobId + if options.ignoreLocked then + if isLocked(prefix, jobId) then + return + end + end + -- Check if job is in the failed zset + local failedSet = prefix .. "failed" + if not (options.ignoreProcessed and rcall("ZSCORE", failedSet, jobId)) then + removeParentDependencyKey(jobKey, false, parentKey, nil) + if options.removeChildren then + removeJobChildren(prefix, jobKey, options) + end + local prev = removeJobFromAnyState(prefix, jobId) + local deduplicationId = rcall("HGET", jobKey, "deid") + removeDeduplicationKeyIfNeededOnRemoval(prefix, jobId, deduplicationId) + if removeJobKeys(jobKey) > 0 then + local metaKey = prefix .. "meta" + local maxEvents = getOrSetMaxEvents(metaKey) + rcall("XADD", prefix .. "events", "MAXLEN", "~", maxEvents, "*", "event", "removed", + "jobId", jobId, "prev", prev) + end + end +end +local prefix = ARGV[1] +local jobId = ARGV[2] +local jobKey = KEYS[1] +local metaKey = KEYS[2] +local options = { + removeChildren = "1", + ignoreProcessed = true, + ignoreLocked = true +} +removeJobChildren(prefix, jobKey, options) +`; +var removeUnprocessedChildren = { + name: "removeUnprocessedChildren", + content: content44, + keys: 2 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/reprocessJob-8.js +var content45 = `--[[ + Attempts to reprocess a job + Input: + KEYS[1] job key + KEYS[2] events stream + KEYS[3] job state + KEYS[4] wait key + KEYS[5] meta + KEYS[6] paused key + KEYS[7] active key + KEYS[8] marker key + ARGV[1] job.id + ARGV[2] (job.opts.lifo ? 'R' : 'L') + 'PUSH' + ARGV[3] propVal - failedReason/returnvalue + ARGV[4] prev state - failed/completed + ARGV[5] reset attemptsMade - "1" or "0" + ARGV[6] reset attemptsStarted - "1" or "0" + Output: + 1 means the operation was a success + -1 means the job does not exist + -3 means the job was not found in the expected set. +]] +local rcall = redis.call; +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +local jobKey = KEYS[1] +if rcall("EXISTS", jobKey) == 1 then + local jobId = ARGV[1] + if (rcall("ZREM", KEYS[3], jobId) == 1) then + local attributesToRemove = {} + if ARGV[5] == "1" then + table.insert(attributesToRemove, "atm") + end + if ARGV[6] == "1" then + table.insert(attributesToRemove, "ats") + end + rcall("HDEL", jobKey, "finishedOn", "processedOn", ARGV[3], unpack(attributesToRemove)) + local target, isPausedOrMaxed = getTargetQueueList(KEYS[5], KEYS[7], KEYS[4], KEYS[6]) + addJobInTargetList(target, KEYS[8], ARGV[2], isPausedOrMaxed, jobId) + local parentKey = rcall("HGET", jobKey, "parentKey") + if parentKey and rcall("EXISTS", parentKey) == 1 then + if ARGV[4] == "failed" then + if rcall("ZREM", parentKey .. ":unsuccessful", jobKey) == 1 or + rcall("ZREM", parentKey .. ":failed", jobKey) == 1 then + rcall("SADD", parentKey .. ":dependencies", jobKey) + end + else + if rcall("HDEL", parentKey .. ":processed", jobKey) == 1 then + rcall("SADD", parentKey .. ":dependencies", jobKey) + end + end + end + local maxEvents = getOrSetMaxEvents(KEYS[5]) + -- Emit waiting event + rcall("XADD", KEYS[2], "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId, "prev", ARGV[4]); + return 1 + else + return -3 + end +else + return -1 +end +`; +var reprocessJob = { + name: "reprocessJob", + content: content45, + keys: 8 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/retryJob-11.js +var content46 = `--[[ + Retries a failed job by moving it back to the wait queue. + Input: + KEYS[1] 'active', + KEYS[2] 'wait' + KEYS[3] 'paused' + KEYS[4] job key + KEYS[5] 'meta' + KEYS[6] events stream + KEYS[7] delayed key + KEYS[8] prioritized key + KEYS[9] 'pc' priority counter + KEYS[10] 'marker' + KEYS[11] 'stalled' + ARGV[1] key prefix + ARGV[2] timestamp + ARGV[3] pushCmd + ARGV[4] jobId + ARGV[5] token + ARGV[6] optional job fields to update + Events: + 'waiting' + Output: + 0 - OK + -1 - Missing key + -2 - Missing lock + -3 - Job not in active set +]] +local rcall = redis.call +-- Includes +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to check if queue is paused or maxed + (since an empty list and !EXISTS are not really the same). +]] +local function isQueuePausedOrMaxed(queueMetaKey, activeKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency") + if queueAttributes[1] then + return true + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + return activeCount >= tonumber(queueAttributes[2]) + end + end + return false +end +--[[ + Updates the delay set, by moving delayed jobs that should + be processed now to "wait". + Events: + 'waiting' +]] +-- Includes +-- Try to get as much as 1000 jobs at once +local function promoteDelayedJobs(delayedKey, markerKey, targetKey, prioritizedKey, + eventStreamKey, prefix, timestamp, priorityCounterKey, isPaused) + local jobs = rcall("ZRANGEBYSCORE", delayedKey, 0, (timestamp + 1) * 0x1000 - 1, "LIMIT", 0, 1000) + if (#jobs > 0) then + rcall("ZREM", delayedKey, unpack(jobs)) + for _, jobId in ipairs(jobs) do + local jobKey = prefix .. jobId + local priority = + tonumber(rcall("HGET", jobKey, "priority")) or 0 + if priority == 0 then + -- LIFO or FIFO + rcall("LPUSH", targetKey, jobId) + else + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + end + -- Emit waiting event + rcall("XADD", eventStreamKey, "*", "event", "waiting", "jobId", + jobId, "prev", "delayed") + rcall("HSET", jobKey, "delay", 0) + end + addBaseMarkerIfNeeded(markerKey, isPaused) + end +end +local function removeLock(jobKey, stalledKey, token, jobId) + if token ~= "0" then + local lockKey = jobKey .. ':lock' + local lockToken = rcall("GET", lockKey) + if lockToken == token then + rcall("DEL", lockKey) + rcall("SREM", stalledKey, jobId) + else + if lockToken then + -- Lock exists but token does not match + return -6 + else + -- Lock is missing completely + return -2 + end + end + end + return 0 +end +--[[ + Function to update a bunch of fields in a job. +]] +local function updateJobFields(jobKey, msgpackedFields) + if msgpackedFields and #msgpackedFields > 0 then + local fieldsToUpdate = cmsgpack.unpack(msgpackedFields) + if fieldsToUpdate then + rcall("HMSET", jobKey, unpack(fieldsToUpdate)) + end + end +end +local target, isPausedOrMaxed = getTargetQueueList(KEYS[5], KEYS[1], KEYS[2], KEYS[3]) +local markerKey = KEYS[10] +-- Check if there are delayed jobs that we can move to wait. +-- test example: when there are delayed jobs between retries +promoteDelayedJobs(KEYS[7], markerKey, target, KEYS[8], KEYS[6], ARGV[1], ARGV[2], KEYS[9], isPausedOrMaxed) +local jobKey = KEYS[4] +if rcall("EXISTS", jobKey) == 1 then + local errorCode = removeLock(jobKey, KEYS[11], ARGV[5], ARGV[4]) + if errorCode < 0 then + return errorCode + end + updateJobFields(jobKey, ARGV[6]) + local numRemovedElements = rcall("LREM", KEYS[1], -1, ARGV[4]) + if (numRemovedElements < 1) then return -3 end + local priority = tonumber(rcall("HGET", jobKey, "priority")) or 0 + --need to re-evaluate after removing job from active + isPausedOrMaxed = isQueuePausedOrMaxed(KEYS[5], KEYS[1]) + -- Standard or priority add + if priority == 0 then + addJobInTargetList(target, markerKey, ARGV[3], isPausedOrMaxed, ARGV[4]) + else + addJobWithPriority(markerKey, KEYS[8], priority, ARGV[4], KEYS[9], isPausedOrMaxed) + end + rcall("HINCRBY", jobKey, "atm", 1) + local maxEvents = getOrSetMaxEvents(KEYS[5]) + -- Emit waiting event + rcall("XADD", KEYS[6], "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", ARGV[4], "prev", "active") + return 0 +else + return -1 +end +`; +var retryJob = { + name: "retryJob", + content: content46, + keys: 11 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/saveStacktrace-1.js +var content47 = `--[[ + Save stacktrace and failedReason. + Input: + KEYS[1] job key + ARGV[1] stacktrace + ARGV[2] failedReason + Output: + 0 - OK + -1 - Missing key +]] +local rcall = redis.call +if rcall("EXISTS", KEYS[1]) == 1 then + rcall("HMSET", KEYS[1], "stacktrace", ARGV[1], "failedReason", ARGV[2]) + return 0 +else + return -1 +end +`; +var saveStacktrace = { + name: "saveStacktrace", + content: content47, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/updateData-1.js +var content48 = `--[[ + Update job data + Input: + KEYS[1] Job id key + ARGV[1] data + Output: + 0 - OK + -1 - Missing job. +]] +local rcall = redis.call +if rcall("EXISTS",KEYS[1]) == 1 then -- // Make sure job exists + rcall("HSET", KEYS[1], "data", ARGV[1]) + return 0 +else + return -1 +end +`; +var updateData = { + name: "updateData", + content: content48, + keys: 1 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/updateJobScheduler-12.js +var content49 = `--[[ + Updates a job scheduler and adds next delayed job + Input: + KEYS[1] 'repeat' key + KEYS[2] 'delayed' + KEYS[3] 'wait' key + KEYS[4] 'paused' key + KEYS[5] 'meta' + KEYS[6] 'prioritized' key + KEYS[7] 'marker', + KEYS[8] 'id' + KEYS[9] events stream key + KEYS[10] 'pc' priority counter + KEYS[11] producer key + KEYS[12] 'active' key + ARGV[1] next milliseconds + ARGV[2] jobs scheduler id + ARGV[3] Json stringified delayed data + ARGV[4] msgpacked delayed opts + ARGV[5] timestamp + ARGV[6] prefix key + ARGV[7] producer id + Output: + next delayed job id - OK +]] local rcall = redis.call +local repeatKey = KEYS[1] +local delayedKey = KEYS[2] +local waitKey = KEYS[3] +local pausedKey = KEYS[4] +local metaKey = KEYS[5] +local prioritizedKey = KEYS[6] +local nextMillis = tonumber(ARGV[1]) +local jobSchedulerId = ARGV[2] +local timestamp = tonumber(ARGV[5]) +local prefixKey = ARGV[6] +local producerId = ARGV[7] +local jobOpts = cmsgpack.unpack(ARGV[4]) +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Shared helper to store a job and enqueue it into the appropriate list/set. + Handles delayed, prioritized, and standard (LIFO/FIFO) jobs. + Emits the appropriate event after enqueuing ("delayed" or "waiting"). + Returns delay, priority from storeJob. +]] +-- Includes +--[[ + Adds a delayed job to the queue by doing the following: + - Creates a new job key with the job data. + - adds to delayed zset. + - Emits a global event 'delayed' if the job is delayed. +]] +-- Includes +--[[ + Add delay marker if needed. +]] +-- Includes +--[[ + Function to return the next delayed job timestamp. +]] +local function getNextDelayedTimestamp(delayedKey) + local result = rcall("ZRANGE", delayedKey, 0, 0, "WITHSCORES") + if #result then + local nextTimestamp = tonumber(result[2]) + if nextTimestamp ~= nil then + return nextTimestamp / 0x1000 + end + end +end +local function addDelayMarkerIfNeeded(markerKey, delayedKey) + local nextTimestamp = getNextDelayedTimestamp(delayedKey) + if nextTimestamp ~= nil then + -- Replace the score of the marker with the newest known + -- next timestamp. + rcall("ZADD", markerKey, nextTimestamp, "1") + end +end +--[[ + Bake in the job id first 12 bits into the timestamp + to guarantee correct execution order of delayed jobs + (up to 4096 jobs per given timestamp or 4096 jobs apart per timestamp) + WARNING: Jobs that are so far apart that they wrap around will cause FIFO to fail +]] +local function getDelayedScore(delayedKey, timestamp, delay) + local delayedTimestamp = (delay > 0 and (tonumber(timestamp) + delay)) or tonumber(timestamp) + local minScore = delayedTimestamp * 0x1000 + local maxScore = (delayedTimestamp + 1 ) * 0x1000 - 1 + local result = rcall("ZREVRANGEBYSCORE", delayedKey, maxScore, + minScore, "WITHSCORES","LIMIT", 0, 1) + if #result then + local currentMaxScore = tonumber(result[2]) + if currentMaxScore ~= nil then + if currentMaxScore >= maxScore then + return maxScore, delayedTimestamp + else + return currentMaxScore + 1, delayedTimestamp + end + end + end + return minScore, delayedTimestamp +end +local function addDelayedJob(jobId, delayedKey, eventsKey, timestamp, + maxEvents, markerKey, delay) + local score, delayedTimestamp = getDelayedScore(delayedKey, timestamp, tonumber(delay)) + rcall("ZADD", delayedKey, score, jobId) + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "delayed", + "jobId", jobId, "delay", delayedTimestamp) + -- mark that a delayed job is available + addDelayMarkerIfNeeded(markerKey, delayedKey) +end +--[[ + Function to add job in target list and add marker if needed. +]] +-- Includes +--[[ + Add marker if needed when a job is available. +]] +local function addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) + if not isPausedOrMaxed then + rcall("ZADD", markerKey, 0, "0") + end +end +local function addJobInTargetList(targetKey, markerKey, pushCmd, isPausedOrMaxed, jobId) + rcall(pushCmd, targetKey, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to add job considering priority. +]] +-- Includes +--[[ + Function to get priority score. +]] +local function getPriorityScore(priority, priorityCounterKey) + local prioCounter = rcall("INCR", priorityCounterKey) + return priority * 0x100000000 + prioCounter % 0x100000000 +end +local function addJobWithPriority(markerKey, prioritizedKey, priority, jobId, priorityCounterKey, + isPausedOrMaxed) + local score = getPriorityScore(priority, priorityCounterKey) + rcall("ZADD", prioritizedKey, score, jobId) + addBaseMarkerIfNeeded(markerKey, isPausedOrMaxed) +end +--[[ + Function to check for the meta.paused key to decide if we are paused or not + (since an empty list and !EXISTS are not really the same). +]] +local function getTargetQueueList(queueMetaKey, activeKey, waitKey, pausedKey) + local queueAttributes = rcall("HMGET", queueMetaKey, "paused", "concurrency", "max", "duration") + if queueAttributes[1] then + return pausedKey, true, queueAttributes[3], queueAttributes[4] + else + if queueAttributes[2] then + local activeCount = rcall("LLEN", activeKey) + if activeCount >= tonumber(queueAttributes[2]) then + return waitKey, true, queueAttributes[3], queueAttributes[4] + else + return waitKey, false, queueAttributes[3], queueAttributes[4] + end + end + end + return waitKey, false, queueAttributes[3], queueAttributes[4] +end +--[[ + Function to store a job +]] +local function storeJob(eventsKey, jobIdKey, jobId, name, data, opts, timestamp, + parentKey, parentData, repeatJobKey) + local jsonOpts = cjson.encode(opts) + local delay = opts['delay'] or 0 + local priority = opts['priority'] or 0 + local debounceId = opts['de'] and opts['de']['id'] + local optionalValues = {} + if parentKey ~= nil then + table.insert(optionalValues, "parentKey") + table.insert(optionalValues, parentKey) + table.insert(optionalValues, "parent") + table.insert(optionalValues, parentData) + end + if repeatJobKey then + table.insert(optionalValues, "rjk") + table.insert(optionalValues, repeatJobKey) + end + if debounceId then + table.insert(optionalValues, "deid") + table.insert(optionalValues, debounceId) + end + rcall("HMSET", jobIdKey, "name", name, "data", data, "opts", jsonOpts, + "timestamp", timestamp, "delay", delay, "priority", priority, + unpack(optionalValues)) + rcall("XADD", eventsKey, "*", "event", "added", "jobId", jobId, "name", name) + return delay, priority +end +local function storeAndEnqueueJob(eventsKey, jobIdKey, jobId, name, data, opts, + timestamp, parentKey, parentData, repeatJobKey, maxEvents, + waitKey, pausedKey, activeKey, metaKey, prioritizedKey, + priorityCounterKey, delayedKey, markerKey) + local delay, priority = storeJob(eventsKey, jobIdKey, jobId, name, data, + opts, timestamp, parentKey, parentData, repeatJobKey) + if delay ~= 0 and delayedKey then + addDelayedJob(jobId, delayedKey, eventsKey, timestamp, maxEvents, markerKey, delay) + else + local target, isPausedOrMaxed = getTargetQueueList(metaKey, activeKey, waitKey, pausedKey) + if priority > 0 then + addJobWithPriority(markerKey, prioritizedKey, priority, jobId, + priorityCounterKey, isPausedOrMaxed) + else + local pushCmd = opts['lifo'] and 'RPUSH' or 'LPUSH' + addJobInTargetList(target, markerKey, pushCmd, isPausedOrMaxed, jobId) + end + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "waiting", + "jobId", jobId) + end + return delay, priority +end +local function addJobFromScheduler(jobKey, jobId, opts, waitKey, pausedKey, activeKey, metaKey, + prioritizedKey, priorityCounter, delayedKey, markerKey, eventsKey, name, maxEvents, timestamp, + data, jobSchedulerId, repeatDelay) + opts['delay'] = repeatDelay + opts['jobId'] = jobId + storeAndEnqueueJob(eventsKey, jobKey, jobId, name, data, opts, + timestamp, nil, nil, jobSchedulerId, maxEvents, + waitKey, pausedKey, activeKey, metaKey, prioritizedKey, + priorityCounter, delayedKey, markerKey) +end +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +local function getJobSchedulerEveryNextMillis(prevMillis, every, now, offset, startDate) + local nextMillis + if not prevMillis then + if startDate then + -- Assuming startDate is passed as milliseconds from JavaScript + nextMillis = tonumber(startDate) + nextMillis = nextMillis > now and nextMillis or now + else + nextMillis = now + end + else + nextMillis = prevMillis + every + -- check if we may have missed some iterations + if nextMillis < now then + nextMillis = math.floor(now / every) * every + every + (offset or 0) + end + end + if not offset or offset == 0 then + local timeSlot = math.floor(nextMillis / every) * every; + offset = nextMillis - timeSlot; + end + -- Return a tuple nextMillis, offset + return math.floor(nextMillis), math.floor(offset) +end +local prevMillis = rcall("ZSCORE", repeatKey, jobSchedulerId) +-- Validate that scheduler exists. +-- If it does not exist we should not iterate anymore. +if prevMillis then + prevMillis = tonumber(prevMillis) + local schedulerKey = repeatKey .. ":" .. jobSchedulerId + local schedulerAttributes = rcall("HMGET", schedulerKey, "name", "data", "every", "startDate", "offset") + local every = tonumber(schedulerAttributes[3]) + local now = tonumber(timestamp) + -- If every is not found in scheduler attributes, try to get it from job options + if not every and jobOpts['repeat'] and jobOpts['repeat']['every'] then + every = tonumber(jobOpts['repeat']['every']) + end + if every then + local startDate = schedulerAttributes[4] + local jobOptsOffset = jobOpts['repeat'] and jobOpts['repeat']['offset'] or 0 + local offset = schedulerAttributes[5] or jobOptsOffset or 0 + local newOffset + nextMillis, newOffset = getJobSchedulerEveryNextMillis(prevMillis, every, now, offset, startDate) + if not offset then + rcall("HSET", schedulerKey, "offset", newOffset) + jobOpts['repeat']['offset'] = newOffset + end + end + local nextDelayedJobId = "repeat:" .. jobSchedulerId .. ":" .. nextMillis + local nextDelayedJobKey = schedulerKey .. ":" .. nextMillis + local currentDelayedJobId = "repeat:" .. jobSchedulerId .. ":" .. prevMillis + if producerId == currentDelayedJobId then + local eventsKey = KEYS[9] + local maxEvents = getOrSetMaxEvents(metaKey) + if rcall("EXISTS", nextDelayedJobKey) ~= 1 then + rcall("ZADD", repeatKey, nextMillis, jobSchedulerId) + rcall("HINCRBY", schedulerKey, "ic", 1) + rcall("INCR", KEYS[8]) + -- TODO: remove this workaround in next breaking change, + -- all job-schedulers must save job data + local templateData = schedulerAttributes[2] or ARGV[3] + if templateData and templateData ~= '{}' then + rcall("HSET", schedulerKey, "data", templateData) + end + local delay = nextMillis - now + -- Fast Clamp delay to minimum of 0 + if delay < 0 then + delay = 0 + end + jobOpts["delay"] = delay + addJobFromScheduler(nextDelayedJobKey, nextDelayedJobId, jobOpts, waitKey, pausedKey, KEYS[12], metaKey, + prioritizedKey, KEYS[10], delayedKey, KEYS[7], eventsKey, schedulerAttributes[1], maxEvents, ARGV[5], + templateData or '{}', jobSchedulerId, delay) + -- TODO: remove this workaround in next breaking change + if KEYS[11] ~= "" then + rcall("HSET", KEYS[11], "nrjid", nextDelayedJobId) + end + return nextDelayedJobId .. "" -- convert to string + else + rcall("XADD", eventsKey, "MAXLEN", "~", maxEvents, "*", "event", "duplicated", "jobId", nextDelayedJobId) + end + end +end +`; +var updateJobScheduler = { + name: "updateJobScheduler", + content: content49, + keys: 12 +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/updateProgress-3.js +var content50 = `--[[ + Update job progress + Input: + KEYS[1] Job id key + KEYS[2] event stream key + KEYS[3] meta key + ARGV[1] id + ARGV[2] progress + Output: + 0 - OK + -1 - Missing job. + Event: + progress(jobId, progress) +]] +local rcall = redis.call +-- Includes +--[[ + Function to get max events value or set by default 10000. +]] +local function getOrSetMaxEvents(metaKey) + local maxEvents = rcall("HGET", metaKey, "opts.maxLenEvents") + if not maxEvents then + maxEvents = 10000 + rcall("HSET", metaKey, "opts.maxLenEvents", maxEvents) + end + return maxEvents +end +if rcall("EXISTS", KEYS[1]) == 1 then -- // Make sure job exists + local maxEvents = getOrSetMaxEvents(KEYS[3]) + rcall("HSET", KEYS[1], "progress", ARGV[2]) + rcall("XADD", KEYS[2], "MAXLEN", "~", maxEvents, "*", "event", "progress", + "jobId", ARGV[1], "data", ARGV[2]); + return 0 +else + return -1 +end +`; +var updateProgress = { + name: "updateProgress", + content: content50, + keys: 3 }; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js -var import_client17 = __toESM(require_client3(), 1); -var import_httpAuthSchemes3 = __toESM(require_httpAuthSchemes(), 1); - -// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js -init_dist_es(); -var import_property_provider23 = __toESM(require_dist_cjs34(), 1); -var import_shared_ini_file_loader12 = __toESM(require_dist_cjs35(), 1); - -// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/remoteProvider.js -var import_property_provider9 = __toESM(require_dist_cjs34(), 1); -var ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -var remoteProvider = async (init3) => { - const { ENV_CMDS_FULL_URI: ENV_CMDS_FULL_URI2, ENV_CMDS_RELATIVE_URI: ENV_CMDS_RELATIVE_URI2, fromContainerMetadata: fromContainerMetadata3, fromInstanceMetadata: fromInstanceMetadata3 } = await Promise.resolve().then(() => (init_dist_es2(), exports_dist_es2)); - if (process.env[ENV_CMDS_RELATIVE_URI2] || process.env[ENV_CMDS_FULL_URI2]) { - init3.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp: fromHttp2 } = await Promise.resolve().then(() => (init_dist_es3(), exports_dist_es3)); - return import_property_provider9.chain(fromHttp2(init3), fromContainerMetadata3(init3)); - } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new import_property_provider9.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init3.logger }); - }; - } - init3.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata3(init3); +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/scripts/updateRepeatableJobMillis-1.js +var content51 = `--[[ + Adds a repeatable job + Input: + KEYS[1] 'repeat' key + ARGV[1] next milliseconds + ARGV[2] custom key + ARGV[3] legacy custom key TODO: remove this logic in next breaking change + Output: + repeatableKey - OK +]] +local rcall = redis.call +local repeatKey = KEYS[1] +local nextMillis = ARGV[1] +local customKey = ARGV[2] +local legacyCustomKey = ARGV[3] +if rcall("ZSCORE", repeatKey, customKey) then + rcall("ZADD", repeatKey, nextMillis, customKey) + return customKey +elseif rcall("ZSCORE", repeatKey, legacyCustomKey) ~= false then + rcall("ZADD", repeatKey, nextMillis, legacyCustomKey) + return legacyCustomKey +end +return '' +`; +var updateRepeatableJobMillis = { + name: "updateRepeatableJobMillis", + content: content51, + keys: 1 }; - -// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/runtime/memoize-chain.js -function memoizeChain(providers, treatAsExpired) { - const chain2 = internalCreateChain(providers); - let activeLock; - let passiveLock; - let credentials; - const provider = async (options) => { - if (options?.forceRefresh) { - return await chain2(options); - } - if (credentials?.expiration) { - if (credentials?.expiration?.getTime() < Date.now()) { - credentials = undefined; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/redis-connection.js +var overrideMessage = [ + "BullMQ: WARNING! Your redis options maxRetriesPerRequest must be null", + "and will be overridden by BullMQ." +].join(" "); +var deprecationMessage = "BullMQ: Your redis options maxRetriesPerRequest must be null."; + +class RedisConnection extends EventEmitter { + constructor(opts, extraOptions) { + super(); + this.extraOptions = extraOptions; + this.capabilities = { + canDoubleTimeout: false, + canBlockFor1Ms: true + }; + this.status = "initializing"; + this.dbType = "redis"; + this.packageVersion = version3; + this.extraOptions = Object.assign({ shared: false, blocking: true, skipVersionCheck: false, skipWaitingForReady: false }, extraOptions); + if (!isRedisInstance(opts)) { + this.checkBlockingOptions(overrideMessage, opts); + this.opts = Object.assign({ port: 6379, host: "127.0.0.1", retryStrategy: function(times) { + return Math.max(Math.min(Math.exp(times), 20000), 1000); + } }, opts); + if (this.extraOptions.blocking) { + this.opts.maxRetriesPerRequest = null; } - } - if (activeLock) { - await activeLock; - } else if (!credentials || treatAsExpired?.(credentials)) { - if (credentials) { - if (!passiveLock) { - passiveLock = chain2(options).then((c2) => { - credentials = c2; - }).finally(() => { - passiveLock = undefined; - }); - } - } else { - activeLock = chain2(options).then((c2) => { - credentials = c2; - }).finally(() => { - activeLock = undefined; - }); - return provider(options); + } else { + this._client = opts; + if (this._client.options.keyPrefix) { + throw new Error("BullMQ: ioredis does not support ioredis prefixes, use the prefix option instead."); } - } - return credentials; - }; - return provider; -} -var internalCreateChain = (providers) => async (awsIdentityProperties) => { - let lastProviderError; - for (const provider of providers) { - try { - return await provider(awsIdentityProperties); - } catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; + if (isRedisCluster(this._client)) { + this.opts = this._client.options.redisOptions; + } else { + this.opts = this._client.options; } - throw err; + this.checkBlockingOptions(deprecationMessage, this.opts, true); } + this.skipVersionCheck = (extraOptions === null || extraOptions === undefined ? undefined : extraOptions.skipVersionCheck) || !!(this.opts && this.opts.skipVersionCheck); + this.handleClientError = (err) => { + this.emit("error", err); + }; + this.handleClientClose = () => { + this.emit("close"); + }; + this.handleClientReady = () => { + this.emit("ready"); + }; + this.initializing = this.init(); + this.initializing.catch((err) => this.emit("error", err)); } - throw lastProviderError; -}; - -// node_modules/.pnpm/@aws-sdk+credential-provider-node@3.972.32/node_modules/@aws-sdk/credential-provider-node/dist-es/defaultProvider.js -var multipleCredentialSourceWarningEmitted = false; -var defaultProvider = (init3 = {}) => memoizeChain([ - async () => { - const profile = init3.profile ?? process.env[import_shared_ini_file_loader12.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[ENV_KEY] && process.env[ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init3.logger?.warn && init3.logger?.constructor?.name !== "NoOpLogger" ? init3.logger.warn.bind(init3.logger) : console.warn; - warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -`); - multipleCredentialSourceWarningEmitted = true; - } + checkBlockingOptions(msg, options, throwError = false) { + if (this.extraOptions.blocking && options && options.maxRetriesPerRequest) { + if (throwError) { + throw new Error(msg); + } else { + console.error(msg); } - throw new import_property_provider23.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init3.logger, - tryNextLink: true - }); - } - init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return fromEnv(init3)(); - }, - async (awsIdentityProperties) => { - init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init3; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new import_property_provider23.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init3.logger }); - } - const { fromSSO: fromSSO3 } = await Promise.resolve().then(() => (init_dist_es5(), exports_dist_es4)); - return fromSSO3(init3)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni: fromIni3 } = await Promise.resolve().then(() => (init_dist_es9(), exports_dist_es7)); - return fromIni3(init3)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess: fromProcess3 } = await Promise.resolve().then(() => (init_dist_es7(), exports_dist_es5)); - return fromProcess3(init3)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile: fromTokenFile3 } = await Promise.resolve().then(() => (init_dist_es8(), exports_dist_es6)); - return fromTokenFile3(init3)(awsIdentityProperties); - }, - async () => { - init3.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init3))(); - }, - async () => { - throw new import_property_provider23.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init3.logger - }); - } -], credentialsTreatedAsExpired); -var credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000; - -// node_modules/.pnpm/@aws-sdk+middleware-bucket-endpoint@3.972.10/node_modules/@aws-sdk/middleware-bucket-endpoint/dist-es/NodeUseArnRegionConfigOptions.js -var import_util_config_provider2 = __toESM(require_dist_cjs23(), 1); -var NODE_USE_ARN_REGION_ENV_NAME = "AWS_S3_USE_ARN_REGION"; -var NODE_USE_ARN_REGION_INI_NAME = "s3_use_arn_region"; -var NODE_USE_ARN_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: (env2) => import_util_config_provider2.booleanSelector(env2, NODE_USE_ARN_REGION_ENV_NAME, import_util_config_provider2.SelectorType.ENV), - configFileSelector: (profile) => import_util_config_provider2.booleanSelector(profile, NODE_USE_ARN_REGION_INI_NAME, import_util_config_provider2.SelectorType.CONFIG), - default: undefined -}; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js -var import_util_user_agent_node = __toESM(require_dist_cjs40(), 1); -var import_config_resolver = __toESM(require_dist_cjs32(), 1); - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js -var import_util_hex_encoding2 = __toESM(require_dist_cjs11(), 1); - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/Int64.js -var import_util_hex_encoding = __toESM(require_dist_cjs11(), 1); - -class Int64 { - bytes; - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number2) { - if (number2 > 9223372036854776000 || number2 < -9223372036854776000) { - throw new Error(`${number2} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i2 = 7, remaining = Math.abs(Math.round(number2));i2 > -1 && remaining > 0; i2--, remaining /= 256) { - bytes[i2] = remaining; - } - if (number2 < 0) { - negate(bytes); - } - return new Int64(bytes); - } - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); } - return parseInt(import_util_hex_encoding.toHex(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } -} -function negate(bytes) { - for (let i2 = 0;i2 < 8; i2++) { - bytes[i2] ^= 255; - } - for (let i2 = 7;i2 > -1; i2--) { - bytes[i2]++; - if (bytes[i2] !== 0) - break; - } -} - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/HeaderMarshaller.js -class HeaderMarshaller { - toUtf8; - fromUtf8; - constructor(toUtf82, fromUtf84) { - this.toUtf8 = toUtf82; - this.fromUtf8 = fromUtf84; } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = this.fromUtf8(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); + static async waitUntilReady(client) { + if (client.status === "ready") { + return; } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; + if (client.status === "connect" && isRedisCluster(client)) { + return; } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 : 1]); - case "byte": - return Uint8Array.from([2, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = this.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9; - uuidBytes.set(import_util_hex_encoding2.fromHex(header.value.replace(/\-/g, "")), 1); - return uuidBytes; + if (client.status === "wait") { + return client.connect(); } - } - parse(headers) { - const out = {}; - let position = 0; - while (position < headers.byteLength) { - const nameLength = headers.getUint8(position++); - const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); - position += nameLength; - switch (headers.getUint8(position++)) { - case 0: - out[name] = { - type: BOOLEAN_TAG, - value: true - }; - break; - case 1: - out[name] = { - type: BOOLEAN_TAG, - value: false - }; - break; - case 2: - out[name] = { - type: BYTE_TAG, - value: headers.getInt8(position++) - }; - break; - case 3: - out[name] = { - type: SHORT_TAG, - value: headers.getInt16(position, false) - }; - position += 2; - break; - case 4: - out[name] = { - type: INT_TAG, - value: headers.getInt32(position, false) - }; - position += 4; - break; - case 5: - out[name] = { - type: LONG_TAG, - value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) - }; - position += 8; - break; - case 6: - const binaryLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: BINARY_TAG, - value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) - }; - position += binaryLength; - break; - case 7: - const stringLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: STRING_TAG, - value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) - }; - position += stringLength; - break; - case 8: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) - }; - position += 8; - break; - case 9: - const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); - position += 16; - out[name] = { - type: UUID_TAG, - value: `${import_util_hex_encoding2.toHex(uuidBytes.subarray(0, 4))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(4, 6))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(6, 8))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(8, 10))}-${import_util_hex_encoding2.toHex(uuidBytes.subarray(10))}` - }; - break; - default: - throw new Error(`Unrecognized header type tag`); - } + if (client.status === "end") { + throw new Error(import_utils58.CONNECTION_CLOSED_ERROR_MSG); } - return out; - } -} -var HEADER_VALUE_TYPE; -(function(HEADER_VALUE_TYPE2) { - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolTrue"] = 0] = "boolTrue"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["boolFalse"] = 1] = "boolFalse"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byte"] = 2] = "byte"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["short"] = 3] = "short"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["integer"] = 4] = "integer"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["long"] = 5] = "long"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["byteArray"] = 6] = "byteArray"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["string"] = 7] = "string"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["timestamp"] = 8] = "timestamp"; - HEADER_VALUE_TYPE2[HEADER_VALUE_TYPE2["uuid"] = 9] = "uuid"; -})(HEADER_VALUE_TYPE || (HEADER_VALUE_TYPE = {})); -var BOOLEAN_TAG = "boolean"; -var BYTE_TAG = "byte"; -var SHORT_TAG = "short"; -var INT_TAG = "integer"; -var LONG_TAG = "long"; -var BINARY_TAG = "binary"; -var STRING_TAG = "string"; -var TIMESTAMP_TAG = "timestamp"; -var UUID_TAG = "uuid"; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/splitMessage.js -var PRELUDE_MEMBER_LENGTH = 4; -var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; -var CHECKSUM_LENGTH = 4; -var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; -function splitMessage({ byteLength, byteOffset, buffer }) { - if (byteLength < MINIMUM_MESSAGE_LENGTH) { - throw new Error("Provided message too short to accommodate event stream message overhead"); - } - const view = new DataView(buffer, byteOffset, byteLength); - const messageLength = view.getUint32(0, false); - if (byteLength !== messageLength) { - throw new Error("Reported message length does not match received message length"); - } - const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); - const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); - const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); - const checksummer = new Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); - if (expectedPreludeChecksum !== checksummer.digest()) { - throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); - } - checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); - if (expectedMessageChecksum !== checksummer.digest()) { - throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); - } - return { - headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), - body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)) - }; -} - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/EventStreamCodec.js -class EventStreamCodec { - headerMarshaller; - messageBuffer; - isEndOfStream; - constructor(toUtf82, fromUtf84) { - this.headerMarshaller = new HeaderMarshaller(toUtf82, fromUtf84); - this.messageBuffer = []; - this.isEndOfStream = false; - } - feed(message) { - this.messageBuffer.push(this.decode(message)); - } - endOfStream() { - this.isEndOfStream = true; - } - getMessage() { - const message = this.messageBuffer.pop(); - const isEndOfStream = this.isEndOfStream; - return { - getMessage() { - return message; - }, - isEndOfStream() { - return isEndOfStream; - } - }; - } - getAvailableMessages() { - const messages = this.messageBuffer; - this.messageBuffer = []; - const isEndOfStream = this.isEndOfStream; - return { - getMessages() { - return messages; - }, - isEndOfStream() { - return isEndOfStream; + let handleReady; + let handleEnd; + let handleError; + try { + await new Promise((resolve, reject) => { + let lastError; + handleError = (err) => { + lastError = err; + }; + handleReady = () => { + resolve(); + }; + handleEnd = () => { + if (client.status !== "end") { + reject(lastError || new Error(import_utils58.CONNECTION_CLOSED_ERROR_MSG)); + } else { + if (lastError) { + reject(lastError); + } else { + resolve(); + } + } + }; + increaseMaxListeners(client, 3); + client.once("ready", handleReady); + client.on("end", handleEnd); + client.once("error", handleError); + }); + } finally { + client.removeListener("end", handleEnd); + client.removeListener("error", handleError); + client.removeListener("ready", handleReady); + decreaseMaxListeners(client, 3); + } + } + get client() { + return this.initializing; + } + loadCommands(packageVersion, providedScripts) { + const finalScripts = providedScripts || exports_scripts; + for (const property in finalScripts) { + const commandName = `${finalScripts[property].name}:${packageVersion}`; + if (!this._client[commandName]) { + this._client.defineCommand(commandName, { + numberOfKeys: finalScripts[property].keys, + lua: finalScripts[property].content + }); } - }; - } - encode({ headers: rawHeaders, body }) { - const headers = this.headerMarshaller.format(rawHeaders); - const length = headers.byteLength + body.byteLength + 16; - const out = new Uint8Array(length); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - const checksum = new Crc32; - view.setUint32(0, length, false); - view.setUint32(4, headers.byteLength, false); - view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); - out.set(headers, 12); - out.set(body, headers.byteLength + 12); - view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); - return out; - } - decode(message) { - const { headers, body } = splitMessage(message); - return { headers: this.headerMarshaller.parse(headers), body }; - } - formatHeaders(rawHeaders) { - return this.headerMarshaller.format(rawHeaders); - } -} - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/MessageDecoderStream.js -class MessageDecoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async* asyncIterator() { - for await (const bytes of this.options.inputStream) { - const decoded = this.options.decoder.decode(bytes); - yield decoded; - } - } -} - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/MessageEncoderStream.js -class MessageEncoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async* asyncIterator() { - for await (const msg of this.options.messageStream) { - const encoded = this.options.encoder.encode(msg); - yield encoded; - } - if (this.options.includeEndFrame) { - yield new Uint8Array(0); - } - } -} - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageDecoderStream.js -class SmithyMessageDecoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async* asyncIterator() { - for await (const message of this.options.messageStream) { - const deserialized = await this.options.deserializer(message); - if (deserialized === undefined) - continue; - yield deserialized; } } -} - -// node_modules/.pnpm/@smithy+eventstream-codec@4.2.14/node_modules/@smithy/eventstream-codec/dist-es/SmithyMessageEncoderStream.js -class SmithyMessageEncoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async* asyncIterator() { - for await (const chunk of this.options.inputStream) { - const payloadBuf = this.options.serializer(chunk); - yield payloadBuf; + async init() { + if (!this._client) { + const _a = this.opts, { url } = _a, rest = __rest(_a, ["url"]); + this._client = url ? new import_ioredis3.default(url, rest) : new import_ioredis3.default(rest); } - } -} - -// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.14/node_modules/@smithy/eventstream-serde-universal/dist-es/getChunkedStream.js -function getChunkedStream(source) { - let currentMessageTotalLength = 0; - let currentMessagePendingLength = 0; - let currentMessage = null; - let messageLengthBuffer = null; - const allocateMessage = (size) => { - if (typeof size !== "number") { - throw new Error("Attempted to allocate an event message where size was not a number: " + size); + increaseMaxListeners(this._client, 3); + this._client.on("error", this.handleClientError); + this._client.on("close", this.handleClientClose); + this._client.on("ready", this.handleClientReady); + if (!this.extraOptions.skipWaitingForReady) { + await RedisConnection.waitUntilReady(this._client); } - currentMessageTotalLength = size; - currentMessagePendingLength = 4; - currentMessage = new Uint8Array(size); - const currentMessageView = new DataView(currentMessage.buffer); - currentMessageView.setUint32(0, size, false); - }; - const iterator = async function* () { - const sourceIterator = source[Symbol.asyncIterator](); - while (true) { - const { value, done } = await sourceIterator.next(); - if (done) { - if (!currentMessageTotalLength) { - return; - } else if (currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - } else { - throw new Error("Truncated event message received."); - } - return; - } - const chunkLength = value.length; - let currentOffset = 0; - while (currentOffset < chunkLength) { - if (!currentMessage) { - const bytesRemaining = chunkLength - currentOffset; - if (!messageLengthBuffer) { - messageLengthBuffer = new Uint8Array(4); - } - const numBytesForTotal = Math.min(4 - currentMessagePendingLength, bytesRemaining); - messageLengthBuffer.set(value.slice(currentOffset, currentOffset + numBytesForTotal), currentMessagePendingLength); - currentMessagePendingLength += numBytesForTotal; - currentOffset += numBytesForTotal; - if (currentMessagePendingLength < 4) { - break; - } - allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0, false)); - messageLengthBuffer = null; + this.loadCommands(this.packageVersion); + if (this._client["status"] !== "end") { + const versionResult = await this.getRedisVersionAndType(); + this.version = versionResult.version; + this.dbType = versionResult.databaseType; + if (this.skipVersionCheck !== true && !this.closing) { + if (isRedisVersionLowerThan(this.version, RedisConnection.minimumVersion, this.dbType)) { + throw new Error(`Redis version needs to be greater or equal than ${RedisConnection.minimumVersion} ` + `Current: ${this.version}`); } - const numBytesToWrite = Math.min(currentMessageTotalLength - currentMessagePendingLength, chunkLength - currentOffset); - currentMessage.set(value.slice(currentOffset, currentOffset + numBytesToWrite), currentMessagePendingLength); - currentMessagePendingLength += numBytesToWrite; - currentOffset += numBytesToWrite; - if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - currentMessage = null; - currentMessageTotalLength = 0; - currentMessagePendingLength = 0; + if (isRedisVersionLowerThan(this.version, RedisConnection.recommendedMinimumVersion, this.dbType)) { + console.warn(`It is highly recommended to use a minimum Redis version of ${RedisConnection.recommendedMinimumVersion} + Current: ${this.version}`); } } - } - }; - return { - [Symbol.asyncIterator]: iterator - }; -} - -// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.14/node_modules/@smithy/eventstream-serde-universal/dist-es/getUnmarshalledStream.js -function getMessageUnmarshaller(deserializer, toUtf82) { - return async function(message) { - const { value: messageType } = message.headers[":message-type"]; - if (messageType === "error") { - const unmodeledError = new Error(message.headers[":error-message"].value || "UnknownError"); - unmodeledError.name = message.headers[":error-code"].value; - throw unmodeledError; - } else if (messageType === "exception") { - const code = message.headers[":exception-type"].value; - const exception = { [code]: message }; - const deserializedException = await deserializer(exception); - if (deserializedException.$unknown) { - const error = new Error(toUtf82(message.body)); - error.name = code; - throw error; - } - throw deserializedException[code]; - } else if (messageType === "event") { - const event = { - [message.headers[":event-type"].value]: message + this.capabilities = { + canDoubleTimeout: !isRedisVersionLowerThan(this.version, "6.0.0", this.dbType), + canBlockFor1Ms: !isRedisVersionLowerThan(this.version, "7.0.8", this.dbType) }; - const deserialized = await deserializer(event); - if (deserialized.$unknown) - return; - return deserialized; - } else { - throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`); - } - }; -} - -// node_modules/.pnpm/@smithy+eventstream-serde-universal@4.2.14/node_modules/@smithy/eventstream-serde-universal/dist-es/EventStreamMarshaller.js -class EventStreamMarshaller { - eventStreamCodec; - utfEncoder; - constructor({ utf8Encoder, utf8Decoder }) { - this.eventStreamCodec = new EventStreamCodec(utf8Encoder, utf8Decoder); - this.utfEncoder = utf8Encoder; - } - deserialize(body, deserializer) { - const inputStream = getChunkedStream(body); - return new SmithyMessageDecoderStream({ - messageStream: new MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), - deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) - }); - } - serialize(inputStream, serializer) { - return new MessageEncoderStream({ - messageStream: new SmithyMessageEncoderStream({ inputStream, serializer }), - encoder: this.eventStreamCodec, - includeEndFrame: true - }); - } -} - -// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js -import { Readable } from "stream"; - -// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/utils.js -async function* readabletoIterable(readStream) { - let streamEnded = false; - let generationEnded = false; - const records = new Array; - readStream.on("error", (err) => { - if (!streamEnded) { - streamEnded = true; - } - if (err) { - throw err; - } - }); - readStream.on("data", (data) => { - records.push(data); - }); - readStream.on("end", () => { - streamEnded = true; - }); - while (!generationEnded) { - const value = await new Promise((resolve) => setTimeout(() => resolve(records.shift()), 0)); - if (value) { - yield value; - } - generationEnded = streamEnded && records.length === 0; - } -} - -// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/EventStreamMarshaller.js -class EventStreamMarshaller2 { - universalMarshaller; - constructor({ utf8Encoder, utf8Decoder }) { - this.universalMarshaller = new EventStreamMarshaller({ - utf8Decoder, - utf8Encoder - }); - } - deserialize(body, deserializer) { - const bodyIterable = typeof body[Symbol.asyncIterator] === "function" ? body : readabletoIterable(body); - return this.universalMarshaller.deserialize(bodyIterable, deserializer); - } - serialize(input, serializer) { - return Readable.from(this.universalMarshaller.serialize(input, serializer)); - } -} - -// node_modules/.pnpm/@smithy+eventstream-serde-node@4.2.14/node_modules/@smithy/eventstream-serde-node/dist-es/provider.js -var eventStreamSerdeProvider = (options) => new EventStreamMarshaller2(options); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js -var import_hash_node = __toESM(require_dist_cjs41(), 1); - -// node_modules/.pnpm/@smithy+hash-stream-node@4.2.14/node_modules/@smithy/hash-stream-node/dist-es/HashCalculator.js -var import_util_utf83 = __toESM(require_dist_cjs5(), 1); -import { Writable } from "stream"; - -class HashCalculator extends Writable { - hash; - constructor(hash4, options) { - super(options); - this.hash = hash4; - } - _write(chunk, encoding, callback) { - try { - this.hash.update(import_util_utf83.toUint8Array(chunk)); - } catch (err) { - return callback(err); + this.status = "ready"; } - callback(); - } -} - -// node_modules/.pnpm/@smithy+hash-stream-node@4.2.14/node_modules/@smithy/hash-stream-node/dist-es/readableStreamHasher.js -var readableStreamHasher = (hashCtor, readableStream) => { - if (readableStream.readableFlowing !== null) { - throw new Error("Unable to calculate hash for flowing readable stream"); + return this._client; } - const hash4 = new hashCtor; - const hashCalculator = new HashCalculator(hash4); - readableStream.pipe(hashCalculator); - return new Promise((resolve, reject) => { - readableStream.on("error", (err) => { - hashCalculator.end(); - reject(err); - }); - hashCalculator.on("error", reject); - hashCalculator.on("finish", () => { - hash4.digest().then(resolve).catch(reject); - }); - }); -}; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js -var import_middleware_retry = __toESM(require_dist_cjs39(), 1); -var import_node_config_provider3 = __toESM(require_dist_cjs36(), 1); -var import_node_http_handler2 = __toESM(require_dist_cjs9(), 1); -var import_smithy_client7 = __toESM(require_dist_cjs21(), 1); -var import_util_body_length_node = __toESM(require_dist_cjs42(), 1); -var import_util_defaults_mode_node = __toESM(require_dist_cjs43(), 1); -var import_util_retry = __toESM(require_dist_cjs30(), 1); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.shared.js -var import_httpAuthSchemes2 = __toESM(require_httpAuthSchemes(), 1); -var import_smithy_client6 = __toESM(require_dist_cjs21(), 1); -var import_url_parser2 = __toESM(require_dist_cjs19(), 1); -var import_util_base64 = __toESM(require_dist_cjs6(), 1); -var import_util_stream5 = __toESM(require_dist_cjs12(), 1); -var import_util_utf84 = __toESM(require_dist_cjs5(), 1); -var getRuntimeConfig = (config) => { - return { - apiVersion: "2006-03-01", - base64Decoder: config?.base64Decoder ?? import_util_base64.fromBase64, - base64Encoder: config?.base64Encoder ?? import_util_base64.toBase64, - disableHostPrefix: config?.disableHostPrefix ?? false, - endpointProvider: config?.endpointProvider ?? defaultEndpointResolver, - extensions: config?.extensions ?? [], - getAwsChunkedEncodingStream: config?.getAwsChunkedEncodingStream ?? import_util_stream5.getAwsChunkedEncodingStream, - httpAuthSchemeProvider: config?.httpAuthSchemeProvider ?? defaultS3HttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new import_httpAuthSchemes2.AwsSdkSigV4Signer - }, - { - schemeId: "aws.auth#sigv4a", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4a"), - signer: new import_httpAuthSchemes2.AwsSdkSigV4ASigner + async disconnect(wait = true) { + const client = await this.client; + if (client.status !== "end") { + let _resolve, _reject; + if (!wait) { + return client.disconnect(); } - ], - logger: config?.logger ?? new import_smithy_client6.NoOpLogger, - protocol: config?.protocol ?? S3RestXmlProtocol, - protocolSettings: config?.protocolSettings ?? { - defaultNamespace: "com.amazonaws.s3", - errorTypeRegistries, - xmlNamespace: "http://s3.amazonaws.com/doc/2006-03-01/", - version: "2006-03-01", - serviceTarget: "AmazonS3" - }, - sdkStreamMixin: config?.sdkStreamMixin ?? import_util_stream5.sdkStreamMixin, - serviceId: config?.serviceId ?? "S3", - signerConstructor: config?.signerConstructor ?? SignatureV4MultiRegion, - signingEscapePath: config?.signingEscapePath ?? false, - urlParser: config?.urlParser ?? import_url_parser2.parseUrl, - useArnRegion: config?.useArnRegion ?? undefined, - utf8Decoder: config?.utf8Decoder ?? import_util_utf84.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? import_util_utf84.toUtf8 - }; -}; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeConfig.js -var getRuntimeConfig2 = (config) => { - import_smithy_client7.emitWarningIfUnsupportedVersion(process.version); - const defaultsMode = import_util_defaults_mode_node.resolveDefaultsModeConfig(config); - const defaultConfigProvider = () => defaultsMode().then(import_smithy_client7.loadConfigsForDefaultMode); - const clientSharedValues = getRuntimeConfig(config); - import_client17.emitWarningIfUnsupportedVersion(process.version); - const loaderConfig = { - profile: config?.profile, - logger: clientSharedValues.logger - }; - return { - ...clientSharedValues, - ...config, - runtime: "node", - defaultsMode, - authSchemePreference: config?.authSchemePreference ?? import_node_config_provider3.loadConfig(import_httpAuthSchemes3.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS, loaderConfig), - bodyLengthChecker: config?.bodyLengthChecker ?? import_util_body_length_node.calculateBodyLength, - credentialDefaultProvider: config?.credentialDefaultProvider ?? defaultProvider, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? import_util_user_agent_node.createDefaultUserAgentProvider({ serviceId: clientSharedValues.serviceId, clientVersion: package_default.version }), - disableS3ExpressSessionAuth: config?.disableS3ExpressSessionAuth ?? import_node_config_provider3.loadConfig(NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS, loaderConfig), - eventStreamSerdeProvider: config?.eventStreamSerdeProvider ?? eventStreamSerdeProvider, - maxAttempts: config?.maxAttempts ?? import_node_config_provider3.loadConfig(import_middleware_retry.NODE_MAX_ATTEMPT_CONFIG_OPTIONS, config), - md5: config?.md5 ?? import_hash_node.Hash.bind(null, "md5"), - region: config?.region ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_REGION_CONFIG_OPTIONS, { ...import_config_resolver.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }), - requestChecksumCalculation: config?.requestChecksumCalculation ?? import_node_config_provider3.loadConfig(NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS, loaderConfig), - requestHandler: import_node_http_handler2.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - responseChecksumValidation: config?.responseChecksumValidation ?? import_node_config_provider3.loadConfig(NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS, loaderConfig), - retryMode: config?.retryMode ?? import_node_config_provider3.loadConfig({ - ...import_middleware_retry.NODE_RETRY_MODE_CONFIG_OPTIONS, - default: async () => (await defaultConfigProvider()).retryMode || import_util_retry.DEFAULT_RETRY_MODE - }, config), - sha1: config?.sha1 ?? import_hash_node.Hash.bind(null, "sha1"), - sha256: config?.sha256 ?? import_hash_node.Hash.bind(null, "sha256"), - sigv4aSigningRegionSet: config?.sigv4aSigningRegionSet ?? import_node_config_provider3.loadConfig(import_httpAuthSchemes3.NODE_SIGV4A_CONFIG_OPTIONS, loaderConfig), - streamCollector: config?.streamCollector ?? import_node_http_handler2.streamCollector, - streamHasher: config?.streamHasher ?? readableStreamHasher, - useArnRegion: config?.useArnRegion ?? import_node_config_provider3.loadConfig(NODE_USE_ARN_REGION_CONFIG_OPTIONS, loaderConfig), - useDualstackEndpoint: config?.useDualstackEndpoint ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - useFipsEndpoint: config?.useFipsEndpoint ?? import_node_config_provider3.loadConfig(import_config_resolver.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS, loaderConfig), - userAgentAppId: config?.userAgentAppId ?? import_node_config_provider3.loadConfig(import_util_user_agent_node.NODE_APP_ID_CONFIG_OPTIONS, loaderConfig) - }; -}; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js -var import_region_config_resolver = __toESM(require_dist_cjs44(), 1); -var import_protocol_http11 = __toESM(require_dist_cjs2(), 1); -var import_smithy_client8 = __toESM(require_dist_cjs21(), 1); - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/auth/httpAuthExtensionConfiguration.js -var getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index2 = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index2 === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } else { - _httpAuthSchemes.splice(index2, 1, httpAuthScheme); + const disconnecting = new Promise((resolve, reject) => { + increaseMaxListeners(client, 2); + client.once("end", resolve); + client.once("error", reject); + _resolve = resolve; + _reject = reject; + }); + client.disconnect(); + try { + await disconnecting; + } finally { + decreaseMaxListeners(client, 2); + client.removeListener("end", _resolve); + client.removeListener("error", _reject); } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; } - }; -}; -var resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials() - }; -}; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/runtimeExtensions.js -var resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(import_region_config_resolver.getAwsRegionExtensionConfiguration(runtimeConfig), import_smithy_client8.getDefaultExtensionConfiguration(runtimeConfig), import_protocol_http11.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, import_region_config_resolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), import_smithy_client8.resolveDefaultRuntimeConfig(extensionConfiguration), import_protocol_http11.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/S3Client.js -class S3Client extends import_smithy_client9.Client { - config; - constructor(...[configuration]) { - const _config_0 = getRuntimeConfig2(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = import_middleware_user_agent.resolveUserAgentConfig(_config_1); - const _config_3 = resolveFlexibleChecksumsConfig(_config_2); - const _config_4 = import_middleware_retry2.resolveRetryConfig(_config_3); - const _config_5 = import_config_resolver2.resolveRegionConfig(_config_4); - const _config_6 = import_middleware_host_header.resolveHostHeaderConfig(_config_5); - const _config_7 = import_middleware_endpoint3.resolveEndpointConfig(_config_6); - const _config_8 = resolveEventStreamSerdeConfig(_config_7); - const _config_9 = resolveHttpAuthSchemeConfig(_config_8); - const _config_10 = resolveS3Config(_config_9, { session: [() => this, CreateSessionCommand] }); - const _config_11 = resolveRuntimeExtensions(_config_10, configuration?.extensions || []); - this.config = _config_11; - this.middlewareStack.use(import_schema8.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(import_middleware_user_agent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(import_middleware_retry2.getRetryPlugin(this.config)); - this.middlewareStack.use(import_middleware_content_length.getContentLengthPlugin(this.config)); - this.middlewareStack.use(import_middleware_host_header.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(import_middleware_logger.getLoggerPlugin(this.config)); - this.middlewareStack.use(import_middleware_recursion_detection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(import_core3.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: defaultS3HttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new import_core3.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - "aws.auth#sigv4a": config.credentials - }) - })); - this.middlewareStack.use(import_core3.getHttpSigningPlugin(this.config)); - this.middlewareStack.use(getValidateBucketNamePlugin(this.config)); - this.middlewareStack.use(getAddExpectContinuePlugin(this.config)); - this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config)); - this.middlewareStack.use(getS3ExpressPlugin(this.config)); - this.middlewareStack.use(getS3ExpressHttpSigningPlugin(this.config)); } - destroy() { - super.destroy(); + async reconnect() { + const client = await this.client; + return client.connect(); } -} - -// node_modules/.pnpm/@aws-sdk+middleware-ssec@3.972.10/node_modules/@aws-sdk/middleware-ssec/dist-es/index.js -function ssecMiddleware(options) { - return (next) => async (args) => { - const input = { ...args.input }; - const properties = [ - { - target: "SSECustomerKey", - hash: "SSECustomerKeyMD5" - }, - { - target: "CopySourceSSECustomerKey", - hash: "CopySourceSSECustomerKeyMD5" - } - ]; - for (const prop of properties) { - const value = input[prop.target]; - if (value) { - let valueForHash; - if (typeof value === "string") { - if (isValidBase64EncodedSSECustomerKey(value, options)) { - valueForHash = options.base64Decoder(value); + async close(force = false) { + if (!this.closing) { + const status = this.status; + this.status = "closing"; + this.closing = true; + try { + if (status === "ready") { + await this.initializing; + } + if (!this.extraOptions.shared) { + if (status == "initializing" || force) { + this._client.disconnect(); } else { - valueForHash = options.utf8Decoder(value); - input[prop.target] = options.base64Encoder(valueForHash); + await this._client.quit(); } - } else { - valueForHash = ArrayBuffer.isView(value) ? new Uint8Array(value.buffer, value.byteOffset, value.byteLength) : new Uint8Array(value); - input[prop.target] = options.base64Encoder(valueForHash); + this._client["status"] = "end"; } - const hash4 = new options.md5; - hash4.update(valueForHash); - input[prop.hash] = options.base64Encoder(await hash4.digest()); + } catch (error) { + if (isNotConnectionError(error)) { + throw error; + } + } finally { + this._client.off("error", this.handleClientError); + this._client.off("close", this.handleClientClose); + this._client.off("ready", this.handleClientReady); + decreaseMaxListeners(this._client, 3); + this.removeAllListeners(); + this.status = "closed"; } } - return next({ - ...args, - input - }); - }; -} -var ssecMiddlewareOptions = { - name: "ssecMiddleware", - step: "initialize", - tags: ["SSE"], - override: true -}; -var getSsecPlugin = (config) => ({ - applyToStack: (clientStack) => { - clientStack.add(ssecMiddleware(config), ssecMiddlewareOptions); } -}); -function isValidBase64EncodedSSECustomerKey(str, options) { - const base64Regex = /^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; - if (!base64Regex.test(str)) - return false; - try { - const decodedBytes = options.base64Decoder(str); - return decodedBytes.length === 32; - } catch { - return false; + async getRedisVersionAndType() { + if (this.skipVersionCheck) { + return { + version: RedisConnection.minimumVersion, + databaseType: "redis" + }; + } + const doc = await this._client.info(); + const redisPrefix = "redis_version:"; + const maxMemoryPolicyPrefix = "maxmemory_policy:"; + const lines = doc.split(/\r?\n/); + let redisVersion; + let databaseType = "redis"; + for (let i2 = 0;i2 < lines.length; i2++) { + const line3 = lines[i2]; + if (line3.includes("dragonfly_version:") || line3.includes("server:Dragonfly")) { + databaseType = "dragonfly"; + if (line3.indexOf("dragonfly_version:") === 0) { + redisVersion = line3.substr("dragonfly_version:".length); + } + } else if (line3.includes("valkey_version:") || line3.includes("server:Valkey")) { + databaseType = "valkey"; + if (line3.indexOf("valkey_version:") === 0) { + redisVersion = line3.substr("valkey_version:".length); + } + } else if (line3.indexOf(redisPrefix) === 0) { + redisVersion = line3.substr(redisPrefix.length); + if (databaseType === "redis") { + databaseType = "redis"; + } + } + if (line3.indexOf(maxMemoryPolicyPrefix) === 0) { + const maxMemoryPolicy = line3.substr(maxMemoryPolicyPrefix.length); + if (maxMemoryPolicy !== "noeviction") { + console.warn(`IMPORTANT! Eviction policy is ${maxMemoryPolicy}. It should be "noeviction"`); + } + } + } + if (!redisVersion) { + for (const line3 of lines) { + if (line3.includes("version:")) { + const parts = line3.split(":"); + if (parts.length >= 2) { + redisVersion = parts[1]; + break; + } + } + } + } + return { + version: redisVersion || RedisConnection.minimumVersion, + databaseType + }; + } + get redisVersion() { + return this.version; + } + get databaseType() { + return this.dbType; } } +RedisConnection.minimumVersion = "5.0.0"; +RedisConnection.recommendedMinimumVersion = "6.2.0"; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/job-scheduler.js +var import_cron_parser = __toESM(require_parser3(), 1); -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/commands/GetObjectCommand.js -var import_middleware_endpoint4 = __toESM(require_dist_cjs38(), 1); -var import_smithy_client10 = __toESM(require_dist_cjs21(), 1); -class GetObjectCommand extends import_smithy_client10.Command.classBuilder().ep({ - ...commonParams, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } -}).m(function(Command, cs2, config, o2) { - return [ - import_middleware_endpoint4.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), - getFlexibleChecksumsPlugin(config, { - requestChecksumRequired: false, - requestValidationModeMember: "ChecksumMode", - responseAlgorithms: ["CRC64NVME", "CRC32", "CRC32C", "SHA256", "SHA1"] - }), - getSsecPlugin(config), - getS3ExpiresMiddlewarePlugin(config) - ]; -}).s("AmazonS3", "GetObject", {}).n("S3Client", "GetObjectCommand").sc(GetObject$).build() { -} - -// node_modules/.pnpm/@aws-sdk+client-s3@3.1032.0/node_modules/@aws-sdk/client-s3/dist-es/commands/PutObjectCommand.js -var import_middleware_endpoint5 = __toESM(require_dist_cjs38(), 1); -var import_smithy_client11 = __toESM(require_dist_cjs21(), 1); -class PutObjectCommand extends import_smithy_client11.Command.classBuilder().ep({ - ...commonParams, - Bucket: { type: "contextParams", name: "Bucket" }, - Key: { type: "contextParams", name: "Key" } -}).m(function(Command, cs2, config, o2) { - return [ - import_middleware_endpoint5.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), - getFlexibleChecksumsPlugin(config, { - requestAlgorithmMember: { httpHeader: "x-amz-sdk-checksum-algorithm", name: "ChecksumAlgorithm" }, - requestChecksumRequired: false - }), - getCheckContentLengthHeaderPlugin(config), - getThrow200ExceptionsPlugin(config), - getSsecPlugin(config) - ]; -}).s("AmazonS3", "PutObject", {}).n("S3Client", "PutObjectCommand").sc(PutObject$).build() { -} - -// node_modules/.pnpm/@aws-sdk+util-format-url@3.972.10/node_modules/@aws-sdk/util-format-url/dist-es/index.js -var import_querystring_builder = __toESM(require_dist_cjs8(), 1); -function formatUrl(request2) { - const { port, query } = request2; - let { protocol, path: path2, hostname } = request2; - if (protocol && protocol.slice(-1) !== ":") { - protocol += ":"; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/queue-base.js +import { EventEmitter as EventEmitter2 } from "events"; +class QueueBase extends EventEmitter2 { + constructor(name, opts = { connection: {} }, Connection2 = RedisConnection, hasBlockingConnection = false) { + super(); + this.name = name; + this.opts = opts; + this.closed = false; + this.hasBlockingConnection = false; + this.hasBlockingConnection = hasBlockingConnection; + this.opts = Object.assign({ prefix: "bull" }, opts); + if (!name) { + throw new Error("Queue name must be provided"); + } + if (name.includes(":")) { + throw new Error("Queue name cannot contain :"); + } + this.connection = new Connection2(opts.connection, { + shared: isRedisInstance(opts.connection), + blocking: hasBlockingConnection, + skipVersionCheck: opts.skipVersionCheck, + skipWaitingForReady: opts.skipWaitingForReady + }); + this.connection.on("error", (error) => this.emit("error", error)); + this.connection.on("close", () => { + if (!this.closing) { + this.emit("ioredis:close"); + } + }); + const queueKeys = new QueueKeys(opts.prefix); + this.qualifiedName = queueKeys.getQueueQualifiedName(name); + this.keys = queueKeys.getKeys(name); + this.toKey = (type) => queueKeys.toKey(name, type); + this.createScripts(); } - if (port) { - hostname += `:${port}`; + get client() { + return this.connection.client; } - if (path2 && path2.charAt(0) !== "/") { - path2 = `/${path2}`; + createScripts() { + this.scripts = createScripts(this); } - let queryString = query ? import_querystring_builder.buildQueryString(query) : ""; - if (queryString && queryString[0] !== "?") { - queryString = `?${queryString}`; + get redisVersion() { + return this.connection.redisVersion; } - let auth = ""; - if (request2.username != null || request2.password != null) { - const username = request2.username ?? ""; - const password = request2.password ?? ""; - auth = `${username}:${password}@`; + get databaseType() { + return this.connection.databaseType; } - let fragment = ""; - if (request2.fragment) { - fragment = `#${request2.fragment}`; + get Job() { + return Job; } - return `${protocol}//${auth}${hostname}${path2}${queryString}${fragment}`; -} - -// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/getSignedUrl.js -var import_middleware_endpoint6 = __toESM(require_dist_cjs38(), 1); -var import_protocol_http12 = __toESM(require_dist_cjs2(), 1); - -// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/constants.js -var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; -var SHA256_HEADER = "X-Amz-Content-Sha256"; - -// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/presigner.js -class S3RequestPresigner { - signer; - constructor(options) { - const resolvedOptions = { - service: options.signingName || options.service || "s3", - uriEscapePath: options.uriEscapePath || false, - applyChecksum: options.applyChecksum || false, - ...options - }; - this.signer = new SignatureV4MultiRegion(resolvedOptions); + emit(event, ...args) { + try { + return super.emit(event, ...args); + } catch (err) { + try { + return super.emit("error", err); + } catch (err2) { + console.error(err2); + return false; + } + } } - presign(requestToSign, { unsignableHeaders = new Set, hoistableHeaders = new Set, unhoistableHeaders = new Set, ...options } = {}) { - this.prepareRequest(requestToSign, { - unsignableHeaders, - unhoistableHeaders, - hoistableHeaders - }); - return this.signer.presign(requestToSign, { - expiresIn: 900, - unsignableHeaders, - unhoistableHeaders, - ...options - }); + waitUntilReady() { + return this.client; } - presignWithCredentials(requestToSign, credentials, { unsignableHeaders = new Set, hoistableHeaders = new Set, unhoistableHeaders = new Set, ...options } = {}) { - this.prepareRequest(requestToSign, { - unsignableHeaders, - unhoistableHeaders, - hoistableHeaders - }); - return this.signer.presignWithCredentials(requestToSign, credentials, { - expiresIn: 900, - unsignableHeaders, - unhoistableHeaders, - ...options - }); + base64Name() { + return Buffer.from(this.name).toString("base64"); } - prepareRequest(requestToSign, { unsignableHeaders = new Set, unhoistableHeaders = new Set, hoistableHeaders = new Set } = {}) { - unsignableHeaders.add("content-type"); - Object.keys(requestToSign.headers).map((header) => header.toLowerCase()).filter((header) => header.startsWith("x-amz-server-side-encryption")).forEach((header) => { - if (!hoistableHeaders.has(header)) { - unhoistableHeaders.add(header); + clientName(suffix = "") { + const queueNameBase64 = this.base64Name(); + return `${this.opts.prefix}:${queueNameBase64}${suffix}`; + } + async close() { + if (!this.closing) { + this.closing = this.connection.close(); + } + await this.closing; + this.closed = true; + } + disconnect() { + return this.connection.disconnect(); + } + async checkConnectionError(fn, delayInMs = DELAY_TIME_5) { + try { + return await fn(); + } catch (error) { + if (isNotConnectionError(error)) { + this.emit("error", error); + } + if (!this.closing && delayInMs) { + await delay(delayInMs); + } else { + return; } - }); - requestToSign.headers[SHA256_HEADER] = UNSIGNED_PAYLOAD; - const currentHostHeader = requestToSign.headers.host; - const port = requestToSign.port; - const expectedHostHeader = `${requestToSign.hostname}${requestToSign.port != null ? ":" + port : ""}`; - if (!currentHostHeader || currentHostHeader === requestToSign.hostname && requestToSign.port != null) { - requestToSign.headers.host = expectedHostHeader; } } + trace(spanKind, operation, destination, callback, srcPropagationMetadata) { + return trace(this.opts.telemetry, spanKind, this.name, operation, destination, callback, srcPropagationMetadata); + } } -// node_modules/.pnpm/@aws-sdk+s3-request-presigner@3.1032.0/node_modules/@aws-sdk/s3-request-presigner/dist-es/getSignedUrl.js -var getSignedUrl = async (client, command, options = {}) => { - let s3Presigner; - let region; - if (typeof client.config.endpointProvider === "function") { - const endpointV2 = await import_middleware_endpoint6.getEndpointFromInstructions(command.input, command.constructor, client.config); - const authScheme = endpointV2.properties?.authSchemes?.[0]; - if (authScheme?.name === "sigv4a") { - region = authScheme?.signingRegionSet?.join(","); - } else { - region = authScheme?.signingRegion; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/job-scheduler.js +class JobScheduler extends QueueBase { + constructor(name, opts, Connection2) { + super(name, opts, Connection2); + this.repeatStrategy = opts.settings && opts.settings.repeatStrategy || defaultRepeatStrategy; + } + async upsertJobScheduler(jobSchedulerId, repeatOpts, jobName, jobData, opts, { override, producerId }) { + const { every, limit, pattern, offset } = repeatOpts; + if (pattern && every) { + throw new Error("Both .pattern and .every options are defined for this repeatable job"); } - s3Presigner = new S3RequestPresigner({ - ...client.config, - signingName: authScheme?.signingName, - region: async () => region + if (!pattern && !every) { + throw new Error("Either .pattern or .every options must be defined for this repeatable job"); + } + if (repeatOpts.immediately && repeatOpts.startDate) { + throw new Error("Both .immediately and .startDate options are defined for this repeatable job"); + } + if (repeatOpts.immediately && repeatOpts.every) { + console.warn("Using option immediately with every does not affect the job's schedule. Job will run immediately anyway."); + } + const iterationCount = repeatOpts.count ? repeatOpts.count + 1 : 1; + if (typeof repeatOpts.limit !== "undefined" && iterationCount > repeatOpts.limit) { + return; + } + let now = Date.now(); + const { endDate } = repeatOpts; + if (endDate && now > new Date(endDate).getTime()) { + return; + } + const prevMillis = opts.prevMillis || 0; + now = prevMillis < now ? now : prevMillis; + const { immediately } = repeatOpts, filteredRepeatOpts = __rest(repeatOpts, ["immediately"]); + let nextMillis; + const newOffset = null; + if (pattern) { + nextMillis = await this.repeatStrategy(now, repeatOpts, jobName); + if (nextMillis < now) { + nextMillis = now; + } + } + if (nextMillis || every) { + return this.trace(SpanKind.PRODUCER, "add", `${this.name}.${jobName}`, async (span, srcPropagationMetadata) => { + var _a, _b; + let telemetry = opts.telemetry; + if (srcPropagationMetadata) { + const omitContext = (_a = opts.telemetry) === null || _a === undefined ? undefined : _a.omitContext; + const telemetryMetadata = ((_b = opts.telemetry) === null || _b === undefined ? undefined : _b.metadata) || !omitContext && srcPropagationMetadata; + if (telemetryMetadata || omitContext) { + telemetry = { + metadata: telemetryMetadata, + omitContext + }; + } + } + const mergedOpts = this.getNextJobOpts(nextMillis, jobSchedulerId, Object.assign(Object.assign({}, opts), { repeat: filteredRepeatOpts, telemetry }), iterationCount, newOffset); + if (override) { + if (nextMillis < now) { + nextMillis = now; + } + const [jobId, delay2] = await this.scripts.addJobScheduler(jobSchedulerId, nextMillis, JSON.stringify(typeof jobData === "undefined" ? {} : jobData), Job.optsAsJSON(opts), { + name: jobName, + startDate: repeatOpts.startDate ? new Date(repeatOpts.startDate).getTime() : undefined, + endDate: endDate ? new Date(endDate).getTime() : undefined, + tz: repeatOpts.tz, + pattern, + every, + limit, + offset: newOffset + }, Job.optsAsJSON(mergedOpts), producerId); + const numericDelay = typeof delay2 === "string" ? parseInt(delay2, 10) : delay2; + const job = new this.Job(this, jobName, jobData, Object.assign(Object.assign({}, mergedOpts), { delay: numericDelay }), jobId); + job.id = jobId; + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobSchedulerId]: jobSchedulerId, + [TelemetryAttributes.JobId]: job.id + }); + return job; + } else { + const jobId = await this.scripts.updateJobSchedulerNextMillis(jobSchedulerId, nextMillis, JSON.stringify(typeof jobData === "undefined" ? {} : jobData), Job.optsAsJSON(mergedOpts), producerId); + if (jobId) { + const job = new this.Job(this, jobName, jobData, mergedOpts, jobId); + job.id = jobId; + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobSchedulerId]: jobSchedulerId, + [TelemetryAttributes.JobId]: job.id + }); + return job; + } + } + }); + } + } + getNextJobOpts(nextMillis, jobSchedulerId, opts, currentCount, offset) { + var _a, _b; + const jobId = this.getSchedulerNextJobId({ + jobSchedulerId, + nextMillis }); - } else { - s3Presigner = new S3RequestPresigner(client.config); + const now = Date.now(); + const delay2 = nextMillis + offset - now; + const mergedOpts = Object.assign(Object.assign({}, opts), { jobId, delay: delay2 < 0 ? 0 : delay2, timestamp: now, prevMillis: nextMillis, repeatJobKey: jobSchedulerId }); + mergedOpts.repeat = Object.assign(Object.assign({}, opts.repeat), { offset, count: currentCount, startDate: ((_a = opts.repeat) === null || _a === undefined ? undefined : _a.startDate) ? new Date(opts.repeat.startDate).getTime() : undefined, endDate: ((_b = opts.repeat) === null || _b === undefined ? undefined : _b.endDate) ? new Date(opts.repeat.endDate).getTime() : undefined }); + return mergedOpts; } - const presignInterceptMiddleware = (next, context) => async (args) => { - const { request: request2 } = args; - if (!import_protocol_http12.HttpRequest.isInstance(request2)) { - throw new Error("Request to be presigned is not an valid HTTP request."); + async removeJobScheduler(jobSchedulerId) { + return this.scripts.removeJobScheduler(jobSchedulerId); + } + async getSchedulerData(client, key, next) { + const jobData = await client.hgetall(this.toKey("repeat:" + key)); + return this.transformSchedulerData(key, jobData, next); + } + transformSchedulerData(key, jobData, next) { + if (jobData && Object.keys(jobData).length > 0) { + const jobSchedulerData = { + key, + name: jobData.name, + next + }; + if (jobData.ic) { + jobSchedulerData.iterationCount = parseInt(jobData.ic); + } + if (jobData.limit) { + jobSchedulerData.limit = parseInt(jobData.limit); + } + if (jobData.startDate) { + jobSchedulerData.startDate = parseInt(jobData.startDate); + } + if (jobData.endDate) { + jobSchedulerData.endDate = parseInt(jobData.endDate); + } + if (jobData.tz) { + jobSchedulerData.tz = jobData.tz; + } + if (jobData.pattern) { + jobSchedulerData.pattern = jobData.pattern; + } + if (jobData.every) { + jobSchedulerData.every = parseInt(jobData.every); + } + if (jobData.offset) { + jobSchedulerData.offset = parseInt(jobData.offset); + } + if (jobData.data || jobData.opts) { + jobSchedulerData.template = this.getTemplateFromJSON(jobData.data, jobData.opts); + } + return jobSchedulerData; } - delete request2.headers["amz-sdk-invocation-id"]; - delete request2.headers["amz-sdk-request"]; - delete request2.headers["x-amz-user-agent"]; - let presigned2; - const presignerOptions = { - ...options, - signingRegion: options.signingRegion ?? context["signing_region"] ?? region, - signingService: options.signingService ?? context["signing_service"] - }; - if (context.s3ExpressIdentity) { - presigned2 = await s3Presigner.presignWithCredentials(request2, context.s3ExpressIdentity, presignerOptions); - } else { - presigned2 = await s3Presigner.presign(request2, presignerOptions); + if (key.includes(":")) { + return this.keyToData(key, next); } - return { - response: {}, - output: { - $metadata: { httpStatusCode: 200 }, - presigned: presigned2 - } - }; - }; - const middlewareName = "presignInterceptMiddleware"; - const clientStack = client.middlewareStack.clone(); - clientStack.addRelativeTo(presignInterceptMiddleware, { - name: middlewareName, - relation: "before", - toMiddleware: "awsAuthMiddleware", - override: true - }); - const handler = command.resolveMiddleware(clientStack, client.config, {}); - const { output } = await handler({ input: command.input }); - const { presigned } = output; - return formatUrl(presigned); -}; - -// src/config/index.js -var import_dotenv2 = __toESM(require_main(), 1); -import_dotenv2.default.config({}); -var envSchema2 = create$3({ - API_VERSION: create$6().required(), - ACCESS_TOKEN_EXPIRY: create$6().required(), - ACCESS_TOKEN_SECRET: create$6().required(), - REFRESH_TOKEN_EXPIRY: create$6().required(), - REFRESH_TOKEN_SECRET: create$6().required(), - PORT: create$5().default(5000), - DATABASE_URL: create$6().required(), - MONGO_URI: create$6().required(), - CLIENT_URL: create$6().required(), - VITE_API_URL: create$6().required(), - AWS_ACCESS_KEY_ID: create$6().required(), - AWS_SECRET_ACCESS_KEY: create$6().required(), - AWS_REGION: create$6().required(), - AWS_BUCKET_NAME: create$6().required(), - CLOUDINARY_API_KEY: create$6().required(), - CLOUDINARY_API_SECRET: create$6().required(), - GOOGLE_CLIENT_ID: create$6().required(), - GOOGLE_CLIENT_SECRET: create$6().required(), - GOOGLE_CALLBACK_URL: create$6().required(), - GEMINI_API_KEY: create$6().required(), - MURF_API_KEY: create$6().required(), - REDIS_HOST: create$6().required(), - REDIS_PORT: create$5().required(), - REDIS_URL: create$6().required(), - REDIS_USER: create$6().required(), - ALLOWED_ORIGINS: create$6().required(), - SMTP_VERIFY_URL: create$6().required(), - EMAIL_FROM: create$6().required(), - EMAIL_HOST: create$6().required(), - EMAIL_PORT: create$5().required(), - EMAIL_USER: create$6().required(), - EMAIL_PASS: create$6().required(), - IDEMPOTENCY_SUBMIT_TTL_SEC: create$5().required() -}); -var parsedEnv2 = envSchema2.validateSync(process.env, { - abortEarly: false, - stripUnknown: true -}); -var env2 = parsedEnv2; -var config_default2 = env2; - -// src/services/aws.service.js -var s3Client = new S3Client({ - region: config_default2.AWS_REGION, - credentials: { - accessKeyId: config_default2.AWS_ACCESS_KEY_ID, - secretAccessKey: config_default2.AWS_SECRET_ACCESS_KEY } -}); -async function generateUploadURL(key, filename) { - const params = new PutObjectCommand({ - Bucket: config_default2.AWS_BUCKET_NAME, - Key: `${key}/${filename}`, - ContentType: "application/json" - }); - const url = await getSignedUrl(s3Client, params, { expiresIn: 3600 }); - return url; -} -var streamToString = (stream) => new Promise((resolve, reject) => { - const chunks = []; - stream.on("data", (chunk) => chunks.push(chunk)); - stream.on("error", reject); - stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8"))); -}); -async function fetchTestcasesFromS3(s3Key) { + keyToData(key, next) { + const data = key.split(":"); + const pattern = data.slice(4).join(":") || null; + return { + key, + name: data[0], + id: data[1] || null, + endDate: parseInt(data[2]) || null, + tz: data[3] || null, + pattern, + next + }; + } + async isJobScheduler(id) { + const client = await this.client; + const exists2 = await client.hexists(`${this.keys.repeat}:${id}`, "ic"); + return exists2 === 1; + } + async getScheduler(id) { + const [rawJobData, next] = await this.scripts.getJobScheduler(id); + return this.transformSchedulerData(id, rawJobData ? array2obj(rawJobData) : null, next ? parseInt(next) : null); + } + getTemplateFromJSON(rawData, rawOpts) { + const template = {}; + if (rawData) { + template.data = JSON.parse(rawData); + } + if (rawOpts) { + template.opts = Job.optsFromJSON(rawOpts); + } + return template; + } + async getJobSchedulers(start = 0, end = -1, asc2 = false) { + const client = await this.client; + const jobSchedulersKey = this.keys.repeat; + const result = asc2 ? await client.zrange(jobSchedulersKey, start, end, "WITHSCORES") : await client.zrevrange(jobSchedulersKey, start, end, "WITHSCORES"); + const jobs = []; + for (let i2 = 0;i2 < result.length; i2 += 2) { + jobs.push(this.getSchedulerData(client, result[i2], parseInt(result[i2 + 1]))); + } + return Promise.all(jobs); + } + async getSchedulersCount() { + const jobSchedulersKey = this.keys.repeat; + const client = await this.client; + return client.zcard(jobSchedulersKey); + } + getSchedulerNextJobId({ nextMillis, jobSchedulerId }) { + return `repeat:${jobSchedulerId}:${nextMillis}`; + } +} +var defaultRepeatStrategy = (millis, opts) => { + const { pattern } = opts; + const dateFromMillis = new Date(millis); + const startDate = opts.startDate && new Date(opts.startDate); + const currentDate = startDate > dateFromMillis ? startDate : dateFromMillis; + const interval3 = import_cron_parser.parseExpression(pattern, Object.assign(Object.assign({}, opts), { currentDate })); try { - const command = new GetObjectCommand({ - Bucket: config_default2.AWS_BUCKET_NAME, - Key: s3Key + if (opts.immediately) { + return new Date().getTime(); + } else { + return interval3.next().getTime(); + } + } catch (e3) {} +}; +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/queue-getters.js +class QueueGetters extends QueueBase { + getJob(jobId) { + return this.Job.fromId(this, jobId); + } + commandByType(types6, count2, callback) { + return types6.map((type) => { + type = type === "waiting" ? "wait" : type; + const key = this.toKey(type); + switch (type) { + case "completed": + case "failed": + case "delayed": + case "prioritized": + case "repeat": + case "waiting-children": + return callback(key, count2 ? "zcard" : "zrange"); + case "active": + case "wait": + case "paused": + return callback(key, count2 ? "llen" : "lrange"); + } }); - const response = await s3Client.send(command); - const jsonString = await streamToString(response.Body); - const data = JSON.parse(jsonString); - return data; - } catch (err) { - console.error("Error fetching testcases:", err); - return null; } -} -async function fetchFileFromS3(s3Key) { - try { - const command = new GetObjectCommand({ - Bucket: config_default2.AWS_BUCKET_NAME, - Key: s3Key - }); - const response = await s3Client.send(command); - const text2 = await streamToString(response.Body); - return text2; - } catch (err) { - console.error("Error fetching file from S3:", err); + sanitizeJobTypes(types6) { + const currentTypes = typeof types6 === "string" ? [types6] : types6; + if (Array.isArray(currentTypes) && currentTypes.length > 0) { + const sanitizedTypes = [...currentTypes]; + if (sanitizedTypes.indexOf("waiting") !== -1) { + sanitizedTypes.push("paused"); + } + return [...new Set(sanitizedTypes)]; + } + return [ + "active", + "completed", + "delayed", + "failed", + "paused", + "prioritized", + "waiting", + "waiting-children" + ]; + } + async count() { + const count2 = await this.getJobCountByTypes("waiting", "paused", "delayed", "prioritized", "waiting-children"); + return count2; + } + async getRateLimitTtl(maxJobs) { + return this.scripts.getRateLimitTtl(maxJobs); + } + async getDebounceJobId(id) { + const client = await this.client; + return client.get(`${this.keys.de}:${id}`); + } + async getDeduplicationJobId(id) { + const client = await this.client; + return client.get(`${this.keys.de}:${id}`); + } + async getGlobalConcurrency() { + const client = await this.client; + const concurrency = await client.hget(this.keys.meta, "concurrency"); + if (concurrency) { + return Number(concurrency); + } return null; } -} - -// src/api/problem/problem-service.ts -var handleCreateProblem = async (userId, input) => { - await verifyProblemCreationPermission(userId); - try { - const existingProblem = await db.select().from(problem).where(eq(problem.slug, input.slug)); - if (existingProblem.length > 0) { - throw new ApiError_default("Problem already exists", E.BAD_REQUEST); + async getGlobalRateLimit() { + const client = await this.client; + const [max, duration] = await client.hmget(this.keys.meta, "max", "duration"); + if (max && duration) { + return { + max: Number(max), + duration: Number(duration) + }; } - const problemId = createId(); - const key = `problems/${problemId}`; - const testcasePromises = Array.from({ length: input.testcases }).map((_, i2) => { - const fileName = `testcase_${i2}.json`; - return generateUploadURL(key, fileName).then((url) => ({ - url, - fileName, - order: i2, - isSample: false, - isHidden: i2 >= Math.min(3, input.testcases) - })); - }); - const samplePromises = Array.from({ length: input.sampleTestcases }).map((_, i2) => { - const fileName = `sampleTestcase_${i2}.json`; - return generateUploadURL(key, fileName).then((url) => ({ - url, - fileName, - order: i2, - isSample: true, - isHidden: false - })); + return null; + } + async getJobCountByTypes(...types6) { + const result = await this.getJobCounts(...types6); + return Object.values(result).reduce((sum, count2) => sum + count2, 0); + } + async getJobCounts(...types6) { + const currentTypes = this.sanitizeJobTypes(types6); + const responses = await this.scripts.getCounts(currentTypes); + const counts = {}; + responses.forEach((res, index3) => { + counts[currentTypes[index3]] = res || 0; }); - const allTestData = await Promise.all([...testcasePromises, ...samplePromises]); - const uploadUrls = allTestData.map((d2) => d2.url); - await db.transaction(async (tx) => { - await tx.insert(problem).values({ - id: problemId, - title: input.title, - description: input.description, - slug: input.slug, - difficulty: input.difficulty, - authorId: userId, - inputFormat: input.inputFormat, - outputFormat: input.outputFormat, - constraints: input.constraints, - timeLimit: input.timeLimit, - memoryLimit: input.memoryLimit - }); - await tx.insert(editorial).values({ - problemId, - contentS3Key: `${key}/content.md`, - solutionS3Key: `${key}/solution.md`, - editorialLink: input.editorialLink - }); - if (input.tags && input.tags.length > 0) { - const uniqueTagNames = [...new Set(input.tags)]; - const tagIds = []; - for (const tagName of uniqueTagNames) { - const insertedTag = await tx.insert(tag).values({ name: tagName }).onConflictDoUpdate({ - target: tag.name, - set: { name: tagName } - }).returning({ id: tag.id }); - tagIds.push(insertedTag[0].id); - } - if (tagIds.length > 0) { - await tx.insert(problemTag).values(tagIds.map((tagId) => ({ - problemId, - tagId - }))).onConflictDoNothing(); - } - } - if (allTestData.length > 0) { - await tx.insert(testcase).values(allTestData.map((td) => ({ - problemId, - order: td.order, - isHidden: td.isHidden, - s3Key: `${key}/${td.fileName}`, - isSample: td.isSample - }))); + return counts; + } + async recordJobCountsMetric(...types6) { + var _a; + const counts = await this.getJobCounts(...types6); + const meter = (_a = this.opts.telemetry) === null || _a === undefined ? undefined : _a.meter; + if (meter && typeof meter.createGauge === "function") { + const gauge = meter.createGauge(MetricNames.QueueJobsCount, { + description: "Number of jobs in the queue by state", + unit: "{jobs}" + }); + for (const [state, jobCount] of Object.entries(counts)) { + gauge.record(jobCount, { + [TelemetryAttributes.QueueName]: this.name, + [TelemetryAttributes.QueueJobsState]: state + }); } - }); - return { - message: "Problem created successfully", - problemId, - uploadUrls, - uploadContentUrl: await generateUploadURL(key, "content.md"), - uploadSolutionUrl: await generateUploadURL(key, "solution.md") - }; - } catch (error) { - if (error instanceof ApiError_default) { - throw error; } - console.error("Error creating problem:", error); - throw new ApiError_default("Failed to create problem", E.INTERNAL_SERVER_ERROR); + return counts; } -}; -var handleFinalizeProblem = async (userId, problemId) => { - try { - const problemResult = await db.select().from(problem).where(eq(problem.id, problemId)); - if (problemResult.length === 0) { - throw new ApiError_default("Problem not found", E.NOT_FOUND); - } - if (problemResult[0].authorId !== userId) { - throw new ApiError_default("You do not have permission to finalize this problem", E.FORBIDDEN); + getJobState(jobId) { + return this.scripts.getState(jobId); + } + async getMeta() { + const client = await this.client; + const config = await client.hgetall(this.keys.meta); + const { concurrency, max, duration, paused, "opts.maxLenEvents": maxLenEvents } = config, rest = __rest(config, ["concurrency", "max", "duration", "paused", "opts.maxLenEvents"]); + const parsedConfig = rest; + if (concurrency) { + parsedConfig["concurrency"] = Number(concurrency); } - const testcasesResult = await db.select().from(testcase).where(eq(testcase.problemId, problemId)); - if (testcasesResult.length === 0) { - throw new ApiError_default("No testcases found. Please upload testcases before finalizing.", E.BAD_REQUEST); + if (maxLenEvents) { + parsedConfig["maxLenEvents"] = Number(maxLenEvents); } - const sampleTestcases = testcasesResult.filter((tc) => tc.isSample); - const hiddenTestcases = testcasesResult.filter((tc) => !tc.isSample); - if (sampleTestcases.length === 0) { - throw new ApiError_default("At least one sample testcase is required.", E.BAD_REQUEST); + if (max) { + parsedConfig["max"] = Number(max); } - if (hiddenTestcases.length === 0) { - throw new ApiError_default("At least one hidden testcase is required.", E.BAD_REQUEST); + if (duration) { + parsedConfig["duration"] = Number(duration); } - await Promise.all(testcasesResult.map(async (tc) => { - const response = await fetchTestcasesFromS3(tc.s3Key); - if (!response) { - throw new ApiError_default(`Testcase file not found in storage: ${tc.s3Key}`, E.BAD_REQUEST); + parsedConfig["paused"] = paused === "1"; + return parsedConfig; + } + getCompletedCount() { + return this.getJobCountByTypes("completed"); + } + getFailedCount() { + return this.getJobCountByTypes("failed"); + } + getDelayedCount() { + return this.getJobCountByTypes("delayed"); + } + getActiveCount() { + return this.getJobCountByTypes("active"); + } + getPrioritizedCount() { + return this.getJobCountByTypes("prioritized"); + } + async getCountsPerPriority(priorities) { + const uniquePriorities = [...new Set(priorities)]; + const responses = await this.scripts.getCountsPerPriority(uniquePriorities); + const counts = {}; + responses.forEach((res, index3) => { + counts[`${uniquePriorities[index3]}`] = res || 0; + }); + return counts; + } + getWaitingCount() { + return this.getJobCountByTypes("waiting"); + } + getWaitingChildrenCount() { + return this.getJobCountByTypes("waiting-children"); + } + getWaiting(start = 0, end = -1) { + return this.getJobs(["waiting"], start, end, true); + } + getWaitingChildren(start = 0, end = -1) { + return this.getJobs(["waiting-children"], start, end, true); + } + getActive(start = 0, end = -1) { + return this.getJobs(["active"], start, end, true); + } + getDelayed(start = 0, end = -1) { + return this.getJobs(["delayed"], start, end, true); + } + getPrioritized(start = 0, end = -1) { + return this.getJobs(["prioritized"], start, end, true); + } + getCompleted(start = 0, end = -1) { + return this.getJobs(["completed"], start, end, false); + } + getFailed(start = 0, end = -1) { + return this.getJobs(["failed"], start, end, false); + } + async getDependencies(parentId, type, start, end) { + const key = this.toKey(type == "processed" ? `${parentId}:processed` : `${parentId}:dependencies`); + const { items, total, jobs } = await this.scripts.paginate(key, { + start, + end, + fetchJobs: true + }); + return { + items, + jobs, + total + }; + } + async getRanges(types6, start = 0, end = 1, asc2 = false) { + const multiCommands = []; + this.commandByType(types6, false, (key, command) => { + switch (command) { + case "lrange": + multiCommands.push("lrange"); + break; + case "zrange": + multiCommands.push("zrange"); + break; } - })); - const editorialResult = await db.select({ - solutionS3Key: editorial.solutionS3Key, - contentS3Key: editorial.contentS3Key - }).from(editorial).where(eq(editorial.problemId, problemId)).limit(1); - if (editorialResult.length === 0) { - throw new ApiError_default("Editorial not found. Please upload editorial before finalizing.", E.BAD_REQUEST); - } - const editorialData = editorialResult[0]; - const contentResponse = await fetchTestcasesFromS3(editorialData.contentS3Key); - if (!contentResponse) { - throw new ApiError_default("Content file not found in storage: /content.md", E.BAD_REQUEST); + }); + const responses = await this.scripts.getRanges(types6, start, end, asc2); + let results = []; + responses.forEach((response, index3) => { + const result = response || []; + if (asc2 && multiCommands[index3] === "lrange") { + results = results.concat(result.reverse()); + } else { + results = results.concat(result); + } + }); + return [...new Set(results)]; + } + async getJobs(types6, start = 0, end = -1, asc2 = false) { + const currentTypes = this.sanitizeJobTypes(types6); + const jobIds = await this.getRanges(currentTypes, start, end, asc2); + return Promise.all(jobIds.map((jobId) => this.Job.fromId(this, jobId))); + } + async getJobLogs(jobId, start = 0, end = -1, asc2 = true) { + const client = await this.client; + const multi = client.multi(); + const logsKey = this.toKey(jobId + ":logs"); + if (asc2) { + multi.lrange(logsKey, start, end); + } else { + multi.lrange(logsKey, -(end + 1), -(start + 1)); } - const solutionResponse = await fetchTestcasesFromS3(editorialData.solutionS3Key); - if (!solutionResponse) { - throw new ApiError_default("Solution file not found in storage: /solution.md", E.BAD_REQUEST); + multi.llen(logsKey); + const result = await multi.exec(); + if (!asc2) { + result[0][1].reverse(); } - await db.update(problem).set({ - status: "DONE" - }).where(eq(problem.id, problemId)); return { - message: "Problem finalized successfully", - status: true + logs: result[0][1], + count: result[1][1] }; - } catch (error) { - if (error instanceof ApiError_default) { - throw error; - } - console.error("Error finalizing problem:", error); - throw new ApiError_default("Failed to finalize problem", E.INTERNAL_SERVER_ERROR); } -}; -var handleGetProblems = async (input) => { - try { - let cursorCreatedAt = null; - let cursorId = null; - if (input.cursor) { - try { - const decoded = Buffer.from(input.cursor, "base64").toString("utf-8"); - const [timeStr, id] = decoded.split(":"); - cursorCreatedAt = new Date(parseInt(timeStr)); - cursorId = id; - } catch (e3) { - throw new ApiError_default("Invalid cursor", E.BAD_REQUEST); + async baseGetClients(matcher) { + const client = await this.client; + try { + if (client.isCluster) { + const clusterNodes = client.nodes(); + const clientsPerNode = []; + for (let nodeIndex = 0;nodeIndex < clusterNodes.length; nodeIndex++) { + const node = clusterNodes[nodeIndex]; + const clients = await node.client("LIST"); + const list = this.parseClientList(clients, matcher); + clientsPerNode.push(list); + } + const clientsFromNodeWithMostConnections = clientsPerNode.reduce((prev, current) => { + return prev.length > current.length ? prev : current; + }, []); + return clientsFromNodeWithMostConnections; + } else { + const clients = await client.client("LIST"); + const list = this.parseClientList(clients, matcher); + return list; + } + } catch (err) { + if (!clientCommandMessageReg.test(err.message)) { + throw err; } + return [{ name: "GCP does not support client list" }]; } - const problemsResult = await db.select({ - id: problem.id, - title: problem.title, - description: problem.description, - slug: problem.slug, - difficulty: problem.difficulty, - createdAt: problem.createdAt, - updatedAt: problem.updatedAt - }).from(problem).where(and(eq(problem.status, "DONE"), cursorCreatedAt && cursorId ? or(lt(problem.createdAt, cursorCreatedAt), and(eq(problem.createdAt, cursorCreatedAt), lt(problem.id, cursorId))) : undefined)).limit(input.limit + 1).orderBy(desc(problem.createdAt), desc(problem.id)); - const hasNextPage = problemsResult.length > input.limit; - const problems = hasNextPage ? problemsResult.slice(0, input.limit) : problemsResult; - let nextCursor = null; - if (hasNextPage && problems.length > 0) { - const lastProblem = problems[problems.length - 1]; - const time2 = lastProblem.createdAt.getTime(); - nextCursor = Buffer.from(`${time2}:${lastProblem.id}`).toString("base64"); + } + getWorkers() { + const unnamedWorkerClientName = `${this.clientName()}`; + const namedWorkerClientName = `${this.clientName()}:w:`; + const matcher = (name) => name && (name === unnamedWorkerClientName || name.startsWith(namedWorkerClientName)); + return this.baseGetClients(matcher); + } + async getWorkersCount() { + const workers = await this.getWorkers(); + return workers.length; + } + async getQueueEvents() { + const clientName = `${this.clientName()}${QUEUE_EVENT_SUFFIX}`; + return this.baseGetClients((name) => name === clientName); + } + async getMetrics(type, start = 0, end = -1) { + const [meta, data, count2] = await this.scripts.getMetrics(type, start, end); + return { + meta: { + count: parseInt(meta[0] || "0", 10), + prevTS: parseInt(meta[1] || "0", 10), + prevCount: parseInt(meta[2] || "0", 10) + }, + data: data.map((point3) => +point3 || 0), + count: count2 + }; + } + parseClientList(list, matcher) { + const lines = list.split(/\r?\n/); + const clients = []; + lines.forEach((line3) => { + const client = {}; + const keyValues = line3.split(" "); + keyValues.forEach(function(keyValue) { + const index3 = keyValue.indexOf("="); + const key = keyValue.substring(0, index3); + const value = keyValue.substring(index3 + 1); + client[key] = value; + }); + const name = client["name"]; + if (matcher(name)) { + client["name"] = this.name; + client["rawname"] = name; + clients.push(client); + } + }); + return clients; + } + async exportPrometheusMetrics(globalVariables) { + const counts = await this.getJobCounts(); + const metrics = []; + metrics.push("# HELP bullmq_job_count Number of jobs in the queue by state"); + metrics.push("# TYPE bullmq_job_count gauge"); + const variables = !globalVariables ? "" : Object.keys(globalVariables).reduce((acc, curr) => `${acc}, ${curr}="${globalVariables[curr]}"`, ""); + for (const [state, count2] of Object.entries(counts)) { + metrics.push(`bullmq_job_count{queue="${this.name}", state="${state}"${variables}} ${count2}`); + } + return metrics.join(` +`); + } +} +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/repeat.js +var import_cron_parser2 = __toESM(require_parser3(), 1); +import { createHash as createHash2 } from "crypto"; +class Repeat extends QueueBase { + constructor(name, opts, Connection2) { + super(name, opts, Connection2); + this.repeatStrategy = opts.settings && opts.settings.repeatStrategy || getNextMillis; + this.repeatKeyHashAlgorithm = opts.settings && opts.settings.repeatKeyHashAlgorithm || "md5"; + } + async updateRepeatableJob(name, data, opts, { override }) { + var _a, _b; + const repeatOpts = Object.assign({}, opts.repeat); + (_a = repeatOpts.pattern) !== null && _a !== undefined || (repeatOpts.pattern = repeatOpts.cron); + delete repeatOpts.cron; + const iterationCount = repeatOpts.count ? repeatOpts.count + 1 : 1; + if (typeof repeatOpts.limit !== "undefined" && iterationCount > repeatOpts.limit) { + return; } - if (problems.length === 0) { - return { problems: [], nextCursor: null }; + let now = Date.now(); + const { endDate } = repeatOpts; + if (endDate && now > new Date(endDate).getTime()) { + return; } - const problemIds = problems.map((p2) => p2.id); - const tagsResult = await db.select({ - problemId: problemTag.problemId, - tagName: tag.name - }).from(problemTag).innerJoin(tag, eq(problemTag.tagId, tag.id)).where(inArray(problemTag.problemId, problemIds)); - const assembledProblems = problems.map((p2) => { - const pTags = tagsResult.filter((t9) => t9.problemId === p2.id).map((t9) => t9.tagName); - return { - ...p2, - tags: pTags - }; - }); - return { - problems: assembledProblems, - nextCursor - }; - } catch (error) { - if (error instanceof ApiError_default) { - throw error; + const prevMillis = opts.prevMillis || 0; + now = prevMillis < now ? now : prevMillis; + const nextMillis = await this.repeatStrategy(now, repeatOpts, name); + const { every, pattern } = repeatOpts; + const hasImmediately = Boolean((every || pattern) && repeatOpts.immediately); + const offset = hasImmediately && every ? now - nextMillis : undefined; + if (nextMillis) { + if (!prevMillis && opts.jobId) { + repeatOpts.jobId = opts.jobId; + } + const legacyRepeatKey = getRepeatConcatOptions(name, repeatOpts); + const newRepeatKey = (_b = opts.repeat.key) !== null && _b !== undefined ? _b : this.hash(legacyRepeatKey); + let repeatJobKey; + if (override) { + repeatJobKey = await this.scripts.addRepeatableJob(newRepeatKey, nextMillis, { + name, + endDate: endDate ? new Date(endDate).getTime() : undefined, + tz: repeatOpts.tz, + pattern, + every + }, legacyRepeatKey); + } else { + const client = await this.client; + repeatJobKey = await this.scripts.updateRepeatableJobMillis(client, newRepeatKey, nextMillis, legacyRepeatKey); + } + const { immediately } = repeatOpts, filteredRepeatOpts = __rest(repeatOpts, ["immediately"]); + return this.createNextJob(name, nextMillis, repeatJobKey, Object.assign(Object.assign({}, opts), { repeat: Object.assign({ offset }, filteredRepeatOpts) }), data, iterationCount, hasImmediately); } - console.error("Error fetching problems:", error); - throw new ApiError_default("Failed to fetch problems", E.INTERNAL_SERVER_ERROR); } -}; -var handleGetProblemById = async (problemId) => { - try { - const problemResult = await db.select().from(problem).where(and(eq(problem.id, problemId), eq(problem.status, "DONE"))).limit(1); - if (problemResult.length === 0) { - throw new ApiError_default("Problem not found", E.NOT_FOUND); + async createNextJob(name, nextMillis, repeatJobKey, opts, data, currentCount, hasImmediately) { + const jobId = this.getRepeatJobKey(name, nextMillis, repeatJobKey, data); + const now = Date.now(); + const delay2 = nextMillis + (opts.repeat.offset ? opts.repeat.offset : 0) - now; + const mergedOpts = Object.assign(Object.assign({}, opts), { jobId, delay: delay2 < 0 || hasImmediately ? 0 : delay2, timestamp: now, prevMillis: nextMillis, repeatJobKey }); + mergedOpts.repeat = Object.assign(Object.assign({}, opts.repeat), { count: currentCount }); + return this.Job.create(this, name, data, mergedOpts); + } + getRepeatJobKey(name, nextMillis, repeatJobKey, data) { + if (repeatJobKey.split(":").length > 2) { + return this.getRepeatJobId({ + name, + nextMillis, + namespace: this.hash(repeatJobKey), + jobId: data === null || data === undefined ? undefined : data.id + }); } - const p2 = problemResult[0]; - const tagsResult = await db.select({ - tagName: tag.name - }).from(problemTag).innerJoin(tag, eq(problemTag.tagId, tag.id)).where(eq(problemTag.problemId, problemId)); - const testcasesResult = await db.select({ - id: testcase.id, - order: testcase.order, - s3Key: testcase.s3Key - }).from(testcase).where(and(eq(testcase.problemId, problemId), eq(testcase.isSample, true))); - const sampleTestcases = await Promise.all(testcasesResult.map(async (tc) => { - const response = await fetchTestcasesFromS3(tc.s3Key); - if (!response) { - throw new ApiError_default("Testcase file not found: " + tc.s3Key, E.INTERNAL_SERVER_ERROR); - } + return this.getRepeatDelayedJobId({ + customKey: repeatJobKey, + nextMillis + }); + } + async removeRepeatable(name, repeat, jobId) { + var _a; + const repeatConcatOptions = getRepeatConcatOptions(name, Object.assign(Object.assign({}, repeat), { jobId })); + const repeatJobKey = (_a = repeat.key) !== null && _a !== undefined ? _a : this.hash(repeatConcatOptions); + const legacyRepeatJobId = this.getRepeatJobId({ + name, + nextMillis: "", + namespace: this.hash(repeatConcatOptions), + jobId: jobId !== null && jobId !== undefined ? jobId : repeat.jobId, + key: repeat.key + }); + return this.scripts.removeRepeatable(legacyRepeatJobId, repeatConcatOptions, repeatJobKey); + } + async removeRepeatableByKey(repeatJobKey) { + const data = this.keyToData(repeatJobKey); + const legacyRepeatJobId = this.getRepeatJobId({ + name: data.name, + nextMillis: "", + namespace: this.hash(repeatJobKey), + jobId: data.id + }); + return this.scripts.removeRepeatable(legacyRepeatJobId, "", repeatJobKey); + } + async getRepeatableData(client, key, next) { + const jobData = await client.hgetall(this.toKey("repeat:" + key)); + if (jobData) { return { - id: tc.id, - order: tc.order, - input: response.input, - output: response.output + key, + name: jobData.name, + endDate: parseInt(jobData.endDate) || null, + tz: jobData.tz || null, + pattern: jobData.pattern || null, + every: jobData.every || null, + next }; - })); + } + return this.keyToData(key, next); + } + keyToData(key, next) { + const data = key.split(":"); + const pattern = data.slice(4).join(":") || null; return { - ...p2, - difficulty: p2.difficulty, - tags: tagsResult.map((t9) => t9.tagName), - sampleTestcases + key, + name: data[0], + id: data[1] || null, + endDate: parseInt(data[2]) || null, + tz: data[3] || null, + pattern, + next }; - } catch (error) { - if (error instanceof ApiError_default) { - throw error; - } - console.error("Error fetching problem by id:", error); - throw new ApiError_default("Failed to fetch problem details", E.INTERNAL_SERVER_ERROR); } -}; -var handleGetEditorialSolution = async (problemId) => { - try { - const editorialResult = await db.select().from(editorial).where(eq(editorial.problemId, problemId)).limit(1); - if (editorialResult.length === 0) { - throw new ApiError_default("Editorial not found", E.NOT_FOUND); - } - const editorials = editorialResult[0]; - const solutionResponse = await fetchFileFromS3(editorials.solutionS3Key); - if (!solutionResponse) { - throw new ApiError_default("Solution file not found in storage: " + editorials.solutionS3Key, E.INTERNAL_SERVER_ERROR); - } - return solutionResponse; - } catch (error) { - if (error instanceof ApiError_default) { - throw error; + async getRepeatableJobs(start = 0, end = -1, asc2 = false) { + const client = await this.client; + const key = this.keys.repeat; + const result = asc2 ? await client.zrange(key, start, end, "WITHSCORES") : await client.zrevrange(key, start, end, "WITHSCORES"); + const jobs = []; + for (let i2 = 0;i2 < result.length; i2 += 2) { + jobs.push(this.getRepeatableData(client, result[i2], parseInt(result[i2 + 1]))); } - console.error("Error fetching editorial solution:", error); - throw new ApiError_default("Failed to fetch editorial solution", E.INTERNAL_SERVER_ERROR); + return Promise.all(jobs); } -}; -var handleGetEditorialContent = async (problemId) => { + async getRepeatableCount() { + const client = await this.client; + return client.zcard(this.toKey("repeat")); + } + hash(str) { + return createHash2(this.repeatKeyHashAlgorithm).update(str).digest("hex"); + } + getRepeatDelayedJobId({ nextMillis, customKey }) { + return `repeat:${customKey}:${nextMillis}`; + } + getRepeatJobId({ name, nextMillis, namespace, jobId, key }) { + const checksum = key !== null && key !== undefined ? key : this.hash(`${name}${jobId || ""}${namespace}`); + return `repeat:${checksum}:${nextMillis}`; + } +} +function getRepeatConcatOptions(name, repeat) { + const endDate = repeat.endDate ? new Date(repeat.endDate).getTime() : ""; + const tz = repeat.tz || ""; + const pattern = repeat.pattern; + const suffix = (pattern ? pattern : String(repeat.every)) || ""; + const jobId = repeat.jobId ? repeat.jobId : ""; + return `${name}:${jobId}:${endDate}:${tz}:${suffix}`; +} +var getNextMillis = (millis, opts) => { + const pattern = opts.pattern; + if (pattern && opts.every) { + throw new Error("Both .pattern and .every options are defined for this repeatable job"); + } + if (opts.every) { + return Math.floor(millis / opts.every) * opts.every + (opts.immediately ? 0 : opts.every); + } + const currentDate = opts.startDate && new Date(opts.startDate) > new Date(millis) ? new Date(opts.startDate) : new Date(millis); + const interval3 = import_cron_parser2.parseExpression(pattern, Object.assign(Object.assign({}, opts), { currentDate })); try { - const editorialResult = await db.select({ - contentS3Key: editorial.contentS3Key, - editorialLink: editorial.editorialLink - }).from(editorial).where(eq(editorial.problemId, problemId)).limit(1); - if (editorialResult.length === 0) { - throw new ApiError_default("Editorial not found", E.NOT_FOUND); - } - const editorials = editorialResult[0]; - const editorialContentResponse = await fetchFileFromS3(editorials.contentS3Key); - if (!editorialContentResponse) { - throw new ApiError_default("Editorial content not found in storage: " + editorials.contentS3Key, E.INTERNAL_SERVER_ERROR); + if (opts.immediately) { + return new Date().getTime(); + } else { + return interval3.next().getTime(); } + } catch (e3) {} +}; + +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/classes/queue.js +class Queue extends QueueGetters { + constructor(name, opts, Connection2) { + var _a; + super(name, Object.assign({}, opts), Connection2); + this.token = v4_default(); + this.libName = "bullmq"; + this.jobsOpts = (_a = opts === null || opts === undefined ? undefined : opts.defaultJobOptions) !== null && _a !== undefined ? _a : {}; + this.waitUntilReady().then((client) => { + if (!this.closing && !(opts === null || opts === undefined ? undefined : opts.skipMetasUpdate)) { + return client.hmset(this.keys.meta, this.metaValues); + } + }).catch((err) => {}); + } + emit(event, ...args) { + return super.emit(event, ...args); + } + off(eventName, listener) { + super.off(eventName, listener); + return this; + } + on(event, listener) { + super.on(event, listener); + return this; + } + once(event, listener) { + super.once(event, listener); + return this; + } + get defaultJobOptions() { + return Object.assign({}, this.jobsOpts); + } + get metaValues() { + var _a, _b, _c2, _d2; return { - editorialContent: editorialContentResponse, - editorialLink: editorials.editorialLink + "opts.maxLenEvents": (_d2 = (_c2 = (_b = (_a = this.opts) === null || _a === undefined ? undefined : _a.streams) === null || _b === undefined ? undefined : _b.events) === null || _c2 === undefined ? undefined : _c2.maxLen) !== null && _d2 !== undefined ? _d2 : 1e4, + version: `${this.libName}:${version3}` }; - } catch (error) { - if (error instanceof ApiError_default) { - throw error; + } + async getVersion() { + const client = await this.client; + return await client.hget(this.keys.meta, "version"); + } + get repeat() { + return new Promise(async (resolve) => { + if (!this._repeat) { + this._repeat = new Repeat(this.name, Object.assign(Object.assign({}, this.opts), { connection: await this.client })); + this._repeat.on("error", this.emit.bind(this, "error")); + } + resolve(this._repeat); + }); + } + get jobScheduler() { + return new Promise(async (resolve) => { + if (!this._jobScheduler) { + this._jobScheduler = new JobScheduler(this.name, Object.assign(Object.assign({}, this.opts), { connection: await this.client })); + this._jobScheduler.on("error", this.emit.bind(this, "error")); + } + resolve(this._jobScheduler); + }); + } + async setGlobalConcurrency(concurrency) { + const client = await this.client; + return client.hset(this.keys.meta, "concurrency", concurrency); + } + async setGlobalRateLimit(max, duration) { + const client = await this.client; + return client.hset(this.keys.meta, "max", max, "duration", duration); + } + async removeGlobalConcurrency() { + const client = await this.client; + return client.hdel(this.keys.meta, "concurrency"); + } + async removeGlobalRateLimit() { + const client = await this.client; + return client.hdel(this.keys.meta, "max", "duration"); + } + async add(name, data, opts) { + return this.trace(SpanKind.PRODUCER, "add", `${this.name}.${name}`, async (span, srcPropagationMetadata) => { + var _a; + if (srcPropagationMetadata && !((_a = opts === null || opts === undefined ? undefined : opts.telemetry) === null || _a === undefined ? undefined : _a.omitContext)) { + const telemetry = { + metadata: srcPropagationMetadata + }; + opts = Object.assign(Object.assign({}, opts), { telemetry }); + } + const job = await this.addJob(name, data, opts); + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobName]: name, + [TelemetryAttributes.JobId]: job.id + }); + return job; + }); + } + async addJob(name, data, opts) { + if (opts && opts.repeat) { + if (opts.repeat.endDate) { + if (+new Date(opts.repeat.endDate) < Date.now()) { + throw new Error("End date must be greater than current timestamp"); + } + } + return (await this.repeat).updateRepeatableJob(name, data, Object.assign(Object.assign({}, this.jobsOpts), opts), { override: true }); + } else { + const jobId = opts === null || opts === undefined ? undefined : opts.jobId; + if (jobId == "0" || (jobId === null || jobId === undefined ? undefined : jobId.startsWith("0:"))) { + throw new Error("JobId cannot be '0' or start with 0:"); + } + const mergedOpts = Object.assign(Object.assign(Object.assign({}, this.jobsOpts), opts), { jobId }); + const job = await this.Job.create(this, name, data, mergedOpts); + this.emit("waiting", job); + return job; } - console.error("Error fetching editorial content:", error); - throw new ApiError_default("Failed to fetch editorial content", E.INTERNAL_SERVER_ERROR); } + async addBulk(jobs) { + return this.trace(SpanKind.PRODUCER, "addBulk", this.name, async (span, srcPropagationMetadata) => { + if (span) { + span.setAttributes({ + [TelemetryAttributes.BulkNames]: jobs.map((job) => job.name), + [TelemetryAttributes.BulkCount]: jobs.length + }); + } + return await this.Job.createBulk(this, jobs.map((job) => { + var _a, _b, _c2, _d2, _e2, _f; + let telemetry = (_a = job.opts) === null || _a === undefined ? undefined : _a.telemetry; + if (srcPropagationMetadata) { + const omitContext = (_c2 = (_b = job.opts) === null || _b === undefined ? undefined : _b.telemetry) === null || _c2 === undefined ? undefined : _c2.omitContext; + const telemetryMetadata = ((_e2 = (_d2 = job.opts) === null || _d2 === undefined ? undefined : _d2.telemetry) === null || _e2 === undefined ? undefined : _e2.metadata) || !omitContext && srcPropagationMetadata; + if (telemetryMetadata || omitContext) { + telemetry = { + metadata: telemetryMetadata, + omitContext + }; + } + } + const mergedOpts = Object.assign(Object.assign(Object.assign({}, this.jobsOpts), job.opts), { jobId: (_f = job.opts) === null || _f === undefined ? undefined : _f.jobId, telemetry }); + return { + name: job.name, + data: job.data, + opts: mergedOpts + }; + })); + }); + } + async upsertJobScheduler(jobSchedulerId, repeatOpts, jobTemplate) { + var _a, _b; + if (repeatOpts.endDate) { + if (+new Date(repeatOpts.endDate) < Date.now()) { + throw new Error("End date must be greater than current timestamp"); + } + } + return (await this.jobScheduler).upsertJobScheduler(jobSchedulerId, repeatOpts, (_a = jobTemplate === null || jobTemplate === undefined ? undefined : jobTemplate.name) !== null && _a !== undefined ? _a : jobSchedulerId, (_b = jobTemplate === null || jobTemplate === undefined ? undefined : jobTemplate.data) !== null && _b !== undefined ? _b : {}, Object.assign(Object.assign({}, this.jobsOpts), jobTemplate === null || jobTemplate === undefined ? undefined : jobTemplate.opts), { override: true }); + } + async pause() { + await this.trace(SpanKind.INTERNAL, "pause", this.name, async () => { + await this.scripts.pause(true); + this.emit("paused"); + }); + } + async close() { + await this.trace(SpanKind.INTERNAL, "close", this.name, async () => { + if (!this.closing) { + if (this._repeat) { + await this._repeat.close(); + } + } + await super.close(); + }); + } + async rateLimit(expireTimeMs) { + await this.trace(SpanKind.INTERNAL, "rateLimit", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.QueueRateLimit]: expireTimeMs + }); + await this.client.then((client) => client.set(this.keys.limiter, Number.MAX_SAFE_INTEGER, "PX", expireTimeMs)); + }); + } + async resume() { + await this.trace(SpanKind.INTERNAL, "resume", this.name, async () => { + await this.scripts.pause(false); + this.emit("resumed"); + }); + } + async isPaused() { + const client = await this.client; + const pausedKeyExists = await client.hexists(this.keys.meta, "paused"); + return pausedKeyExists === 1; + } + isMaxed() { + return this.scripts.isMaxed(); + } + async getRepeatableJobs(start, end, asc2) { + return (await this.repeat).getRepeatableJobs(start, end, asc2); + } + async getJobScheduler(id) { + return (await this.jobScheduler).getScheduler(id); + } + async getJobSchedulers(start, end, asc2) { + return (await this.jobScheduler).getJobSchedulers(start, end, asc2); + } + async getJobSchedulersCount() { + return (await this.jobScheduler).getSchedulersCount(); + } + async removeRepeatable(name, repeatOpts, jobId) { + return this.trace(SpanKind.INTERNAL, "removeRepeatable", `${this.name}.${name}`, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobName]: name, + [TelemetryAttributes.JobId]: jobId + }); + const repeat = await this.repeat; + const removed = await repeat.removeRepeatable(name, repeatOpts, jobId); + return !removed; + }); + } + async removeJobScheduler(jobSchedulerId) { + const jobScheduler = await this.jobScheduler; + const removed = await jobScheduler.removeJobScheduler(jobSchedulerId); + return !removed; + } + async removeDebounceKey(id) { + return this.trace(SpanKind.INTERNAL, "removeDebounceKey", `${this.name}`, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobKey]: id + }); + const client = await this.client; + return await client.del(`${this.keys.de}:${id}`); + }); + } + async removeDeduplicationKey(id) { + return this.trace(SpanKind.INTERNAL, "removeDeduplicationKey", `${this.name}`, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.DeduplicationKey]: id + }); + const client = await this.client; + return client.del(`${this.keys.de}:${id}`); + }); + } + async removeRateLimitKey() { + const client = await this.client; + return client.del(this.keys.limiter); + } + async removeRepeatableByKey(key) { + return this.trace(SpanKind.INTERNAL, "removeRepeatableByKey", `${this.name}`, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobKey]: key + }); + const repeat = await this.repeat; + const removed = await repeat.removeRepeatableByKey(key); + return !removed; + }); + } + async remove(jobId, { removeChildren = true } = {}) { + return this.trace(SpanKind.INTERNAL, "remove", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobId]: jobId, + [TelemetryAttributes.JobOptions]: JSON.stringify({ + removeChildren + }) + }); + const code = await this.scripts.remove(jobId, removeChildren); + if (code === 1) { + this.emit("removed", jobId); + } + return code; + }); + } + async updateJobProgress(jobId, progress) { + await this.trace(SpanKind.INTERNAL, "updateJobProgress", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.JobId]: jobId, + [TelemetryAttributes.JobProgress]: JSON.stringify(progress) + }); + await this.scripts.updateProgress(jobId, progress); + this.emit("progress", jobId, progress); + }); + } + async addJobLog(jobId, logRow, keepLogs) { + return Job.addJobLog(this, jobId, logRow, keepLogs); + } + async drain(delayed = false) { + await this.trace(SpanKind.INTERNAL, "drain", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.QueueDrainDelay]: delayed + }); + await this.scripts.drain(delayed); + }); + } + async clean(grace, limit, type = "completed") { + return this.trace(SpanKind.INTERNAL, "clean", this.name, async (span) => { + const maxCount = limit || Infinity; + const maxCountPerCall = Math.min(1e4, maxCount); + const timestamp3 = Date.now() - grace; + let deletedCount = 0; + const deletedJobsIds = []; + const normalizedType = type === "waiting" ? "wait" : type; + while (deletedCount < maxCount) { + const jobsIds = await this.scripts.cleanJobsInSet(normalizedType, timestamp3, maxCountPerCall); + this.emit("cleaned", jobsIds, normalizedType); + deletedCount += jobsIds.length; + deletedJobsIds.push(...jobsIds); + if (jobsIds.length < maxCountPerCall) { + break; + } + } + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.QueueGrace]: grace, + [TelemetryAttributes.JobType]: type, + [TelemetryAttributes.QueueCleanLimit]: maxCount, + [TelemetryAttributes.JobIds]: deletedJobsIds + }); + return deletedJobsIds; + }); + } + async obliterate(opts) { + await this.trace(SpanKind.INTERNAL, "obliterate", this.name, async () => { + await this.pause(); + let cursor = 0; + do { + cursor = await this.scripts.obliterate(Object.assign({ force: false, count: 1000 }, opts)); + } while (cursor); + }); + } + async retryJobs(opts = {}) { + await this.trace(SpanKind.PRODUCER, "retryJobs", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.QueueOptions]: JSON.stringify(opts) + }); + let cursor = 0; + do { + cursor = await this.scripts.retryJobs(opts.state, opts.count, opts.timestamp); + } while (cursor); + }); + } + async promoteJobs(opts = {}) { + await this.trace(SpanKind.INTERNAL, "promoteJobs", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.QueueOptions]: JSON.stringify(opts) + }); + let cursor = 0; + do { + cursor = await this.scripts.promoteJobs(opts.count); + } while (cursor); + }); + } + async trimEvents(maxLength) { + return this.trace(SpanKind.INTERNAL, "trimEvents", this.name, async (span) => { + span === null || span === undefined || span.setAttributes({ + [TelemetryAttributes.QueueEventMaxLength]: maxLength + }); + const client = await this.client; + return await client.xtrim(this.keys.events, "MAXLEN", "~", maxLength); + }); + } + async removeDeprecatedPriorityKey() { + const client = await this.client; + return client.del(this.toKey("priority")); + } + async removeOrphanedJobs(count2 = 1000, limit = 0) { + const client = await this.client; + const knownSuffixes = new Set(Object.keys(this.keys)); + const stateKeySuffixes = Object.keys(this.keys).filter((s2) => s2 !== ""); + const jobSubKeySuffixes = [ + "logs", + "dependencies", + "processed", + "failed", + "unsuccessful", + "lock" + ]; + const basePrefix = this.qualifiedName + ":"; + const scanPattern = basePrefix + "*"; + let totalRemoved = 0; + let cursor = "0"; + do { + const [nextCursor, keys] = await client.scan(cursor, "MATCH", scanPattern, "COUNT", count2); + cursor = nextCursor; + const candidateJobIds = new Set; + for (const key of keys) { + const suffix = key.slice(basePrefix.length); + if (knownSuffixes.has(suffix)) { + continue; + } + const colonIdx = suffix.indexOf(":"); + if (colonIdx !== -1) { + const prefixPart = suffix.slice(0, colonIdx); + if (knownSuffixes.has(prefixPart)) { + continue; + } + } + const jobId = colonIdx === -1 ? suffix : suffix.slice(0, colonIdx); + if (colonIdx !== -1) { + const subKey = suffix.slice(colonIdx + 1); + if (!jobSubKeySuffixes.includes(subKey)) { + continue; + } + } + candidateJobIds.add(jobId); + } + if (candidateJobIds.size === 0) { + continue; + } + const result = await this.scripts.removeOrphanedJobs([...candidateJobIds], stateKeySuffixes, jobSubKeySuffixes); + totalRemoved += result || 0; + if (limit > 0 && totalRemoved >= limit) { + break; + } + } while (cursor !== "0"); + return totalRemoved; + } +} +// node_modules/.pnpm/bullmq@5.76.1/node_modules/bullmq/dist/esm/interfaces/queue-options.js +var ClientType; +(function(ClientType2) { + ClientType2["blocking"] = "blocking"; + ClientType2["normal"] = "normal"; +})(ClientType || (ClientType = {})); +// src/loaders/queue.ts +var connection2 = { + url: config_default.REDIS_URL }; - -// src/api/problem/problem-controller.ts -var createProblem = asyncHandler_default(async (req, res) => { - const response = await handleCreateProblem(req.user.id, req.body); - return res.status(200).json({ - status: "success", - message: "Problem created successfully", - data: response - }); -}); -var finalizeProblem = asyncHandler_default(async (req, res) => { - const problemId = req.query.problemId; - await handleFinalizeProblem(req.user.id, problemId); - return res.status(200).json({ - status: "success", - message: "Problem finalized successfully" - }); -}); -var getProblems = asyncHandler_default(async (req, res) => { - const limit = parseInt(req.query.limit) || 10; - const cursor = req.query.cursor; - const response = await handleGetProblems({ limit, cursor }); - return res.status(200).json({ - status: "success", - message: "Problems fetched successfully", - data: response - }); -}); -var getProblemById = asyncHandler_default(async (req, res) => { - const problemId = req.params.problemId; - const response = await handleGetProblemById(problemId); - return res.status(200).json({ - status: "success", - message: "Problem fetched successfully", - data: response - }); -}); -var getEditorialSolution = asyncHandler_default(async (req, res) => { - const problemId = req.params.problemId; - const response = await handleGetEditorialSolution(problemId); - return res.status(200).json({ - status: "success", - message: "Editorial solution fetched successfully", - data: response +var runQueue = new Queue("run-queue", { connection: connection2 }); +var submitQueue = new Queue("submit-queue", { connection: connection2 }); + +// src/api/submission/submission-helper.ts +async function createRunQueue(submissionId, code, language, problemId, timeLimit, memoryLimit) { + return await runQueue.add("run-code", { + submissionId, + code, + language, + problemId, + timeLimit, + memoryLimit + }, { + jobId: submissionId, + attempts: 1, + priority: 1, + removeOnComplete: true, + removeOnFail: 50 }); -}); -var getEditorialContent = asyncHandler_default(async (req, res) => { - const problemId = req.params.problemId; - const response = await handleGetEditorialContent(problemId); - return res.status(200).json({ - status: "success", - message: "Editorial solution fetched successfully", - data: response +} +async function createSubmitQueue(submissionId, code, language, problemId, timeLimit, memoryLimit) { + return await submitQueue.add("submit-code", { + submissionId, + code, + language, + problemId, + timeLimit, + memoryLimit + }, { + jobId: submissionId, + attempts: 2, + backoff: { + type: "exponential", + delay: 1000 + }, + priority: 2, + removeOnComplete: true, + removeOnFail: 50 }); -}); - -// src/api/problem/problem-route.ts -var router2 = import_express2.Router(); -router2.post("/create", validate("body", createProblemSchema), verifyJWT, createProblem); -router2.post("/finalize", verifyJWT, finalizeProblem); -router2.get("/", validate("query", getProblemsSchema), getProblems); -router2.get("/:problemId", getProblemById); -router2.get("/:problemId/editorial-solution", getEditorialSolution); -router2.get("/:problemId/editorial-content", getEditorialContent); -var problem_route_default = router2; - -// src/api/submission/submission-route.ts -var import_express3 = __toESM(require_express(), 1); - -// src/api/submission/submission-schema.ts -var createsubmissionSchema = create$3({ - code: create$6().required("Code is required"), - language: create$6().required("Language is required") -}); -var problemIdSchema = create$3({ - problemId: create$6().required("Problem ID is required") -}); - -// src/loaders/queue.ts -var import_bull = __toESM(require_bull(), 1); -var redis = config_default.REDIS_URL; -var myQueue = new import_bull.default("job-queue", redis); - -// src/loaders/redis.ts -var import_ioredis = __toESM(require_built3(), 1); -var import_dotenv3 = __toESM(require_main(), 1); -import_dotenv3.default.config(); -var redisUrl = process.env.REDIS_URL; -if (!redisUrl) { - throw new Error("REDIS_URL is not set"); } -var redis2 = new import_ioredis.default(redisUrl); -var redis_default = redis2; // src/api/submission/submission-service.ts var handleCreateSubmission = async (userId, problemId, code, language, mode) => { @@ -173990,53 +171066,86 @@ var handleCreateSubmission = async (userId, problemId, code, language, mode) => status: "PENDING" }).returning({ id: submission.id }); const submissionId = insertedSubmission.id; - try { - await myQueue.add({ + const prob = await db.select({ + timeLimit: problem.timeLimit, + memoryLimit: problem.memoryLimit + }).from(problem).where(eq(problem.id, problemId)); + if (prob.length === 0) { + return { submissionId, - mode: normalizedMode - }); + status: "FAILED", + startedAt: new Date + }; + } + try { + if (normalizedMode === "RUN") { + await createRunQueue(submissionId, code, language, problemId, prob[0].timeLimit, prob[0].memoryLimit); + } else { + await createSubmitQueue(submissionId, code, language, problemId, prob[0].timeLimit, prob[0].memoryLimit); + } return { submissionId, - status: "PENDING" + status: "PENDING", + startedAt: new Date }; } catch (queueError) { console.error("Queue error:", queueError); return { submissionId, - status: "FAILED" + status: "FAILED", + startedAt: new Date }; } } catch (dbError) { console.error("Database error:", dbError); return { submissionId: "", - status: "ERROR" + status: "ERROR", + startedAt: new Date }; } }; var handlegetSubmissionStatus = async (userId, submissionId) => { try { + const [dbResult] = await db.select({ + id: submission.id, + status: submission.status, + createdAt: submission.createdAt + }).from(submission).where(eq(submission.id, submissionId)); + if (!dbResult) { + throw new ApiError_default("Submission not found", E.NOT_FOUND); + } const redisStatus = await redis_default.get(`submission:${submissionId}`); if (redisStatus) { const parsed = JSON.parse(redisStatus); + const redisState = String(parsed?.status || "").toUpperCase(); + const dbState = String(dbResult.status || "").toUpperCase(); + const dbIsTerminal = dbState === "COMPLETED" || dbState === "FAILED"; + const redisIsNonTerminal = redisState === "PENDING" || redisState === "RUNNING"; + if (dbIsTerminal && redisIsNonTerminal) { + return { + submissionId: dbResult.id, + status: dbResult.status, + startedAt: new Date(dbResult.createdAt) + }; + } return { submissionId, - status: parsed.status + status: parsed.status, + startedAt: new Date(parsed.updatedAt || parsed.createdAt || dbResult.createdAt) }; } - const [result] = await db.select().from(submission).where(eq(submission.id, submissionId)); - if (!result) { - throw new ApiError_default("Submission not found", E.NOT_FOUND); - } return { - submissionId: result.id, - status: result.status + submissionId: dbResult.id, + status: dbResult.status, + startedAt: new Date(dbResult.createdAt) }; } catch (error) { console.error("Database error:", error); return { submissionId: "", - status: "ERROR" + status: "ERROR", + startedAt: null }; } }; @@ -174085,6 +171194,57 @@ var handleGetSubmissionResults = async (userId, submissionId) => { }; } }; +var handleGetUserDashboardStats = async (userId) => { + try { + const recentSubs = await db.select({ + id: submission.id, + language: submission.language, + status: submission.status, + verdict: executionResult.verdict, + timeTaken: submission.timeTaken, + memoryTaken: submission.memoryTaken, + createdAt: submission.createdAt, + problemId: submission.problemId, + problemTitle: problem.title, + problemSlug: problem.slug, + problemDifficulty: problem.difficulty + }).from(submission).leftJoin(executionResult, eq(executionResult.submissionId, submission.id)).leftJoin(problem, eq(problem.id, submission.problemId)).where(and(eq(submission.userId, userId), eq(submission.mode, "SUBMIT"))).orderBy(desc(submission.createdAt)).limit(20); + const [totalRow] = await db.select({ count: count() }).from(submission).where(and(eq(submission.userId, userId), eq(submission.mode, "SUBMIT"))); + const acceptedProblems = await db.selectDistinct({ problemId: submission.problemId }).from(submission).innerJoin(executionResult, eq(executionResult.submissionId, submission.id)).where(and(eq(submission.userId, userId), eq(submission.mode, "SUBMIT"), eq(executionResult.verdict, "ACCEPTED"))); + const acceptedWithDiff = await db.selectDistinct({ problemId: submission.problemId, difficulty: problem.difficulty }).from(submission).innerJoin(executionResult, eq(executionResult.submissionId, submission.id)).innerJoin(problem, eq(problem.id, submission.problemId)).where(and(eq(submission.userId, userId), eq(submission.mode, "SUBMIT"), eq(executionResult.verdict, "ACCEPTED"))); + const easyCount = acceptedWithDiff.filter((r2) => r2.difficulty === "EASY").length; + const mediumCount = acceptedWithDiff.filter((r2) => r2.difficulty === "MEDIUM").length; + const hardCount = acceptedWithDiff.filter((r2) => r2.difficulty === "HARD").length; + const formatted = recentSubs.map((r2) => ({ + id: r2.id, + language: r2.language, + status: r2.verdict && r2.verdict !== "PENDING" ? r2.verdict : r2.status, + timeTaken: r2.timeTaken, + memoryTaken: r2.memoryTaken, + createdAt: r2.createdAt, + problem: { + id: r2.problemId, + title: r2.problemTitle, + slug: r2.problemSlug, + difficulty: r2.problemDifficulty + } + })); + return { + totalSubmissions: totalRow?.count ?? 0, + totalSolved: acceptedProblems.length, + solvedByDifficulty: { easy: easyCount, medium: mediumCount, hard: hardCount }, + recentSubmissions: formatted + }; + } catch (error) { + console.error("Dashboard stats error:", error); + return { + totalSubmissions: 0, + totalSolved: 0, + solvedByDifficulty: { easy: 0, medium: 0, hard: 0 }, + recentSubmissions: [] + }; + } +}; var handleGetAllSubmissions = async (userId, problemId) => { try { const results = await db.select({ @@ -174157,13 +171317,22 @@ var getAllSubmissions = asyncHandler_default(async (req, res) => { message: response }); }); +var getUserDashboardStats = asyncHandler_default(async (req, res) => { + const userId = req.user.id; + const response = await handleGetUserDashboardStats(userId); + return res.status(200).json({ + success: true, + data: response + }); +}); // src/api/submission/submission-route.ts var router3 = import_express3.Router(); -router3.post("/:problemId/:mode", validate("body", createsubmissionSchema), verifyJWT, createSubmission); +router3.get("/user/dashboard", verifyJWT, getUserDashboardStats); +router3.get("/problem/:problemId", verifyJWT, getAllSubmissions); router3.get("/:submissionId", verifyJWT, getSubmissionStatus); router3.get("/:submissionId/result", verifyJWT, getSubmissionResults); -router3.get("/problem/:problemId", verifyJWT, getAllSubmissions); +router3.post("/:problemId/:mode", validate("body", createSubmissionSchema), verifyJWT, createSubmission); var submission_route_default = router3; // src/api/interview/interview-route.ts @@ -174188,936 +171357,6 @@ class ApiResponse { } } -// node_modules/.pnpm/@google+generative-ai@0.24.1/node_modules/@google/generative-ai/dist/index.mjs -var SchemaType; -(function(SchemaType2) { - SchemaType2["STRING"] = "string"; - SchemaType2["NUMBER"] = "number"; - SchemaType2["INTEGER"] = "integer"; - SchemaType2["BOOLEAN"] = "boolean"; - SchemaType2["ARRAY"] = "array"; - SchemaType2["OBJECT"] = "object"; -})(SchemaType || (SchemaType = {})); -var ExecutableCodeLanguage; -(function(ExecutableCodeLanguage2) { - ExecutableCodeLanguage2["LANGUAGE_UNSPECIFIED"] = "language_unspecified"; - ExecutableCodeLanguage2["PYTHON"] = "python"; -})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {})); -var Outcome; -(function(Outcome2) { - Outcome2["OUTCOME_UNSPECIFIED"] = "outcome_unspecified"; - Outcome2["OUTCOME_OK"] = "outcome_ok"; - Outcome2["OUTCOME_FAILED"] = "outcome_failed"; - Outcome2["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded"; -})(Outcome || (Outcome = {})); -var POSSIBLE_ROLES = ["user", "model", "function", "system"]; -var HarmCategory; -(function(HarmCategory2) { - HarmCategory2["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; - HarmCategory2["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; - HarmCategory2["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; - HarmCategory2["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; - HarmCategory2["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; - HarmCategory2["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; -})(HarmCategory || (HarmCategory = {})); -var HarmBlockThreshold; -(function(HarmBlockThreshold2) { - HarmBlockThreshold2["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; - HarmBlockThreshold2["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; - HarmBlockThreshold2["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; - HarmBlockThreshold2["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; - HarmBlockThreshold2["BLOCK_NONE"] = "BLOCK_NONE"; -})(HarmBlockThreshold || (HarmBlockThreshold = {})); -var HarmProbability; -(function(HarmProbability2) { - HarmProbability2["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; - HarmProbability2["NEGLIGIBLE"] = "NEGLIGIBLE"; - HarmProbability2["LOW"] = "LOW"; - HarmProbability2["MEDIUM"] = "MEDIUM"; - HarmProbability2["HIGH"] = "HIGH"; -})(HarmProbability || (HarmProbability = {})); -var BlockReason; -(function(BlockReason2) { - BlockReason2["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; - BlockReason2["SAFETY"] = "SAFETY"; - BlockReason2["OTHER"] = "OTHER"; -})(BlockReason || (BlockReason = {})); -var FinishReason; -(function(FinishReason2) { - FinishReason2["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; - FinishReason2["STOP"] = "STOP"; - FinishReason2["MAX_TOKENS"] = "MAX_TOKENS"; - FinishReason2["SAFETY"] = "SAFETY"; - FinishReason2["RECITATION"] = "RECITATION"; - FinishReason2["LANGUAGE"] = "LANGUAGE"; - FinishReason2["BLOCKLIST"] = "BLOCKLIST"; - FinishReason2["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; - FinishReason2["SPII"] = "SPII"; - FinishReason2["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; - FinishReason2["OTHER"] = "OTHER"; -})(FinishReason || (FinishReason = {})); -var TaskType; -(function(TaskType2) { - TaskType2["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED"; - TaskType2["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY"; - TaskType2["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT"; - TaskType2["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY"; - TaskType2["CLASSIFICATION"] = "CLASSIFICATION"; - TaskType2["CLUSTERING"] = "CLUSTERING"; -})(TaskType || (TaskType = {})); -var FunctionCallingMode; -(function(FunctionCallingMode2) { - FunctionCallingMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; - FunctionCallingMode2["AUTO"] = "AUTO"; - FunctionCallingMode2["ANY"] = "ANY"; - FunctionCallingMode2["NONE"] = "NONE"; -})(FunctionCallingMode || (FunctionCallingMode = {})); -var DynamicRetrievalMode; -(function(DynamicRetrievalMode2) { - DynamicRetrievalMode2["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; - DynamicRetrievalMode2["MODE_DYNAMIC"] = "MODE_DYNAMIC"; -})(DynamicRetrievalMode || (DynamicRetrievalMode = {})); - -class GoogleGenerativeAIError extends Error { - constructor(message) { - super(`[GoogleGenerativeAI Error]: ${message}`); - } -} - -class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError { - constructor(message, response) { - super(message); - this.response = response; - } -} - -class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError { - constructor(message, status, statusText, errorDetails) { - super(message); - this.status = status; - this.statusText = statusText; - this.errorDetails = errorDetails; - } -} - -class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError { -} - -class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError { -} -var DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com"; -var DEFAULT_API_VERSION = "v1beta"; -var PACKAGE_VERSION = "0.24.1"; -var PACKAGE_LOG_HEADER = "genai-js"; -var Task; -(function(Task2) { - Task2["GENERATE_CONTENT"] = "generateContent"; - Task2["STREAM_GENERATE_CONTENT"] = "streamGenerateContent"; - Task2["COUNT_TOKENS"] = "countTokens"; - Task2["EMBED_CONTENT"] = "embedContent"; - Task2["BATCH_EMBED_CONTENTS"] = "batchEmbedContents"; -})(Task || (Task = {})); - -class RequestUrl { - constructor(model, task, apiKey, stream, requestOptions) { - this.model = model; - this.task = task; - this.apiKey = apiKey; - this.stream = stream; - this.requestOptions = requestOptions; - } - toString() { - var _a, _b; - const apiVersion = ((_a = this.requestOptions) === null || _a === undefined ? undefined : _a.apiVersion) || DEFAULT_API_VERSION; - const baseUrl2 = ((_b = this.requestOptions) === null || _b === undefined ? undefined : _b.baseUrl) || DEFAULT_BASE_URL; - let url = `${baseUrl2}/${apiVersion}/${this.model}:${this.task}`; - if (this.stream) { - url += "?alt=sse"; - } - return url; - } -} -function getClientHeaders(requestOptions) { - const clientHeaders = []; - if (requestOptions === null || requestOptions === undefined ? undefined : requestOptions.apiClient) { - clientHeaders.push(requestOptions.apiClient); - } - clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`); - return clientHeaders.join(" "); -} -async function getHeaders(url) { - var _a; - const headers = new Headers; - headers.append("Content-Type", "application/json"); - headers.append("x-goog-api-client", getClientHeaders(url.requestOptions)); - headers.append("x-goog-api-key", url.apiKey); - let customHeaders = (_a = url.requestOptions) === null || _a === undefined ? undefined : _a.customHeaders; - if (customHeaders) { - if (!(customHeaders instanceof Headers)) { - try { - customHeaders = new Headers(customHeaders); - } catch (e3) { - throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e3.message}`); - } - } - for (const [headerName, headerValue] of customHeaders.entries()) { - if (headerName === "x-goog-api-key") { - throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`); - } else if (headerName === "x-goog-api-client") { - throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`); - } - headers.append(headerName, headerValue); - } - } - return headers; -} -async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) { - const url = new RequestUrl(model, task, apiKey, stream, requestOptions); - return { - url: url.toString(), - fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }) - }; -} -async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, fetchFn = fetch) { - const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions); - return makeRequest(url, fetchOptions, fetchFn); -} -async function makeRequest(url, fetchOptions, fetchFn = fetch) { - let response; - try { - response = await fetchFn(url, fetchOptions); - } catch (e3) { - handleResponseError(e3, url); - } - if (!response.ok) { - await handleResponseNotOk(response, url); - } - return response; -} -function handleResponseError(e3, url) { - let err = e3; - if (err.name === "AbortError") { - err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e3.message}`); - err.stack = e3.stack; - } else if (!(e3 instanceof GoogleGenerativeAIFetchError || e3 instanceof GoogleGenerativeAIRequestInputError)) { - err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e3.message}`); - err.stack = e3.stack; - } - throw err; -} -async function handleResponseNotOk(response, url) { - let message = ""; - let errorDetails; - try { - const json2 = await response.json(); - message = json2.error.message; - if (json2.error.details) { - message += ` ${JSON.stringify(json2.error.details)}`; - errorDetails = json2.error.details; - } - } catch (e3) {} - throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails); -} -function buildFetchOptions(requestOptions) { - const fetchOptions = {}; - if ((requestOptions === null || requestOptions === undefined ? undefined : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === undefined ? undefined : requestOptions.timeout) >= 0) { - const controller = new AbortController; - if ((requestOptions === null || requestOptions === undefined ? undefined : requestOptions.timeout) >= 0) { - setTimeout(() => controller.abort(), requestOptions.timeout); - } - if (requestOptions === null || requestOptions === undefined ? undefined : requestOptions.signal) { - requestOptions.signal.addEventListener("abort", () => { - controller.abort(); - }); - } - fetchOptions.signal = controller.signal; - } - return fetchOptions; -} -function addHelpers(response) { - response.text = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning text from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - return getText(response); - } else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response); - } - return ""; - }; - response.functionCall = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning function calls from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - console.warn(`response.functionCall() is deprecated. ` + `Use response.functionCalls() instead.`); - return getFunctionCalls(response)[0]; - } else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); - } - return; - }; - response.functionCalls = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning function calls from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - return getFunctionCalls(response); - } else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); - } - return; - }; - return response; -} -function getText(response) { - var _a, _b, _c2, _d2; - const textStrings = []; - if ((_b = (_a = response.candidates) === null || _a === undefined ? undefined : _a[0].content) === null || _b === undefined ? undefined : _b.parts) { - for (const part of (_d2 = (_c2 = response.candidates) === null || _c2 === undefined ? undefined : _c2[0].content) === null || _d2 === undefined ? undefined : _d2.parts) { - if (part.text) { - textStrings.push(part.text); - } - if (part.executableCode) { - textStrings.push("\n```" + part.executableCode.language + ` -` + part.executableCode.code + "\n```\n"); - } - if (part.codeExecutionResult) { - textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n"); - } - } - } - if (textStrings.length > 0) { - return textStrings.join(""); - } else { - return ""; - } -} -function getFunctionCalls(response) { - var _a, _b, _c2, _d2; - const functionCalls = []; - if ((_b = (_a = response.candidates) === null || _a === undefined ? undefined : _a[0].content) === null || _b === undefined ? undefined : _b.parts) { - for (const part of (_d2 = (_c2 = response.candidates) === null || _c2 === undefined ? undefined : _c2[0].content) === null || _d2 === undefined ? undefined : _d2.parts) { - if (part.functionCall) { - functionCalls.push(part.functionCall); - } - } - } - if (functionCalls.length > 0) { - return functionCalls; - } else { - return; - } -} -var badFinishReasons = [ - FinishReason.RECITATION, - FinishReason.SAFETY, - FinishReason.LANGUAGE -]; -function hadBadFinishReason(candidate) { - return !!candidate.finishReason && badFinishReasons.includes(candidate.finishReason); -} -function formatBlockErrorMessage(response) { - var _a, _b, _c2; - let message = ""; - if ((!response.candidates || response.candidates.length === 0) && response.promptFeedback) { - message += "Response was blocked"; - if ((_a = response.promptFeedback) === null || _a === undefined ? undefined : _a.blockReason) { - message += ` due to ${response.promptFeedback.blockReason}`; - } - if ((_b = response.promptFeedback) === null || _b === undefined ? undefined : _b.blockReasonMessage) { - message += `: ${response.promptFeedback.blockReasonMessage}`; - } - } else if ((_c2 = response.candidates) === null || _c2 === undefined ? undefined : _c2[0]) { - const firstCandidate = response.candidates[0]; - if (hadBadFinishReason(firstCandidate)) { - message += `Candidate was blocked due to ${firstCandidate.finishReason}`; - if (firstCandidate.finishMessage) { - message += `: ${firstCandidate.finishMessage}`; - } - } - } - return message; -} -function __await2(v2) { - return this instanceof __await2 ? (this.v = v2, this) : new __await2(v2); -} -function __asyncGenerator2(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) - throw new TypeError("Symbol.asyncIterator is not defined."); - var g2 = generator.apply(thisArg, _arguments || []), i2, q2 = []; - return i2 = {}, verb("next"), verb("throw"), verb("return"), i2[Symbol.asyncIterator] = function() { - return this; - }, i2; - function verb(n2) { - if (g2[n2]) - i2[n2] = function(v2) { - return new Promise(function(a2, b2) { - q2.push([n2, v2, a2, b2]) > 1 || resume(n2, v2); - }); - }; - } - function resume(n2, v2) { - try { - step(g2[n2](v2)); - } catch (e3) { - settle(q2[0][3], e3); - } - } - function step(r2) { - r2.value instanceof __await2 ? Promise.resolve(r2.value.v).then(fulfill, reject) : settle(q2[0][2], r2); - } - function fulfill(value) { - resume("next", value); - } - function reject(value) { - resume("throw", value); - } - function settle(f2, v2) { - if (f2(v2), q2.shift(), q2.length) - resume(q2[0][0], q2[0][1]); - } -} -var responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/; -function processStream(response) { - const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true })); - const responseStream = getResponseStream(inputStream); - const [stream1, stream2] = responseStream.tee(); - return { - stream: generateResponseSequence(stream1), - response: getResponsePromise(stream2) - }; -} -async function getResponsePromise(stream) { - const allResponses = []; - const reader = stream.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - return addHelpers(aggregateResponses(allResponses)); - } - allResponses.push(value); - } -} -function generateResponseSequence(stream) { - return __asyncGenerator2(this, arguments, function* generateResponseSequence_1() { - const reader = stream.getReader(); - while (true) { - const { value, done } = yield __await2(reader.read()); - if (done) { - break; - } - yield yield __await2(addHelpers(value)); - } - }); -} -function getResponseStream(inputStream) { - const reader = inputStream.getReader(); - const stream = new ReadableStream({ - start(controller) { - let currentText = ""; - return pump(); - function pump() { - return reader.read().then(({ value, done }) => { - if (done) { - if (currentText.trim()) { - controller.error(new GoogleGenerativeAIError("Failed to parse stream")); - return; - } - controller.close(); - return; - } - currentText += value; - let match = currentText.match(responseLineRE); - let parsedResponse; - while (match) { - try { - parsedResponse = JSON.parse(match[1]); - } catch (e3) { - controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`)); - return; - } - controller.enqueue(parsedResponse); - currentText = currentText.substring(match[0].length); - match = currentText.match(responseLineRE); - } - return pump(); - }).catch((e3) => { - let err = e3; - err.stack = e3.stack; - if (err.name === "AbortError") { - err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream"); - } else { - err = new GoogleGenerativeAIError("Error reading from the stream"); - } - throw err; - }); - } - } - }); - return stream; -} -function aggregateResponses(responses) { - const lastResponse = responses[responses.length - 1]; - const aggregatedResponse = { - promptFeedback: lastResponse === null || lastResponse === undefined ? undefined : lastResponse.promptFeedback - }; - for (const response of responses) { - if (response.candidates) { - let candidateIndex = 0; - for (const candidate of response.candidates) { - if (!aggregatedResponse.candidates) { - aggregatedResponse.candidates = []; - } - if (!aggregatedResponse.candidates[candidateIndex]) { - aggregatedResponse.candidates[candidateIndex] = { - index: candidateIndex - }; - } - aggregatedResponse.candidates[candidateIndex].citationMetadata = candidate.citationMetadata; - aggregatedResponse.candidates[candidateIndex].groundingMetadata = candidate.groundingMetadata; - aggregatedResponse.candidates[candidateIndex].finishReason = candidate.finishReason; - aggregatedResponse.candidates[candidateIndex].finishMessage = candidate.finishMessage; - aggregatedResponse.candidates[candidateIndex].safetyRatings = candidate.safetyRatings; - if (candidate.content && candidate.content.parts) { - if (!aggregatedResponse.candidates[candidateIndex].content) { - aggregatedResponse.candidates[candidateIndex].content = { - role: candidate.content.role || "user", - parts: [] - }; - } - const newPart = {}; - for (const part of candidate.content.parts) { - if (part.text) { - newPart.text = part.text; - } - if (part.functionCall) { - newPart.functionCall = part.functionCall; - } - if (part.executableCode) { - newPart.executableCode = part.executableCode; - } - if (part.codeExecutionResult) { - newPart.codeExecutionResult = part.codeExecutionResult; - } - if (Object.keys(newPart).length === 0) { - newPart.text = ""; - } - aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart); - } - } - } - candidateIndex++; - } - if (response.usageMetadata) { - aggregatedResponse.usageMetadata = response.usageMetadata; - } - } - return aggregatedResponse; -} -async function generateContentStream(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, true, JSON.stringify(params), requestOptions); - return processStream(response); -} -async function generateContent(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); - const responseJson = await response.json(); - const enhancedResponse = addHelpers(responseJson); - return { - response: enhancedResponse - }; -} -function formatSystemInstruction(input) { - if (input == null) { - return; - } else if (typeof input === "string") { - return { role: "system", parts: [{ text: input }] }; - } else if (input.text) { - return { role: "system", parts: [input] }; - } else if (input.parts) { - if (!input.role) { - return { role: "system", parts: input.parts }; - } else { - return input; - } - } -} -function formatNewContent(request2) { - let newParts = []; - if (typeof request2 === "string") { - newParts = [{ text: request2 }]; - } else { - for (const partOrString of request2) { - if (typeof partOrString === "string") { - newParts.push({ text: partOrString }); - } else { - newParts.push(partOrString); - } - } - } - return assignRoleToPartsAndValidateSendMessageRequest(newParts); -} -function assignRoleToPartsAndValidateSendMessageRequest(parts) { - const userContent = { role: "user", parts: [] }; - const functionContent = { role: "function", parts: [] }; - let hasUserContent = false; - let hasFunctionContent = false; - for (const part of parts) { - if ("functionResponse" in part) { - functionContent.parts.push(part); - hasFunctionContent = true; - } else { - userContent.parts.push(part); - hasUserContent = true; - } - } - if (hasUserContent && hasFunctionContent) { - throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."); - } - if (!hasUserContent && !hasFunctionContent) { - throw new GoogleGenerativeAIError("No content is provided for sending chat message."); - } - if (hasUserContent) { - return userContent; - } - return functionContent; -} -function formatCountTokensInput(params, modelParams) { - var _a; - let formattedGenerateContentRequest = { - model: modelParams === null || modelParams === undefined ? undefined : modelParams.model, - generationConfig: modelParams === null || modelParams === undefined ? undefined : modelParams.generationConfig, - safetySettings: modelParams === null || modelParams === undefined ? undefined : modelParams.safetySettings, - tools: modelParams === null || modelParams === undefined ? undefined : modelParams.tools, - toolConfig: modelParams === null || modelParams === undefined ? undefined : modelParams.toolConfig, - systemInstruction: modelParams === null || modelParams === undefined ? undefined : modelParams.systemInstruction, - cachedContent: (_a = modelParams === null || modelParams === undefined ? undefined : modelParams.cachedContent) === null || _a === undefined ? undefined : _a.name, - contents: [] - }; - const containsGenerateContentRequest = params.generateContentRequest != null; - if (params.contents) { - if (containsGenerateContentRequest) { - throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both."); - } - formattedGenerateContentRequest.contents = params.contents; - } else if (containsGenerateContentRequest) { - formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest); - } else { - const content = formatNewContent(params); - formattedGenerateContentRequest.contents = [content]; - } - return { generateContentRequest: formattedGenerateContentRequest }; -} -function formatGenerateContentInput(params) { - let formattedRequest; - if (params.contents) { - formattedRequest = params; - } else { - const content = formatNewContent(params); - formattedRequest = { contents: [content] }; - } - if (params.systemInstruction) { - formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction); - } - return formattedRequest; -} -function formatEmbedContentInput(params) { - if (typeof params === "string" || Array.isArray(params)) { - const content = formatNewContent(params); - return { content }; - } - return params; -} -var VALID_PART_FIELDS = [ - "text", - "inlineData", - "functionCall", - "functionResponse", - "executableCode", - "codeExecutionResult" -]; -var VALID_PARTS_PER_ROLE = { - user: ["text", "inlineData"], - function: ["functionResponse"], - model: ["text", "functionCall", "executableCode", "codeExecutionResult"], - system: ["text"] -}; -function validateChatHistory(history) { - let prevContent = false; - for (const currContent of history) { - const { role, parts } = currContent; - if (!prevContent && role !== "user") { - throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`); - } - if (!POSSIBLE_ROLES.includes(role)) { - throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`); - } - if (!Array.isArray(parts)) { - throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts"); - } - if (parts.length === 0) { - throw new GoogleGenerativeAIError("Each Content should have at least one part"); - } - const countFields = { - text: 0, - inlineData: 0, - functionCall: 0, - functionResponse: 0, - fileData: 0, - executableCode: 0, - codeExecutionResult: 0 - }; - for (const part of parts) { - for (const key of VALID_PART_FIELDS) { - if (key in part) { - countFields[key] += 1; - } - } - } - const validParts = VALID_PARTS_PER_ROLE[role]; - for (const key of VALID_PART_FIELDS) { - if (!validParts.includes(key) && countFields[key] > 0) { - throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`); - } - } - prevContent = true; - } -} -function isValidResponse(response) { - var _a; - if (response.candidates === undefined || response.candidates.length === 0) { - return false; - } - const content = (_a = response.candidates[0]) === null || _a === undefined ? undefined : _a.content; - if (content === undefined) { - return false; - } - if (content.parts === undefined || content.parts.length === 0) { - return false; - } - for (const part of content.parts) { - if (part === undefined || Object.keys(part).length === 0) { - return false; - } - if (part.text !== undefined && part.text === "") { - return false; - } - } - return true; -} -var SILENT_ERROR = "SILENT_ERROR"; - -class ChatSession { - constructor(apiKey, model, params, _requestOptions = {}) { - this.model = model; - this.params = params; - this._requestOptions = _requestOptions; - this._history = []; - this._sendPromise = Promise.resolve(); - this._apiKey = apiKey; - if (params === null || params === undefined ? undefined : params.history) { - validateChatHistory(params.history); - this._history = params.history; - } - } - async getHistory() { - await this._sendPromise; - return this._history; - } - async sendMessage(request2, requestOptions = {}) { - var _a, _b, _c2, _d2, _e2, _f; - await this._sendPromise; - const newContent = formatNewContent(request2); - const generateContentRequest = { - safetySettings: (_a = this.params) === null || _a === undefined ? undefined : _a.safetySettings, - generationConfig: (_b = this.params) === null || _b === undefined ? undefined : _b.generationConfig, - tools: (_c2 = this.params) === null || _c2 === undefined ? undefined : _c2.tools, - toolConfig: (_d2 = this.params) === null || _d2 === undefined ? undefined : _d2.toolConfig, - systemInstruction: (_e2 = this.params) === null || _e2 === undefined ? undefined : _e2.systemInstruction, - cachedContent: (_f = this.params) === null || _f === undefined ? undefined : _f.cachedContent, - contents: [...this._history, newContent] - }; - const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - let finalResult; - this._sendPromise = this._sendPromise.then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)).then((result) => { - var _a2; - if (isValidResponse(result.response)) { - this._history.push(newContent); - const responseContent = Object.assign({ - parts: [], - role: "model" - }, (_a2 = result.response.candidates) === null || _a2 === undefined ? undefined : _a2[0].content); - this._history.push(responseContent); - } else { - const blockErrorMessage = formatBlockErrorMessage(result.response); - if (blockErrorMessage) { - console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); - } - } - finalResult = result; - }).catch((e3) => { - this._sendPromise = Promise.resolve(); - throw e3; - }); - await this._sendPromise; - return finalResult; - } - async sendMessageStream(request2, requestOptions = {}) { - var _a, _b, _c2, _d2, _e2, _f; - await this._sendPromise; - const newContent = formatNewContent(request2); - const generateContentRequest = { - safetySettings: (_a = this.params) === null || _a === undefined ? undefined : _a.safetySettings, - generationConfig: (_b = this.params) === null || _b === undefined ? undefined : _b.generationConfig, - tools: (_c2 = this.params) === null || _c2 === undefined ? undefined : _c2.tools, - toolConfig: (_d2 = this.params) === null || _d2 === undefined ? undefined : _d2.toolConfig, - systemInstruction: (_e2 = this.params) === null || _e2 === undefined ? undefined : _e2.systemInstruction, - cachedContent: (_f = this.params) === null || _f === undefined ? undefined : _f.cachedContent, - contents: [...this._history, newContent] - }; - const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions); - this._sendPromise = this._sendPromise.then(() => streamPromise).catch((_ignored) => { - throw new Error(SILENT_ERROR); - }).then((streamResult) => streamResult.response).then((response) => { - if (isValidResponse(response)) { - this._history.push(newContent); - const responseContent = Object.assign({}, response.candidates[0].content); - if (!responseContent.role) { - responseContent.role = "model"; - } - this._history.push(responseContent); - } else { - const blockErrorMessage = formatBlockErrorMessage(response); - if (blockErrorMessage) { - console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); - } - } - }).catch((e3) => { - if (e3.message !== SILENT_ERROR) { - console.error(e3); - } - }); - return streamPromise; - } -} -async function countTokens(apiKey, model, params, singleRequestOptions) { - const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions); - return response.json(); -} -async function embedContent(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); - return response.json(); -} -async function batchEmbedContents(apiKey, model, params, requestOptions) { - const requestsWithModel = params.requests.map((request2) => { - return Object.assign(Object.assign({}, request2), { model }); - }); - const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions); - return response.json(); -} - -class GenerativeModel { - constructor(apiKey, modelParams, _requestOptions = {}) { - this.apiKey = apiKey; - this._requestOptions = _requestOptions; - if (modelParams.model.includes("/")) { - this.model = modelParams.model; - } else { - this.model = `models/${modelParams.model}`; - } - this.generationConfig = modelParams.generationConfig || {}; - this.safetySettings = modelParams.safetySettings || []; - this.tools = modelParams.tools; - this.toolConfig = modelParams.toolConfig; - this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction); - this.cachedContent = modelParams.cachedContent; - } - async generateContent(request2, requestOptions = {}) { - var _a; - const formattedParams = formatGenerateContentInput(request2); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === undefined ? undefined : _a.name }, formattedParams), generativeModelRequestOptions); - } - async generateContentStream(request2, requestOptions = {}) { - var _a; - const formattedParams = formatGenerateContentInput(request2); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === undefined ? undefined : _a.name }, formattedParams), generativeModelRequestOptions); - } - startChat(startChatParams) { - var _a; - return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === undefined ? undefined : _a.name }, startChatParams), this._requestOptions); - } - async countTokens(request2, requestOptions = {}) { - const formattedParams = formatCountTokensInput(request2, { - model: this.model, - generationConfig: this.generationConfig, - safetySettings: this.safetySettings, - tools: this.tools, - toolConfig: this.toolConfig, - systemInstruction: this.systemInstruction, - cachedContent: this.cachedContent - }); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); - } - async embedContent(request2, requestOptions = {}) { - const formattedParams = formatEmbedContentInput(request2); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); - } - async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) { - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions); - } -} - -class GoogleGenerativeAI { - constructor(apiKey) { - this.apiKey = apiKey; - } - getGenerativeModel(modelParams, requestOptions) { - if (!modelParams.model) { - throw new GoogleGenerativeAIError(`Must provide a model name. ` + `Example: genai.getGenerativeModel({ model: 'my-model-name' })`); - } - return new GenerativeModel(this.apiKey, modelParams, requestOptions); - } - getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) { - if (!cachedContent.name) { - throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field."); - } - if (!cachedContent.model) { - throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field."); - } - const disallowedDuplicates = ["model", "systemInstruction"]; - for (const key of disallowedDuplicates) { - if ((modelParams === null || modelParams === undefined ? undefined : modelParams[key]) && cachedContent[key] && (modelParams === null || modelParams === undefined ? undefined : modelParams[key]) !== cachedContent[key]) { - if (key === "model") { - const modelParamsComp = modelParams.model.startsWith("models/") ? modelParams.model.replace("models/", "") : modelParams.model; - const cachedContentComp = cachedContent.model.startsWith("models/") ? cachedContent.model.replace("models/", "") : cachedContent.model; - if (modelParamsComp === cachedContentComp) { - continue; - } - } - throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` + ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`); - } - } - const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent }); - return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions); - } -} - // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/helpers/bind.js function bind(fn, thisArg) { return function wrap() { @@ -175302,11 +171541,11 @@ var extend = (a2, b2, thisArg, { allOwnKeys } = {}) => { }, { allOwnKeys }); return a2; }; -var stripBOM = (content) => { - if (content.charCodeAt(0) === 65279) { - content = content.slice(1); +var stripBOM = (content52) => { + if (content52.charCodeAt(0) === 65279) { + content52 = content52.slice(1); } - return content; + return content52; }; var inherits = (constructor, superConstructor, props, descriptors) => { constructor.prototype = Object.create(superConstructor.prototype, descriptors); @@ -175343,14 +171582,14 @@ var toFlatObject = (sourceObj, destObj, filter, propFilter) => { } while (sourceObj && (!filter || filter(sourceObj, destObj)) && sourceObj !== Object.prototype); return destObj; }; -var endsWith = (str, searchString, position) => { +var endsWith = (str, searchString, position3) => { str = String(str); - if (position === undefined || position > str.length) { - position = str.length; + if (position3 === undefined || position3 > str.length) { + position3 = str.length; } - position -= searchString.length; - const lastIndex = str.indexOf(searchString, position); - return lastIndex !== -1 && lastIndex === position; + position3 -= searchString.length; + const lastIndex = str.indexOf(searchString, position3); + return lastIndex !== -1 && lastIndex === position3; }; var toArray2 = (thing) => { if (!thing) @@ -175456,13 +171695,13 @@ var toJSONObject = (obj) => { } if (!("toJSON" in source)) { stack[i2] = source; - const target = isArray(source) ? [] : {}; + const target2 = isArray(source) ? [] : {}; forEach2(source, (value, key) => { const reducedValue = visit(value, i2 + 1); - !isUndefined(reducedValue) && (target[key] = reducedValue); + !isUndefined(reducedValue) && (target2[key] = reducedValue); }); stack[i2] = undefined; - return target; + return target2; } } return source; @@ -175686,8 +171925,8 @@ function toFormData(obj, formData, options) { value = JSON.stringify(value); } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { key = removeBrackets(key); - arr.forEach(function each(el, index2) { - !(utils_default.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", convertValue(el)); + arr.forEach(function each(el, index3) { + !(utils_default.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index3, dots) : indexes === null ? key : key + "[]", convertValue(el)); }); return false; } @@ -175728,7 +171967,7 @@ function toFormData(obj, formData, options) { var toFormData_default = toFormData; // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/helpers/AxiosURLSearchParams.js -function encode(str) { +function encode2(str) { const charMap = { "!": "%21", "'": "%27", @@ -175752,8 +171991,8 @@ prototype.append = function append(name, value) { }; prototype.toString = function toString3(encoder) { const _encode = encoder ? function(value) { - return encoder.call(this, value, encode); - } : encode; + return encoder.call(this, value, encode2); + } : encode2; return this._pairs.map(function each(pair) { return _encode(pair[0]) + "=" + _encode(pair[1]); }, "").join("&"); @@ -175761,14 +172000,14 @@ prototype.toString = function toString3(encoder) { var AxiosURLSearchParams_default = AxiosURLSearchParams; // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/helpers/buildURL.js -function encode2(val) { +function encode3(val) { return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+"); } function buildURL(url, params, options) { if (!params) { return url; } - const _encode = options && options.encode || encode2; + const _encode = options && options.encode || encode3; const _options = utils_default.isFunction(options) ? { serialize: options } : options; @@ -175924,27 +172163,27 @@ function arrayToObject(arr) { return obj; } function formDataToJSON(formData) { - function buildPath(path2, value, target, index2) { - let name = path2[index2++]; + function buildPath(path2, value, target2, index3) { + let name = path2[index3++]; if (name === "__proto__") return true; const isNumericKey = Number.isFinite(+name); - const isLast = index2 >= path2.length; - name = !name && utils_default.isArray(target) ? target.length : name; + const isLast = index3 >= path2.length; + name = !name && utils_default.isArray(target2) ? target2.length : name; if (isLast) { - if (utils_default.hasOwnProp(target, name)) { - target[name] = [target[name], value]; + if (utils_default.hasOwnProp(target2, name)) { + target2[name] = [target2[name], value]; } else { - target[name] = value; + target2[name] = value; } return !isNumericKey; } - if (!target[name] || !utils_default.isObject(target[name])) { - target[name] = []; + if (!target2[name] || !utils_default.isObject(target2[name])) { + target2[name] = []; } - const result = buildPath(path2, value, target[name], index2); - if (result && utils_default.isArray(target[name])) { - target[name] = arrayToObject(target[name]); + const result = buildPath(path2, value, target2[name], index3); + if (result && utils_default.isArray(target2[name])) { + target2[name] = arrayToObject(target2[name]); } return !isNumericKey; } @@ -176090,10 +172329,10 @@ var parseHeaders_default = (rawHeaders) => { let val; let i2; rawHeaders && rawHeaders.split(` -`).forEach(function parser(line2) { - i2 = line2.indexOf(":"); - key = line2.substring(0, i2).trim().toLowerCase(); - val = line2.substring(i2 + 1).trim(); +`).forEach(function parser(line3) { + i2 = line3.indexOf(":"); + key = line3.substring(0, i2).trim().toLowerCase(); + val = line3.substring(i2 + 1).trim(); if (!key || parsed[key] && ignoreDuplicateOf[key]) { return; } @@ -176172,8 +172411,8 @@ function matchHeaderValue(context, value, header, filter2, isHeaderNameFilter) { } } function formatHeader(header) { - return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char2, str) => { - return char2.toUpperCase() + str; + return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w2, char3, str) => { + return char3.toUpperCase() + str; }); } function buildAccessors(obj, header) { @@ -176334,7 +172573,7 @@ class AxiosHeaders { } static concat(first, ...targets) { const computed = new this(first); - targets.forEach((target) => computed.set(target)); + targets.forEach((target2) => computed.set(target2)); return computed; } static accessor(header) { @@ -176667,7 +172906,7 @@ class AxiosTransformStream extends stream.Transform { var AxiosTransformStream_default = AxiosTransformStream; // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/adapters/http.js -import { EventEmitter } from "events"; +import { EventEmitter as EventEmitter3 } from "events"; // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/helpers/formDataToStream.js import util from "util"; @@ -176690,10 +172929,10 @@ var readBlob_default = readBlob; // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/helpers/formDataToStream.js var BOUNDARY_ALPHABET = platform_default.ALPHABET.ALPHA_DIGIT + "-_"; -var textEncoder = typeof TextEncoder === "function" ? new TextEncoder : new util.TextEncoder; +var textEncoder3 = typeof TextEncoder === "function" ? new TextEncoder : new util.TextEncoder; var CRLF = `\r `; -var CRLF_BYTES = textEncoder.encode(CRLF); +var CRLF_BYTES = textEncoder3.encode(CRLF); var CRLF_BYTES_COUNT = 2; class FormDataPart { @@ -176702,11 +172941,11 @@ class FormDataPart { const isStringValue = utils_default.isString(value); let headers = `Content-Disposition: form-data; name="${escapeName(name)}"${!isStringValue && value.name ? `; filename="${escapeName(value.name)}"` : ""}${CRLF}`; if (isStringValue) { - value = textEncoder.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); + value = textEncoder3.encode(String(value).replace(/\r?\n|\r\n?/g, CRLF)); } else { headers += `Content-Type: ${value.type || "application/octet-stream"}${CRLF}`; } - this.headers = textEncoder.encode(headers + CRLF); + this.headers = textEncoder3.encode(headers + CRLF); this.contentLength = isStringValue ? value.byteLength : value.size; this.size = this.headers.byteLength + this.contentLength + CRLF_BYTES_COUNT; this.name = name; @@ -176732,9 +172971,9 @@ class FormDataPart { } var formDataToStream = (form, headersHandler, options) => { const { - tag: tag2 = "form-data-boundary", + tag: tag3 = "form-data-boundary", size = 25, - boundary = tag2 + "-" + platform_default.generateString(size, BOUNDARY_ALPHABET) + boundary = tag3 + "-" + platform_default.generateString(size, BOUNDARY_ALPHABET) } = options || {}; if (!utils_default.isFormData(form)) { throw TypeError("FormData instance required"); @@ -176742,8 +172981,8 @@ var formDataToStream = (form, headersHandler, options) => { if (boundary.length < 1 || boundary.length > 70) { throw Error("boundary must be 10-70 characters long"); } - const boundaryBytes = textEncoder.encode("--" + boundary + CRLF); - const footerBytes = textEncoder.encode("--" + boundary + "--" + CRLF); + const boundaryBytes = textEncoder3.encode("--" + boundary + CRLF); + const footerBytes = textEncoder3.encode("--" + boundary + "--" + CRLF); let contentLength = footerBytes.byteLength; const parts = Array.from(form.entries()).map(([name, value]) => { const part = new FormDataPart(name, value); @@ -176922,12 +173161,12 @@ var speedometer_default = speedometer; // node_modules/.pnpm/axios@1.15.0/node_modules/axios/lib/helpers/throttle.js function throttle(fn, freq) { - let timestamp2 = 0; + let timestamp3 = 0; let threshold = 1000 / freq; let lastArgs; let timer; const invoke = (args, now = Date.now()) => { - timestamp2 = now; + timestamp3 = now; lastArgs = null; if (timer) { clearTimeout(timer); @@ -176937,7 +173176,7 @@ function throttle(fn, freq) { }; const throttled = (...args) => { const now = Date.now(); - const passed = now - timestamp2; + const passed = now - timestamp3; if (passed >= threshold) { invoke(args, now); } else { @@ -177083,7 +173322,7 @@ class Http2Sessions { } } } - const session2 = http2.connect(authority, options); + const session3 = http2.connect(authority, options); let removed; const removeSession = () => { if (removed) { @@ -177092,25 +173331,25 @@ class Http2Sessions { removed = true; let entries = authoritySessions, len = entries.length, i2 = len; while (i2--) { - if (entries[i2][0] === session2) { + if (entries[i2][0] === session3) { if (len === 1) { delete this.sessions[authority]; } else { entries.splice(i2, 1); } - if (!session2.closed) { - session2.close(); + if (!session3.closed) { + session3.close(); } return; } } }; - const originalRequestFn = session2.request; + const originalRequestFn = session3.request; const { sessionTimeout } = options; if (sessionTimeout != null) { let timer; let streamsCount = 0; - session2.request = function() { + session3.request = function() { const stream4 = originalRequestFn.apply(this, arguments); streamsCount++; if (timer) { @@ -177128,10 +173367,10 @@ class Http2Sessions { return stream4; }; } - session2.once("close", removeSession); - let entry = [session2, options]; + session3.once("close", removeSession); + let entry = [session3, options]; authoritySessions ? authoritySessions.push(entry) : authoritySessions = this.sessions[authority] = [entry]; - return session2; + return session3; } } var http2Sessions = new Http2Sessions; @@ -177217,7 +173456,7 @@ var http2Transport = { request(options, cb2) { const authority = options.protocol + "//" + options.hostname + ":" + (options.port || (options.protocol === "https:" ? 443 : 80)); const { http2Options, headers } = options; - const session2 = http2Sessions.getSession(authority, http2Options); + const session3 = http2Sessions.getSession(authority, http2Options); const { HTTP2_HEADER_SCHEME, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS } = http2.constants; const http2Headers = { [HTTP2_HEADER_SCHEME]: options.protocol.replace(":", ""), @@ -177227,7 +173466,7 @@ var http2Transport = { utils_default.forEach(headers, (header, name) => { name.charAt(0) !== ":" && (http2Headers[name] = header); }); - const req = session2.request(http2Headers); + const req = session3.request(http2Headers); req.once("response", (responseHeaders) => { const response = req; responseHeaders = Object.assign({}, responseHeaders); @@ -177268,7 +173507,7 @@ var http_default = isHttpAdapterSupported && function httpAdapter(config) { }); }; } - const abortEmitter = new EventEmitter; + const abortEmitter = new EventEmitter3; function abort(reason) { try { abortEmitter.emit("abort", !reason || reason.type ? new CanceledError_default(null, config, req) : reason); @@ -177687,9 +173926,9 @@ var headersToObject = (thing) => thing instanceof AxiosHeaders_default ? { ...th function mergeConfig(config1, config2) { config2 = config2 || {}; const config = {}; - function getMergedValue(target, source, prop, caseless) { - if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { - return utils_default.merge.call({ caseless }, target, source); + function getMergedValue(target2, source, prop, caseless) { + if (utils_default.isPlainObject(target2) && utils_default.isPlainObject(source)) { + return utils_default.merge.call({ caseless }, target2, source); } else if (utils_default.isPlainObject(source)) { return utils_default.merge({}, source); } else if (utils_default.isArray(source)) { @@ -178215,14 +174454,14 @@ var getFetch = (config) => { let env3 = config && config.env || {}; const { fetch: fetch2, Request: Request2, Response: Response2 } = env3; const seeds = [Request2, Response2, fetch2]; - let len = seeds.length, i2 = len, seed, target, map = seedCache; + let len = seeds.length, i2 = len, seed, target2, map = seedCache; while (i2--) { seed = seeds[i2]; - target = map.get(seed); - target === undefined && map.set(seed, target = i2 ? new Map : factory(env3)); - map = target; + target2 = map.get(seed); + target2 === undefined && map.set(seed, target2 = i2 ? new Map : factory(env3)); + map = target2; } - return target; + return target2; }; var adapter = getFetch(); @@ -178321,17 +174560,17 @@ var validators = {}; }; }); var deprecatedWarnings = {}; -validators.transitional = function transitional(validator, version2, message) { +validators.transitional = function transitional(validator, version4, message) { function formatMessage(opt, desc2) { return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc2 + (message ? ". " + message : ""); } return (value, opt, opts) => { if (validator === false) { - throw new AxiosError_default(formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")), AxiosError_default.ERR_DEPRECATED); + throw new AxiosError_default(formatMessage(opt, " has been removed" + (version4 ? " in " + version4 : "")), AxiosError_default.ERR_DEPRECATED); } - if (version2 && !deprecatedWarnings[opt]) { + if (version4 && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; - console.warn(formatMessage(opt, " has been deprecated since v" + version2 + " and will be removed in the near future")); + console.warn(formatMessage(opt, " has been deprecated since v" + version4 + " and will be removed in the near future")); } return validator ? validator(value, opt, opts) : true; }; @@ -178607,9 +174846,9 @@ class CancelToken { if (!this._listeners) { return; } - const index2 = this._listeners.indexOf(listener); - if (index2 !== -1) { - this._listeners.splice(index2, 1); + const index3 = this._listeners.indexOf(listener); + if (index3 !== -1) { + this._listeners.splice(index3, 1); } } toAbortSignal() { @@ -178757,8 +174996,8 @@ axios.default = axios; var axios_default = axios; // src/api/interview/interview-service.ts -var genAI = new GoogleGenerativeAI(config_default.GEMINI_API_KEY); -var model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" }); +var genAI2 = new GoogleGenerativeAI(config_default.GEMINI_API_KEY); +var model2 = genAI2.getGenerativeModel({ model: "gemini-2.5-flash" }); var ROUND_FOCUS = { technical: `TECHNICAL (DSA) ROUND: Ask classic data structures & algorithms problems only (e.g. arrays/strings, two pointers, sliding window, binary search, trees, graphs, heaps, hash maps, DP, greedy). Each question should be solvable by implementing a function or algorithm with clear constraints, edge cases, and time/space complexity discussion. Do NOT ask for large system or service design. Do NOT ask behavioral questions.`, behavioral: `BEHAVIORAL ROUND: Use situational and past-experience questions only. Prefer STAR-style prompts (Situation, Task, Action, Result). Cover teamwork, conflict, leadership, deadlines, mistakes, and communication. Do not ask for code, pseudocode, or system architecture.`, @@ -178771,9 +175010,9 @@ var LEVEL_FOCUS = { hard: "Difficulty: HARD \u2014 demanding questions; expect strong depth and trade-off reasoning.", mixed: "Difficulty: MIXED \u2014 vary difficulty within the set while staying appropriate to experience." }; -async function textToAudio(text2) { +async function textToAudio(text3) { const data = { - text: text2, + text: text3, voiceId: "en-US-terrell" }; try { @@ -178795,16 +175034,23 @@ async function generateQuestions(data) { role, experience, customRequirements, + resumeContext, questionCount, interviewLevel, round, codingLanguage } = data; - const count = Math.min(Math.max(Number(questionCount) || 1, 1), 5); + const count2 = Math.min(Math.max(Number(questionCount) || 1, 1), 5); const levelLine = LEVEL_FOCUS[interviewLevel]; const roundLine = ROUND_FOCUS[round]; const langLine = (round === "technical" || round === "lld") && codingLanguage ? ` PROGRAMMING LANGUAGE: The candidate selected "${codingLanguage}" for their editor. Phrase each question so a solution is naturally written in that language (syntax may vary; keep the problem language-agnostic but mention they may implement in ${codingLanguage}).` : ""; + const MAX_RESUME_CHARS = 3500; + const resumeLine = resumeContext?.trim() ? ` +CANDIDATE RESUME PROFILE: +${resumeContext.slice(0, MAX_RESUME_CHARS)} + +IMPORTANT: Use the resume profile above to personalise the questions. Reference specific technologies, projects, or experiences mentioned. Prioritise gaps or depth opportunities visible in the resume.` : ""; const prompt = ` You are an expert interviewer for software development roles. Generate a set of high-quality interview questions tailored to the candidate's role, experience, round type, and difficulty. @@ -178818,15 +175064,17 @@ ROUND AND LEVEL: ${roundLine} ${levelLine} ${langLine} +${resumeLine} CUSTOM REQUIREMENTS FROM CANDIDATE: ${customRequirements?.trim() ? customRequirements : "No extra requirements provided."} INSTRUCTIONS: -- Generate exactly ${count} questions (no more, no fewer). +- Generate exactly ${count2} questions (no more, no fewer). - Every question must fit the selected round type above; do not blend unrelated round types. - Calibrate depth to the experience level and the interview level (${interviewLevel}). - Prioritize custom requirements when provided. +- When a resume profile is present, tailor at least half the questions to the candidate's actual experience, tech stack, or projects from their resume. - Avoid generic filler; be specific and practical for the role. - Do not repeat questions. Do not include answers. @@ -178847,14 +175095,14 @@ Use null for audioUrl on every question (the server will fill audio). } }; try { - const result = await model.generateContent(payload); + const result = await model2.generateContent(payload); const data2 = JSON.parse(result.response.text()); if (!data2.interviewId) { data2.interviewId = v4_default(); } if (Array.isArray(data2.questions)) { - if (data2.questions.length > count) { - data2.questions = data2.questions.slice(0, count); + if (data2.questions.length > count2) { + data2.questions = data2.questions.slice(0, count2); } for (const question of data2.questions) { const audioData = await textToAudio(question.text); @@ -178905,7 +175153,7 @@ Answer: ${answer}`; } } }; - const result = await model.generateContent(payload); + const result = await model2.generateContent(payload); let responseText; if (result && result.response && typeof result.response.text === "function") { responseText = result.response.text(); @@ -178933,6 +175181,7 @@ var generateInterviewQuestionsSchema = create$3({ role: create$6().required("Role is required"), experience: create$6().required("Experience is required"), customRequirements: create$6().optional(), + resumeContext: create$6().optional().max(4000, "Resume context too long"), questionCount: create$5().required("Question count is required"), interviewLevel: create$6().required("Interview level is required"), round: create$6().required("Round is required"), @@ -178968,14 +175217,6 @@ var api_default = () => { // src/loaders/express.ts var import_cookie_parser = __toESM(require_cookie_parser(), 1); -// src/utils/redis.js -var import_ioredis2 = __toESM(require_built3(), 1); -var redisUrl2 = config_default2.REDIS_URL; -if (!redisUrl2) { - throw new Error("REDIS_URL must be set in your environment"); -} -var redisClient = new import_ioredis2.default(redisUrl2); - // src/shared/ratelimiter.ts var CAPACITY = 10; var WINDOW = 60; @@ -178989,7 +175230,7 @@ var rateLimitMiddleware = asyncHandler_default(async (req, res, next) => { } const key = `${KEY_PREFIX}:${userId}`; const now = Date.now() / 1000; - const bucket = await redisClient.hgetall(key); + const bucket = await redis_default.hgetall(key); let tokens = parseFloat(bucket.tokens) || CAPACITY; let last = parseFloat(bucket.last) || now; const delta = now - last; @@ -179000,7 +175241,7 @@ var rateLimitMiddleware = asyncHandler_default(async (req, res, next) => { return res.set("Retry-After", String(retrySecs)).status(429).json({ error: `Too many submissions. Try again in ${retrySecs}s.` }); } tokens -= 1; - const pipeline = redisClient.multi(); + const pipeline = redis_default.multi(); pipeline.hset(key, "tokens", tokens, "last", last); pipeline.expire(key, WINDOW); await pipeline.exec(); @@ -179057,12 +175298,12 @@ var express_default = ({ app }) => { var loaders_default = async ({ expressApp }) => { - express_default({ app: expressApp }); await getDrizzleClient(); logger_default.info("\uD83D\uDEE1\uFE0F Database loaded \uD83D\uDEE1\uFE0F"); + express_default({ app: expressApp }); + logger_default.info("\uD83D\uDEE1\uFE0F Express loaded \uD83D\uDEE1\uFE0F"); await loadGoogleOAuthClient(); logger_default.info("\uD83D\uDEE1\uFE0F Google OAuth loaded \uD83D\uDEE1\uFE0F"); - logger_default.info("\uD83D\uDEE1\uFE0F Express loaded \uD83D\uDEE1\uFE0F"); logger_default.info("\uD83D\uDEE1\uFE0F All modules loaded! \uD83D\uDEE1\uFE0F"); }; diff --git a/backend/src/api/contest/contest.route.ts b/backend/src/api/contest/contest.route.ts index bdfbcc8..aa809c0 100644 --- a/backend/src/api/contest/contest.route.ts +++ b/backend/src/api/contest/contest.route.ts @@ -1,6 +1,6 @@ // import {createContest,getAllContests,getContestById,getClock,getLeaderboard,registerContest} from "./contest.controller.js" // import { Router } from 'express'; -import { verifyJWT } from '../../middlewares/auth.middleware.js'; +// import { verifyJWT } from '../../middlewares/auth.middleware.js'; // const router = Router(); diff --git a/backend/src/config/index.ts b/backend/src/config/index.ts index 1e9c914..431382e 100644 --- a/backend/src/config/index.ts +++ b/backend/src/config/index.ts @@ -1,13 +1,17 @@ import dotenv from 'dotenv'; import path from 'path'; import * as yup from 'yup'; +import { fileURLToPath } from 'url'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); dotenv.config({ path: path.join(__dirname, '../../.env') }); const envSchema = yup.object().shape({ - NODE_ENV : yup.string().oneOf(['dev','production']).default('dev'), - DATABASE_URL : yup.string().required('Database URL is Required'), - PORT : yup.string().default('8000'), + NODE_ENV: yup.string().oneOf(['dev', 'production']).default('dev'), + DATABASE_URL: yup.string().required('Database URL is Required'), + PORT: yup.string().default('8000'), ALLOWED_ORIGINS: yup.string(), // JWT_SECRET : yup.string().required(), // JWT_REFRESH_SECRET: yup.string().required(), @@ -17,13 +21,13 @@ const envSchema = yup.object().shape({ GEMINI_API_KEY: yup.string().optional(), // GOOGLE_CALLBACK_URL : yup.string().required(), LOG_LEVEL: yup - .string() - .oneOf(['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly']) - .default('info'), + .string() + .oneOf(['error', 'warn', 'info', 'http', 'verbose', 'debug', 'silly']) + .default('info'), API_VERSION: yup.string().default('v1'), MAX_API_REQUEST_RETRIES: yup.number().integer().default(3), - CLIENT_URL : yup.string().default('https://code-sm.vercel.app'), - MURF_API_KEY : yup.string().optional(), + CLIENT_URL: yup.string().default('https://code-sm.vercel.app'), + MURF_API_KEY: yup.string().optional(), REDIS_HOST: yup.string().required(), REDIS_PASSWORD: yup.string().required(), REDIS_PORT: yup.string().required(), @@ -31,19 +35,19 @@ const envSchema = yup.object().shape({ REDIS_URL: yup.string().required(), REFRESH_TOKEN_EXPIRY: yup.string().required(), REFRESH_TOKEN_SECRET: yup.string().required(), - MONGO_URI : yup.string().required(), + MONGO_URI: yup.string().required(), ACCESS_TOKEN_EXPIRY: yup.string().required(), ACCESS_TOKEN_SECRET: yup.string().required(), AWS_ACCESS_KEY_ID: yup.string().required(), AWS_BUCKET_NAME: yup.string().required(), - AWS_REGION : yup.string().required(), - VITE_API_URL : yup.string().required(), + AWS_REGION: yup.string().required(), + VITE_API_URL: yup.string().required(), EMAIL_FROM: yup.string().required(), EMAIL_HOST: yup.string().required(), EMAIL_PASS: yup.string().required(), EMAIL_PORT: yup.number().required(), EMAIL_USER: yup.string().required(), - SMTP_VERIFY_URL : yup.string().required(), + SMTP_VERIFY_URL: yup.string().required(), GOOGLE_REDIRECT_URI: yup.string().required(), JWT_SECRET: yup.string().required(), }) diff --git a/backend/src/scripts/seed-admin.js b/backend/src/scripts/seed-admin.js index aa106f7..63a03af 100644 --- a/backend/src/scripts/seed-admin.js +++ b/backend/src/scripts/seed-admin.js @@ -1,27 +1,27 @@ import bcrypt from "bcryptjs"; -import User from "../models/user.model.js"; -import env from '../config/index.js' +import { user } from "../db/schema.ts"; +import env from '../config/index.ts' export async function seedAdmin() { - const adminExists = await User.findOne({ role: "admin" }); + const adminExists = await user.findOne({ role: "ADMIN" }); if (adminExists) { console.log("Admin already exists. Skipping."); process.exit(0); } - const { ADMIN_USERNAME,ADMIN_FULLNAME, ADMIN_EMAIL, ADMIN_PASSWORD } = env; + const { ADMIN_USERNAME, ADMIN_FULLNAME, ADMIN_EMAIL, ADMIN_PASSWORD } = env; if (!ADMIN_EMAIL || !ADMIN_PASSWORD) { throw new Error("ADMIN_EMAIL / ADMIN_PASSWORD missing"); } const passwordHash = await bcrypt.hash(ADMIN_PASSWORD, 12); - await User.create({ + await user.create({ username: ADMIN_USERNAME, - fullName : ADMIN_FULLNAME, + fullName: ADMIN_FULLNAME, email: ADMIN_EMAIL, - password : passwordHash, + password: passwordHash, role: "admin", }); diff --git a/backend/tsconfig.json b/backend/tsconfig.json index 2de74a7..cacc83c 100644 --- a/backend/tsconfig.json +++ b/backend/tsconfig.json @@ -10,8 +10,8 @@ "experimentalDecorators": true, "emitDecoratorMetadata": true, "forceConsistentCasingInFileNames": true, - "moduleResolution": "node", - "module": "commonjs", + "moduleResolution": "node16", + "module": "node16", "pretty": true, "sourceMap": false, "outDir": "./dist", From 620e2acfb2e58983638a0117d64e65819c527f14 Mon Sep 17 00:00:00 2001 From: Kmadhav824 Date: Fri, 15 May 2026 23:58:13 +0530 Subject: [PATCH 2/2] Corrected navitems for create problem and corrected problem-schema to match data from form --- Frontend/src/components/NavBar.jsx | 28 +++++++++++------------ backend/src/api/problem/problem-schema.ts | 6 ++--- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/Frontend/src/components/NavBar.jsx b/Frontend/src/components/NavBar.jsx index bbbc454..94af9c3 100644 --- a/Frontend/src/components/NavBar.jsx +++ b/Frontend/src/components/NavBar.jsx @@ -61,9 +61,9 @@ export default function NewNav() { { to: "/problems", label: "Problems" }, ...(userRole === "AUTHOR" || userRole === "ADMIN" ? [ - { to: "/newproblem", label: "Create Problem" }, - { to: "/contests/create", label: "Create Contest" }, - ] + { to: "/createProblem", label: "Create Problem" }, + { to: "/contests/create", label: "Create Contest" }, + ] : []), { to: "/contests", label: "Contests" }, { to: "/interview", label: "Interview" }, @@ -72,10 +72,10 @@ export default function NewNav() { return (

- +