ente-cli 0.1.0 → 0.4.53
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +274 -0
- package/dist/SKILL.md +344 -0
- package/dist/cli.mjs +16485 -0
- package/dist/cli.mjs.map +7 -0
- package/package.json +28 -15
- package/dist/api.d.ts +0 -221
- package/dist/api.js +0 -182
- package/dist/commands/activity.d.ts +0 -16
- package/dist/commands/activity.js +0 -345
- package/dist/commands/auth.d.ts +0 -7
- package/dist/commands/auth.js +0 -86
- package/dist/commands/entity.d.ts +0 -13
- package/dist/commands/entity.js +0 -205
- package/dist/commands/search.d.ts +0 -3
- package/dist/commands/search.js +0 -13
- package/dist/commands/task.d.ts +0 -3
- package/dist/commands/task.js +0 -305
- package/dist/commands/update.d.ts +0 -7
- package/dist/commands/update.js +0 -104
- package/dist/deadline.d.ts +0 -6
- package/dist/deadline.js +0 -171
- package/dist/format.d.ts +0 -21
- package/dist/format.js +0 -287
- package/dist/guide/index.d.ts +0 -2
- package/dist/guide/index.js +0 -27
- package/dist/guide/topics.d.ts +0 -5
- package/dist/guide/topics.js +0 -208
- package/dist/index.d.ts +0 -2
- package/dist/index.js +0 -54
- package/dist/resolve.d.ts +0 -11
- package/dist/resolve.js +0 -66
- package/dist/utils.d.ts +0 -4
- package/dist/utils.js +0 -18
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../node_modules/.pnpm/typanion@3.14.0/node_modules/typanion/lib/index.js", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/constants.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/errors.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/utils.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/Command.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/platform/node.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/core.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/format.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/HelpCommand.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/Cli.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/index.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/definitions.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/help.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Proxy.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/tokens.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/builtins/version.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/index.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Array.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Boolean.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Counter.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/Rest.mjs", "../node_modules/.pnpm/clipanion@4.0.0-rc.4_typanion@3.14.0/node_modules/clipanion/lib/advanced/options/String.mjs", "../core/config.ts", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/error.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/primitive.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/date.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/extract.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/util.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/struct.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/parse.js", "../node_modules/.pnpm/smol-toml@1.9.0/node_modules/smol-toml/dist/stringify.js", "../core/update.ts", "../ente/version.ts", "../ente/branding.ts", "../ente/skill.ts", "../core/jwt-cache.ts", "../core/errors.ts", "../core/output.ts", "../core/command.ts", "../ente/attrs.ts", "../core/transport.ts", "../ente/client.ts", "../ente/datetime.ts", "../ente/format.ts", "../ente/entityResolution.ts", "../ente/resolve.ts", "../ente/command.ts", "../ente/convexClient.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/index.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/values/base64.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/common/index.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/values/value.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/values/validators.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/values/validator.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/values/errors.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/values/compare_utf8.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/browser/logging.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/server/functionName.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/server/components/paths.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/server/api.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/vendor/long.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/vendor/jwt-decode/index.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/browser/sync/authentication_manager.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/browser/simple_client.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/constants.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/node-gyp-build.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/node-gyp-build@4.8.4/node_modules/node-gyp-build/index.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/fallback.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/bufferutil@4.0.9/node_modules/bufferutil/index.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/buffer-util.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/limiter.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/permessage-deflate.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/validation.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/receiver.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/sender.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/event-target.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/extension.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/websocket.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/stream.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/subprotocol.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/lib/websocket-server.js", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/browser/simple_client-node.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/node_modules/.pnpm/ws@8.21.0_bufferutil@4.0.9/node_modules/ws/wrapper.mjs", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/browser/http_client.ts", "../core/convex.ts", "../ente/commands/authPair.ts", "../ente/commands/auth.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/server/pagination.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/server/logVars.ts", "../node_modules/.pnpm/convex@1.46.0/node_modules/convex/src/server/schema.ts", "../ente/convexResolve.ts", "../ente/pinRole.ts", "../ente/htmlBlocks.ts", "../ente/commands/pins.ts", "../ente/commands/entity.ts", "../ente/commands/activity.ts", "../ente/content.ts", "../ente/fileAttachments.ts", "../ente/source-created-at.ts", "../ente/deadline.ts", "../ente/commands/task.ts", "../ente/commands/list.ts", "../ente/commands/users.ts", "../ente/commands/models.ts", "../ente/commands/space.ts", "../ente/commands/search.ts", "../ente/commands/evidence.ts", "../ente/commands/ask.ts", "../ente/commands/query.ts", "../ente/commands/recordingPipeline.ts", "../ente/commands/recordings.ts", "../ente/commands/agent.ts", "../ente/commands/agenda.ts", "../ente/commands/feedback.ts", "../ente/commands/guide.ts", "../ente/canvasHtml.ts", "../ente/commands/canvas.ts", "../ente/commands/notification.ts", "../ente/notificationEmailContract.ts", "../ente/commands/agentMail.ts", "../ente/agentMailContract.ts", "../ente/inlineImages.ts", "../cli.ts"],
|
|
4
|
+
"sourcesContent": ["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nconst simpleKeyRegExp = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nfunction getPrintable(value) {\n if (value === null)\n return `null`;\n if (value === undefined)\n return `undefined`;\n if (value === ``)\n return `an empty string`;\n if (typeof value === 'symbol')\n return `<${value.toString()}>`;\n if (Array.isArray(value))\n return `an array`;\n return JSON.stringify(value);\n}\nfunction getPrintableArray(value, conjunction) {\n if (value.length === 0)\n return `nothing`;\n if (value.length === 1)\n return getPrintable(value[0]);\n const rest = value.slice(0, -1);\n const trailing = value[value.length - 1];\n const separator = value.length > 2\n ? `, ${conjunction} `\n : ` ${conjunction} `;\n return `${rest.map(value => getPrintable(value)).join(`, `)}${separator}${getPrintable(trailing)}`;\n}\nfunction computeKey(state, key) {\n var _a, _b, _c;\n if (typeof key === `number`) {\n return `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}[${key}]`;\n }\n else if (simpleKeyRegExp.test(key)) {\n return `${(_b = state === null || state === void 0 ? void 0 : state.p) !== null && _b !== void 0 ? _b : ``}.${key}`;\n }\n else {\n return `${(_c = state === null || state === void 0 ? void 0 : state.p) !== null && _c !== void 0 ? _c : `.`}[${JSON.stringify(key)}]`;\n }\n}\nfunction plural(n, singular, plural) {\n return n === 1 ? singular : plural;\n}\n\nconst colorStringRegExp = /^#[0-9a-f]{6}$/i;\nconst colorStringAlphaRegExp = /^#[0-9a-f]{6}([0-9a-f]{2})?$/i;\n// https://stackoverflow.com/a/475217/880703\nconst base64RegExp = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;\n// https://stackoverflow.com/a/14166194/880703\nconst uuid4RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i;\n// https://stackoverflow.com/a/28022901/880703 + https://www.debuggex.com/r/bl8J35wMKk48a7u_\nconst iso8601RegExp = /^(?:[1-9]\\d{3}(-?)(?:(?:0[1-9]|1[0-2])\\1(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])\\1(?:29|30)|(?:0[13578]|1[02])(?:\\1)31|00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[0-5]))|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\\2)29|-?366))T(?:[01]\\d|2[0-3])(:?)[0-5]\\d(?:\\3[0-5]\\d)?(?:Z|[+-][01]\\d(?:\\3[0-5]\\d)?)$/;\n\nfunction pushError({ errors, p } = {}, message) {\n errors === null || errors === void 0 ? void 0 : errors.push(`${p !== null && p !== void 0 ? p : `.`}: ${message}`);\n return false;\n}\nfunction makeSetter(target, key) {\n return (v) => {\n target[key] = v;\n };\n}\nfunction makeCoercionFn(target, key) {\n return (v) => {\n const previous = target[key];\n target[key] = v;\n return makeCoercionFn(target, key).bind(null, previous);\n };\n}\nfunction makeLazyCoercionFn(fn, orig, generator) {\n const commit = () => {\n fn(generator());\n return revert;\n };\n const revert = () => {\n fn(orig);\n return commit;\n };\n return commit;\n}\n\n/**\n * Create a validator that always returns true and never refines the type.\n */\nfunction isUnknown() {\n return makeValidator({\n test: (value, state) => {\n return true;\n },\n });\n}\nfunction isLiteral(expected) {\n return makeValidator({\n test: (value, state) => {\n if (value !== expected)\n return pushError(state, `Expected ${getPrintable(expected)} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a string.\n * Refines the type to `string`.\n */\nfunction isString() {\n return makeValidator({\n test: (value, state) => {\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\nfunction isEnum(enumSpec) {\n const valuesArray = Array.isArray(enumSpec) ? enumSpec : Object.values(enumSpec);\n const isAlphaNum = valuesArray.every(item => typeof item === 'string' || typeof item === 'number');\n const values = new Set(valuesArray);\n if (values.size === 1)\n return isLiteral([...values][0]);\n return makeValidator({\n test: (value, state) => {\n if (!values.has(value)) {\n if (isAlphaNum) {\n return pushError(state, `Expected one of ${getPrintableArray(valuesArray, `or`)} (got ${getPrintable(value)})`);\n }\n else {\n return pushError(state, `Expected a valid enumeration value (got ${getPrintable(value)})`);\n }\n }\n return true;\n },\n });\n}\nconst BOOLEAN_COERCIONS = new Map([\n [`true`, true],\n [`True`, true],\n [`1`, true],\n [1, true],\n [`false`, false],\n [`False`, false],\n [`0`, false],\n [0, false],\n]);\n/**\n * Create a validator that only returns true when the tested value is a\n * boolean. Refines the type to `boolean`.\n *\n * Supports coercion:\n * - 'true' / 'True' / '1' / 1 will turn to `true`\n * - 'false' / 'False' / '0' / 0 will turn to `false`\n */\nfunction isBoolean() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `boolean`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const coercion = BOOLEAN_COERCIONS.get(value);\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a boolean (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * number (including floating numbers; use `cascade` and `isInteger` to\n * restrict the range further). Refines the type to `number`.\n *\n * Supports coercion.\n */\nfunction isNumber() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value !== `number`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n // We check against JSON.stringify that the output is the same to ensure that the number can be safely represented in JS\n if (typeof val === `number`) {\n if (JSON.stringify(val) === value) {\n coercion = val;\n }\n else {\n return pushError(state, `Received a number that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a number (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Important: This validator only makes sense when used in conjunction with\n * coercion! It will always error when used without.\n *\n * Create a validator that only returns true when the tested value is a\n * JSON representation of the expected type. Refines the type to the\n * expected type, and casts the value into its inner value.\n */\nfunction isPayload(spec) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) === `undefined`)\n return pushError(state, `The isPayload predicate can only be used with coercion enabled`);\n if (typeof state.coercion === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (typeof value !== `string`)\n return pushError(state, `Expected a string (got ${getPrintable(value)})`);\n let inner;\n try {\n inner = JSON.parse(value);\n }\n catch (_b) {\n return pushError(state, `Expected a JSON string (got ${getPrintable(value)})`);\n }\n const wrapper = { value: inner };\n if (!spec(inner, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(wrapper, `value`) })))\n return false;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, wrapper.value)]);\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * valid date. Refines the type to `Date`.\n *\n * Supports coercion via one of the following formats:\n * - ISO86001 strings\n * - Unix timestamps\n */\nfunction isDate() {\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (!(value instanceof Date)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n let coercion;\n if (typeof value === `string` && iso8601RegExp.test(value)) {\n coercion = new Date(value);\n }\n else {\n let timestamp;\n if (typeof value === `string`) {\n let val;\n try {\n val = JSON.parse(value);\n }\n catch (_b) { }\n if (typeof val === `number`) {\n timestamp = val;\n }\n }\n else if (typeof value === `number`) {\n timestamp = value;\n }\n if (typeof timestamp !== `undefined`) {\n if (Number.isSafeInteger(timestamp) || !Number.isSafeInteger(timestamp * 1000)) {\n coercion = new Date(timestamp * 1000);\n }\n else {\n return pushError(state, `Received a timestamp that can't be safely represented by the runtime (${value})`);\n }\n }\n }\n if (typeof coercion !== `undefined`) {\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, coercion)]);\n return true;\n }\n }\n return pushError(state, `Expected a date (got ${getPrintable(value)})`);\n }\n return true;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * array whose all values match the provided subspec. Refines the type to\n * `Array<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isArray(spec, { delimiter } = {}) {\n return makeValidator({\n test: (value, state) => {\n var _a;\n const originalValue = value;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected an array (got ${getPrintable(value)})`);\n let valid = true;\n for (let t = 0, T = value.length; t < T; ++t) {\n valid = spec(value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (value !== originalValue)\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * set whose all values match the provided subspec. Refines the type to\n * `Set<T>`, with `T` being the subspec inferred type.\n *\n * Supports coercion from arrays (or anything that can be coerced into an\n * array).\n */\nfunction isSet(spec, { delimiter } = {}) {\n const isArrayValidator = isArray(spec, { delimiter });\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n if (Object.getPrototypeOf(value).toString() === `[object Set]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val !== originalValues[t])\n ? new Set(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const subValue of value) {\n valid = spec(subValue, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Set(store.value))]);\n return true;\n }\n return pushError(state, `Expected a set (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * map whose all values match the provided subspecs. Refines the type to\n * `Map<U, V>`, with `U` being the key subspec inferred type and `V` being\n * the value subspec inferred type.\n *\n * Supports coercion from array of tuples (or anything that can be coerced into\n * an array of tuples).\n */\nfunction isMap(keySpec, valueSpec) {\n const isArrayValidator = isArray(isTuple([keySpec, valueSpec]));\n const isRecordValidator = isRecord(valueSpec, { keys: keySpec });\n return makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n if (Object.getPrototypeOf(value).toString() === `[object Map]`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const originalValues = [...value];\n const coercedValues = [...value];\n if (!isArrayValidator(coercedValues, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n const updateValue = () => coercedValues.some((val, t) => val[0] !== originalValues[t][0] || val[1] !== originalValues[t][1])\n ? new Map(coercedValues)\n : value;\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, makeLazyCoercionFn(state.coercion, value, updateValue)]);\n return true;\n }\n else {\n let valid = true;\n for (const [key, subValue] of value) {\n valid = keySpec(key, Object.assign({}, state)) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n valid = valueSpec(subValue, Object.assign(Object.assign({}, state), { p: computeKey(state, key) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n }\n }\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n const store = { value };\n if (Array.isArray(value)) {\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n state.coercions.push([(_b = state.p) !== null && _b !== void 0 ? _b : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(store.value))]);\n return true;\n }\n else {\n if (!isRecordValidator(value, Object.assign(Object.assign({}, state), { coercion: makeCoercionFn(store, `value`) })))\n return false;\n state.coercions.push([(_c = state.p) !== null && _c !== void 0 ? _c : `.`, makeLazyCoercionFn(state.coercion, value, () => new Map(Object.entries(store.value)))]);\n return true;\n }\n }\n return pushError(state, `Expected a map (got ${getPrintable(value)})`);\n }\n });\n}\n/**\n * Create a validator that only returns true when the tested value is a\n * tuple whose each value matches the corresponding subspec. Refines the type\n * into a tuple whose each item has the type inferred by the corresponding\n * tuple.\n *\n * Supports coercion if the `delimiter` option is set, in which case strings\n * will be split accordingly.\n */\nfunction isTuple(spec, { delimiter } = {}) {\n const lengthValidator = hasExactLength(spec.length);\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (typeof value === `string` && typeof delimiter !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n value = value.split(delimiter);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n }\n }\n if (!Array.isArray(value))\n return pushError(state, `Expected a tuple (got ${getPrintable(value)})`);\n let valid = lengthValidator(value, Object.assign({}, state));\n for (let t = 0, T = value.length; t < T && t < spec.length; ++t) {\n valid = spec[t](value[t], Object.assign(Object.assign({}, state), { p: computeKey(state, t), coercion: makeCoercionFn(value, t) })) && valid;\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n return valid;\n },\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object with any amount of properties that must all match the provided\n * subspec. Refines the type to `Record<string, T>`, with `T` being the\n * subspec inferred type.\n *\n * Keys can be optionally validated as well by using the `keys` optional\n * subspec parameter.\n */\nfunction isRecord(spec, { keys: keySpec = null, } = {}) {\n const isArrayValidator = isArray(isTuple([keySpec !== null && keySpec !== void 0 ? keySpec : isString(), spec]));\n return makeValidator({\n test: (value, state) => {\n var _a;\n if (Array.isArray(value)) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n if (!isArrayValidator(value, Object.assign(Object.assign({}, state), { coercion: undefined })))\n return false;\n value = Object.fromEntries(value);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, value)]);\n return true;\n }\n }\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = Object.keys(value);\n let valid = true;\n for (let t = 0, T = keys.length; t < T && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null); ++t) {\n const key = keys[t];\n const sub = value[key];\n if (key === `__proto__` || key === `constructor`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n continue;\n }\n if (keySpec !== null && !keySpec(key, state)) {\n valid = false;\n continue;\n }\n if (!spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) }))) {\n valid = false;\n continue;\n }\n }\n return valid;\n },\n });\n}\n/**\n * @deprecated Replace `isDict` by `isRecord`\n */\nfunction isDict(spec, opts = {}) {\n return isRecord(spec, opts);\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isPartial`, `t.isObject` doesn't allow extraneous properties by\n * default. This behaviour can be altered by using the `extra` optional\n * subspec parameter, which will be called to validate an object only\n * containing the extraneous properties.\n *\n * Calling `t.isObject(..., {extra: t.isRecord(t.isUnknown())})` is\n * essentially the same as calling `t.isPartial(...)`.\n */\nfunction isObject(props, { extra: extraSpec = null, } = {}) {\n const specKeys = Object.keys(props);\n const validator = makeValidator({\n test: (value, state) => {\n if (typeof value !== `object` || value === null)\n return pushError(state, `Expected an object (got ${getPrintable(value)})`);\n const keys = new Set([...specKeys, ...Object.keys(value)]);\n const extra = {};\n let valid = true;\n for (const key of keys) {\n if (key === `constructor` || key === `__proto__`) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Unsafe property name`);\n }\n else {\n const spec = Object.prototype.hasOwnProperty.call(props, key)\n ? props[key]\n : undefined;\n const sub = Object.prototype.hasOwnProperty.call(value, key)\n ? value[key]\n : undefined;\n if (typeof spec !== `undefined`) {\n valid = spec(sub, Object.assign(Object.assign({}, state), { p: computeKey(state, key), coercion: makeCoercionFn(value, key) })) && valid;\n }\n else if (extraSpec === null) {\n valid = pushError(Object.assign(Object.assign({}, state), { p: computeKey(state, key) }), `Extraneous property (got ${getPrintable(sub)})`);\n }\n else {\n Object.defineProperty(extra, key, {\n enumerable: true,\n get: () => sub,\n set: makeSetter(value, key)\n });\n }\n }\n if (!valid && (state === null || state === void 0 ? void 0 : state.errors) == null) {\n break;\n }\n }\n if (extraSpec !== null && (valid || (state === null || state === void 0 ? void 0 : state.errors) != null))\n valid = extraSpec(extra, state) && valid;\n return valid;\n },\n });\n return Object.assign(validator, {\n properties: props,\n });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose all properties match their corresponding subspec. Refines\n * the type into an object whose each property has the type inferred by the\n * corresponding subspec.\n *\n * Unlike `t.isObject`, `t.isPartial` allows extraneous properties. The\n * resulting type will reflect this behaviour by including an index\n * signature (each extraneous property being typed `unknown`).\n *\n * Calling `t.isPartial(...)` is essentially the same as calling\n * `t.isObject(..., {extra: t.isRecord(t.isUnknown())})`.\n */\nfunction isPartial(props) {\n return isObject(props, { extra: isRecord(isUnknown()) });\n}\n/**\n * Create a validator that only returns true when the tested value is an\n * object whose prototype is derived from the given class. Refines the type\n * into a class instance.\n */\nconst isInstanceOf = (constructor) => makeValidator({\n test: (value, state) => {\n if (!(value instanceof constructor))\n return pushError(state, `Expected an instance of ${constructor.name} (got ${getPrintable(value)})`);\n return true;\n },\n});\n/**\n * Create a validator that only returns true when the tested value is an\n * object matching any of the provided subspecs. If the optional `exclusive`\n * parameter is set to `true`, the behaviour changes so that the validator\n * only returns true when exactly one subspec matches.\n */\nconst isOneOf = (specs, { exclusive = false, } = {}) => makeValidator({\n test: (value, state) => {\n var _a, _b, _c;\n const matches = [];\n const errorBuffer = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n for (let t = 0, T = specs.length; t < T; ++t) {\n const subErrors = typeof (state === null || state === void 0 ? void 0 : state.errors) !== `undefined`\n ? [] : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (specs[t](value, Object.assign(Object.assign({}, state), { errors: subErrors, coercions: subCoercions, p: `${(_a = state === null || state === void 0 ? void 0 : state.p) !== null && _a !== void 0 ? _a : `.`}#${t + 1}` }))) {\n matches.push([`#${t + 1}`, subCoercions]);\n if (!exclusive) {\n break;\n }\n }\n else {\n errorBuffer === null || errorBuffer === void 0 ? void 0 : errorBuffer.push(subErrors[0]);\n }\n }\n if (matches.length === 1) {\n const [, subCoercions] = matches[0];\n if (typeof subCoercions !== `undefined`)\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n return true;\n }\n if (matches.length > 1)\n pushError(state, `Expected to match exactly a single predicate (matched ${matches.join(`, `)})`);\n else\n (_c = state === null || state === void 0 ? void 0 : state.errors) === null || _c === void 0 ? void 0 : _c.push(...errorBuffer);\n return false;\n },\n});\n\nfunction makeTrait(value) {\n return () => {\n return value;\n };\n}\nfunction makeValidator({ test }) {\n return makeTrait(test)();\n}\nclass TypeAssertionError extends Error {\n constructor({ errors } = {}) {\n let errorMessage = `Type mismatch`;\n if (errors && errors.length > 0) {\n errorMessage += `\\n`;\n for (const error of errors) {\n errorMessage += `\\n- ${error}`;\n }\n }\n super(errorMessage);\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n */\nfunction assert(val, validator) {\n if (!validator(val)) {\n throw new TypeAssertionError();\n }\n}\n/**\n * Check that the specified value matches the given validator, and throws an\n * exception if it doesn't. Refine the type if it passes.\n *\n * Thrown exceptions include details about what exactly looks invalid in the\n * tested value.\n */\nfunction assertWithErrors(val, validator) {\n const errors = [];\n if (!validator(val, { errors })) {\n throw new TypeAssertionError({ errors });\n }\n}\n/**\n * Compile-time only. Refine the type as if the validator was matching the\n * tested value, but doesn't actually run it. Similar to the classic `as`\n * operator in TypeScript.\n */\nfunction softAssert(val, validator) {\n // It's a soft assert; we tell TypeScript about the type, but we don't need to check it\n}\nfunction as(value, validator, { coerce = false, errors: storeErrors, throw: throws } = {}) {\n const errors = storeErrors ? [] : undefined;\n if (!coerce) {\n if (validator(value, { errors })) {\n return throws ? value : { value, errors: undefined };\n }\n else if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n const state = { value };\n const coercion = makeCoercionFn(state, `value`);\n const coercions = [];\n if (!validator(value, { errors, coercion, coercions })) {\n if (!throws) {\n return { value: undefined, errors: errors !== null && errors !== void 0 ? errors : true };\n }\n else {\n throw new TypeAssertionError({ errors });\n }\n }\n for (const [, apply] of coercions)\n apply();\n if (throws) {\n return state.value;\n }\n else {\n return { value: state.value, errors: undefined };\n }\n}\n/**\n * Create and return a new function that apply the given validators to each\n * corresponding argument passed to the function and throws an exception in\n * case of a mismatch.\n */\nfunction fn(validators, fn) {\n const isValidArgList = isTuple(validators);\n return ((...args) => {\n const check = isValidArgList(args);\n if (!check)\n throw new TypeAssertionError();\n return fn(...args);\n });\n}\n\n/**\n * Create a validator that checks that the tested array or string has at least\n * the specified length.\n */\nfunction hasMinLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length >= length))\n return pushError(state, `Expected to have a length of at least ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has at most\n * the specified length.\n */\nfunction hasMaxLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length <= length))\n return pushError(state, `Expected to have a length of at most ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array or string has exactly\n * the specified length.\n */\nfunction hasExactLength(length) {\n return makeValidator({\n test: (value, state) => {\n if (!(value.length === length))\n return pushError(state, `Expected to have a length of exactly ${length} elements (got ${value.length})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested array only contains unique\n * elements. The optional `map` parameter lets you define a transform to\n * apply before making the check (the result of this transform will be\n * discarded afterwards).\n */\nfunction hasUniqueItems({ map, } = {}) {\n return makeValidator({\n test: (value, state) => {\n const set = new Set();\n const dup = new Set();\n for (let t = 0, T = value.length; t < T; ++t) {\n const sub = value[t];\n const key = typeof map !== `undefined`\n ? map(sub)\n : sub;\n if (set.has(key)) {\n if (dup.has(key))\n continue;\n pushError(state, `Expected to contain unique elements; got a duplicate with ${getPrintable(value)}`);\n dup.add(key);\n }\n else {\n set.add(key);\n }\n }\n return dup.size === 0;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is strictly less than 0.\n */\nfunction isNegative() {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= 0))\n return pushError(state, `Expected to be negative (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than 0.\n */\nfunction isPositive() {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= 0))\n return pushError(state, `Expected to be positive (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or greater\n * than the specified reference.\n */\nfunction isAtLeast(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= n))\n return pushError(state, `Expected to be at least ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is equal or smaller\n * than the specified reference.\n */\nfunction isAtMost(n) {\n return makeValidator({\n test: (value, state) => {\n if (!(value <= n))\n return pushError(state, `Expected to be at most ${n} (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (including the upper boundary).\n */\nfunction isInInclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value <= b))\n return pushError(state, `Expected to be in the [${a}; ${b}] range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is between the\n * specified references (excluding the upper boundary).\n */\nfunction isInExclusiveRange(a, b) {\n return makeValidator({\n test: (value, state) => {\n if (!(value >= a && value < b))\n return pushError(state, `Expected to be in the [${a}; ${b}[ range (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested number is an integer.\n *\n * By default Typanion will also check that it's a *safe* integer. For example,\n * 2^53 wouldn't be a safe integer because 2^53+1 would be rounded to 2^53,\n * which could put your applications at risk when used in loops.\n */\nfunction isInteger({ unsafe = false, } = {}) {\n return makeValidator({\n test: (value, state) => {\n if (value !== Math.round(value))\n return pushError(state, `Expected to be an integer (got ${value})`);\n if (!unsafe && !Number.isSafeInteger(value))\n return pushError(state, `Expected to be a safe integer (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string matches the given\n * regular expression.\n */\nfunction matchesRegExp(regExp) {\n return makeValidator({\n test: (value, state) => {\n if (!regExp.test(value))\n return pushError(state, `Expected to match the pattern ${regExp.toString()} (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain lowercase\n * characters.\n */\nfunction isLowerCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toLowerCase())\n return pushError(state, `Expected to be all-lowercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string only contain uppercase\n * characters.\n */\nfunction isUpperCase() {\n return makeValidator({\n test: (value, state) => {\n if (value !== value.toUpperCase())\n return pushError(state, `Expected to be all-uppercase (got ${value})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid UUID v4.\n */\nfunction isUUID4() {\n return makeValidator({\n test: (value, state) => {\n if (!uuid4RegExp.test(value))\n return pushError(state, `Expected to be a valid UUID v4 (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid ISO8601\n * date.\n */\nfunction isISO8601() {\n return makeValidator({\n test: (value, state) => {\n if (!iso8601RegExp.test(value))\n return pushError(state, `Expected to be a valid ISO 8601 date string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is a valid hexadecimal\n * color. Setting the optional `alpha` parameter to `true` allows an additional\n * transparency channel to be included.\n */\nfunction isHexColor({ alpha = false, }) {\n return makeValidator({\n test: (value, state) => {\n const res = alpha\n ? colorStringRegExp.test(value)\n : colorStringAlphaRegExp.test(value);\n if (!res)\n return pushError(state, `Expected to be a valid hexadecimal color string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid base64.\n */\nfunction isBase64() {\n return makeValidator({\n test: (value, state) => {\n if (!base64RegExp.test(value))\n return pushError(state, `Expected to be a valid base 64 string (got ${getPrintable(value)})`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested string is valid JSON. A\n * optional spec can be passed as parameter, in which case the data will be\n * deserialized and validated against the spec (coercion will be disabled\n * for this check, and even if successful the returned value will still be\n * the original string).\n */\nfunction isJSON(spec = isUnknown()) {\n return makeValidator({\n test: (value, state) => {\n let data;\n try {\n data = JSON.parse(value);\n }\n catch (_a) {\n return pushError(state, `Expected to be a valid JSON string (got ${getPrintable(value)})`);\n }\n return spec(data, state);\n },\n });\n}\n\nfunction cascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return makeValidator({\n test: (value, state) => {\n var _a, _b;\n const context = { value: value };\n const subCoercion = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? makeCoercionFn(context, `value`) : undefined;\n const subCoercions = typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`\n ? [] : undefined;\n if (!spec(value, Object.assign(Object.assign({}, state), { coercion: subCoercion, coercions: subCoercions })))\n return false;\n const reverts = [];\n if (typeof subCoercions !== `undefined`)\n for (const [, coercion] of subCoercions)\n reverts.push(coercion());\n try {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercions) !== `undefined`) {\n if (context.value !== value) {\n if (typeof (state === null || state === void 0 ? void 0 : state.coercion) === `undefined`)\n return pushError(state, `Unbound coercion result`);\n state.coercions.push([(_a = state.p) !== null && _a !== void 0 ? _a : `.`, state.coercion.bind(null, context.value)]);\n }\n (_b = state === null || state === void 0 ? void 0 : state.coercions) === null || _b === void 0 ? void 0 : _b.push(...subCoercions);\n }\n return resolvedFollowups.every(spec => {\n return spec(context.value, state);\n });\n }\n finally {\n for (const revert of reverts) {\n revert();\n }\n }\n },\n });\n}\nfunction applyCascade(spec, ...followups) {\n const resolvedFollowups = Array.isArray(followups[0])\n ? followups[0]\n : followups;\n return cascade(spec, resolvedFollowups);\n}\n/**\n * Wraps the given spec to also allow `undefined`.\n */\nfunction isOptional(spec) {\n return makeValidator({\n test: (value, state) => {\n if (typeof value === `undefined`)\n return true;\n return spec(value, state);\n },\n });\n}\n/**\n * Wraps the given spec to also allow `null`.\n */\nfunction isNullable(spec) {\n return makeValidator({\n test: (value, state) => {\n if (value === null)\n return true;\n return spec(value, state);\n },\n });\n}\nconst checks = {\n missing: (keys, key) => keys.has(key),\n undefined: (keys, key, value) => keys.has(key) && typeof value[key] !== `undefined`,\n nil: (keys, key, value) => keys.has(key) && value[key] != null,\n falsy: (keys, key, value) => keys.has(key) && !!value[key],\n};\n/**\n * Create a validator that checks that the tested object contains the specified\n * keys.\n*/\nfunction hasRequiredKeys(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of requiredSet)\n if (!check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Missing required ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n* Create a validator that checks that the tested object contains at least one\n* of the specified keys.\n*/\nfunction hasAtLeastOneKey(requiredKeys, options) {\n var _a;\n const requiredSet = new Set(requiredKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = Object.keys(value);\n const valid = keys.some(key => check(requiredSet, key, value));\n if (!valid)\n return pushError(state, `Missing at least one property from ${getPrintableArray(Array.from(requiredSet), `or`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains none of the\n * specified keys.\n*/\nfunction hasForbiddenKeys(forbiddenKeys, options) {\n var _a;\n const forbiddenSet = new Set(forbiddenKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const problems = [];\n for (const key of forbiddenSet)\n if (check(keys, key, value))\n problems.push(key);\n if (problems.length > 0)\n return pushError(state, `Forbidden ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, `and`)}`);\n return true;\n },\n });\n}\n/**\n * Create a validator that checks that the tested object contains at most one\n * of the specified keys.\n */\nfunction hasMutuallyExclusiveKeys(exclusiveKeys, options) {\n var _a;\n const exclusiveSet = new Set(exclusiveKeys);\n const check = checks[(_a = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _a !== void 0 ? _a : 'missing'];\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n const used = [];\n for (const key of exclusiveSet)\n if (check(keys, key, value))\n used.push(key);\n if (used.length > 1)\n return pushError(state, `Mutually exclusive properties ${getPrintableArray(used, `and`)}`);\n return true;\n },\n });\n}\n(function (KeyRelationship) {\n KeyRelationship[\"Forbids\"] = \"Forbids\";\n KeyRelationship[\"Requires\"] = \"Requires\";\n})(exports.KeyRelationship || (exports.KeyRelationship = {}));\nconst keyRelationships = {\n [exports.KeyRelationship.Forbids]: {\n expect: false,\n message: `forbids using`,\n },\n [exports.KeyRelationship.Requires]: {\n expect: true,\n message: `requires using`,\n },\n};\n/**\n * Create a validator that checks that, when the specified subject property is\n * set, the relationship is satisfied.\n */\nfunction hasKeyRelationship(subject, relationship, others, options) {\n var _a, _b;\n const skipped = new Set((_a = options === null || options === void 0 ? void 0 : options.ignore) !== null && _a !== void 0 ? _a : []);\n const check = checks[(_b = options === null || options === void 0 ? void 0 : options.missingIf) !== null && _b !== void 0 ? _b : 'missing'];\n const otherSet = new Set(others);\n const spec = keyRelationships[relationship];\n const conjunction = relationship === exports.KeyRelationship.Forbids\n ? `or`\n : `and`;\n return makeValidator({\n test: (value, state) => {\n const keys = new Set(Object.keys(value));\n if (!check(keys, subject, value) || skipped.has(value[subject]))\n return true;\n const problems = [];\n for (const key of otherSet)\n if ((check(keys, key, value) && !skipped.has(value[key])) !== spec.expect)\n problems.push(key);\n if (problems.length >= 1)\n return pushError(state, `Property \"${subject}\" ${spec.message} ${plural(problems.length, `property`, `properties`)} ${getPrintableArray(problems, conjunction)}`);\n return true;\n },\n });\n}\n\nexports.TypeAssertionError = TypeAssertionError;\nexports.applyCascade = applyCascade;\nexports.as = as;\nexports.assert = assert;\nexports.assertWithErrors = assertWithErrors;\nexports.cascade = cascade;\nexports.fn = fn;\nexports.hasAtLeastOneKey = hasAtLeastOneKey;\nexports.hasExactLength = hasExactLength;\nexports.hasForbiddenKeys = hasForbiddenKeys;\nexports.hasKeyRelationship = hasKeyRelationship;\nexports.hasMaxLength = hasMaxLength;\nexports.hasMinLength = hasMinLength;\nexports.hasMutuallyExclusiveKeys = hasMutuallyExclusiveKeys;\nexports.hasRequiredKeys = hasRequiredKeys;\nexports.hasUniqueItems = hasUniqueItems;\nexports.isArray = isArray;\nexports.isAtLeast = isAtLeast;\nexports.isAtMost = isAtMost;\nexports.isBase64 = isBase64;\nexports.isBoolean = isBoolean;\nexports.isDate = isDate;\nexports.isDict = isDict;\nexports.isEnum = isEnum;\nexports.isHexColor = isHexColor;\nexports.isISO8601 = isISO8601;\nexports.isInExclusiveRange = isInExclusiveRange;\nexports.isInInclusiveRange = isInInclusiveRange;\nexports.isInstanceOf = isInstanceOf;\nexports.isInteger = isInteger;\nexports.isJSON = isJSON;\nexports.isLiteral = isLiteral;\nexports.isLowerCase = isLowerCase;\nexports.isMap = isMap;\nexports.isNegative = isNegative;\nexports.isNullable = isNullable;\nexports.isNumber = isNumber;\nexports.isObject = isObject;\nexports.isOneOf = isOneOf;\nexports.isOptional = isOptional;\nexports.isPartial = isPartial;\nexports.isPayload = isPayload;\nexports.isPositive = isPositive;\nexports.isRecord = isRecord;\nexports.isSet = isSet;\nexports.isString = isString;\nexports.isTuple = isTuple;\nexports.isUUID4 = isUUID4;\nexports.isUnknown = isUnknown;\nexports.isUpperCase = isUpperCase;\nexports.makeTrait = makeTrait;\nexports.makeValidator = makeValidator;\nexports.matchesRegExp = matchesRegExp;\nexports.softAssert = softAssert;\n", "var SpecialToken;\n(function (SpecialToken) {\n SpecialToken[\"StartOfInput\"] = \"\\0\";\n SpecialToken[\"EndOfInput\"] = \"\\u0001\";\n SpecialToken[\"EndOfPartialInput\"] = \"\\u0002\";\n})(SpecialToken || (SpecialToken = {}));\nvar NodeType;\n(function (NodeType) {\n NodeType[NodeType[\"InitialNode\"] = 0] = \"InitialNode\";\n NodeType[NodeType[\"SuccessNode\"] = 1] = \"SuccessNode\";\n NodeType[NodeType[\"ErrorNode\"] = 2] = \"ErrorNode\";\n NodeType[NodeType[\"CustomNode\"] = 3] = \"CustomNode\";\n})(NodeType || (NodeType = {}));\nconst HELP_COMMAND_INDEX = -1;\nconst HELP_REGEX = /^(-h|--help)(?:=([0-9]+))?$/;\nconst OPTION_REGEX = /^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/;\nconst BATCH_REGEX = /^-[a-zA-Z]{2,}$/;\nconst BINDING_REGEX = /^([^=]+)=([\\s\\S]*)$/;\nconst IS_DEBUG = process.env.DEBUG_CLI === `1`;\n\nexport { BATCH_REGEX, BINDING_REGEX, HELP_COMMAND_INDEX, HELP_REGEX, IS_DEBUG, NodeType, OPTION_REGEX, SpecialToken };\n", "import { SpecialToken } from './constants.mjs';\n\n/**\n * A generic usage error with the name `UsageError`.\n *\n * It should be used over `Error` only when it's the user's fault.\n */\nclass UsageError extends Error {\n constructor(message) {\n super(message);\n this.clipanion = { type: `usage` };\n this.name = `UsageError`;\n }\n}\nclass UnknownSyntaxError extends Error {\n constructor(input, candidates) {\n super();\n this.input = input;\n this.candidates = candidates;\n this.clipanion = { type: `none` };\n this.name = `UnknownSyntaxError`;\n if (this.candidates.length === 0) {\n this.message = `Command not found, but we're not sure what's the alternative.`;\n }\n else if (this.candidates.every(candidate => candidate.reason !== null && candidate.reason === candidates[0].reason)) {\n const [{ reason }] = this.candidates;\n this.message = `${reason}\\n\\n${this.candidates.map(({ usage }) => `$ ${usage}`).join(`\\n`)}`;\n }\n else if (this.candidates.length === 1) {\n const [{ usage }] = this.candidates;\n this.message = `Command not found; did you mean:\\n\\n$ ${usage}\\n${whileRunning(input)}`;\n }\n else {\n this.message = `Command not found; did you mean one of:\\n\\n${this.candidates.map(({ usage }, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n }\n}\nclass AmbiguousSyntaxError extends Error {\n constructor(input, usages) {\n super();\n this.input = input;\n this.usages = usages;\n this.clipanion = { type: `none` };\n this.name = `AmbiguousSyntaxError`;\n this.message = `Cannot find which to pick amongst the following alternatives:\\n\\n${this.usages.map((usage, index) => {\n return `${`${index}.`.padStart(4)} ${usage}`;\n }).join(`\\n`)}\\n\\n${whileRunning(input)}`;\n }\n}\nconst whileRunning = (input) => `While running ${input.filter(token => {\n return token !== SpecialToken.EndOfInput && token !== SpecialToken.EndOfPartialInput;\n}).map(token => {\n const json = JSON.stringify(token);\n if (token.match(/\\s/) || token.length === 0 || json !== `\"${token}\"`) {\n return json;\n }\n else {\n return token;\n }\n}).join(` `)}`;\n\nexport { AmbiguousSyntaxError, UnknownSyntaxError, UsageError };\n", "import { UsageError } from '../../errors.mjs';\n\nconst isOptionSymbol = Symbol(`clipanion/isOption`);\nfunction makeCommandOption(spec) {\n // We lie! But it's for the good cause: the cli engine will turn the specs into proper values after instantiation.\n return { ...spec, [isOptionSymbol]: true };\n}\nfunction rerouteArguments(a, b) {\n if (typeof a === `undefined`)\n return [a, b];\n if (typeof a === `object` && a !== null && !Array.isArray(a)) {\n return [undefined, a];\n }\n else {\n return [a, b];\n }\n}\nfunction cleanValidationError(message, { mergeName = false } = {}) {\n const match = message.match(/^([^:]+): (.*)$/m);\n if (!match)\n return `validation failed`;\n let [, path, line] = match;\n if (mergeName)\n line = line[0].toLowerCase() + line.slice(1);\n line = path !== `.` || !mergeName\n ? `${path.replace(/^\\.(\\[|$)/, `$1`)}: ${line}`\n : `: ${line}`;\n return line;\n}\nfunction formatError(message, errors) {\n if (errors.length === 1) {\n return new UsageError(`${message}${cleanValidationError(errors[0], { mergeName: true })}`);\n }\n else {\n return new UsageError(`${message}:\\n${errors.map(error => `\\n- ${cleanValidationError(error)}`).join(``)}`);\n }\n}\nfunction applyValidator(name, value, validator) {\n if (typeof validator === `undefined`)\n return value;\n const errors = [];\n const coercions = [];\n const coercion = (v) => {\n const orig = value;\n value = v;\n return coercion.bind(null, orig);\n };\n const check = validator(value, { errors, coercions, coercion });\n if (!check)\n throw formatError(`Invalid value for ${name}`, errors);\n for (const [, op] of coercions)\n op();\n return value;\n}\n\nexport { applyValidator, cleanValidationError, formatError, isOptionSymbol, makeCommandOption, rerouteArguments };\n", "import { formatError, isOptionSymbol } from './options/utils.mjs';\n\n/**\n * Base abstract class for CLI commands. The main thing to remember is to\n * declare an async `execute` member function that will be called when the\n * command is invoked from the CLI, and optionally a `paths` property to\n * declare the set of paths under which the command should be exposed.\n */\nclass Command {\n constructor() {\n /**\n * Predefined that will be set to true if `-h,--help` has been used, in\n * which case `Command#execute` won't be called.\n */\n this.help = false;\n }\n /**\n * Defines the usage information for the given command.\n */\n static Usage(usage) {\n return usage;\n }\n /**\n * Standard error handler which will simply rethrow the error. Can be used\n * to add custom logic to handle errors from the command or simply return\n * the parent class error handling.\n */\n async catch(error) {\n throw error;\n }\n async validateAndExecute() {\n const commandClass = this.constructor;\n const cascade = commandClass.schema;\n if (Array.isArray(cascade)) {\n const { isDict, isUnknown, applyCascade } = await import('typanion');\n const schema = applyCascade(isDict(isUnknown()), cascade);\n const errors = [];\n const coercions = [];\n const check = schema(this, { errors, coercions });\n if (!check)\n throw formatError(`Invalid option schema`, errors);\n for (const [, op] of coercions) {\n op();\n }\n }\n else if (cascade != null) {\n throw new Error(`Invalid command schema`);\n }\n const exitCode = await this.execute();\n if (typeof exitCode !== `undefined`) {\n return exitCode;\n }\n else {\n return 0;\n }\n }\n}\n/**\n * Used to detect option definitions.\n */\nCommand.isOption = isOptionSymbol;\n/**\n * Just an helper to use along with the `paths` fields, to make it\n * clearer that a command is the default one.\n *\n * @example\n * class MyCommand extends Command {\n * static paths = [Command.Default];\n * }\n */\nCommand.Default = [];\n\nexport { Command };\n", "import tty from 'tty';\n\nfunction getDefaultColorDepth() {\n if (tty && `getColorDepth` in tty.WriteStream.prototype)\n return tty.WriteStream.prototype.getColorDepth();\n if (process.env.FORCE_COLOR === `0`)\n return 1;\n if (process.env.FORCE_COLOR === `1`)\n return 8;\n if (typeof process.stdout !== `undefined` && process.stdout.isTTY)\n return 8;\n return 1;\n}\nlet gContextStorage;\nfunction getCaptureActivator(context) {\n let contextStorage = gContextStorage;\n if (typeof contextStorage === `undefined`) {\n if (context.stdout === process.stdout && context.stderr === process.stderr)\n return null;\n const { AsyncLocalStorage: LazyAsyncLocalStorage } = require(`async_hooks`);\n contextStorage = gContextStorage = new LazyAsyncLocalStorage();\n const origStdoutWrite = process.stdout._write;\n process.stdout._write = function (chunk, encoding, cb) {\n const context = contextStorage.getStore();\n if (typeof context === `undefined`)\n return origStdoutWrite.call(this, chunk, encoding, cb);\n return context.stdout.write(chunk, encoding, cb);\n };\n const origStderrWrite = process.stderr._write;\n process.stderr._write = function (chunk, encoding, cb) {\n const context = contextStorage.getStore();\n if (typeof context === `undefined`)\n return origStderrWrite.call(this, chunk, encoding, cb);\n return context.stderr.write(chunk, encoding, cb);\n };\n }\n return (fn) => {\n return contextStorage.run(context, fn);\n };\n}\n\nexport { getCaptureActivator, getDefaultColorDepth };\n", "import { IS_DEBUG, NodeType, SpecialToken, HELP_COMMAND_INDEX, BATCH_REGEX, BINDING_REGEX, OPTION_REGEX, HELP_REGEX } from './constants.mjs';\nimport { UnknownSyntaxError, AmbiguousSyntaxError } from './errors.mjs';\n\n// ------------------------------------------------------------------------\nfunction debug(str) {\n if (IS_DEBUG) {\n console.log(str);\n }\n}\nconst basicHelpState = {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n path: [],\n positionals: [],\n options: [],\n remainder: null,\n selectedIndex: HELP_COMMAND_INDEX,\n tokens: [],\n};\nfunction makeStateMachine() {\n const stateMachine = {\n nodes: [],\n };\n for (let t = 0; t < NodeType.CustomNode; ++t)\n stateMachine.nodes.push(makeNode());\n return stateMachine;\n}\nfunction makeAnyOfMachine(inputs) {\n const output = makeStateMachine();\n const heads = [];\n let offset = output.nodes.length;\n for (const input of inputs) {\n heads.push(offset);\n for (let t = 0; t < input.nodes.length; ++t)\n if (!isTerminalNode(t))\n output.nodes.push(cloneNode(input.nodes[t], offset));\n offset += input.nodes.length - NodeType.CustomNode + 1;\n }\n for (const head of heads)\n registerShortcut(output, NodeType.InitialNode, head);\n return output;\n}\nfunction injectNode(machine, node) {\n machine.nodes.push(node);\n return machine.nodes.length - 1;\n}\nfunction simplifyMachine(input) {\n const visited = new Set();\n const process = (node) => {\n if (visited.has(node))\n return;\n visited.add(node);\n const nodeDef = input.nodes[node];\n for (const transitions of Object.values(nodeDef.statics))\n for (const { to } of transitions)\n process(to);\n for (const [, { to }] of nodeDef.dynamics)\n process(to);\n for (const { to } of nodeDef.shortcuts)\n process(to);\n const shortcuts = new Set(nodeDef.shortcuts.map(({ to }) => to));\n while (nodeDef.shortcuts.length > 0) {\n const { to } = nodeDef.shortcuts.shift();\n const toDef = input.nodes[to];\n for (const [segment, transitions] of Object.entries(toDef.statics)) {\n const store = !Object.prototype.hasOwnProperty.call(nodeDef.statics, segment)\n ? nodeDef.statics[segment] = []\n : nodeDef.statics[segment];\n for (const transition of transitions) {\n if (!store.some(({ to }) => transition.to === to)) {\n store.push(transition);\n }\n }\n }\n for (const [test, transition] of toDef.dynamics)\n if (!nodeDef.dynamics.some(([otherTest, { to }]) => test === otherTest && transition.to === to))\n nodeDef.dynamics.push([test, transition]);\n for (const transition of toDef.shortcuts) {\n if (!shortcuts.has(transition.to)) {\n nodeDef.shortcuts.push(transition);\n shortcuts.add(transition.to);\n }\n }\n }\n };\n process(NodeType.InitialNode);\n}\nfunction debugMachine(machine, { prefix = `` } = {}) {\n // Don't iterate unless it's needed\n if (IS_DEBUG) {\n debug(`${prefix}Nodes are:`);\n for (let t = 0; t < machine.nodes.length; ++t) {\n debug(`${prefix} ${t}: ${JSON.stringify(machine.nodes[t])}`);\n }\n }\n}\nfunction runMachineInternal(machine, input, partial = false) {\n debug(`Running a vm on ${JSON.stringify(input)}`);\n let branches = [{\n node: NodeType.InitialNode,\n state: {\n candidateUsage: null,\n requiredOptions: [],\n errorMessage: null,\n ignoreOptions: false,\n options: [],\n path: [],\n positionals: [],\n remainder: null,\n selectedIndex: null,\n tokens: [],\n },\n }];\n debugMachine(machine, { prefix: ` ` });\n const tokens = [SpecialToken.StartOfInput, ...input];\n for (let t = 0; t < tokens.length; ++t) {\n const segment = tokens[t];\n const isEOI = segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput;\n // The -1 is because we added a START_OF_INPUT token\n const segmentIndex = t - 1;\n debug(` Processing ${JSON.stringify(segment)}`);\n const nextBranches = [];\n for (const { node, state } of branches) {\n debug(` Current node is ${node}`);\n const nodeDef = machine.nodes[node];\n if (node === NodeType.ErrorNode) {\n nextBranches.push({ node, state });\n continue;\n }\n console.assert(nodeDef.shortcuts.length === 0, `Shortcuts should have been eliminated by now`);\n const hasExactMatch = Object.prototype.hasOwnProperty.call(nodeDef.statics, segment);\n if (!partial || t < tokens.length - 1 || hasExactMatch) {\n if (hasExactMatch) {\n const transitions = nodeDef.statics[segment];\n for (const { to, reducer } of transitions) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n debug(` No static transition found`);\n }\n }\n else {\n let hasMatches = false;\n for (const candidate of Object.keys(nodeDef.statics)) {\n if (!candidate.startsWith(segment))\n continue;\n if (segment === candidate) {\n for (const { to, reducer } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Static transition to ${to} found`);\n }\n }\n else {\n for (const { to } of nodeDef.statics[candidate]) {\n nextBranches.push({ node: to, state: { ...state, remainder: candidate.slice(segment.length) } });\n debug(` Static transition to ${to} found (partial match)`);\n }\n }\n hasMatches = true;\n }\n if (!hasMatches) {\n debug(` No partial static transition found`);\n }\n }\n if (!isEOI) {\n for (const [test, { to, reducer }] of nodeDef.dynamics) {\n if (execute(tests, test, state, segment, segmentIndex)) {\n nextBranches.push({ node: to, state: typeof reducer !== `undefined` ? execute(reducers, reducer, state, segment, segmentIndex) : state });\n debug(` Dynamic transition to ${to} found (via ${test})`);\n }\n }\n }\n }\n if (nextBranches.length === 0 && isEOI && input.length === 1) {\n return [{\n node: NodeType.InitialNode,\n state: basicHelpState,\n }];\n }\n if (nextBranches.length === 0) {\n throw new UnknownSyntaxError(input, branches.filter(({ node }) => {\n return node !== NodeType.ErrorNode;\n }).map(({ state }) => {\n return { usage: state.candidateUsage, reason: null };\n }));\n }\n if (nextBranches.every(({ node }) => node === NodeType.ErrorNode)) {\n throw new UnknownSyntaxError(input, nextBranches.map(({ state }) => {\n return { usage: state.candidateUsage, reason: state.errorMessage };\n }));\n }\n branches = trimSmallerBranches(nextBranches);\n }\n if (branches.length > 0) {\n debug(` Results:`);\n for (const branch of branches) {\n debug(` - ${branch.node} -> ${JSON.stringify(branch.state)}`);\n }\n }\n else {\n debug(` No results`);\n }\n return branches;\n}\nfunction runMachine(machine, input, { endToken = SpecialToken.EndOfInput } = {}) {\n const branches = runMachineInternal(machine, [...input, endToken]);\n return selectBestState(input, branches.map(({ state }) => {\n return state;\n }));\n}\nfunction trimSmallerBranches(branches) {\n let maxPathSize = 0;\n for (const { state } of branches)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n return branches.filter(({ state }) => {\n return state.path.length === maxPathSize;\n });\n}\nfunction selectBestState(input, states) {\n const terminalStates = states.filter(state => {\n return state.selectedIndex !== null;\n });\n if (terminalStates.length === 0)\n throw new Error();\n const requiredOptionsSetStates = terminalStates.filter(state => state.selectedIndex === HELP_COMMAND_INDEX || state.requiredOptions.every(names => names.some(name => state.options.find(opt => opt.name === name))));\n if (requiredOptionsSetStates.length === 0) {\n throw new UnknownSyntaxError(input, terminalStates.map(state => ({\n usage: state.candidateUsage,\n reason: null,\n })));\n }\n let maxPathSize = 0;\n for (const state of requiredOptionsSetStates)\n if (state.path.length > maxPathSize)\n maxPathSize = state.path.length;\n const bestPathBranches = requiredOptionsSetStates.filter(state => {\n return state.path.length === maxPathSize;\n });\n const getPositionalCount = (state) => state.positionals.filter(({ extra }) => {\n return !extra;\n }).length + state.options.length;\n const statesWithPositionalCount = bestPathBranches.map(state => {\n return { state, positionalCount: getPositionalCount(state) };\n });\n let maxPositionalCount = 0;\n for (const { positionalCount } of statesWithPositionalCount)\n if (positionalCount > maxPositionalCount)\n maxPositionalCount = positionalCount;\n const bestPositionalStates = statesWithPositionalCount.filter(({ positionalCount }) => {\n return positionalCount === maxPositionalCount;\n }).map(({ state }) => {\n return state;\n });\n const fixedStates = aggregateHelpStates(bestPositionalStates);\n if (fixedStates.length > 1)\n throw new AmbiguousSyntaxError(input, fixedStates.map(state => state.candidateUsage));\n return fixedStates[0];\n}\nfunction aggregateHelpStates(states) {\n const notHelps = [];\n const helps = [];\n for (const state of states) {\n if (state.selectedIndex === HELP_COMMAND_INDEX) {\n helps.push(state);\n }\n else {\n notHelps.push(state);\n }\n }\n if (helps.length > 0) {\n notHelps.push({\n ...basicHelpState,\n path: findCommonPrefix(...helps.map(state => state.path)),\n options: helps.reduce((options, state) => options.concat(state.options), []),\n });\n }\n return notHelps;\n}\nfunction findCommonPrefix(firstPath, secondPath, ...rest) {\n if (secondPath === undefined)\n return Array.from(firstPath);\n return findCommonPrefix(firstPath.filter((segment, i) => segment === secondPath[i]), ...rest);\n}\nfunction makeNode() {\n return {\n dynamics: [],\n shortcuts: [],\n statics: {},\n };\n}\nfunction isTerminalNode(node) {\n return node === NodeType.SuccessNode || node === NodeType.ErrorNode;\n}\nfunction cloneTransition(input, offset = 0) {\n const to = !isTerminalNode(input.to)\n ? input.to >= NodeType.CustomNode\n ? input.to + offset - NodeType.CustomNode + 1\n : input.to + offset\n : input.to;\n return {\n to,\n reducer: input.reducer,\n };\n}\nfunction cloneNode(input, offset = 0) {\n const output = makeNode();\n for (const [test, transition] of input.dynamics)\n output.dynamics.push([test, cloneTransition(transition, offset)]);\n for (const transition of input.shortcuts)\n output.shortcuts.push(cloneTransition(transition, offset));\n for (const [segment, transitions] of Object.entries(input.statics))\n output.statics[segment] = transitions.map(transition => cloneTransition(transition, offset));\n return output;\n}\nfunction registerDynamic(machine, from, test, to, reducer) {\n machine.nodes[from].dynamics.push([\n test,\n { to, reducer: reducer },\n ]);\n}\nfunction registerShortcut(machine, from, to, reducer) {\n machine.nodes[from].shortcuts.push({ to, reducer: reducer });\n}\nfunction registerStatic(machine, from, test, to, reducer) {\n const store = !Object.prototype.hasOwnProperty.call(machine.nodes[from].statics, test)\n ? machine.nodes[from].statics[test] = []\n : machine.nodes[from].statics[test];\n store.push({ to, reducer: reducer });\n}\nfunction execute(store, callback, state, segment, segmentIndex) {\n // TypeScript's control flow can't properly narrow\n // generic conditionals for some mysterious reason\n if (Array.isArray(callback)) {\n const [name, ...args] = callback;\n return store[name](state, segment, segmentIndex, ...args);\n }\n else {\n return store[callback](state, segment, segmentIndex);\n }\n}\nconst tests = {\n always: () => {\n return true;\n },\n isOptionLike: (state, segment) => {\n return !state.ignoreOptions && (segment !== `-` && segment.startsWith(`-`));\n },\n isNotOptionLike: (state, segment) => {\n return state.ignoreOptions || segment === `-` || !segment.startsWith(`-`);\n },\n isOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === name;\n },\n isBatchOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && BATCH_REGEX.test(segment) && [...segment.slice(1)].every(name => names.has(`-${name}`));\n },\n isBoundOption: (state, segment, segmentIndex, names, options) => {\n const optionParsing = segment.match(BINDING_REGEX);\n return !state.ignoreOptions && !!optionParsing && OPTION_REGEX.test(optionParsing[1]) && names.has(optionParsing[1])\n // Disallow bound options with no arguments (i.e. booleans)\n && options.filter(opt => opt.nameSet.includes(optionParsing[1])).every(opt => opt.allowBinding);\n },\n isNegatedOption: (state, segment, segmentIndex, name) => {\n return !state.ignoreOptions && segment === `--no-${name.slice(2)}`;\n },\n isHelp: (state, segment) => {\n return !state.ignoreOptions && HELP_REGEX.test(segment);\n },\n isUnsupportedOption: (state, segment, segmentIndex, names) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && OPTION_REGEX.test(segment) && !names.has(segment);\n },\n isInvalidOption: (state, segment) => {\n return !state.ignoreOptions && segment.startsWith(`-`) && !OPTION_REGEX.test(segment);\n },\n};\nconst reducers = {\n setCandidateState: (state, segment, segmentIndex, candidateState) => {\n return { ...state, ...candidateState };\n },\n setSelectedIndex: (state, segment, segmentIndex, index) => {\n return { ...state, selectedIndex: index };\n },\n pushBatch: (state, segment, segmentIndex, names) => {\n const options = state.options.slice();\n const tokens = state.tokens.slice();\n for (let t = 1; t < segment.length; ++t) {\n const name = names.get(`-${segment[t]}`);\n const slice = t === 1 ? [0, 2] : [t, t + 1];\n options.push({ name, value: true });\n tokens.push({ segmentIndex, type: `option`, option: name, slice });\n }\n return { ...state, options, tokens };\n },\n pushBound: (state, segment, segmentIndex) => {\n const [, name, value] = segment.match(BINDING_REGEX);\n const options = state.options.concat({ name, value });\n const tokens = state.tokens.concat([\n { segmentIndex, type: `option`, slice: [0, name.length], option: name },\n { segmentIndex, type: `assign`, slice: [name.length, name.length + 1] },\n { segmentIndex, type: `value`, slice: [name.length + 1, name.length + value.length + 1] },\n ]);\n return { ...state, options, tokens };\n },\n pushPath: (state, segment, segmentIndex) => {\n const path = state.path.concat(segment);\n const tokens = state.tokens.concat({ segmentIndex, type: `path` });\n return { ...state, path, tokens };\n },\n pushPositional: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtra: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushExtraNoLimits: (state, segment, segmentIndex) => {\n const positionals = state.positionals.concat({ value: segment, extra: NoLimits });\n const tokens = state.tokens.concat({ segmentIndex, type: `positional` });\n return { ...state, positionals, tokens };\n },\n pushTrue: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: true });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushFalse: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name, value: false });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: name });\n return { ...state, options, tokens };\n },\n pushUndefined: (state, segment, segmentIndex, name) => {\n const options = state.options.concat({ name: segment, value: undefined });\n const tokens = state.tokens.concat({ segmentIndex, type: `option`, option: segment });\n return { ...state, options, tokens };\n },\n pushStringValue: (state, segment, segmentIndex) => {\n var _a;\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = ((_a = lastOption.value) !== null && _a !== void 0 ? _a : []).concat([segment]);\n return { ...state, options, tokens };\n },\n setStringValue: (state, segment, segmentIndex) => {\n const lastOption = state.options[state.options.length - 1];\n const options = state.options.slice();\n const tokens = state.tokens.concat({ segmentIndex, type: `value` });\n lastOption.value = segment;\n return { ...state, options, tokens };\n },\n inhibateOptions: (state) => {\n return { ...state, ignoreOptions: true };\n },\n useHelp: (state, segment, segmentIndex, command) => {\n const [, /* name */ , index] = segment.match(HELP_REGEX);\n if (typeof index !== `undefined`) {\n return { ...state, options: [{ name: `-c`, value: String(command) }, { name: `-i`, value: index }] };\n }\n else {\n return { ...state, options: [{ name: `-c`, value: String(command) }] };\n }\n },\n setError: (state, segment, segmentIndex, errorMessage) => {\n if (segment === SpecialToken.EndOfInput || segment === SpecialToken.EndOfPartialInput) {\n return { ...state, errorMessage: `${errorMessage}.` };\n }\n else {\n return { ...state, errorMessage: `${errorMessage} (\"${segment}\").` };\n }\n },\n setOptionArityError: (state, segment) => {\n const lastOption = state.options[state.options.length - 1];\n return { ...state, errorMessage: `Not enough arguments to option ${lastOption.name}.` };\n },\n};\n// ------------------------------------------------------------------------\nconst NoLimits = Symbol();\nclass CommandBuilder {\n constructor(cliIndex, cliOpts) {\n this.allOptionNames = new Map();\n this.arity = { leading: [], trailing: [], extra: [], proxy: false };\n this.options = [];\n this.paths = [];\n this.cliIndex = cliIndex;\n this.cliOpts = cliOpts;\n }\n addPath(path) {\n this.paths.push(path);\n }\n setArity({ leading = this.arity.leading, trailing = this.arity.trailing, extra = this.arity.extra, proxy = this.arity.proxy }) {\n Object.assign(this.arity, { leading, trailing, extra, proxy });\n }\n addPositional({ name = `arg`, required = true } = {}) {\n if (!required && this.arity.extra === NoLimits)\n throw new Error(`Optional parameters cannot be declared when using .rest() or .proxy()`);\n if (!required && this.arity.trailing.length > 0)\n throw new Error(`Optional parameters cannot be declared after the required trailing positional arguments`);\n if (!required && this.arity.extra !== NoLimits) {\n this.arity.extra.push(name);\n }\n else if (this.arity.extra !== NoLimits && this.arity.extra.length === 0) {\n this.arity.leading.push(name);\n }\n else {\n this.arity.trailing.push(name);\n }\n }\n addRest({ name = `arg`, required = 0 } = {}) {\n if (this.arity.extra === NoLimits)\n throw new Error(`Infinite lists cannot be declared multiple times in the same command`);\n if (this.arity.trailing.length > 0)\n throw new Error(`Infinite lists cannot be declared after the required trailing positional arguments`);\n for (let t = 0; t < required; ++t)\n this.addPositional({ name });\n this.arity.extra = NoLimits;\n }\n addProxy({ required = 0 } = {}) {\n this.addRest({ required });\n this.arity.proxy = true;\n }\n addOption({ names: nameSet, description, arity = 0, hidden = false, required = false, allowBinding = true }) {\n if (!allowBinding && arity > 1)\n throw new Error(`The arity cannot be higher than 1 when the option only supports the --arg=value syntax`);\n if (!Number.isInteger(arity))\n throw new Error(`The arity must be an integer, got ${arity}`);\n if (arity < 0)\n throw new Error(`The arity must be positive, got ${arity}`);\n const preferredName = nameSet.reduce((longestName, name) => {\n return name.length > longestName.length ? name : longestName;\n }, ``);\n for (const name of nameSet)\n this.allOptionNames.set(name, preferredName);\n this.options.push({ preferredName, nameSet, description, arity, hidden, required, allowBinding });\n }\n setContext(context) {\n this.context = context;\n }\n usage({ detailed = true, inlineOptions = true } = {}) {\n const segments = [this.cliOpts.binaryName];\n const detailedOptionList = [];\n if (this.paths.length > 0)\n segments.push(...this.paths[0]);\n if (detailed) {\n for (const { preferredName, nameSet, arity, hidden, description, required } of this.options) {\n if (hidden)\n continue;\n const args = [];\n for (let t = 0; t < arity; ++t)\n args.push(` #${t}`);\n const definition = `${nameSet.join(`,`)}${args.join(``)}`;\n if (!inlineOptions && description) {\n detailedOptionList.push({ preferredName, nameSet, definition, description, required });\n }\n else {\n segments.push(required ? `<${definition}>` : `[${definition}]`);\n }\n }\n segments.push(...this.arity.leading.map(name => `<${name}>`));\n if (this.arity.extra === NoLimits)\n segments.push(`...`);\n else\n segments.push(...this.arity.extra.map(name => `[${name}]`));\n segments.push(...this.arity.trailing.map(name => `<${name}>`));\n }\n const usage = segments.join(` `);\n return { usage, options: detailedOptionList };\n }\n compile() {\n if (typeof this.context === `undefined`)\n throw new Error(`Assertion failed: No context attached`);\n const machine = makeStateMachine();\n let firstNode = NodeType.InitialNode;\n const candidateUsage = this.usage().usage;\n const requiredOptions = this.options\n .filter(opt => opt.required)\n .map(opt => opt.nameSet);\n firstNode = injectNode(machine, makeNode());\n registerStatic(machine, NodeType.InitialNode, SpecialToken.StartOfInput, firstNode, [`setCandidateState`, { candidateUsage, requiredOptions }]);\n const positionalArgument = this.arity.proxy\n ? `always`\n : `isNotOptionLike`;\n const paths = this.paths.length > 0\n ? this.paths\n : [[]];\n for (const path of paths) {\n let lastPathNode = firstNode;\n // We allow options to be specified before the path. Note that we\n // only do this when there is a path, otherwise there would be\n // some redundancy with the options attached later.\n if (path.length > 0) {\n const optionPathNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastPathNode, optionPathNode);\n this.registerOptions(machine, optionPathNode);\n lastPathNode = optionPathNode;\n }\n for (let t = 0; t < path.length; ++t) {\n const nextPathNode = injectNode(machine, makeNode());\n registerStatic(machine, lastPathNode, path[t], nextPathNode, `pushPath`);\n lastPathNode = nextPathNode;\n if (t + 1 < path.length) {\n // Allow to pass `-h` (without anything after it) after each part of a path.\n // Note that we do not do this for the last part, otherwise there would be\n // some redundancy with the `useHelp` attached later.\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n }\n }\n if (this.arity.leading.length > 0 || !this.arity.proxy) {\n const helpNode = injectNode(machine, makeNode());\n registerDynamic(machine, lastPathNode, `isHelp`, helpNode, [`useHelp`, this.cliIndex]);\n registerDynamic(machine, helpNode, `always`, helpNode, `pushExtra`);\n registerStatic(machine, helpNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, HELP_COMMAND_INDEX]);\n this.registerOptions(machine, lastPathNode);\n }\n if (this.arity.leading.length > 0) {\n registerStatic(machine, lastPathNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastPathNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastLeadingNode = lastPathNode;\n for (let t = 0; t < this.arity.leading.length; ++t) {\n const nextLeadingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t + 1 !== this.arity.leading.length)\n this.registerOptions(machine, nextLeadingNode);\n if (this.arity.trailing.length > 0 || t + 1 !== this.arity.leading.length) {\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextLeadingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastLeadingNode, `isNotOptionLike`, nextLeadingNode, `pushPositional`);\n lastLeadingNode = nextLeadingNode;\n }\n let lastExtraNode = lastLeadingNode;\n if (this.arity.extra === NoLimits || this.arity.extra.length > 0) {\n const extraShortcutNode = injectNode(machine, makeNode());\n registerShortcut(machine, lastLeadingNode, extraShortcutNode);\n if (this.arity.extra === NoLimits) {\n const extraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, extraNode);\n registerDynamic(machine, lastLeadingNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerDynamic(machine, extraNode, positionalArgument, extraNode, `pushExtraNoLimits`);\n registerShortcut(machine, extraNode, extraShortcutNode);\n }\n else {\n for (let t = 0; t < this.arity.extra.length; ++t) {\n const nextExtraNode = injectNode(machine, makeNode());\n if (!this.arity.proxy || t > 0)\n this.registerOptions(machine, nextExtraNode);\n registerDynamic(machine, lastExtraNode, positionalArgument, nextExtraNode, `pushExtra`);\n registerShortcut(machine, nextExtraNode, extraShortcutNode);\n lastExtraNode = nextExtraNode;\n }\n }\n lastExtraNode = extraShortcutNode;\n }\n if (this.arity.trailing.length > 0) {\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, lastExtraNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n let lastTrailingNode = lastExtraNode;\n for (let t = 0; t < this.arity.trailing.length; ++t) {\n const nextTrailingNode = injectNode(machine, makeNode());\n if (!this.arity.proxy)\n this.registerOptions(machine, nextTrailingNode);\n if (t + 1 < this.arity.trailing.length) {\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfInput, NodeType.ErrorNode, [`setError`, `Not enough positional arguments`]);\n registerStatic(machine, nextTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n registerDynamic(machine, lastTrailingNode, `isNotOptionLike`, nextTrailingNode, `pushPositional`);\n lastTrailingNode = nextTrailingNode;\n }\n registerDynamic(machine, lastTrailingNode, positionalArgument, NodeType.ErrorNode, [`setError`, `Extraneous positional argument`]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n registerStatic(machine, lastTrailingNode, SpecialToken.EndOfPartialInput, NodeType.SuccessNode, [`setSelectedIndex`, this.cliIndex]);\n }\n return {\n machine,\n context: this.context,\n };\n }\n registerOptions(machine, node) {\n registerDynamic(machine, node, [`isOption`, `--`], node, `inhibateOptions`);\n registerDynamic(machine, node, [`isBatchOption`, this.allOptionNames], node, [`pushBatch`, this.allOptionNames]);\n registerDynamic(machine, node, [`isBoundOption`, this.allOptionNames, this.options], node, `pushBound`);\n registerDynamic(machine, node, [`isUnsupportedOption`, this.allOptionNames], NodeType.ErrorNode, [`setError`, `Unsupported option name`]);\n registerDynamic(machine, node, [`isInvalidOption`], NodeType.ErrorNode, [`setError`, `Invalid option name`]);\n for (const option of this.options) {\n if (option.arity === 0) {\n for (const name of option.nameSet) {\n registerDynamic(machine, node, [`isOption`, name], node, [`pushTrue`, option.preferredName]);\n if (name.startsWith(`--`) && !name.startsWith(`--no-`)) {\n registerDynamic(machine, node, [`isNegatedOption`, name], node, [`pushFalse`, option.preferredName]);\n }\n }\n }\n else {\n // We inject a new node at the end of the state machine\n let lastNode = injectNode(machine, makeNode());\n // We register transitions from the starting node to this new node\n for (const name of option.nameSet)\n registerDynamic(machine, node, [`isOption`, name], lastNode, [`pushUndefined`, option.preferredName]);\n // For each argument, we inject a new node at the end and we\n // register a transition from the current node to this new node\n for (let t = 0; t < option.arity; ++t) {\n const nextNode = injectNode(machine, makeNode());\n // We can provide better errors when another option or EndOfInput is encountered\n registerStatic(machine, lastNode, SpecialToken.EndOfInput, NodeType.ErrorNode, `setOptionArityError`);\n registerStatic(machine, lastNode, SpecialToken.EndOfPartialInput, NodeType.ErrorNode, `setOptionArityError`);\n registerDynamic(machine, lastNode, `isOptionLike`, NodeType.ErrorNode, `setOptionArityError`);\n // If the option has a single argument, no need to store it in an array\n const action = option.arity === 1\n ? `setStringValue`\n : `pushStringValue`;\n registerDynamic(machine, lastNode, `isNotOptionLike`, nextNode, action);\n lastNode = nextNode;\n }\n // In the end, we register a shortcut from\n // the last node back to the starting node\n registerShortcut(machine, lastNode, node);\n }\n }\n }\n}\nclass CliBuilder {\n static build(cbs, opts = {}) {\n return new CliBuilder(opts).commands(cbs).compile();\n }\n constructor({ binaryName = `...` } = {}) {\n this.builders = [];\n this.opts = { binaryName };\n }\n getBuilderByIndex(n) {\n if (!(n >= 0 && n < this.builders.length))\n throw new Error(`Assertion failed: Out-of-bound command index (${n})`);\n return this.builders[n];\n }\n commands(cbs) {\n for (const cb of cbs)\n cb(this.command());\n return this;\n }\n command() {\n const builder = new CommandBuilder(this.builders.length, this.opts);\n this.builders.push(builder);\n return builder;\n }\n compile() {\n const machines = [];\n const contexts = [];\n for (const builder of this.builders) {\n const { machine, context } = builder.compile();\n machines.push(machine);\n contexts.push(context);\n }\n const machine = makeAnyOfMachine(machines);\n simplifyMachine(machine);\n return {\n machine,\n contexts,\n process: (input, { partial } = {}) => {\n const endToken = partial\n ? SpecialToken.EndOfPartialInput\n : SpecialToken.EndOfInput;\n return runMachine(machine, input, { endToken });\n },\n };\n }\n}\n\nexport { CliBuilder, CommandBuilder, NoLimits, aggregateHelpStates, cloneNode, cloneTransition, debug, debugMachine, execute, injectNode, isTerminalNode, makeAnyOfMachine, makeNode, makeStateMachine, reducers, registerDynamic, registerShortcut, registerStatic, runMachineInternal, selectBestState, simplifyMachine, tests, trimSmallerBranches };\n", "const MAX_LINE_LENGTH = 80;\nconst richLine = Array(MAX_LINE_LENGTH).fill(`\u2501`);\nfor (let t = 0; t <= 24; ++t)\n richLine[richLine.length - t] = `\\x1b[38;5;${232 + t}m\u2501`;\nconst richFormat = {\n header: str => `\\x1b[1m\u2501\u2501\u2501 ${str}${str.length < MAX_LINE_LENGTH - 5 ? ` ${richLine.slice(str.length + 5).join(``)}` : `:`}\\x1b[0m`,\n bold: str => `\\x1b[1m${str}\\x1b[22m`,\n error: str => `\\x1b[31m\\x1b[1m${str}\\x1b[22m\\x1b[39m`,\n code: str => `\\x1b[36m${str}\\x1b[39m`,\n};\nconst textFormat = {\n header: str => str,\n bold: str => str,\n error: str => str,\n code: str => str,\n};\nfunction dedent(text) {\n const lines = text.split(`\\n`);\n const nonEmptyLines = lines.filter(line => line.match(/\\S/));\n const indent = nonEmptyLines.length > 0 ? nonEmptyLines.reduce((minLength, line) => Math.min(minLength, line.length - line.trimStart().length), Number.MAX_VALUE) : 0;\n return lines\n .map(line => line.slice(indent).trimRight())\n .join(`\\n`);\n}\n/**\n * Formats markdown text to be displayed to the console. Not all markdown features are supported.\n *\n * @param text The markdown text to format.\n * @param opts.format The format to use.\n * @param opts.paragraphs Whether to cut the text into paragraphs of 80 characters at most.\n */\nfunction formatMarkdownish(text, { format, paragraphs }) {\n // Enforce \\n as newline character\n text = text.replace(/\\r\\n?/g, `\\n`);\n // Remove the indentation, since it got messed up with the JS indentation\n text = dedent(text);\n // Remove surrounding newlines, since they got added for JS formatting\n text = text.replace(/^\\n+|\\n+$/g, ``);\n // List items always end with at least two newlines (in order to not be collapsed)\n text = text.replace(/^(\\s*)-([^\\n]*?)\\n+/gm, `$1-$2\\n\\n`);\n // Single newlines are removed; larger than that are collapsed into one\n text = text.replace(/\\n(\\n)?\\n*/g, ($0, $1) => $1 ? $1 : ` `);\n if (paragraphs) {\n text = text.split(/\\n/).map(paragraph => {\n // Does the paragraph starts with a list?\n const bulletMatch = paragraph.match(/^\\s*[*-][\\t ]+(.*)/);\n if (!bulletMatch)\n // No, cut the paragraphs into segments of 80 characters\n return paragraph.match(/(.{1,80})(?: |$)/g).join(`\\n`);\n const indent = paragraph.length - paragraph.trimStart().length;\n // Yes, cut the paragraphs into segments of (78 - indent) characters (to account for the prefix)\n return bulletMatch[1].match(new RegExp(`(.{1,${78 - indent}})(?: |$)`, `g`)).map((line, index) => {\n return ` `.repeat(indent) + (index === 0 ? `- ` : ` `) + line;\n }).join(`\\n`);\n }).join(`\\n\\n`);\n }\n // Highlight the code segments\n text = text.replace(/(`+)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.code($1 + $2 + $1);\n });\n // Highlight the bold segments\n text = text.replace(/(\\*\\*)((?:.|[\\n])*?)\\1/g, ($0, $1, $2) => {\n return format.bold($1 + $2 + $1);\n });\n return text ? `${text}\\n` : ``;\n}\n\nexport { formatMarkdownish, richFormat, textFormat };\n", "import { Command } from './Command.mjs';\n\nclass HelpCommand extends Command {\n static from(state, contexts) {\n const command = new HelpCommand(contexts);\n command.path = state.path;\n for (const opt of state.options) {\n switch (opt.name) {\n case `-c`:\n {\n command.commands.push(Number(opt.value));\n }\n break;\n case `-i`:\n {\n command.index = Number(opt.value);\n }\n break;\n }\n }\n return command;\n }\n constructor(contexts) {\n super();\n this.contexts = contexts;\n this.commands = [];\n }\n async execute() {\n let commands = this.commands;\n if (typeof this.index !== `undefined` && this.index >= 0 && this.index < commands.length)\n commands = [commands[this.index]];\n if (commands.length === 0) {\n this.context.stdout.write(this.cli.usage());\n }\n else if (commands.length === 1) {\n this.context.stdout.write(this.cli.usage(this.contexts[commands[0]].commandClass, { detailed: true }));\n }\n else if (commands.length > 1) {\n this.context.stdout.write(`Multiple commands match your selection:\\n`);\n this.context.stdout.write(`\\n`);\n let index = 0;\n for (const command of this.commands)\n this.context.stdout.write(this.cli.usage(this.contexts[command].commandClass, { prefix: `${index++}. `.padStart(5) }));\n this.context.stdout.write(`\\n`);\n this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.\\n`);\n }\n }\n}\n\nexport { HelpCommand };\n", "import { getDefaultColorDepth, getCaptureActivator } from '../platform/node.mjs';\nimport { HELP_COMMAND_INDEX } from '../constants.mjs';\nimport { CliBuilder } from '../core.mjs';\nimport { formatMarkdownish, richFormat, textFormat } from '../format.mjs';\nimport { Command } from './Command.mjs';\nimport { HelpCommand } from './HelpCommand.mjs';\n\nconst errorCommandSymbol = Symbol(`clipanion/errorCommand`);\nasync function runExit(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.runExit(resolvedArgv, resolvedContext);\n}\nasync function run(...args) {\n const { resolvedOptions, resolvedCommandClasses, resolvedArgv, resolvedContext, } = resolveRunParameters(args);\n const cli = Cli.from(resolvedCommandClasses, resolvedOptions);\n return cli.run(resolvedArgv, resolvedContext);\n}\nfunction resolveRunParameters(args) {\n let resolvedOptions;\n let resolvedCommandClasses;\n let resolvedArgv;\n let resolvedContext;\n if (typeof process !== `undefined` && typeof process.argv !== `undefined`)\n resolvedArgv = process.argv.slice(2);\n switch (args.length) {\n case 1:\n {\n resolvedCommandClasses = args[0];\n }\n break;\n case 2:\n {\n if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n if (Array.isArray(args[1])) {\n resolvedArgv = args[1];\n }\n else {\n resolvedContext = args[1];\n }\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n }\n }\n break;\n case 3:\n {\n if (Array.isArray(args[2])) {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n }\n else if (args[0] && (args[0].prototype instanceof Command) || Array.isArray(args[0])) {\n resolvedCommandClasses = args[0];\n resolvedArgv = args[1];\n resolvedContext = args[2];\n }\n else {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedContext = args[2];\n }\n }\n break;\n default:\n {\n resolvedOptions = args[0];\n resolvedCommandClasses = args[1];\n resolvedArgv = args[2];\n resolvedContext = args[3];\n }\n break;\n }\n if (typeof resolvedArgv === `undefined`)\n throw new Error(`The argv parameter must be provided when running Clipanion outside of a Node context`);\n return {\n resolvedOptions,\n resolvedCommandClasses,\n resolvedArgv,\n resolvedContext,\n };\n}\n/**\n * @template Context The context shared by all commands. Contexts are a set of values, defined when calling the `run`/`runExit` functions from the CLI instance, that will be made available to the commands via `this.context`.\n */\nclass Cli {\n /**\n * Creates a new Cli and registers all commands passed as parameters.\n *\n * @param commandClasses The Commands to register\n * @returns The created `Cli` instance\n */\n static from(commandClasses, options = {}) {\n const cli = new Cli(options);\n const resolvedCommandClasses = Array.isArray(commandClasses)\n ? commandClasses\n : [commandClasses];\n for (const commandClass of resolvedCommandClasses)\n cli.register(commandClass);\n return cli;\n }\n constructor({ binaryLabel, binaryName: binaryNameOpt = `...`, binaryVersion, enableCapture = false, enableColors } = {}) {\n this.registrations = new Map();\n this.builder = new CliBuilder({ binaryName: binaryNameOpt });\n this.binaryLabel = binaryLabel;\n this.binaryName = binaryNameOpt;\n this.binaryVersion = binaryVersion;\n this.enableCapture = enableCapture;\n this.enableColors = enableColors;\n }\n /**\n * Registers a command inside the CLI.\n */\n register(commandClass) {\n var _a;\n if (this.registrations.has(commandClass))\n throw new RangeError(`${commandClass.name} has already been registered`);\n const specs = new Map();\n const command = new commandClass();\n for (const key in command) {\n const value = command[key];\n if (typeof value === `object` && value !== null && value[Command.isOption]) {\n specs.set(key, value);\n }\n }\n const builder = this.builder.command();\n const index = builder.cliIndex;\n const paths = (_a = commandClass.paths) !== null && _a !== void 0 ? _a : command.paths;\n if (typeof paths !== `undefined`)\n for (const path of paths)\n builder.addPath(path);\n this.registrations.set(commandClass, { specs, builder, index });\n for (const [key, { definition }] of specs.entries())\n definition(builder, key);\n builder.setContext({\n commandClass,\n });\n }\n process(opts, contextArg) {\n const { input, context: userContext, partial } = typeof opts === `object` && Array.isArray(opts)\n ? { input: opts, context: contextArg }\n : opts;\n const { contexts, process } = this.builder.compile();\n const state = process(input, { partial });\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n switch (state.selectedIndex) {\n case HELP_COMMAND_INDEX:\n {\n const command = HelpCommand.from(state, contexts);\n command.context = context;\n command.tokens = state.tokens;\n return command;\n }\n default:\n {\n const { commandClass } = contexts[state.selectedIndex];\n const record = this.registrations.get(commandClass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Expected the command class to have been registered.`);\n const command = new commandClass();\n command.context = context;\n command.tokens = state.tokens;\n command.path = state.path;\n try {\n for (const [key, { transformer }] of record.specs.entries())\n command[key] = transformer(record.builder, key, state, context);\n return command;\n }\n catch (error) {\n error[errorCommandSymbol] = command;\n throw error;\n }\n }\n break;\n }\n }\n async run(input, userContext) {\n var _a, _b;\n let command;\n const context = {\n ...Cli.defaultContext,\n ...userContext,\n };\n const colored = (_a = this.enableColors) !== null && _a !== void 0 ? _a : context.colorDepth > 1;\n if (!Array.isArray(input)) {\n command = input;\n }\n else {\n try {\n command = this.process(input, context);\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored }));\n return 1;\n }\n }\n if (command.help) {\n context.stdout.write(this.usage(command, { colored, detailed: true }));\n return 0;\n }\n command.context = context;\n command.cli = {\n binaryLabel: this.binaryLabel,\n binaryName: this.binaryName,\n binaryVersion: this.binaryVersion,\n enableCapture: this.enableCapture,\n enableColors: this.enableColors,\n definitions: () => this.definitions(),\n definition: command => this.definition(command),\n error: (error, opts) => this.error(error, opts),\n format: colored => this.format(colored),\n process: (input, subContext) => this.process(input, { ...context, ...subContext }),\n run: (input, subContext) => this.run(input, { ...context, ...subContext }),\n usage: (command, opts) => this.usage(command, opts),\n };\n const activate = this.enableCapture\n ? (_b = getCaptureActivator(context)) !== null && _b !== void 0 ? _b : noopCaptureActivator\n : noopCaptureActivator;\n let exitCode;\n try {\n exitCode = await activate(() => command.validateAndExecute().catch(error => command.catch(error).then(() => 0)));\n }\n catch (error) {\n context.stdout.write(this.error(error, { colored, command }));\n return 1;\n }\n return exitCode;\n }\n async runExit(input, context) {\n process.exitCode = await this.run(input, context);\n }\n definition(commandClass, { colored = false } = {}) {\n if (!commandClass.usage)\n return null;\n const { usage: path } = this.getUsageByRegistration(commandClass, { detailed: false });\n const { usage, options } = this.getUsageByRegistration(commandClass, { detailed: true, inlineOptions: false });\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : undefined;\n const description = typeof commandClass.usage.description !== `undefined`\n ? formatMarkdownish(commandClass.usage.description, { format: this.format(colored), paragraphs: false })\n : undefined;\n const details = typeof commandClass.usage.details !== `undefined`\n ? formatMarkdownish(commandClass.usage.details, { format: this.format(colored), paragraphs: true })\n : undefined;\n const examples = typeof commandClass.usage.examples !== `undefined`\n ? commandClass.usage.examples.map(([label, cli]) => [formatMarkdownish(label, { format: this.format(colored), paragraphs: false }), cli.replace(/\\$0/g, this.binaryName)])\n : undefined;\n return { path, usage, category, description, details, examples, options };\n }\n definitions({ colored = false } = {}) {\n const data = [];\n for (const commandClass of this.registrations.keys()) {\n const usage = this.definition(commandClass, { colored });\n if (!usage)\n continue;\n data.push(usage);\n }\n return data;\n }\n usage(command = null, { colored, detailed = false, prefix = `$ ` } = {}) {\n var _a;\n // In case the default command is the only one, we can just show the command help rather than the general one\n if (command === null) {\n for (const commandClass of this.registrations.keys()) {\n const paths = commandClass.paths;\n const isDocumented = typeof commandClass.usage !== `undefined`;\n const isExclusivelyDefault = !paths || paths.length === 0 || (paths.length === 1 && paths[0].length === 0);\n const isDefault = isExclusivelyDefault || ((_a = paths === null || paths === void 0 ? void 0 : paths.some(path => path.length === 0)) !== null && _a !== void 0 ? _a : false);\n if (isDefault) {\n if (command) {\n command = null;\n break;\n }\n else {\n command = commandClass;\n }\n }\n else {\n if (isDocumented) {\n command = null;\n continue;\n }\n }\n }\n if (command) {\n detailed = true;\n }\n }\n // @ts-ignore\n const commandClass = command !== null && command instanceof Command\n ? command.constructor\n : command;\n let result = ``;\n if (!commandClass) {\n const commandsByCategories = new Map();\n for (const [commandClass, { index }] of this.registrations.entries()) {\n if (typeof commandClass.usage === `undefined`)\n continue;\n const category = typeof commandClass.usage.category !== `undefined`\n ? formatMarkdownish(commandClass.usage.category, { format: this.format(colored), paragraphs: false })\n : null;\n let categoryCommands = commandsByCategories.get(category);\n if (typeof categoryCommands === `undefined`)\n commandsByCategories.set(category, categoryCommands = []);\n const { usage } = this.getUsageByIndex(index);\n categoryCommands.push({ commandClass, usage });\n }\n const categoryNames = Array.from(commandsByCategories.keys()).sort((a, b) => {\n if (a === null)\n return -1;\n if (b === null)\n return +1;\n return a.localeCompare(b, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const hasLabel = typeof this.binaryLabel !== `undefined`;\n const hasVersion = typeof this.binaryVersion !== `undefined`;\n if (hasLabel || hasVersion) {\n if (hasLabel && hasVersion)\n result += `${this.format(colored).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\\n\\n`;\n else if (hasLabel)\n result += `${this.format(colored).header(`${this.binaryLabel}`)}\\n`;\n else\n result += `${this.format(colored).header(`${this.binaryVersion}`)}\\n`;\n result += ` ${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n else {\n result += `${this.format(colored).bold(prefix)}${this.binaryName} <command>\\n`;\n }\n for (const categoryName of categoryNames) {\n const commands = commandsByCategories.get(categoryName).slice().sort((a, b) => {\n return a.usage.localeCompare(b.usage, `en`, { usage: `sort`, caseFirst: `upper` });\n });\n const header = categoryName !== null\n ? categoryName.trim()\n : `General commands`;\n result += `\\n`;\n result += `${this.format(colored).header(`${header}`)}\\n`;\n for (const { commandClass, usage } of commands) {\n const doc = commandClass.usage.description || `undocumented`;\n result += `\\n`;\n result += ` ${this.format(colored).bold(usage)}\\n`;\n result += ` ${formatMarkdownish(doc, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n result += `\\n`;\n result += formatMarkdownish(`You can also print more details about any of these commands by calling them with the \\`-h,--help\\` flag right after the command name.`, { format: this.format(colored), paragraphs: true });\n }\n else {\n if (!detailed) {\n const { usage } = this.getUsageByRegistration(commandClass);\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n }\n else {\n const { description = ``, details = ``, examples = [], } = commandClass.usage || {};\n if (description !== ``) {\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false }).replace(/^./, $0 => $0.toUpperCase());\n result += `\\n`;\n }\n if (details !== `` || examples.length > 0) {\n result += `${this.format(colored).header(`Usage`)}\\n`;\n result += `\\n`;\n }\n const { usage, options } = this.getUsageByRegistration(commandClass, { inlineOptions: false });\n result += `${this.format(colored).bold(prefix)}${usage}\\n`;\n if (options.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Options`)}\\n`;\n const maxDefinitionLength = options.reduce((length, option) => {\n return Math.max(length, option.definition.length);\n }, 0);\n result += `\\n`;\n for (const { definition, description } of options) {\n result += ` ${this.format(colored).bold(definition.padEnd(maxDefinitionLength))} ${formatMarkdownish(description, { format: this.format(colored), paragraphs: false })}`;\n }\n }\n if (details !== ``) {\n result += `\\n`;\n result += `${this.format(colored).header(`Details`)}\\n`;\n result += `\\n`;\n result += formatMarkdownish(details, { format: this.format(colored), paragraphs: true });\n }\n if (examples.length > 0) {\n result += `\\n`;\n result += `${this.format(colored).header(`Examples`)}\\n`;\n for (const [description, example] of examples) {\n result += `\\n`;\n result += formatMarkdownish(description, { format: this.format(colored), paragraphs: false });\n result += `${example\n .replace(/^/m, ` ${this.format(colored).bold(prefix)}`)\n .replace(/\\$0/g, this.binaryName)}\\n`;\n }\n }\n }\n }\n return result;\n }\n error(error, _a) {\n var _b;\n var { colored, command = (_b = error[errorCommandSymbol]) !== null && _b !== void 0 ? _b : null } = _a === void 0 ? {} : _a;\n if (!error || typeof error !== `object` || !(`stack` in error))\n error = new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(error)})`);\n let result = ``;\n let name = error.name.replace(/([a-z])([A-Z])/g, `$1 $2`);\n if (name === `Error`)\n name = `Internal Error`;\n result += `${this.format(colored).error(name)}: ${error.message}\\n`;\n const meta = error.clipanion;\n if (typeof meta !== `undefined`) {\n if (meta.type === `usage`) {\n result += `\\n`;\n result += this.usage(command);\n }\n }\n else {\n if (error.stack) {\n result += `${error.stack.replace(/^.*\\n/, ``)}\\n`;\n }\n }\n return result;\n }\n format(colored) {\n var _a;\n return ((_a = colored !== null && colored !== void 0 ? colored : this.enableColors) !== null && _a !== void 0 ? _a : Cli.defaultContext.colorDepth > 1) ? richFormat : textFormat;\n }\n getUsageByRegistration(klass, opts) {\n const record = this.registrations.get(klass);\n if (typeof record === `undefined`)\n throw new Error(`Assertion failed: Unregistered command`);\n return this.getUsageByIndex(record.index, opts);\n }\n getUsageByIndex(n, opts) {\n return this.builder.getBuilderByIndex(n).usage(opts);\n }\n}\n/**\n * The default context of the CLI.\n *\n * Contains the stdio of the current `process`.\n */\nCli.defaultContext = {\n env: process.env,\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n colorDepth: getDefaultColorDepth(),\n};\nfunction noopCaptureActivator(fn) {\n return fn();\n}\n\nexport { Cli, run, runExit };\n", "export { DefinitionsCommand } from './definitions.mjs';\nexport { HelpCommand } from './help.mjs';\nexport { TokensCommand } from './tokens.mjs';\nexport { VersionCommand } from './version.mjs';\n", "import { Command } from '../Command.mjs';\n\n/**\n * A command that prints the clipanion definitions.\n */\nclass DefinitionsCommand extends Command {\n async execute() {\n this.context.stdout.write(`${JSON.stringify(this.cli.definitions(), null, 2)}\\n`);\n }\n}\nDefinitionsCommand.paths = [[`--clipanion=definitions`]];\n\nexport { DefinitionsCommand };\n", "import { Command } from '../Command.mjs';\n\n/**\n * A command that prints the usage of all commands.\n *\n * Paths: `-h`, `--help`\n */\nclass HelpCommand extends Command {\n async execute() {\n this.context.stdout.write(this.cli.usage());\n }\n}\nHelpCommand.paths = [[`-h`], [`--help`]];\n\nexport { HelpCommand };\n", "import { makeCommandOption } from './utils.mjs';\n\n/**\n * Used to annotate that the command wants to retrieve all trailing\n * arguments that cannot be tied to a declared option.\n *\n * Be careful: this function is order-dependent! Make sure to define it\n * after any positional argument you want to declare.\n *\n * This function is mutually exclusive with Option.Rest.\n *\n * @example\n * yarn run foo hello --foo=bar world\n * \u25BA proxy = [\"hello\", \"--foo=bar\", \"world\"]\n */\nfunction Proxy(opts = {}) {\n return makeCommandOption({\n definition(builder, key) {\n var _a;\n builder.addProxy({\n name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n return state.positionals.map(({ value }) => value);\n },\n });\n}\n\nexport { Proxy };\n", "import { Command } from '../Command.mjs';\nimport { Proxy } from '../options/Proxy.mjs';\n\n/**\n * A command that prints the clipanion tokens.\n */\nclass TokensCommand extends Command {\n constructor() {\n super(...arguments);\n this.args = Proxy();\n }\n async execute() {\n this.context.stdout.write(`${JSON.stringify(this.cli.process(this.args).tokens, null, 2)}\\n`);\n }\n}\nTokensCommand.paths = [[`--clipanion=tokens`]];\n\nexport { TokensCommand };\n", "import { Command } from '../Command.mjs';\n\n/**\n * A command that prints the version of the binary (`cli.binaryVersion`).\n *\n * Paths: `-v`, `--version`\n */\nclass VersionCommand extends Command {\n async execute() {\n var _a;\n this.context.stdout.write(`${(_a = this.cli.binaryVersion) !== null && _a !== void 0 ? _a : `<unknown>`}\\n`);\n }\n}\nVersionCommand.paths = [[`-v`], [`--version`]];\n\nexport { VersionCommand };\n", "export { Array } from './Array.mjs';\nexport { Boolean } from './Boolean.mjs';\nexport { Counter } from './Counter.mjs';\nexport { Proxy } from './Proxy.mjs';\nexport { Rest } from './Rest.mjs';\nexport { String } from './String.mjs';\nexport { applyValidator, cleanValidationError, formatError, isOptionSymbol, makeCommandOption, rerouteArguments } from './utils.mjs';\n", "import { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction Array(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity,\n hidden: opts === null || opts === void 0 ? void 0 : opts.hidden,\n description: opts === null || opts === void 0 ? void 0 : opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n let usedName;\n let currentValue = typeof initialValue !== `undefined`\n ? [...initialValue]\n : undefined;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = currentValue !== null && currentValue !== void 0 ? currentValue : [];\n currentValue.push(value);\n }\n if (typeof currentValue !== `undefined`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\n\nexport { Array };\n", "import { makeCommandOption, rerouteArguments } from './utils.mjs';\n\nfunction Boolean(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n allowBinding: false,\n arity: 0,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builer, key, state) {\n let currentValue = initialValue;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n currentValue = value;\n }\n return currentValue;\n },\n });\n}\n\nexport { Boolean };\n", "import { makeCommandOption, rerouteArguments } from './utils.mjs';\n\nfunction Counter(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n allowBinding: false,\n arity: 0,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n let currentValue = initialValue;\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n currentValue !== null && currentValue !== void 0 ? currentValue : (currentValue = 0);\n // Negated options reset the counter\n if (!value) {\n currentValue = 0;\n }\n else {\n currentValue += 1;\n }\n }\n return currentValue;\n },\n });\n}\n\nexport { Counter };\n", "import { NoLimits } from '../../core.mjs';\nimport { makeCommandOption } from './utils.mjs';\n\n/**\n * Used to annotate that the command supports any number of positional\n * arguments.\n *\n * Be careful: this function is order-dependent! Make sure to define it\n * after any positional argument you want to declare.\n *\n * This function is mutually exclusive with Option.Proxy.\n *\n * @example\n * yarn add hello world\n * \u25BA rest = [\"hello\", \"world\"]\n */\nfunction Rest(opts = {}) {\n return makeCommandOption({\n definition(builder, key) {\n var _a;\n builder.addRest({\n name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n // The builder's arity.extra will always be NoLimits,\n // because it is set when we call registerDefinition\n const isRestPositional = (index) => {\n const positional = state.positionals[index];\n // A NoLimits extra (i.e. an optional rest argument)\n if (positional.extra === NoLimits)\n return true;\n // A leading positional (i.e. a required rest argument)\n if (positional.extra === false && index < builder.arity.leading.length)\n return true;\n return false;\n };\n let count = 0;\n while (count < state.positionals.length && isRestPositional(count))\n count += 1;\n return state.positionals.splice(0, count).map(({ value }) => value);\n },\n });\n}\n\nexport { Rest };\n", "import { NoLimits } from '../../core.mjs';\nimport { makeCommandOption, applyValidator, rerouteArguments } from './utils.mjs';\n\nfunction StringOption(descriptor, initialValueBase, optsBase) {\n const [initialValue, opts] = rerouteArguments(initialValueBase, optsBase !== null && optsBase !== void 0 ? optsBase : {});\n const { arity = 1 } = opts;\n const optNames = descriptor.split(`,`);\n const nameSet = new Set(optNames);\n return makeCommandOption({\n definition(builder) {\n builder.addOption({\n names: optNames,\n arity: opts.tolerateBoolean ? 0 : arity,\n hidden: opts.hidden,\n description: opts.description,\n required: opts.required,\n });\n },\n transformer(builder, key, state, context) {\n let usedName;\n let currentValue = initialValue;\n if (typeof opts.env !== `undefined` && context.env[opts.env]) {\n usedName = opts.env;\n currentValue = context.env[opts.env];\n }\n for (const { name, value } of state.options) {\n if (!nameSet.has(name))\n continue;\n usedName = name;\n currentValue = value;\n }\n if (typeof currentValue === `string`) {\n return applyValidator(usedName !== null && usedName !== void 0 ? usedName : key, currentValue, opts.validator);\n }\n else {\n return currentValue;\n }\n },\n });\n}\nfunction StringPositional(opts = {}) {\n const { required = true } = opts;\n return makeCommandOption({\n definition(builder, key) {\n var _a;\n builder.addPositional({\n name: (_a = opts.name) !== null && _a !== void 0 ? _a : key,\n required: opts.required,\n });\n },\n transformer(builder, key, state) {\n var _a;\n for (let i = 0; i < state.positionals.length; ++i) {\n // We skip NoLimits extras. We only care about\n // required and optional finite positionals.\n if (state.positionals[i].extra === NoLimits)\n continue;\n // We skip optional positionals when we only\n // care about required positionals.\n if (required && state.positionals[i].extra === true)\n continue;\n // We skip required positionals when we only\n // care about optional positionals.\n if (!required && state.positionals[i].extra === false)\n continue;\n // We remove the positional from the list\n const [positional] = state.positionals.splice(i, 1);\n return applyValidator((_a = opts.name) !== null && _a !== void 0 ? _a : key, positional.value, opts.validator);\n }\n return undefined;\n },\n });\n}\n// This function is badly typed, but it doesn't matter because the overloads provide the true public typings\nfunction String(descriptor, ...args) {\n if (typeof descriptor === `string`) {\n return StringOption(descriptor, ...args);\n }\n else {\n return StringPositional(descriptor);\n }\n}\n\nexport { String };\n", "// Credential config resolution, brand-neutral. The default TOML file preserves\n// the original CLI path; named profiles live below profiles/. A complete env-var\n// pair overrides the selected file. The platform config directory mirrors\n// Python's platformdirs (so an existing `~/.config/<app>/config.toml` written by\n// the old CLI keeps working). Branded layers pass their own `ConfigBranding`.\n\nimport {\n closeSync,\n existsSync,\n mkdirSync,\n openSync,\n readFileSync,\n readdirSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nimport { parse as parseToml } from \"smol-toml\";\n\nexport interface ConfigBranding {\n /** App name \u2192 config directory leaf, e.g. \"ente\". */\n appName: string;\n /** Config file name, e.g. \"config.toml\". */\n configFileName: string;\n /** Env var that overrides the stored API url, e.g. \"ENTE_API_URL\". */\n urlEnvVar: string;\n /** Env var that overrides the stored API key, e.g. \"ENTE_API_KEY\". */\n keyEnvVar: string;\n /** Env var that selects a named credential profile, e.g. \"ENTE_PROFILE\". */\n profileEnvVar: string;\n}\n\nexport interface Credentials {\n apiUrl: string;\n apiKey: string;\n source: \"env\" | \"file\";\n /** Undefined means the backward-compatible default profile. */\n profile?: string;\n}\n\nconst PROFILE_MAX_LENGTH = 64;\n\n/** Validate and canonicalize a profile name. \"default\" selects the legacy file. */\nexport function normalizeProfileName(value: string | null | undefined): string | undefined {\n const trimmed = value?.trim();\n if (!trimmed || trimmed.toLowerCase() === \"default\") return undefined;\n const normalized = trimmed.toLowerCase();\n if (\n normalized.length > PROFILE_MAX_LENGTH\n || !/^[a-z0-9][a-z0-9._-]*$/u.test(normalized)\n ) {\n throw new Error(\n \"Profile names must start with a letter or number and contain at most 64 \"\n + \"lowercase letters, numbers, dots, underscores, or hyphens.\",\n );\n }\n return normalized;\n}\n\n/** Resolve an explicit profile first, then the branded profile environment variable. */\nexport function selectedProfile(\n branding: ConfigBranding,\n explicit?: string,\n): string | undefined {\n return normalizeProfileName(explicit ?? process.env[branding.profileEnvVar]);\n}\n\n/** Platform config directory, mirroring Python platformdirs.user_config_dir. */\nexport function configDir(branding: ConfigBranding): string {\n const home = os.homedir();\n if (process.platform === \"darwin\") {\n return path.join(home, \"Library\", \"Application Support\", branding.appName);\n }\n if (process.platform === \"win32\") {\n const appData = process.env.APPDATA ?? path.join(home, \"AppData\", \"Roaming\");\n return path.join(appData, branding.appName);\n }\n const xdg = process.env.XDG_CONFIG_HOME;\n const base = xdg && xdg.trim() ? xdg : path.join(home, \".config\");\n return path.join(base, branding.appName);\n}\n\nexport function configPath(branding: ConfigBranding, profile?: string): string {\n const selected = selectedProfile(branding, profile);\n return selected\n ? path.join(configDir(branding), \"profiles\", `${selected}.toml`)\n : path.join(configDir(branding), branding.configFileName);\n}\n\nfunction readTomlFile(\n branding: ConfigBranding,\n profile?: string,\n): Record<string, unknown> {\n const file = configPath(branding, profile);\n if (!existsSync(file)) return {};\n try {\n return parseToml(readFileSync(file, \"utf8\")) as Record<string, unknown>;\n } catch {\n // A present-but-corrupt config is a real error \u2014 surfacing it beats silently\n // pretending the user is logged out (they'd re-run `auth login` for nothing).\n throw new Error(\n `Config at ${file} is unreadable. Re-run ${branding.appName} auth login to repair it; do not share the file contents.`,\n );\n }\n}\n\n/**\n * Read stored credentials. Returns null only when the config is genuinely\n * absent (logged out). A file that is present but has malformed/non-string\n * credential values is a real error \u2014 fail loud rather than let a bad value\n * reach the transport layer and surface as a confusing runtime crash.\n */\nexport function readStoredCredentials(\n branding: ConfigBranding,\n profile?: string,\n): Credentials | null {\n const selected = selectedProfile(branding, profile);\n const cfg = readTomlFile(branding, profile);\n const apiUrl = cfg.api_url;\n const apiKey = cfg.api_key;\n if (apiUrl === undefined && apiKey === undefined) return null;\n if (\n typeof apiUrl !== \"string\" ||\n !apiUrl.trim() ||\n typeof apiKey !== \"string\" ||\n !apiKey.trim()\n ) {\n throw new Error(\n `Config at ${configPath(branding, profile)} is invalid: 'api_url' and 'api_key' must both be ` +\n `non-empty strings. Re-run '${branding.appName} auth login'.`,\n );\n }\n return { apiUrl, apiKey, source: \"file\", profile: selected };\n}\n\n/** Read credentials from env vars only. */\nexport function readEnvCredentials(\n branding: ConfigBranding,\n profile?: string,\n): Credentials | null {\n const url = process.env[branding.urlEnvVar];\n const key = process.env[branding.keyEnvVar];\n const hasOverride = url !== undefined || key !== undefined;\n if (!hasOverride) return null;\n if (!url?.trim() || !key?.trim()) {\n throw new Error(\n `${branding.urlEnvVar} and ${branding.keyEnvVar} must both be non-empty when either is set. `\n + \"Refusing to fall back to stored credentials while the override is incomplete.\",\n );\n }\n return {\n apiUrl: url,\n apiKey: key,\n source: \"env\",\n profile: selectedProfile(branding, profile),\n };\n}\n\n/** Resolve credentials. Priority: env vars > config file. Throws if neither. */\nexport function loadCredentials(branding: ConfigBranding): Credentials {\n const fromEnv = readEnvCredentials(branding);\n if (fromEnv) return fromEnv;\n const stored = readStoredCredentials(branding);\n if (stored) return stored;\n const profile = selectedProfile(branding) ?? \"default\";\n throw new Error(\n `Profile '${profile}' is not authenticated.\\n\\n` +\n \"Either run:\\n\" +\n ` ${branding.appName} auth login --url <url> --key <key> --profile ${profile}\\n\\n` +\n \"Or set environment variables:\\n\" +\n ` export ${branding.urlEnvVar}=https://your-deployment.convex.site\\n` +\n ` export ${branding.keyEnvVar}=your-key-here`,\n );\n}\n\nexport function saveCredentials(\n branding: ConfigBranding,\n apiUrl: string,\n apiKey: string,\n profile?: string,\n options?: { ifAbsent?: boolean },\n): void {\n const file = configPath(branding, profile);\n const dir = path.dirname(file);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n // A new file must get mode 0600 at creation. Replacement removes the old\n // file first; exclusive creation uses wx so a concurrent profile survives.\n // Match the old CLI's exact two-key file shape.\n const contents = `api_url = \"${apiUrl}\"\\napi_key = \"${apiKey}\"\\n`;\n if (options?.ifAbsent) {\n const handle = openSync(file, \"wx\", 0o600);\n try {\n writeFileSync(handle, contents);\n } catch (error) {\n closeSync(handle);\n rmSync(file, { force: true });\n throw error;\n }\n closeSync(handle);\n return;\n }\n rmSync(file, { force: true });\n writeFileSync(file, contents, { mode: 0o600 });\n}\n\n/** Delete the config file. Returns true if it existed. */\nexport function deleteCredentials(branding: ConfigBranding, profile?: string): boolean {\n const file = configPath(branding, profile);\n if (!existsSync(file)) return false;\n rmSync(file);\n return true;\n}\n\nexport function configExists(branding: ConfigBranding, profile?: string): boolean {\n return existsSync(configPath(branding, profile));\n}\n\n/** List stored profile names. The legacy config is reported as \"default\". */\nexport function listStoredProfiles(branding: ConfigBranding): string[] {\n const profiles: string[] = [];\n const defaultFile = path.join(configDir(branding), branding.configFileName);\n if (existsSync(defaultFile)) profiles.push(\"default\");\n const dir = path.join(configDir(branding), \"profiles\");\n if (!existsSync(dir)) return profiles;\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isFile() || !entry.name.endsWith(\".toml\")) continue;\n const name = entry.name.slice(0, -\".toml\".length);\n try {\n const normalized = normalizeProfileName(name);\n if (normalized && normalized === name) profiles.push(normalized);\n } catch {\n // Ignore files that cannot have been created by this CLI.\n }\n }\n return profiles.sort((left, right) => {\n if (left === \"default\") return -1;\n if (right === \"default\") return 1;\n return left.localeCompare(right);\n });\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nfunction getLineColFromPtr(string, ptr) {\n let lines = string.slice(0, ptr).split(/\\r?\\n/);\n return [lines.length, lines.pop().length + 1];\n}\nfunction makeCodeBlock(string, line, column) {\n let lines = string.split(/\\r?\\n/);\n let codeblock = '';\n let numberLen = (Math.log10(line + 1) | 0) + 1;\n for (let i = line - 1; i <= line + 1; i++) {\n let l = lines[i - 1];\n if (!l)\n continue;\n codeblock += i.toString().padEnd(numberLen, ' ');\n codeblock += ': ';\n codeblock += l;\n codeblock += '\\n';\n if (i === line) {\n codeblock += ' '.repeat(numberLen + column + 2);\n codeblock += '^\\n';\n }\n }\n return codeblock;\n}\nexport class TomlError extends Error {\n line;\n column;\n codeblock;\n constructor(message, options) {\n const [line, column] = getLineColFromPtr(options.toml, options.ptr);\n const codeblock = makeCodeBlock(options.toml, line, column);\n super(`Invalid TOML document: ${message}\\n\\n${codeblock}`, options);\n this.line = line;\n this.column = column;\n this.codeblock = codeblock;\n }\n /** @internal */\n static x(message, ctx, ptr) {\n throw new TomlError(message, { toml: ctx.s, ptr: ptr ?? ctx.p });\n }\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\n/** @internal */\nexport function parseString(ctx) {\n let startPtr = ctx.p;\n let c = ctx.s.charCodeAt(ctx.p++);\n let first = c;\n let isLiteral = c === 0x27; /* ' */\n let isMultiline = c === ctx.s.charCodeAt(ctx.p) && c === ctx.s.charCodeAt(ctx.p + 1);\n if (isMultiline) {\n // Trim initial newline\n if ((c = ctx.s.charCodeAt(ctx.p += 2)) === 0xa /* \\n */)\n ctx.p++;\n else if (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */)\n ctx.p += 2;\n }\n // For the record: it is not worth it to use a fast-path for literal strings using `indexOf`.\n // Doing a char-by-char iteration ends up dispatching less instructions, for the same wall-clock runtime.\n let parsed = '';\n let sliceStart = ctx.p;\n // states:\n // 0 - decoding\n // 1 - decoding escape\n // 2 - whitespace escape (no newline encountered yet, must fail on non-whitespace)\n // 3 - whitespace escape (newline encountered, allowed to transition back to normal decode)\n let state = 0;\n for (; ctx.p < ctx.s.length; ctx.p++) {\n c = ctx.s.charCodeAt(ctx.p);\n // Deal with newlines first, since that simplifies control character checking and handling across all states\n if (isMultiline && (c === 0xa /* \\n */ || (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */))) {\n state = state && 3;\n }\n // Control characters are banned in TOML, so we throw an error if we encounter them\n else if ((c < 0x20 && c !== 0x9 /* \\t */) || c === 0x7f) {\n TomlError.x('control characters are not allowed in strings', ctx);\n }\n // The string might terminate while we're parsing through a newline escape.\n // It must have encountered a newline; otherwise, it'll simply fail in another branch.\n else if ((!state || state === 3) && c === first && (!isMultiline || (ctx.s.charCodeAt(ctx.p + 1) === first && ctx.s.charCodeAt(ctx.p + 2) === first))) {\n if (isMultiline) {\n // If the string ends with 4-5 quotes, then the first 1-2 are part of the string\n if (ctx.s.charCodeAt(ctx.p + 3) === first)\n ctx.p++;\n if (ctx.s.charCodeAt(ctx.p + 3) === first)\n ctx.p++;\n }\n // If we're in a newline escape still, then there's nothing to add.\n if (!state) {\n // Avoid a useless concat operation if the string can be used as-is.\n let s = ctx.s.slice(sliceStart, ctx.p);\n parsed = parsed ? parsed + s : s;\n }\n ctx.p += isMultiline ? 3 : 1;\n return parsed;\n }\n // Baseline state; keep moving forward unless an escape sequence starts\n else if (!state) {\n if (!isLiteral && c === 0x5c /* \\ */) {\n parsed += ctx.s.slice(sliceStart, (sliceStart = ctx.p));\n state = 1;\n }\n }\n else if (state === 1) {\n if (c === 0x78 /* x */ || c === 0x75 /* u */ || c === 0x55 /* U */) { // Unicode escape\n let errPtr = ctx.p++ - 1;\n let value = 0;\n let len = c === 0x78 /* x */ ? 2 : c === 0x75 /* u */ ? 4 : 8;\n for (let j = 0; j < len; j++, ctx.p++) {\n let hex = ctx.s.charCodeAt(ctx.p);\n let digit = \n /* 0-9 */ hex >= 0x30 && hex <= 0x39 ? hex - 0x30 :\n /* A-F */ hex >= 0x41 && hex <= 0x46 ? hex - 0x41 + 10 :\n /* a-f */ hex >= 0x61 && hex <= 0x66 ? hex - 0x61 + 10 : -1;\n if (digit < 0)\n TomlError.x('invalid non-hex character in unicode escape', ctx);\n value = (value << 4) | digit;\n }\n // Because JS does bitwise on signed 32bit integers, all 0xfzzzzzzz values are actually seen as negative\n if (value < 0 || value > 0x10ffff || (value >= 0xd800 && value <= 0xdfff)) {\n TomlError.x('invalid unicode escape', ctx, errPtr);\n }\n parsed += String.fromCodePoint(value);\n sliceStart = ctx.p--;\n state = 0;\n }\n // Newline escape sequence. We only need to care about spaces and tabs; newlines are dealt with earlier\n else if (isMultiline && (c === 0x20 || c === 0x9 /* \\t */)) {\n state = 2;\n }\n // Basic escape sequence\n else {\n if (c === 0x62 /* b */)\n parsed += '\\b';\n else if (c === 0x74 /* t */)\n parsed += '\\t';\n else if (c === 0x6e /* n */)\n parsed += '\\n';\n else if (c === 0x66 /* f */)\n parsed += '\\f';\n else if (c === 0x72 /* r */)\n parsed += '\\r';\n else if (c === 0x65 /* e */)\n parsed += '\\x1b';\n else if (c === 0x22 /* \" */)\n parsed += '\"';\n else if (c === 0x5c /* \\ */)\n parsed += '\\\\';\n else\n TomlError.x('unrecognised escape sequence', ctx);\n sliceStart = ctx.p + 1;\n state = 0;\n }\n }\n // Newline escape continuation: keep moving forward until the first non-whitespace char\n else if (c !== 0x20 && c !== 0x9 /* \\t */) {\n if (state === 2)\n TomlError.x('invalid escape: only line-ending whitespace may be escaped', ctx, sliceStart);\n // State cannot be zero, or we'd have branched earlier already.\n // If it's a backslash, immediately transition to the escape state so it can be processed.\n state = !isLiteral && c === 0x5c /* \\ */ ? 1 : 0;\n sliceStart = ctx.p;\n }\n }\n TomlError.x('unfinished string', ctx, startPtr);\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet DATE_TIME_RE = /^(\\d{4}-\\d{2}-\\d{2})?[Tt ]?(?:(\\d{2}):\\d{2}(?::\\d{2}(?:\\.\\d+)?)?)?(Z|z|[-+]\\d{2}:\\d{2})?$/i;\nexport class TomlDate extends Date {\n #hasDate = false;\n #hasTime = false;\n #offset = null;\n constructor(date, fasttype, unsafeDelim) {\n let hasDate = true;\n let hasTime = true;\n let offset = 'Z';\n let c;\n if (typeof date === 'string') {\n if (fasttype)\n prep: {\n // Date-time\n if (fasttype < 3) {\n if (+date.slice(11, 13) > 23) {\n date = '';\n break prep;\n }\n // Local\n if (fasttype === 2) {\n offset = null;\n date += 'Z';\n }\n // Offset; keep track of offset if not Z\n else if ((c = date.charCodeAt(date.length - 1)) !== 0x5a /* Z */ && c !== 0x7a /* z */) {\n offset = date.slice(date.length - 6);\n }\n if (unsafeDelim)\n date = date.slice(0, 10) + 'T' + date.slice(11);\n }\n // Time\n else if (fasttype === 4) {\n date = +date.slice(0, 2) > 23 ? '' : `0000-01-01T${date}Z`;\n }\n hasDate = fasttype !== 4;\n hasTime = fasttype !== 3;\n }\n else {\n let match = date.match(DATE_TIME_RE);\n if (match) {\n if (!match[1]) {\n hasDate = false;\n date = `0000-01-01T${date}`;\n }\n hasTime = !!match[2];\n // Make sure to use T instead of a space. Breaks in case of extreme values otherwise.\n hasTime && date[10] === ' ' && (date = date.replace(' ', 'T'));\n // Do not allow rollover hours.\n if (match[2] && +match[2] > 23) {\n date = '';\n }\n else {\n offset = match[3] || null;\n if (!offset && hasTime)\n date += 'Z';\n }\n }\n else {\n date = '';\n }\n }\n }\n super(date);\n if (!isNaN(this.getTime())) {\n this.#hasDate = hasDate;\n this.#hasTime = hasTime;\n this.#offset = offset;\n }\n }\n isDateTime() {\n return this.#hasDate && this.#hasTime;\n }\n isLocal() {\n return !this.#hasDate || !this.#hasTime || !this.#offset;\n }\n isDate() {\n return this.#hasDate && !this.#hasTime;\n }\n isTime() {\n return this.#hasTime && !this.#hasDate;\n }\n isValid() {\n return this.#hasDate || this.#hasTime;\n }\n toISOString() {\n let iso = super.toISOString();\n // Local Date\n if (this.isDate())\n return iso.slice(0, 10);\n // Local Time\n if (this.isTime())\n return iso.slice(11, 23);\n // Local DateTime\n if (this.#offset === null)\n return iso.slice(0, -1);\n // Offset DateTime\n if (this.#offset === 'Z' || this.#offset === 'z')\n return iso;\n // This part is quite annoying: JS strips the original timezone from the ISO string representation\n // Instead of using a \"modified\" date and \"Z\", we restore the representation \"as authored\"\n let offset = (+(this.#offset.slice(1, 3)) * 60) + +(this.#offset.slice(4, 6));\n offset = this.#offset[0] === '-' ? offset : -offset;\n let offsetDate = new Date(this.getTime() - (offset * 60e3));\n return offsetDate.toISOString().slice(0, -1) + this.#offset;\n }\n static wrapAsOffsetDateTime(jsDate, offset = 'Z') {\n let date = new TomlDate(jsDate);\n date.#offset = offset;\n return date;\n }\n static wrapAsLocalDateTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#offset = null;\n return date;\n }\n static wrapAsLocalDate(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasTime = false;\n date.#offset = null;\n return date;\n }\n static wrapAsLocalTime(jsDate) {\n let date = new TomlDate(jsDate);\n date.#hasDate = false;\n date.#offset = null;\n return date;\n }\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { parseArray, parseInlineTable } from './struct.js';\nimport { TomlError } from './error.js';\nimport { TomlDate } from './date.js';\nfunction isDigit(char, base = 10) {\n return base === 16\n ? (char > 0x2f && char < 0x3a) || (char > 0x40 && char < 0x47) || (char > 0x60 && char < 0x67)\n : (char > 0x2f && char < 0x30 + base);\n}\nfunction isEndOfValue(char, delim) {\n // Whitespace -- we're permissive on `\\r` for performance; it'll be dealt with later anyway\n return char === 0x20 || char === 0x9 /* \\t */ || char === 0xa /* \\n */ || char === 0xd /* \\r */ ||\n // Structure end or next value delimiter\n (delim && (char === delim || char === 0x2c /* , */)) ||\n // Comment\n char === 0x23; /* # */\n}\n/** @internal */\nexport function extractValue(ctx, end) {\n let errPtr = ctx.p;\n let c = ctx.s.charCodeAt(ctx.p);\n // Structs\n if (c === 0x5b /* [ */ || c === 0x7b /* { */) {\n ctx.d-- || TomlError.x('document contains excessively nested structures. aborting.', ctx);\n let value = c === 0x5b /* [ */\n ? parseArray(ctx)\n : parseInlineTable(ctx);\n ctx.d++;\n return value;\n }\n // Strings\n if (c === 0x22 /* \" */ || c === 0x27 /* ' */) {\n return parseString(ctx);\n }\n // Booleans\n // We can fast-path because the first character is enough to know the only possible value\n if (c === 0x74 /* t */) { // Only possible valid value is `true`\n if (ctx.s.charCodeAt(++ctx.p) !== 0x72 || ctx.s.charCodeAt(++ctx.p) !== 0x75 || ctx.s.charCodeAt(++ctx.p) !== 0x65)\n TomlError.x('invalid value', ctx, errPtr);\n return ctx.p++, true;\n }\n if (c === 0x66 /* f */) { // Only possible valid value is `false`\n if (ctx.s.charCodeAt(++ctx.p) !== 0x61 || ctx.s.charCodeAt(++ctx.p) !== 0x6c || ctx.s.charCodeAt(++ctx.p) !== 0x73 || ctx.s.charCodeAt(++ctx.p) !== 0x65)\n TomlError.x('invalid value', ctx, errPtr);\n return ctx.p++, false;\n }\n if (c === 0x2b /* + */ || c === 0x2d /* - */) {\n return parseNumber(ctx, ctx.p, ctx.s.charCodeAt(++ctx.p), 0x2c - c, end);\n }\n // Rough heuristic, but `parseDate` falls back to number parsing if it's a false positive.\n // e.g.: `a = 1\\n-------------- = 1` would match this heuristic, but gracefully fallback to numbers.\n if (ctx.s.charCodeAt(ctx.p + 4) === 0x2d /* - */ && ctx.s.charCodeAt(ctx.p + 7) === 0x2d /* - */) {\n return parseDate(ctx, c, end);\n }\n // Same logic as above; `parseTime` falls back to number parsing if it's a false positive.\n if (ctx.s.charCodeAt(ctx.p + 2) === 0x3a /* : */) {\n return parseTime(ctx, c, end);\n }\n return parseNumber(ctx, ctx.p, c, 0, end);\n}\n// State:\n// 0: init\n// 1: integer\n// 2: fractional dot\n// 3: fractional\n// 4: exponent letter\n// 5: exponent\n// >9: underscore; see below\n// -> 12: was integer\n// -> 14: was fractional\n// -> 16: was exponent\n// states 2-5, 14, 16 are ONLY permitted iif base === 10\nfunction parseNumber(ctx, startPtr, startChr, sign, endChr) {\n let c = startChr;\n let state = 0;\n let hasUnderscores = false;\n // (+/-)inf\n if (c === 0x69 /* i */) {\n if (ctx.s.charCodeAt(++ctx.p) !== 0x6e || ctx.s.charCodeAt(++ctx.p) !== 0x66)\n TomlError.x('invalid value', ctx, startPtr);\n return ctx.p++, (sign || 1) / 0;\n }\n // (+/-)nan\n if (c === 0x6e /* n */) {\n if (ctx.s.charCodeAt(++ctx.p) !== 0x61 || ctx.s.charCodeAt(++ctx.p) !== 0x6e)\n TomlError.x('invalid value', ctx, startPtr);\n return ctx.p++, NaN;\n }\n // Leading zero\n // Only allowed cases: `0<EOV>`, `0.(...)`, `0e(...)`, `0x(...)`, `0b(...)`, `0o(...)`\n // FWIW, `0e(...)` is a stupid case, but it's not banned per-se so we have to parse it\n if (c === 0x30 /* 0 */) {\n if (++ctx.p >= ctx.s.length || isEndOfValue(c = ctx.s.charCodeAt(ctx.p), endChr))\n return ctx.bi === true ? 0n : 0; // note: conveniently deals with `-0`\n if (!sign) {\n if (c === 0x78 /* x */)\n return parseIntegerBaseN(ctx, startPtr, 16, endChr);\n else if (c === 0x62 /* b */)\n return parseIntegerBaseN(ctx, startPtr, 2, endChr);\n else if (c === 0x6f /* o */)\n return parseIntegerBaseN(ctx, startPtr, 8, endChr);\n }\n if (c === 0x2e /* . */)\n state = 2;\n else if (c === 0x65 /* e */ || c === 0x45 /* E */)\n state = 4;\n else\n TomlError.x('illegal leading zero', ctx, startPtr);\n }\n // If the 1st char is not a digit by now, then it's not a valid TOML value at all\n else if (!isDigit(c))\n TomlError.x('invalid value', ctx, startPtr);\n while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {\n if (!state)\n state = 1; // Detects single-digit numbers we can use a fast parse path for\n // The way the states are numbered is not random: underscores are always permitted in odd-numbered states and\n // never permitted in even-numbered ones.\n if (c === 0x5f /* _ */) {\n if (!(state & 1))\n TomlError.x('illegal underscore', ctx);\n state += 11; // 11 is a marker that makes the state even and greater than 9; see the numbering + rationale above\n hasUnderscores = true;\n }\n // Transition to fractional part.\n else if (state === 1 && c === 0x2e /* . */)\n state = 2;\n // Transition to exponent part.\n else if ((state === 1 || state === 3) && (c === 0x65 /* e */ || c === 0x45 /* E */))\n state = 4;\n // + and - are permitted in state 4 only (handled before entering the function for state 0)\n else if (state === 4 && (c === 0x2b /* + */ || c === 0x2d /* - */)) { /* no-op */ }\n // All special cases have been handled; only digits are allowed here\n else if (!isDigit(c))\n TomlError.x(`illegal character in numeric literal`, ctx);\n // Clear state flags\n else if (state > 9)\n state -= 11;\n else if (!(state & 1))\n state++;\n }\n // Single-char number; we can fast-path these very easily.\n if (!state) {\n let val = (startChr - 0x30 /* 0 */) * (sign || 1);\n return ctx.bi === true ? BigInt(val) : val;\n }\n // Even-numbered states absolutely require a digit next; not even end of value is permitted\n if (!(state & 1))\n TomlError.x('unfinished numeric value', ctx, startPtr);\n let str = ctx.s.slice(startPtr, ctx.p);\n if (hasUnderscores)\n str = str.replaceAll('_', ''); // perf: replaceAll 1.25x faster than replace with a regex\n return state > 1\n ? parseFloat(str)\n : parseInteger(ctx, str, 10, startPtr);\n}\nfunction parseIntegerBaseN(ctx, startPtr, base, endChr) {\n let c, underscore = 1;\n while (++ctx.p < ctx.s.length && (c = ctx.s.charCodeAt(ctx.p), !isEndOfValue(c, endChr))) {\n if (c === 0x5f /* _ */) {\n if (underscore & 1)\n TomlError.x('illegal underscore', ctx);\n underscore = 3;\n }\n // We only need to check if the number is a valid digit, nothing else is permitted\n else if (!isDigit(c, base))\n TomlError.x(`illegal character in numeric literal`, ctx);\n // Clear underscore flag\n else if (underscore & 1)\n underscore--;\n }\n // Trailing underscore is not allowed\n if (underscore & 1)\n TomlError.x('unfinished numeric value', ctx);\n let str = ctx.s.slice(startPtr + 2, ctx.p);\n if (underscore)\n str = str.replaceAll('_', ''); // perf: replaceAll 1.25x faster than replace with a regex\n return parseInteger(ctx, str, base, startPtr);\n}\nfunction parseInteger(ctx, str, base, startPtr) {\n if (ctx.bi !== true)\n int: {\n let val = parseInt(str, base);\n if (!Number.isSafeInteger(val)) {\n if (ctx.bi)\n break int;\n TomlError.x('integer value cannot be represented losslessly', ctx, startPtr);\n }\n return val;\n }\n return base === 10 ? BigInt(str) : BigInt((base === 2 ? '0b' : base === 8 ? '0o' : '0x') + str);\n}\nfunction parseDate(ctx, c, endChr) {\n let startPtr = ctx.p++, unsafeSeparator;\n if (!isDigit(c) ||\n !isDigit(ctx.s.charCodeAt(ctx.p++)) ||\n !isDigit(ctx.s.charCodeAt(ctx.p++)) ||\n !isDigit(ctx.s.charCodeAt(ctx.p++))) {\n return parseNumber(ctx, ctx.p = startPtr, c, 0, endChr);\n }\n ctx.p += 5;\n if (!isDigit(ctx.s.charCodeAt(ctx.p++)))\n TomlError.x('invalid date-time: date part is malformed', ctx, startPtr);\n if (ctx.p >= ctx.s.length || (((c = ctx.s.charCodeAt(ctx.p)) !== 0x20 || (unsafeSeparator = true, !isDigit(ctx.s.charCodeAt(ctx.p + 1)))) && c !== 0x54 /* T */ && c !== 0x74 /* t */)) {\n let t = ctx.s.slice(startPtr, ctx.p);\n return readDate(ctx, t, 3, false, startPtr);\n }\n if (ctx.s.charCodeAt(ctx.p += 3) !== 0x3a /* : */)\n TomlError.x('invalid date-time: time part is malformed', ctx, startPtr);\n if (ctx.s.charCodeAt(ctx.p += 3) === 0x3a /* : */)\n ctx.p += 3;\n if (ctx.s.charCodeAt(ctx.p) === 0x2e /* . */)\n while (isDigit(ctx.s.charCodeAt(++ctx.p)))\n ;\n if (c = ctx.s.charCodeAt(ctx.p)) {\n if (c === 0x5a /* Z */ || c === 0x7a /* z */) {\n let t = ctx.s.slice(startPtr, ++ctx.p);\n return readDate(ctx, t, 1, unsafeSeparator, startPtr, '[+00:00]');\n }\n if (c === 0x2b /* + */ || c === 0x2d /* - */) {\n // Temporal's ZonedDateTime is weird asf when it comes to dealing with traditional offsets...\n // It's 1.2x faster to allocate a new string to pass to ZDT than use Instant.toZonedDateTimeISO\n let t = ctx.s.slice(startPtr, ctx.p += 6);\n return readDate(ctx, t, 1, unsafeSeparator, startPtr, !ctx.ld && ('[' + ctx.s.slice(ctx.p - 6, ctx.p) + ']'));\n }\n }\n let t = ctx.s.slice(startPtr, ctx.p);\n return readDate(ctx, t, 2, unsafeSeparator, startPtr);\n}\nfunction parseTime(ctx, c, endChr) {\n let start = ctx.p;\n if (!isDigit(c) || !isDigit(ctx.s.charCodeAt(++ctx.p))) {\n return parseNumber(ctx, --ctx.p, c, 0, endChr);\n }\n if (ctx.s.charCodeAt(ctx.p += 4) === 0x3a /* : */)\n ctx.p += 3;\n if (ctx.s.charCodeAt(ctx.p) === 0x2e /* . */)\n while (isDigit(ctx.s.charCodeAt(++ctx.p)))\n ;\n let t = ctx.s.slice(start, ctx.p);\n return readDate(ctx, t, 4, false, start);\n}\nfunction readDate(ctx, str, type, unsafeDelim, errPtr, temporalSuffix) {\n if (ctx.ld) {\n let date = new TomlDate(str, type, unsafeDelim);\n if (!date.isValid())\n TomlError.x('invalid date', ctx, errPtr);\n return date;\n }\n try {\n if (temporalSuffix)\n str += temporalSuffix;\n switch (type) {\n case 1: return Temporal.ZonedDateTime.from(str);\n case 2: return Temporal.PlainDateTime.from(str);\n case 3: return Temporal.PlainDate.from(str);\n case 4: return Temporal.PlainTime.from(str);\n }\n }\n catch (e) {\n TomlError.x(e instanceof Error ? e.message : '' + e, ctx, errPtr);\n }\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { TomlError } from './error.js';\n/** @internal */\nexport function skipComment(ctx) {\n for (; ctx.p < ctx.s.length; ctx.p++) {\n let c = ctx.s.charCodeAt(ctx.p);\n if (c === 0xa /* \\n */)\n break;\n if (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */) {\n ctx.p++;\n break;\n }\n if ((c < 0x20 && c !== 0x9 /* \\t */) || c === 0x7f) {\n TomlError.x('control characters are not allowed in comments', ctx);\n }\n }\n}\n/** @internal */\nexport function skipVoid(ctx, banNewLines, banComments) {\n let c;\n while (ctx.p < ctx.s.length) {\n while (ctx.p < ctx.s.length && ((c = ctx.s.charCodeAt(ctx.p)) === 0x20 ||\n c === 0x9 /* \\t */ ||\n (!banNewLines &&\n (c === 0xa /* \\n */ || (c === 0xd /* \\r */ && ctx.s.charCodeAt(ctx.p + 1) === 0xa /* \\n */)))))\n ctx.p++;\n if (banComments || c !== 0x23 /* # */)\n break;\n skipComment(ctx);\n }\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseString } from './primitive.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\n/** @internal */\nexport function parseKey(ctx, end = 0x3d /* = */) {\n // States:\n // 0: before first char\n // 1: parsing bare key\n // 2: after key component\n let startPtr;\n let state = 0;\n let parsed = [];\n let sliceStart;\n let c = ctx.s.charCodeAt(startPtr = ctx.p);\n do {\n // End of key\n if (c === end) {\n if (!state)\n TomlError.x('unexpected end of key', ctx);\n if (state === 1)\n parsed.push(ctx.s.slice(sliceStart, ctx.p));\n return ctx.p++, parsed;\n }\n // Dotted key separator\n else if (c === 0x2e /* . */) {\n if (!state)\n TomlError.x('illegal empty bare key', ctx);\n if (state === 1)\n parsed.push(ctx.s.slice(sliceStart, ctx.p));\n state = 0;\n }\n // Quoted key\n else if (!state && (c === 0x22 /* \" */ || c === 0x27 /* ' */)) {\n if (c === ctx.s.charCodeAt(ctx.p + 1) && c === ctx.s.charCodeAt(ctx.p + 2))\n TomlError.x('illegal quoted key: multiline strings are not allowed', ctx);\n parsed.push(parseString(ctx));\n state = 2;\n ctx.p--;\n }\n // Whitespace; no-op in state 0 and 2, end of bare key in state 1\n else if (c === 0x20 || c === 0x9 /* \\t */) {\n if (state === 1) {\n parsed.push(ctx.s.slice(sliceStart, ctx.p));\n state = 2;\n }\n }\n // If state is post-key, no character is allowed; otherwise ensure it's a bare-key component\n else if (state === 2 || (c < 0x30 && c !== 0x2d /* - */) || (c > 0x39 && c < 0x41) || (c > 0x5a && c < 0x61 && c !== 0x5f /* _ */) || c > 0x7a) {\n TomlError.x('illegal character in key', ctx);\n }\n // Illegal character\n else if (!state) {\n state = 1;\n sliceStart = ctx.p;\n }\n } while (c = ctx.s.charCodeAt(++ctx.p));\n TomlError.x('incomplete key-value: cannot find end of key', ctx, startPtr);\n}\n/** @internal */\nexport function parseInlineTable(ctx) {\n let startPtr = ctx.p++;\n let res = Object.create(null);\n let seen = new Set();\n let c;\n while (ctx.p < ctx.s.length) {\n skipVoid(ctx);\n if ((c = ctx.s.charCodeAt(ctx.p)) === 0x7d /* } */) {\n ctx.p++;\n return res;\n }\n let k;\n let t = res;\n let hasOwn = false;\n let errPtr = ctx.p;\n let key = parseKey(ctx);\n for (let i = 0; i < key.length; i++) {\n if (i)\n t = hasOwn ? t[k] : (t[k] = Object.create(null));\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && (typeof t[k] !== 'object' || seen.has(t[k]))) {\n TomlError.x('trying to redefine an already defined value', ctx, errPtr);\n }\n let unsafe = k === '__proto__';\n if (ctx.uk && (unsafe || k === 'constructor')) {\n t = ctx.uk !== 1 && TomlError.x('document contains an unsafe property', ctx, errPtr);\n break;\n }\n if (!hasOwn && unsafe) {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n }\n }\n if (hasOwn) {\n TomlError.x('trying to redefine an already defined value', ctx, errPtr);\n }\n skipVoid(ctx, true, true);\n let value = extractValue(ctx, 0x7d /* } */);\n if (t && typeof (t[k] = value) === 'object')\n seen.add(value);\n skipVoid(ctx);\n if ((c = ctx.s.charCodeAt(ctx.p++)) === 0x7d /* } */) {\n return res;\n }\n if (c !== 0x2c /* , */)\n TomlError.x('expected comma or end of structure', ctx, ctx.p - 1);\n }\n TomlError.x('unfinished table', ctx, startPtr);\n}\n/** @internal */\nexport function parseArray(ctx) {\n let startPtr = ctx.p++;\n let res = [];\n let c;\n while (ctx.p < ctx.s.length) {\n skipVoid(ctx);\n if ((c = ctx.s.charCodeAt(ctx.p)) === 0x5d /* ] */) {\n ctx.p++;\n return res;\n }\n res.push(extractValue(ctx, 0x5d /* ] */));\n skipVoid(ctx);\n if ((c = ctx.s.charCodeAt(ctx.p++)) === 0x5d /* ] */) {\n return res;\n }\n if (c !== 0x2c /* , */)\n TomlError.x('expected comma or end of structure', ctx, ctx.p - 1);\n }\n TomlError.x('unfinished array', ctx, startPtr);\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nimport { parseKey } from './struct.js';\nimport { extractValue } from './extract.js';\nimport { skipVoid } from './util.js';\nimport { TomlError } from './error.js';\nfunction peekTable(ctx, key, table, meta, type) {\n let t = table;\n let m = meta;\n let k;\n let hasOwn = false;\n let state;\n for (let i = 0; i < key.length; i++) {\n if (i) {\n t = hasOwn ? t[k] : (t[k] = Object.create(null));\n m = (state = m[k]).c;\n if (type === 0 /* Type.DOTTED */ && (state.t === 1 /* Type.EXPLICIT */ || state.t === 2 /* Type.ARRAY */)) {\n return null;\n }\n if (state.t === 2 /* Type.ARRAY */) {\n let l = t.length - 1;\n t = t[l];\n m = m[l].c;\n }\n }\n k = key[i];\n if ((hasOwn = Object.hasOwn(t, k)) && m[k]?.t === 0 /* Type.DOTTED */ && m[k]?.d) {\n return null;\n }\n if (!hasOwn) {\n let unsafe = k === '__proto__';\n if (ctx.uk && (unsafe || k === 'constructor'))\n return false;\n if (unsafe) {\n Object.defineProperty(t, k, { enumerable: true, configurable: true, writable: true });\n Object.defineProperty(m, k, { enumerable: true, configurable: true, writable: true });\n }\n m[k] = {\n t: i < key.length - 1 && type === 2 /* Type.ARRAY */\n ? 3 /* Type.ARRAY_DOTTED */ : type,\n d: false,\n i: 0,\n c: Object.create(null),\n };\n }\n }\n state = m[k];\n if (state.t !== type && !(type === 1 /* Type.EXPLICIT */ && state.t === 3 /* Type.ARRAY_DOTTED */)) {\n // Bad key type!\n return null;\n }\n if (type === 2 /* Type.ARRAY */) {\n if (!state.d) {\n state.d = true;\n t[k] = [];\n }\n t[k].push(t = Object.create(null));\n state.c[state.i++] = (state = { t: 1 /* Type.EXPLICIT */, d: false, i: 0, c: Object.create(null) });\n }\n if (state.d) {\n // Redefining a table!\n return null;\n }\n state.d = true;\n if (type === 1 /* Type.EXPLICIT */) {\n t = hasOwn ? t[k] : (t[k] = Object.create(null));\n }\n else if (type === 0 /* Type.DOTTED */ && hasOwn) {\n return null;\n }\n return [k, t, state.c];\n}\nfunction validateTablePeek(ctx, peek, ptr) {\n if (peek === null || ctx.uk === 2)\n TomlError.x(peek === null\n ? 'trying to redefine an already defined table or value'\n : 'document contains an unsafe property', ctx, ptr);\n}\nexport function parse(toml, options = {}) {\n let ctx = {\n s: toml,\n p: 0,\n d: options.maxDepth ?? 1000,\n bi: options.integersAsBigInt ?? false,\n ld: options.useLegacyDate ?? true,\n uk: options.unsafeKeyBehaviour === 'throw' ? 2 : options.unsafeKeyBehaviour === 'drop' ? 1 : 0,\n };\n let res = Object.create(null);\n let meta = Object.create(null);\n let tmp;\n let skipping = false;\n let tbl = res;\n let m = meta;\n // BOM is allowed, skip.\n // JS is UTF-16, so we have to check for the UTF-16 BOM instead of the UTF-8 BOM sequence!\n if (toml.charCodeAt(0) === 0xfeff)\n ctx.p++;\n skipVoid(ctx);\n while (ctx.p < toml.length) {\n if (toml.charCodeAt(ctx.p) === 0x5b /* [ */) {\n let isTableArray = toml.charCodeAt(++ctx.p) === 0x5b; /* [ */\n tmp = ctx.p += +isTableArray;\n skipping = false;\n let k = parseKey(ctx, 0x5d /* ] */);\n if (isTableArray) {\n if (toml.charCodeAt(ctx.p) !== 0x5d /* ] */) {\n TomlError.x('expected end of table array declaration', ctx);\n }\n ctx.p++;\n }\n let p = peekTable(ctx, k, res, meta, isTableArray ? 2 /* Type.ARRAY */ : 1 /* Type.EXPLICIT */);\n if (!p) {\n validateTablePeek(ctx, p, tmp);\n skipping = true;\n }\n else {\n m = p[2];\n tbl = p[1];\n }\n }\n else {\n tmp = ctx.p;\n let k = parseKey(ctx);\n let p = peekTable(ctx, k, tbl, m, 0 /* Type.DOTTED */);\n if (!p && !skipping)\n validateTablePeek(ctx, p, tmp);\n skipVoid(ctx, true, true);\n let v = extractValue(ctx, void 0);\n if (p && !skipping)\n p[1][p[0]] = v;\n }\n skipVoid(ctx, true);\n if (ctx.p < toml.length && (tmp = toml.charCodeAt(ctx.p)) !== 0xa /* \\n */ && (tmp !== 0xd /* \\r */ || toml.charCodeAt(ctx.p + 1) !== 0xa /* \\n */)) {\n TomlError.x('each key-value declaration must be followed by an end-of-line', ctx);\n }\n skipVoid(ctx);\n }\n return res;\n}\n", "/*!\n * Copyright (c) Squirrel Chat et al., All rights reserved.\n * SPDX-License-Identifier: BSD-3-Clause\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the names of its contributors\n * may be used to endorse or promote products derived from this software without\n * specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\nlet BARE_KEY = /^[a-z0-9-_]+$/i;\nlet HAS_WELLFORMED = !!(''.isWellFormed);\nfunction extendedTypeOf(obj) {\n let type = typeof obj;\n if (type === 'object') {\n if (Array.isArray(obj))\n return 'array';\n if (typeof obj.getUTCDate === 'function' && obj instanceof Date)\n return 'date';\n if (globalThis.Temporal) {\n if (obj.until) {\n if (obj instanceof Temporal.ZonedDateTime)\n return 'temporal/tz+uc';\n if (obj instanceof Temporal.PlainDateTime || obj instanceof Temporal.PlainDate)\n return 'temporal/uc';\n if (obj instanceof Temporal.PlainTime || obj instanceof Temporal.Instant)\n return 'temporal';\n if (obj instanceof Temporal.PlainYearMonth)\n return 'temporal/x';\n }\n else if ((obj.toPlainDate && obj instanceof Temporal.PlainMonthDay) ||\n (obj.negated && obj instanceof Temporal.Duration)) {\n return 'temporal/x';\n }\n }\n }\n return type;\n}\nfunction isArrayOfTables(obj) {\n for (let i = 0; i < obj.length; i++) {\n if (extendedTypeOf(obj[i]) !== 'object')\n return false;\n }\n return obj.length != 0;\n}\nfunction formatWellFormedStringUnchecked(s) {\n return JSON.stringify(s).replaceAll('\\x7f', '\\\\u007f');\n}\nfunction formatString(s) {\n return formatWellFormedStringUnchecked(HAS_WELLFORMED ? s.toWellFormed() : s);\n}\nfunction formatKey(s) {\n if (BARE_KEY.test(s))\n return s;\n if (HAS_WELLFORMED && !s.isWellFormed())\n throw new RangeError('key contains illegal lone surrogates');\n return formatWellFormedStringUnchecked(s);\n}\nfunction stringifyValue(val, type, depth, numberAsFloat, strictTemporal) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n switch (type) {\n // @ts-expect-error -- intentional fallthrough case\n case 'number':\n if (isNaN(val))\n return 'nan';\n if (val === Infinity)\n return 'inf';\n if (val === -Infinity)\n return '-inf';\n if (Number.isInteger(val) && (numberAsFloat || !Number.isSafeInteger(val)))\n return val.toFixed(1);\n case 'bigint':\n case 'boolean':\n case 'temporal':\n return val.toString();\n case 'string':\n return formatString(val);\n case 'date':\n if (isNaN(val.getTime()))\n throw new TypeError('cannot serialize invalid date');\n return val.toISOString();\n case 'object':\n return stringifyInlineTable(val, depth, numberAsFloat, strictTemporal);\n case 'array':\n return stringifyArray(val, depth, numberAsFloat, strictTemporal);\n // @ts-expect-error -- intentional fallthrough case\n case 'temporal/tz+uc':\n if (strictTemporal) {\n let tz = val.timeZoneId;\n let tzc = tz.charCodeAt(0);\n if (\n // Classic offset\n tzc !== 0x2b /* + */ && tzc !== 0x2d /* - */ &&\n (\n // Fast pre-check pass; see below for the actually accepted values\n (tzc !== 0x55 /* U */ && tzc !== 0x47 /* G */ && tzc !== 0x5a /* Z */ && tzc !== 0x45 /* E */) ||\n (\n // UTC and its aliases; Temporal implementations don't all canonicalise unfortunately\n tz !== 'UTC' && tz !== 'UCT' && tz !== 'Universal' && tz !== 'Zulu' &&\n // GMT is a TZ but it's for all intents and purposes equivalent to UTC. Safe to downgrade.\n !tz.startsWith('GMT') && tz !== 'Greenwich' &&\n // Etc/* are all safe to downgrade to offset (either UTC, GMT, or offset)\n !tz.startsWith('Etc/')))) {\n throw new TypeError('Temporal objects with an IANA timezone are not allowed in Temporal strict mode');\n }\n }\n case 'temporal/uc':\n if (strictTemporal && val.calendarId !== 'iso8601')\n throw new TypeError('Temporal objects with a non-default calendar are not allowed in Temporal strict mode');\n return val.toString({\n calendarName: 'never',\n timeZoneName: 'never',\n });\n case 'temporal/x':\n throw new TypeError('Unsupported ' + val[Symbol.toStringTag]);\n }\n}\nfunction stringifyInlineTable(obj, depth, numberAsFloat, strictTemporal) {\n let keys = Object.keys(obj);\n if (keys.length === 0)\n return '{}';\n let res = '{ ';\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n if (i)\n res += ', ';\n res += formatKey(k) + ' = ' + stringifyValue(obj[k], extendedTypeOf(obj[k]), depth - 1, numberAsFloat, strictTemporal);\n }\n return res + ' }';\n}\nfunction stringifyArray(array, depth, numberAsFloat, strictTemporal) {\n if (array.length === 0)\n return '[]';\n let res = '[ ';\n for (let i = 0; i < array.length; i++) {\n if (i)\n res += ', ';\n if (array[i] === null || array[i] === void 0) {\n throw new TypeError('arrays cannot contain null or undefined values');\n }\n res += stringifyValue(array[i], extendedTypeOf(array[i]), depth - 1, numberAsFloat, strictTemporal);\n }\n return res + ' ]';\n}\nfunction stringifyArrayTable(array, key, depth, numberAsFloat, strictTemporal) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n let res = '';\n for (let i = 0; i < array.length; i++) {\n res += `${res && '\\n'}[[${key}]]\\n`;\n res += stringifyTable(0, array[i], key, depth, numberAsFloat, strictTemporal);\n }\n return res;\n}\nfunction stringifyTable(tableKey, obj, prefix, depth, numberAsFloat, strictTemporal) {\n if (depth === 0) {\n throw new Error('Could not stringify the object: maximum object depth exceeded');\n }\n let preamble = '';\n let tables = '';\n let keys = Object.keys(obj);\n for (let i = 0; i < keys.length; i++) {\n let k = keys[i];\n if (obj[k] !== null && obj[k] !== void 0) {\n let type = extendedTypeOf(obj[k]);\n if (type === 'symbol' || type === 'function') {\n throw new TypeError(`cannot serialize values of type '${type}'`);\n }\n let key = formatKey(k);\n if (type === 'array' && isArrayOfTables(obj[k])) {\n tables += (tables && '\\n') + stringifyArrayTable(obj[k], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat, strictTemporal);\n }\n else if (type === 'object') {\n let tblKey = prefix ? `${prefix}.${key}` : key;\n tables += (tables && '\\n') + stringifyTable(tblKey, obj[k], tblKey, depth - 1, numberAsFloat, strictTemporal);\n }\n else {\n preamble += key;\n preamble += ' = ';\n preamble += stringifyValue(obj[k], type, depth, numberAsFloat, strictTemporal);\n preamble += '\\n';\n }\n }\n }\n if (tableKey && (preamble || !tables)) // Create table only if necessary\n preamble = preamble ? `[${tableKey}]\\n${preamble}` : `[${tableKey}]`;\n return preamble && tables\n ? `${preamble}\\n${tables}`\n : preamble || tables;\n}\nexport function stringify(obj, { maxDepth = 1000, numbersAsFloat = false, strictTemporal = false } = {}) {\n if (extendedTypeOf(obj) !== 'object') {\n throw new TypeError('stringify can only be called with an object');\n }\n let str = stringifyTable(0, obj, '', maxDepth, numbersAsFloat, strictTemporal);\n if (str[str.length - 1] !== '\\n')\n return str + '\\n';\n return str;\n}\n", "// Non-blocking auto-update check against an npm-compatible registry. Best-effort: any\n// failure (offline, registry down, parse error) is swallowed \u2014 it must never\n// disrupt a real command. Brand-neutral; the branded layer supplies the package\n// name, registry URL, current version, and cache path.\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst CHECK_INTERVAL_MS = 86_400_000; // 24h\nconst FETCH_TIMEOUT_MS = 2_000;\n\nexport interface UpdateCheckOptions {\n /** npm package name, e.g. \"ente-cli\". */\n packageName: string;\n /** npm-compatible registry base, e.g. \"https://registry.npmjs.org\". */\n registryUrl: string;\n /** Currently running version. */\n currentVersion: string;\n /** Directory for the 24h cache file. */\n cacheDir: string;\n /** Command shown to upgrade. */\n upgradeCommand: string;\n}\n\n/** Compare two `x.y.z` versions. Returns >0 if a>b, <0 if a<b, 0 if equal. */\nexport function compareSemver(a: string, b: string): number {\n const pa = a.split(\".\").map((n) => parseInt(n, 10) || 0);\n const pb = b.split(\".\").map((n) => parseInt(n, 10) || 0);\n for (let i = 0; i < 3; i++) {\n const d = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (d !== 0) return d > 0 ? 1 : -1;\n }\n return 0;\n}\n\nexport async function checkForUpdate(opts: UpdateCheckOptions): Promise<void> {\n try {\n const cacheFile = path.join(opts.cacheDir, \"update_check.json\");\n\n if (existsSync(cacheFile)) {\n const cache = JSON.parse(readFileSync(cacheFile, \"utf8\")) as {\n last_check?: number;\n latest?: string;\n };\n if (cache.last_check && Date.now() - cache.last_check < CHECK_INTERVAL_MS) {\n if (cache.latest && compareSemver(cache.latest, opts.currentVersion) > 0) {\n warn(opts, cache.latest);\n }\n return;\n }\n }\n\n const latest = await fetchLatest(opts);\n if (!latest) return;\n\n mkdirSync(opts.cacheDir, { recursive: true });\n writeFileSync(cacheFile, JSON.stringify({ last_check: Date.now(), latest }));\n\n if (compareSemver(latest, opts.currentVersion) > 0) warn(opts, latest);\n } catch {\n // best-effort: never disrupt a command\n }\n}\n\nasync function fetchLatest(opts: UpdateCheckOptions): Promise<string | null> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n try {\n const resp = await fetch(`${opts.registryUrl.replace(/\\/+$/, \"\")}/${opts.packageName}`, {\n headers: { Accept: \"application/json\" },\n signal: controller.signal,\n });\n if (!resp.ok) return null;\n const meta = (await resp.json()) as {\n \"dist-tags\"?: { latest?: string };\n versions?: Record<string, unknown>;\n };\n const tagged = meta[\"dist-tags\"]?.latest;\n if (tagged) return tagged;\n const versions = Object.keys(meta.versions ?? {});\n if (versions.length === 0) return null;\n return versions.sort(compareSemver).at(-1) ?? null;\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction warn(opts: UpdateCheckOptions, latest: string): void {\n process.stderr.write(\n `[${opts.packageName}] Update available: ${opts.currentVersion} \u2192 ${latest}. ` +\n `Run: ${opts.upgradeCommand}\\n`,\n );\n}\n", "// Single source of truth for the running version. The publish workflow bumps\n// this literal (and package.json) on every release \u2014 keep it a plain string so a\n// `sed` can rewrite it.\nexport const VERSION = \"0.4.53\";\n", "// ente brand constants. The one place that names the app, its config file, env\n// vars, web UI, and the public npm registry. core/ stays brand-neutral by taking\n// these as parameters; ente/ supplies this object.\n\nimport type { ConfigBranding } from \"../core/config.ts\";\nimport { VERSION } from \"./version.ts\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org\";\n\nexport interface EnteBranding extends ConfigBranding {\n /** Binary / display name. */\n name: string;\n /** Published npm package name. */\n packageName: string;\n /** npm registry base (no trailing slash). */\n registryUrl: string;\n /** Current running version. */\n version: string;\n /** Upgrade command shown by the update check. */\n upgradeCommand: string;\n /** Web UI base for human \"open in browser\" hints. */\n webUiBase: string;\n}\n\nexport const ENTE_BRANDING: EnteBranding = {\n name: \"ente\",\n appName: \"ente\",\n configFileName: \"config.toml\",\n urlEnvVar: \"ENTE_API_URL\",\n keyEnvVar: \"ENTE_API_KEY\",\n profileEnvVar: \"ENTE_PROFILE\",\n packageName: \"ente-cli\",\n registryUrl: NPM_REGISTRY,\n version: VERSION,\n upgradeCommand: \"npm i -g ente-cli --registry https://registry.npmjs.org\",\n // TODO: derive from config once the API advertises its corresponding web URL.\n webUiBase: \"https://ente.fast\",\n};\n", "// Auto-install the ente-cli skill for supported agent apps (Claude Code, Codex).\n// Ports skills/__init__.ensure_skill_installed. Best-effort: any failure is\n// swallowed so it never disrupts a command.\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport os from \"node:os\";\nimport path from \"node:path\";\n\nfunction readSkillSource(): string | null {\n const candidates = [\n path.join(import.meta.dirname, \"SKILL.md\"), // next to the bundle (dist/)\n path.join(import.meta.dirname, \"..\", \"skills\", \"ente-cli\", \"SKILL.md\"), // dev (tsx)\n ];\n for (const c of candidates) {\n if (existsSync(c)) {\n try {\n return readFileSync(c, \"utf8\");\n } catch {\n return null;\n }\n }\n }\n return null;\n}\n\n/**\n * Force the frontmatter to match the target app's skill-loading behaviour.\n *\n * The name is rewritten to the target's spelling, and `disable-model-invocation`\n * is stripped wherever it appears: it removes the description from the model's\n * context entirely, so the skill could never be chosen automatically. Stripping\n * (rather than never adding) also repairs a copy installed by an older release.\n */\nfunction enforcePolicy(content: string, skillName: string): string {\n const nameLine = `name: ${skillName}`;\n\n if (content.startsWith(\"---\\n\")) {\n const end = content.indexOf(\"\\n---\", 4);\n if (end > 0) {\n const frontmatterLines = content.slice(4, end).split(\"\\n\");\n const body = content.slice(end);\n const kept = frontmatterLines.filter(\n (l) => !l.startsWith(\"name:\") && !l.startsWith(\"disable-model-invocation:\"),\n );\n return `---\\n${[nameLine, ...kept].join(\"\\n\")}${body}`;\n }\n }\n return `---\\n${nameLine}\\n---\\n\\n${content}`;\n}\n\nconst md5 = (s: string) => createHash(\"md5\").update(s).digest(\"hex\");\n\nexport function ensureSkillInstalled(): void {\n try {\n const src = readSkillSource();\n if (!src) return;\n\n const home = os.homedir();\n const targets = [\n {\n // `m:` marks the file as owned by this package: it is rewritten from the\n // bundle on every CLI run, so edits belong in cli/skills/, not in\n // ~/.claude. (`c:` is reserved for skills the user writes there himself.)\n appDir: path.join(home, \".claude\"),\n dst: path.join(home, \".claude\", \"skills\", \"ente-cli\", \"SKILL.md\"),\n skillName: \"m:ente-cli\",\n },\n {\n appDir: path.join(home, \".codex\"),\n dst: path.join(home, \".codex\", \"skills\", \"ente-cli\", \"SKILL.md\"),\n skillName: \"ente-cli\",\n },\n ];\n\n for (const t of targets) {\n if (!existsSync(t.appDir)) continue;\n const rendered = enforcePolicy(src, t.skillName);\n if (existsSync(t.dst)) {\n try {\n if (md5(readFileSync(t.dst, \"utf8\")) === md5(rendered)) continue;\n } catch {\n // fall through to rewrite\n }\n }\n mkdirSync(path.dirname(t.dst), { recursive: true });\n writeFileSync(t.dst, rendered);\n }\n } catch {\n // best-effort\n }\n}\n", "// On-disk cache for the short-lived CLI JWT, so consecutive invocations within\n// the token's TTL skip the /cli/token round-trip. One file per (app, deployment)\n// under the app's config dir, mode 0600. Brand-neutral \u2014 caller supplies the\n// cache dir + key. Never throws on read: a bad cache just forces a re-exchange.\n\nimport { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\n\nconst SKEW_MS = 60_000; // treat as expired 60s early to avoid edge-of-expiry races\n\ninterface CacheEntry {\n jwt: string;\n expiresAt: number; // ms epoch\n}\n\n/** Sanitize an arbitrary cache key (e.g. a deployment host) into a filename. */\nfunction keyToFile(cacheDir: string, key: string): string {\n const safe = key.replace(/[^a-zA-Z0-9._-]/g, \"_\");\n return path.join(cacheDir, `jwt-${safe}.json`);\n}\n\n/** Returns the cached JWT if still valid (with skew), else null. Never throws. */\nexport function loadJwt(cacheDir: string, key: string): string | null {\n try {\n const file = keyToFile(cacheDir, key);\n if (!existsSync(file)) return null;\n const entry = JSON.parse(readFileSync(file, \"utf8\")) as CacheEntry;\n if (typeof entry.jwt !== \"string\" || typeof entry.expiresAt !== \"number\") return null;\n return entry.expiresAt - SKEW_MS > Date.now() ? entry.jwt : null;\n } catch {\n return null;\n }\n}\n\nexport function storeJwt(cacheDir: string, key: string, jwt: string, expiresAt: number): void {\n const file = keyToFile(cacheDir, key);\n mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n writeFileSync(file, JSON.stringify({ jwt, expiresAt } satisfies CacheEntry), \"utf8\");\n chmodSync(file, 0o600);\n}\n\n/** Remove one key-specific cached JWT. Returns true when a cache existed. */\nexport function deleteJwt(cacheDir: string, key: string): boolean {\n const file = keyToFile(cacheDir, key);\n if (!existsSync(file)) return false;\n rmSync(file);\n return true;\n}\n", "// HTTP error from a REST backend, carrying status code and the parsed structured\n// `error` object (codes like `space_entity_mismatch`, fields like\n// `invalidEntities`). Brand-neutral \u2014 branded layers narrow `.error` to their\n// own shapes. Mirrors the Python `ApiError` so command-level catch logic ports\n// 1:1.\n\nexport type StructuredError = Record<string, unknown>;\n\nexport class ApiError extends Error {\n readonly statusCode: number;\n readonly error: StructuredError;\n\n constructor(statusCode: number, message: string, error?: StructuredError) {\n super(`HTTP ${statusCode}: ${message}`);\n this.name = \"ApiError\";\n this.statusCode = statusCode;\n // `message` (without the HTTP prefix) is what command-level surfacing prints.\n this.detail = message;\n this.error = error ?? {};\n }\n\n /** The backend's human message, without the `HTTP <code>:` prefix. */\n readonly detail: string;\n}\n\n/**\n * A control-flow signal that a command has already printed everything the user\n * needs and just wants to exit with a specific code (e.g. partial-success\n * exit 2). The base command turns it into the return code without printing an\n * `Error:` line. Brand-neutral.\n */\nexport class ExitWithCode extends Error {\n readonly code: number;\n constructor(code: number) {\n super(`exit ${code}`);\n this.name = \"ExitWithCode\";\n this.code = code;\n }\n}\n", "// Output convention shared by every command: `--json` prints the raw value;\n// otherwise a caller-supplied rows-fn renders a plain-text table. One helper so\n// adding a command never re-invents formatting. Brand-neutral.\n\nimport type { Writable } from \"node:stream\";\n\nexport type Row = Record<string, string>;\nexport type RowsFn<T> = (data: T) => Row[];\n\nexport function emit<T>(\n stdout: Writable,\n data: T,\n json: boolean,\n rowsFn?: RowsFn<T>,\n headers?: readonly string[],\n): void {\n if (json || !rowsFn) {\n stdout.write(`${JSON.stringify(data, null, 2)}\\n`);\n return;\n }\n stdout.write(`${renderTable(rowsFn(data), headers)}\\n`);\n}\n\n/**\n * Human message for a thrown value. A Convex function that throws a\n * `ConvexError` arrives as an Error whose `message` is redacted to\n * \"Server Error\" on production deployments, while the structured payload\n * survives in `.data` \u2014 so that payload is the message to show.\n */\nexport function errorMessage(err: unknown): string {\n if (!(err instanceof Error)) return String(err);\n const data = (err as { data?: unknown }).data;\n if (typeof data === \"string\" && data.length > 0) return data;\n if (data && typeof data === \"object\") {\n const { message, code } = data as { message?: unknown; code?: unknown };\n if (typeof message === \"string\" && message.length > 0) {\n return typeof code === \"string\" ? `${message} (${code})` : message;\n }\n return `${err.message}: ${JSON.stringify(data)}`;\n }\n return err.message;\n}\n\nfunction renderTable(rows: Row[], headers?: readonly string[]): string {\n if (rows.length === 0) return \"(none)\";\n const cols = headers ?? Object.keys(rows[0] ?? {});\n const widths = cols.map((c) => Math.max(c.length, ...rows.map((r) => (r[c] ?? \"\").length)));\n const line = (cells: readonly string[]) =>\n cells.map((cell, i) => cell.padEnd(widths[i] ?? 0)).join(\" \").trimEnd();\n const out = [line(cols), line(cols.map((_, i) => \"\u2500\".repeat(widths[i] ?? 0)))];\n for (const r of rows) out.push(line(cols.map((c) => r[c] ?? \"\")));\n return out.join(\"\\n\");\n}\n", "// clipanion base class. BaseCommand carries the shared `--json` flag, the two\n// output conventions (table via `print`, bespoke text via `emitText`), and the\n// uniform error boundary (a template `run()` that the concrete `execute()`\n// wraps \u2014 the equivalent of the Python `@handle_errors` decorator). Brand-\n// neutral: it knows nothing about ente, auth, or the backend. Client-bearing\n// commands extend the branded ClientCommand (ente/command.ts).\n\nimport { Command, Option } from \"clipanion\";\n\nimport { ExitWithCode } from \"./errors.ts\";\nimport { emit, errorMessage, type RowsFn } from \"./output.ts\";\n\nexport abstract class BaseCommand extends Command {\n json = Option.Boolean(\"--json\", false, {\n description: \"Print raw JSON instead of formatted output\",\n });\n\n /** Render `data` as JSON (when --json) or via the rows-fn as a table. */\n protected print<T>(data: T, rowsFn?: RowsFn<T>, headers?: readonly string[]): void {\n emit(this.context.stdout, data, this.json, rowsFn, headers);\n }\n\n /** `--json` \u2192 raw `jsonData`; otherwise the string returned by `render()`. */\n protected emitText(jsonData: unknown, render: () => string): void {\n if (this.json) {\n this.context.stdout.write(`${JSON.stringify(jsonData, null, 2)}\\n`);\n return;\n }\n const text = render();\n if (text) this.context.stdout.write(`${text}\\n`);\n }\n\n protected out(line: string): void {\n this.context.stdout.write(`${line}\\n`);\n }\n\n protected err(line: string): void {\n this.context.stderr.write(`${line}\\n`);\n }\n\n /** Command body. Return a non-zero number to set the exit code. */\n abstract run(): Promise<number | void>;\n\n // Template method: every command gets the same error boundary. A thrown\n // ExitWithCode is an already-reported exit (no `Error:` line); anything else\n // is surfaced as `Error: <message>` on stderr with exit 1.\n async execute(): Promise<number> {\n try {\n const code = await this.run();\n return typeof code === \"number\" ? code : 0;\n } catch (err) {\n if (err instanceof ExitWithCode) return err.code;\n this.context.stderr.write(`Error: ${errorMessage(err)}\\n`);\n return 1;\n }\n }\n}\n", "// Parse `key=value` attribute pairs. Ports utils.parse_attrs.\n\nexport function parseAttrs(pairs?: string[]): Record<string, string> {\n const result: Record<string, string> = {};\n if (!pairs) return result;\n for (const pair of pairs) {\n const eq = pair.indexOf(\"=\");\n if (eq === -1) throw new Error(`Invalid attribute format: '${pair}'. Use key=value.`);\n result[pair.slice(0, eq)] = pair.slice(eq + 1);\n }\n return result;\n}\n", "// Generic typed REST client over fetch. Brand-neutral: it knows about Bearer\n// auth, query params, JSON bodies, timeouts and structured-error parsing, but\n// nothing about ente endpoints. The branded EnteClient (ente/client.ts) builds\n// one of these and wraps the `/api/external/*` routes.\n//\n// (Plexus uses a ConvexHttpClient + function refs here; ente's backend is a\n// REST surface with a static api-key, so this is the faithful transport.)\n\nimport { ApiError, type StructuredError } from \"./errors.ts\";\n\nexport type QueryParams = Record<string, string | undefined>;\n\nexport interface RestClientOptions {\n baseUrl: string;\n apiKey: string;\n timeoutMs?: number;\n}\n\n/** Per-call overrides (e.g. a longer timeout for AI synthesis or large uploads). */\nexport interface RequestOverrides {\n timeoutMs?: number;\n headers?: Readonly<Record<string, string>>;\n}\n\nexport class RestClient {\n private readonly baseUrl: string;\n private readonly apiKey: string;\n private readonly timeoutMs: number;\n\n constructor(opts: RestClientOptions) {\n // Strip trailing slash and a trailing `/api/external` if the user pasted it.\n let base = opts.baseUrl.replace(/\\/+$/, \"\");\n if (base.endsWith(\"/api/external\")) base = base.slice(0, -\"/api/external\".length);\n this.baseUrl = base;\n this.apiKey = opts.apiKey;\n this.timeoutMs = opts.timeoutMs ?? 15_000;\n }\n\n get<T = unknown>(path: string, params?: QueryParams, opts?: RequestOverrides): Promise<T> {\n return this.request<T>(\"GET\", path, undefined, params, opts);\n }\n post<T = unknown>(path: string, body?: unknown, params?: QueryParams, opts?: RequestOverrides): Promise<T> {\n return this.request<T>(\"POST\", path, body, params, opts);\n }\n patch<T = unknown>(path: string, body?: unknown, params?: QueryParams, opts?: RequestOverrides): Promise<T> {\n return this.request<T>(\"PATCH\", path, body, params, opts);\n }\n put<T = unknown>(path: string, body?: unknown, params?: QueryParams, opts?: RequestOverrides): Promise<T> {\n return this.request<T>(\"PUT\", path, body, params, opts);\n }\n delete<T = unknown>(path: string, params?: QueryParams, opts?: RequestOverrides): Promise<T> {\n return this.request<T>(\"DELETE\", path, undefined, params, opts);\n }\n\n /**\n * POST raw bytes with an explicit Content-Type (not JSON). Used for binary\n * uploads where the request body is the file itself, not a JSON envelope.\n */\n postRaw<T = unknown>(\n path: string,\n bytes: Uint8Array,\n contentType: string,\n params?: QueryParams,\n opts?: RequestOverrides,\n ): Promise<T> {\n return this.request<T>(\"POST\", path, undefined, params, opts, { bytes, contentType });\n }\n\n private buildUrl(path: string, params?: QueryParams): string {\n const url = new URL(this.baseUrl + path);\n if (params) {\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined) url.searchParams.set(k, v);\n }\n }\n return url.toString();\n }\n\n private async request<T>(\n method: string,\n path: string,\n body: unknown,\n params?: QueryParams,\n opts?: RequestOverrides,\n raw?: { bytes: Uint8Array; contentType: string },\n ): Promise<T> {\n const timeoutMs = opts?.timeoutMs ?? this.timeoutMs;\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let resp: Response;\n try {\n resp = await fetch(this.buildUrl(path, params), {\n method,\n headers: {\n Authorization: `Bearer ${this.apiKey}`,\n \"Content-Type\": raw ? raw.contentType : \"application/json\",\n ...opts?.headers,\n },\n body: raw\n ? // Node's Buffer is Uint8Array<ArrayBufferLike>; the DOM BlobPart type\n // wants ArrayBufferView<ArrayBuffer>. The bytes are valid at runtime,\n // so assert past the lib-level typed-array mismatch.\n new Blob([raw.bytes as BlobPart], { type: raw.contentType })\n : method === \"POST\" || method === \"PATCH\" || method === \"PUT\"\n ? JSON.stringify(body ?? {})\n : undefined,\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new Error(`Request to ${path} timed out after ${timeoutMs}ms.`);\n }\n throw new Error(`Could not reach the ente API (${path}): ${String(err)}`);\n }\n clearTimeout(timer);\n\n const text = await resp.text();\n if (resp.status >= 400) throw toApiError(resp.status, resp.statusText, text);\n if (!text) return null as T;\n return JSON.parse(text) as T;\n }\n}\n\nfunction toApiError(status: number, statusText: string, text: string): ApiError {\n let message = statusText || \"Unknown error\";\n let structured: StructuredError = {};\n if (text) {\n try {\n const data = JSON.parse(text) as { error?: unknown };\n const raw = data.error;\n if (raw && typeof raw === \"object\") {\n structured = raw as StructuredError;\n const m = (raw as { message?: unknown }).message;\n if (typeof m === \"string\") message = m;\n } else if (typeof raw === \"string\") {\n message = raw;\n }\n } catch {\n // non-JSON error body \u2014 keep the status text\n }\n }\n return new ApiError(status, message, structured);\n}\n", "// EnteClient \u2014 typed wrappers over the ente external REST API. The ONE place\n// that knows the `/api/external/*` routes and their request/response shapes.\n// Builds on the brand-neutral RestClient (core/transport.ts).\n\nimport { RestClient, type QueryParams } from \"../core/transport.ts\";\nimport type { ConfigBranding } from \"../core/config.ts\";\nimport { loadCredentials } from \"../core/config.ts\";\nimport type {\n ActivitiesResponse,\n ActivityResponse,\n AgendaPointCreateResponse,\n AskResponse,\n CreateActivityResponse,\n CreateEntityResponse,\n EntitiesResponse,\n EntityResponse,\n EvidenceQueryBody,\n PinResponse,\n PinsResponse,\n QueryResponse,\n NotificationEmailRequest,\n NotificationEmailAttachmentInput,\n NotificationEmailResponse,\n AgentMailboxResponse,\n AgentMailOperationResponse,\n AgentMailMarkResponse,\n AgentMailThreadResponse,\n AgentMailThreadsResponse,\n AgentConfigurationResponse,\n AgentScheduleInput,\n AgentThreadResponse,\n AgentThreadMutationResponse,\n AgentThreadClaimResponse,\n AgentThreadsResponse,\n ExternalAuthContextResponse,\n SpaceCreateResponse,\n SpaceListFullResponse,\n SpaceMembersResponse,\n SpacesMap,\n TaskByNumberResponse,\n TasksResponse,\n UploadAttachmentResponse,\n} from \"./types.ts\";\n\n/** `/ask` synthesises with an LLM \u2014 allow far longer than the default timeout. */\nconst ASK_TIMEOUT_MS = 90_000;\n/** Uploads stream file bytes \u2014 allow a generous window for large files. */\nconst UPLOAD_TIMEOUT_MS = 300_000;\n\nexport class EnteClient {\n private readonly rest: RestClient;\n\n constructor(rest: RestClient) {\n this.rest = rest;\n }\n\n /** Build a client from stored/env credentials (throws if not authenticated). */\n static fromConfig(branding: ConfigBranding): EnteClient {\n const { apiUrl, apiKey } = loadCredentials(branding);\n return new EnteClient(new RestClient({ baseUrl: apiUrl, apiKey }));\n }\n\n // --- entities -----------------------------------------------------------\n listEntities(params: QueryParams): Promise<EntitiesResponse> {\n return this.rest.get<EntitiesResponse>(\"/api/external/entities\", params);\n }\n getEntity(id: string, params?: QueryParams): Promise<EntityResponse> {\n return this.rest.get<EntityResponse>(\"/api/external/entity\", { id, ...params });\n }\n createEntity(body: unknown): Promise<CreateEntityResponse> {\n return this.rest.post<CreateEntityResponse>(\"/api/external/entities\", body);\n }\n updateEntity(id: string, body: unknown): Promise<unknown> {\n return this.rest.patch(\"/api/external/entities\", body, { id });\n }\n archiveEntity(id: string): Promise<unknown> {\n return this.rest.delete(\"/api/external/entities\", { id });\n }\n restoreEntity(id: string): Promise<unknown> {\n return this.rest.post(\"/api/external/entities/restore\", undefined, { id });\n }\n removeFromSpace(entityId: string, spaceId: string): Promise<unknown> {\n return this.rest.delete(\"/api/external/entity-spaces\", { entityId, spaceId });\n }\n\n /** Spaces map (id \u2192 {spaceName, memberEmails}) via a minimal entities call. */\n async listSpaces(): Promise<SpacesMap> {\n const res = await this.listEntities({ limit: \"1\" });\n return res.data?.spaces ?? {};\n }\n\n /** Full space list with the caller's role + member emails (GET /api/external/spaces). */\n listSpacesFull(): Promise<SpaceListFullResponse> {\n return this.rest.get<SpaceListFullResponse>(\"/api/external/spaces\");\n }\n createSpace(body: { name: string; color?: string; memberEmails?: string[] }): Promise<SpaceCreateResponse> {\n return this.rest.post<SpaceCreateResponse>(\"/api/external/spaces\", body);\n }\n renameSpace(spaceId: string, name: string): Promise<unknown> {\n return this.rest.patch(\"/api/external/spaces\", { name }, { id: spaceId });\n }\n\n // --- pins ---------------------------------------------------------------\n createPin(sourceEntityId: string, targetEntityId: string, spaceId?: string): Promise<PinResponse> {\n return this.rest.post<PinResponse>(\"/api/external/pins\", {\n sourceEntityId,\n targetEntityId,\n ...(spaceId ? { spaceId } : {}),\n });\n }\n deletePin(sourceEntityId: string, targetEntityId: string, spaceId?: string): Promise<unknown> {\n return this.rest.delete(\"/api/external/pins\", {\n sourceEntityId,\n targetEntityId,\n ...(spaceId ? { spaceId } : {}),\n });\n }\n listPins(entityId: string): Promise<PinsResponse> {\n return this.rest.get<PinsResponse>(\"/api/external/pins\", { entityId });\n }\n\n // --- activities ---------------------------------------------------------\n listActivities(params: QueryParams): Promise<ActivitiesResponse> {\n return this.rest.get<ActivitiesResponse>(\"/api/external/activities\", params);\n }\n getActivity(id: string): Promise<ActivityResponse> {\n return this.rest.get<ActivityResponse>(\"/api/external/activity\", { id });\n }\n createActivity(body: unknown): Promise<CreateActivityResponse> {\n return this.rest.post<CreateActivityResponse>(\"/api/external/activities\", body);\n }\n updateActivity(id: string, body: unknown): Promise<unknown> {\n return this.rest.patch(\"/api/external/activities\", body, { id });\n }\n deleteActivity(id: string): Promise<unknown> {\n return this.rest.delete(\"/api/external/activities\", { id });\n }\n restoreActivity(id: string): Promise<unknown> {\n return this.rest.post(\"/api/external/activities/restore\", undefined, { id });\n }\n searchActivities(params: QueryParams): Promise<ActivitiesResponse> {\n return this.rest.get<ActivitiesResponse>(\"/api/external/activities/search\", params);\n }\n\n // --- tasks --------------------------------------------------------------\n listTasks(params: QueryParams): Promise<TasksResponse> {\n return this.rest.get<TasksResponse>(\"/api/external/tasks\", params);\n }\n taskByNumber(num: number, spaceId?: string): Promise<TaskByNumberResponse> {\n return this.rest.get<TaskByNumberResponse>(\"/api/external/tasks/number\", {\n number: String(num),\n ...(spaceId ? { spaceId } : {}),\n });\n }\n\n // --- meeting agendas ---------------------------------------------------\n createAgendaPoint(body: {\n meetingActivityId: string;\n title: string;\n contentMarkdown?: string;\n parentPointId?: string;\n afterPointId?: string;\n }): Promise<AgendaPointCreateResponse> {\n return this.rest.post<AgendaPointCreateResponse>(\"/api/external/agenda-points\", body);\n }\n\n uploadAttachment(\n activityId: string,\n bytes: Uint8Array,\n name: string,\n mimeType: string,\n ): Promise<UploadAttachmentResponse> {\n return this.rest.postRaw<UploadAttachmentResponse>(\n \"/api/external/activities/upload\",\n bytes,\n mimeType,\n { id: activityId, name },\n { timeoutMs: UPLOAD_TIMEOUT_MS },\n );\n }\n\n // --- ask / query (evidence retrieval) -----------------------------------\n ask(body: EvidenceQueryBody): Promise<AskResponse> {\n return this.rest.post<AskResponse>(\"/api/external/ask\", body, undefined, {\n timeoutMs: ASK_TIMEOUT_MS,\n });\n }\n query(body: EvidenceQueryBody): Promise<QueryResponse> {\n return this.rest.post<QueryResponse>(\"/api/external/query\", body);\n }\n\n // --- notifications -----------------------------------------------------\n sendNotificationEmail(body: NotificationEmailRequest): Promise<NotificationEmailResponse> {\n return this.rest.post<NotificationEmailResponse>(\n \"/api/external/notifications/email\",\n body,\n );\n }\n\n // --- external credential context / bound agent ------------------------\n getAuthContext(): Promise<ExternalAuthContextResponse> {\n return this.rest.get<ExternalAuthContextResponse>(\"/api/external/auth-context\");\n }\n getAgentConfiguration(): Promise<AgentConfigurationResponse> {\n return this.rest.get<AgentConfigurationResponse>(\"/api/external/agent\");\n }\n updateAgentPrompt(prompt: string): Promise<AgentConfigurationResponse> {\n return this.rest.patch<AgentConfigurationResponse>(\n \"/api/external/agent\",\n { prompt },\n );\n }\n listAgentThreads(params: QueryParams): Promise<AgentThreadsResponse> {\n return this.rest.get<AgentThreadsResponse>(\"/api/external/agent/threads\", params);\n }\n getAgentThread(\n threadId: string,\n cursor?: string,\n limit?: number,\n ): Promise<AgentThreadResponse> {\n return this.rest.get<AgentThreadResponse>(\"/api/external/agent/thread\", {\n threadId,\n ...(cursor ? { cursor } : {}),\n ...(limit ? { limit: String(limit) } : {}),\n });\n }\n createAgentThread(body: {\n title?: string;\n text: string;\n html?: string;\n requestKind?: \"ack\" | \"text\";\n requestPrompt?: string;\n idempotencyKey: string;\n }): Promise<AgentThreadMutationResponse> {\n return this.rest.post<AgentThreadMutationResponse>(\"/api/external/agent/threads\", body);\n }\n claimAgentThread(threadId: string, attentionVersion: number): Promise<AgentThreadClaimResponse> {\n return this.rest.post<AgentThreadClaimResponse>(\"/api/external/agent/thread/claim\", {\n threadId,\n attentionVersion,\n });\n }\n replyAgentThread(body: {\n threadId: string;\n claimId?: string;\n text: string;\n html?: string;\n requestKind?: \"ack\" | \"text\";\n requestPrompt?: string;\n idempotencyKey: string;\n }): Promise<AgentThreadMutationResponse> {\n return this.rest.post<AgentThreadMutationResponse>(\"/api/external/agent/thread/reply\", body);\n }\n configureAgentSchedules(\n schedules: AgentScheduleInput[],\n ): Promise<AgentConfigurationResponse> {\n return this.rest.put<AgentConfigurationResponse>(\n \"/api/external/agent/schedules\",\n { schedules },\n );\n }\n\n // --- agent mail --------------------------------------------------------\n getAgentMailbox(): Promise<AgentMailboxResponse> {\n return this.rest.get<AgentMailboxResponse>(\"/api/external/agent-mailbox\");\n }\n listAgentMailThreads(params: QueryParams): Promise<AgentMailThreadsResponse> {\n return this.rest.get<AgentMailThreadsResponse>(\n \"/api/external/agent-mail/threads\",\n params,\n );\n }\n getAgentMailThread(\n threadId: string,\n cursor?: string,\n ): Promise<AgentMailThreadResponse> {\n return this.rest.get<AgentMailThreadResponse>(\n \"/api/external/agent-mail/thread\",\n { threadId, cursor },\n );\n }\n sendAgentMail(body: {\n to: string;\n subject: string;\n text: string;\n html?: string;\n attachments?: NotificationEmailAttachmentInput[];\n }, idempotencyKey: string): Promise<AgentMailOperationResponse> {\n return this.rest.post<AgentMailOperationResponse>(\n \"/api/external/agent-mail/send\",\n body,\n undefined,\n { headers: { \"Idempotency-Key\": idempotencyKey } },\n );\n }\n replyAgentMail(body: {\n threadId: string;\n replyToMessageId: string;\n text: string;\n html?: string;\n attachments?: NotificationEmailAttachmentInput[];\n }, idempotencyKey: string): Promise<AgentMailOperationResponse> {\n return this.rest.post<AgentMailOperationResponse>(\n \"/api/external/agent-mail/reply\",\n body,\n undefined,\n { headers: { \"Idempotency-Key\": idempotencyKey } },\n );\n }\n markAgentMailThread(body: {\n threadId: string;\n stateVersion: number;\n state?: \"open\" | \"needsReply\" | \"handled\";\n hasUnread?: boolean;\n }): Promise<AgentMailMarkResponse> {\n return this.rest.patch<AgentMailMarkResponse>(\n \"/api/external/agent-mail/thread\",\n body,\n );\n }\n\n // --- spaces -------------------------------------------------------------\n spaceMembers(spaceId: string): Promise<SpaceMembersResponse> {\n return this.rest.get<SpaceMembersResponse>(\"/api/external/spaces/members\", { spaceId });\n }\n}\n", "// Europe/Berlin date math + formatting, dependency-free (Intl only). Replaces\n// the Python zoneinfo usage in output.py / deadline.py. Epoch values are\n// milliseconds, matching the backend.\n\nconst TZ = \"Europe/Berlin\";\nconst MONTHS = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sep\", \"Oct\", \"Nov\", \"Dec\"];\n\ninterface Parts {\n year: number;\n month: number;\n day: number;\n hour: number;\n minute: number;\n second: number;\n}\n\nfunction berlinParts(utcMs: number): Parts {\n const dtf = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: TZ,\n hour12: false,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n });\n const parts = dtf.formatToParts(new Date(utcMs));\n const get = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);\n let hour = get(\"hour\");\n if (hour === 24) hour = 0; // some ICU builds render midnight as 24\n return { year: get(\"year\"), month: get(\"month\"), day: get(\"day\"), hour, minute: get(\"minute\"), second: get(\"second\") };\n}\n\n/** Berlin's UTC offset (ms) at a given instant. */\nfunction berlinOffsetMs(utcMs: number): number {\n const p = berlinParts(utcMs);\n const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second);\n return asUtc - utcMs;\n}\n\n/** Convert a Berlin wall-clock time to epoch ms (DST-correct). */\nexport function berlinToEpochMs(\n year: number,\n month: number,\n day: number,\n hour: number,\n minute: number,\n second = 0,\n): number {\n const naive = Date.UTC(year, month - 1, day, hour, minute, second);\n const off = berlinOffsetMs(naive);\n let ms = naive - off;\n const off2 = berlinOffsetMs(ms);\n if (off2 !== off) ms = naive - off2; // refine across a DST boundary\n return ms;\n}\n\nconst pad2 = (n: number) => String(n).padStart(2, \"0\");\n\n/** Epoch ms \u2192 \"DD.MM.YYYY\" (Berlin). Empty string for falsy input. */\nexport function formatDate(tsMs?: number | null): string {\n if (!tsMs) return \"\";\n const p = berlinParts(tsMs);\n return `${pad2(p.day)}.${pad2(p.month)}.${p.year}`;\n}\n\n/** Epoch ms \u2192 \"DD.MM.YYYY, HH:MM\" (Berlin). */\nexport function formatDatetime(tsMs?: number | null): string {\n if (!tsMs) return \"\";\n const p = berlinParts(tsMs);\n return `${pad2(p.day)}.${pad2(p.month)}.${p.year}, ${pad2(p.hour)}:${pad2(p.minute)}`;\n}\n\n/** Epoch ms \u2192 \"today\" | \"yesterday\" | \"Mar 25\" | \"Dec 2024\" (Berlin). */\nexport function formatRelativeDate(tsMs: number): string {\n const now = berlinParts(Date.now());\n const d = berlinParts(tsMs);\n const sameDay = d.year === now.year && d.month === now.month && d.day === now.day;\n if (sameDay) return \"today\";\n const yesterday = berlinParts(Date.now() - 86_400_000);\n if (d.year === yesterday.year && d.month === yesterday.month && d.day === yesterday.day) {\n return \"yesterday\";\n }\n const mon = MONTHS[d.month - 1] ?? \"\";\n if (d.year === now.year) return `${mon} ${d.day}`;\n return `${mon} ${d.year}`;\n}\n\n/** Today's Berlin calendar date as {year, month, day}. */\nexport function berlinToday(): { year: number; month: number; day: number } {\n const p = berlinParts(Date.now());\n return { year: p.year, month: p.month, day: p.day };\n}\n\n/** End of today in Berlin as epoch ms (23:59:59). */\nexport function endOfTodayBerlin(): number {\n const t = berlinToday();\n return berlinToEpochMs(t.year, t.month, t.day, 23, 59, 59);\n}\n", "// Human-readable formatting for ente shapes \u2014 tables, details, footers, colors.\n// Ports output.py (the rendering half; error handling lives in BaseCommand).\n// Branded: these read Entity/Activity/Task shapes from types.ts.\n\nimport { formatDate, formatDatetime, formatRelativeDate } from \"./datetime.ts\";\nimport type {\n Activity,\n EntityDetail,\n EntityListItem,\n PinSummary,\n SpacesMap,\n TaskItem,\n UsersMap,\n} from \"./types.ts\";\n\nconst NO_COLOR = process.env.NO_COLOR !== undefined;\n\nexport const dim = (s: string) => (NO_COLOR ? s : `\\x1b[2m${s}\\x1b[0m`);\nexport const green = (s: string) => (NO_COLOR ? s : `\\x1b[32m${s}\\x1b[0m`);\nexport const red = (s: string) => (NO_COLOR ? s : `\\x1b[31m${s}\\x1b[0m`);\nexport const bold = (s: string) => (NO_COLOR ? s : `\\x1b[1m${s}\\x1b[0m`);\n\nexport function truncate(s: string, maxLen: number): string {\n if (s.length <= maxLen) return s;\n return s.slice(0, maxLen - 1) + \"\u2026\";\n}\n\nfunction padEnd(s: string, length: number): string {\n return s + \" \".repeat(Math.max(0, length - s.length));\n}\n\n/** Merge a spaces map into a JSON payload (mirrors json_output_with_spaces). */\nexport function jsonWithSpaces(data: unknown, spaces: SpacesMap): unknown {\n if (data && typeof data === \"object\" && !Array.isArray(data)) {\n return { ...(data as Record<string, unknown>), spaces };\n }\n return { data, spaces };\n}\n\n// --- entities -------------------------------------------------------------\n\nexport function formatEntityList(entities: EntityListItem[], spaces?: SpacesMap): string {\n if (entities.length === 0) return \"No entities found.\";\n\n interface R {\n name: string;\n type: string;\n space: string;\n id: string;\n descriptionPlainText?: string;\n hiddenFromGraph?: boolean;\n aliases?: string[];\n activityCount: number;\n lastActivityAt?: number;\n openTasks: NonNullable<EntityListItem[\"openTasks\"]>;\n }\n const rows: R[] = entities.map((e) => {\n const entity = e.entity;\n const spaceIds = e.spaceIds ?? [];\n const spaceNames =\n spaces && spaceIds.length\n ? spaceIds.map((sid) => spaces[sid]?.spaceName ?? sid).join(\", \")\n : \"\";\n return {\n name: entity.displayName ?? entity.name ?? \"\",\n type: `(${entity.type ?? \"\"})`,\n space: spaceNames,\n id: entity._id ?? \"\",\n descriptionPlainText: e.descriptionPlainText,\n hiddenFromGraph: entity.hiddenFromGraph,\n aliases: entity.aliases && entity.aliases.length ? entity.aliases : undefined,\n activityCount: e.activityCount ?? 0,\n lastActivityAt: e.lastActivityAt,\n openTasks: e.openTasks ?? [],\n };\n });\n\n const nameW = Math.max(...rows.map((r) => r.name.length));\n const typeW = Math.max(...rows.map((r) => r.type.length));\n const showSpaces = !!spaces && rows.some((r) => r.space);\n const spaceW = showSpaces ? Math.max(0, ...rows.map((r) => r.space.length)) : 0;\n\n const lines: string[] = [];\n for (const r of rows) {\n let line = `${padEnd(r.name, nameW)} ${padEnd(r.type, typeW)}`;\n if (showSpaces) line += ` ${padEnd(r.space, spaceW)}`;\n line += ` ${r.id}`;\n lines.push(line);\n\n const parts: string[] = [];\n if (r.descriptionPlainText) parts.push(`description: ${truncate(r.descriptionPlainText, 120)}`);\n if (r.hiddenFromGraph) parts.push(\"hidden from graph\");\n if (r.aliases) parts.push(`aka: ${r.aliases.join(\", \")}`);\n if (r.activityCount > 0) parts.push(`${r.activityCount} activities`);\n if (r.lastActivityAt) parts.push(`last: ${formatRelativeDate(r.lastActivityAt)}`);\n if (parts.length) lines.push(` ${parts.join(\" \u00B7 \")}`);\n\n for (const t of r.openTasks) {\n const label = t.shortId ? `#${t.shortId}` : (t.activityId ?? \"\").slice(0, 10);\n lines.push(` Open: ${label} ${t.title || \"(untitled)\"}`);\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatEntityDetail(data: EntityDetail): string {\n const e = data.entity;\n const lines: string[] = [];\n lines.push(`${e.name ?? \"\"} (${e.type ?? \"\"})`);\n lines.push(`ID: ${e._id ?? \"\"}`);\n if (data.aggregationMode === \"directOnly\")\n lines.push(\"Aggregation: direct only (more than 20 active direct children)\");\n\n if (e.hiddenFromGraph) lines.push(\"Graph: hidden\");\n if (e.aliases && e.aliases.length) lines.push(`Aliases: ${e.aliases.join(\", \")}`);\n if (e.tags && e.tags.length) lines.push(`Tags: ${e.tags.join(\", \")}`);\n if (e.attributes && Object.keys(e.attributes).length) {\n for (const [k, v] of Object.entries(e.attributes)) lines.push(` ${k}: ${String(v)}`);\n }\n\n if (data.descriptionPlainText) {\n lines.push(\"\");\n lines.push(truncate(data.descriptionPlainText, 200));\n }\n\n if (data.pins && data.pins.length) {\n lines.push(\"\");\n lines.push(\"Pins:\");\n for (const p of data.pins) {\n const parentLabel = p.role ? `${p.name ?? \"\"} \u00B7 ${p.role}` : (p.name ?? \"\");\n lines.push(` ${parentLabel} (${p.type ?? \"\"})`);\n }\n }\n\n if (data.openTasks && data.openTasks.length) {\n lines.push(\"\");\n lines.push(\"Open tasks:\");\n for (const t of data.openTasks) {\n const label = t.shortId ? `#${t.shortId}` : (t.activityId ?? \"\").slice(0, 10);\n lines.push(` ${label} ${t.title || \"(untitled)\"}`);\n }\n }\n\n if (data.activities && data.activities.length) {\n lines.push(\"\");\n lines.push(\"Recent activities:\");\n for (const a of data.activities.slice(0, 10)) {\n const prefix = a.shortId ? `#${a.shortId}` : (a.type ?? \"\");\n const title = a.title || truncate(a.contentPlainText ?? \"\", 50);\n lines.push(` ${prefix} ${title} ${formatDate(a.createdAt)}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n// --- pins ------------------------------------------------------------------\n\n/** GET /api/external/pins may return an array or a `{ pins: [...] }` envelope. */\nexport function normalizePins(raw: unknown): PinSummary[] {\n if (Array.isArray(raw)) return raw as PinSummary[];\n const pins = (raw as { pins?: PinSummary[] } | undefined)?.pins;\n return Array.isArray(pins) ? pins : [];\n}\n\nexport function formatPinsList(pins: PinSummary[]): string {\n if (pins.length === 0) return \"No pins found.\";\n return pins\n .map((p) => {\n const parentLabel = p.role ? `${p.name ?? \"\"} \u00B7 ${p.role}` : (p.name ?? \"\");\n return `${parentLabel} (${p.type ?? \"\"}) ${p.entityId ?? \"\"}`.trim();\n })\n .join(\"\\n\");\n}\n\n// --- tasks ----------------------------------------------------------------\n\nexport function formatTaskList(tasks: TaskItem[], _users?: UsersMap): string {\n if (tasks.length === 0) return \"No tasks found.\";\n\n const rows = tasks.map((t) => {\n const a = t.activity ?? ({} as Activity);\n return {\n shortId: a.shortId ? `#${a.shortId}` : (a._id ?? \"\").slice(0, 8),\n status: a.completed ? \"\u2713\" : \" \",\n title: a.title || \"(untitled)\",\n deadline: formatDate(a.deadline),\n entities: (t.entities ?? []).map((e) => e.name ?? \"\").join(\", \"),\n };\n });\n\n const idW = Math.max(...rows.map((r) => r.shortId.length));\n const titleW = Math.min(Math.max(...rows.map((r) => r.title.length)), 50);\n\n return rows\n .map(\n (r) =>\n `${padEnd(r.shortId, idW)} ${r.status} ` +\n `${padEnd(truncate(r.title, 50), titleW)} ` +\n `${padEnd(r.deadline, 10)} ${r.entities}`,\n )\n .join(\"\\n\");\n}\n\nexport function formatTaskDetail(task: TaskItem, users?: UsersMap): string {\n const a = task.activity ?? ({} as Activity);\n const lines: string[] = [];\n\n const shortId = a.shortId ? `#${a.shortId}` : (a._id ?? \"\");\n const status = a.completed ? \"[done]\" : \"[open]\";\n lines.push(`${shortId} ${status} ${a.title || \"(untitled)\"}`);\n lines.push(`ID: ${a._id ?? \"\"}`);\n\n if (a.deadline) lines.push(`Deadline: ${formatDatetime(a.deadline)}`);\n const entities = task.entities ?? [];\n if (entities.length) lines.push(`Entities: ${entities.map((e) => e.name ?? \"\").join(\", \")}`);\n const assignees = a.assigneeIds ?? [];\n if (assignees.length && users) {\n const names = assignees.map((uid) => users[uid]?.name || users[uid]?.email || uid);\n lines.push(`Assignees: ${names.join(\", \")}`);\n }\n if (a.contentPlainText) {\n lines.push(\"\");\n lines.push(a.contentPlainText);\n }\n\n return lines.join(\"\\n\");\n}\n\n// --- activities -----------------------------------------------------------\n\nexport function formatActivityList(activities: Activity[]): string {\n if (activities.length === 0) return \"No activities found.\";\n\n const rows = activities.map((a) => ({\n id: a.shortId ? `#${a.shortId}` : (a._id ?? \"\").slice(0, 10),\n type: a.type ?? \"\",\n title: a.title || truncate(a.contentPlainText ?? \"\", 40),\n date: formatDate(a.createdAt),\n }));\n\n const idW = Math.max(...rows.map((r) => r.id.length));\n const typeW = Math.max(...rows.map((r) => r.type.length));\n const titleW = Math.min(Math.max(...rows.map((r) => r.title.length)), 50);\n\n return rows\n .map(\n (r) =>\n `${padEnd(r.id, idW)} ${padEnd(r.type, typeW)} ` +\n `${padEnd(truncate(r.title, 50), titleW)} ${r.date}`,\n )\n .join(\"\\n\");\n}\n\nexport function formatActivityDetail(a: Activity): string {\n const lines: string[] = [];\n lines.push(`${a.type ?? \"\"}: ${a.title || \"(untitled)\"}`);\n lines.push(`ID: ${a._id ?? \"\"}`);\n lines.push(`Created: ${formatDatetime(a.createdAt)}`);\n\n if (a.deadline) lines.push(`Deadline: ${formatDatetime(a.deadline)}`);\n if (a.completed !== undefined) lines.push(`Status: ${a.completed ? \"completed\" : \"open\"}`);\n if (a.attributes && Object.keys(a.attributes).length) {\n lines.push(\"Attributes:\");\n for (const [k, v] of Object.entries(a.attributes)) lines.push(` ${k}: ${String(v)}`);\n }\n if (a.attachments?.length) {\n lines.push(\"Attachments:\");\n for (const attachment of a.attachments) {\n const size = attachment.sizeBytes > 0\n ? `, ${(attachment.sizeBytes / 1024).toFixed(1)} KB`\n : \"\";\n lines.push(` ${attachment.name} (${attachment.mimeType}${size})`);\n if (attachment.url) lines.push(` ${attachment.url}`);\n }\n }\n if (a.contentPlainText) {\n lines.push(\"\");\n lines.push(a.contentPlainText);\n }\n\n if (a.agendaPoints?.length) {\n lines.push(\"\");\n lines.push(`Agenda (${a.agendaPoints.length}):`);\n const depthById = new Map<string, number>();\n for (const point of a.agendaPoints) {\n const depth = point.parentPointId\n ? (depthById.get(point.parentPointId) ?? 0) + 1\n : 0;\n depthById.set(point._id, depth);\n const indent = \" \".repeat(depth);\n lines.push(`${indent}- ${point.title}`);\n if (point.contentMarkdown.trim()) {\n for (const contentLine of point.contentMarkdown.split(\"\\n\"))\n lines.push(`${indent} ${contentLine}`);\n }\n }\n }\n\n if (a.messages?.length) {\n lines.push(\"\");\n lines.push(`Messages (${a.messages.length}):`);\n for (const message of a.messages) {\n const indent = \" \".repeat(message.depth ?? 0);\n const author = message.createdByUser?.name\n || message.createdByUser?.email\n || message.createdBy;\n const contentLines = message.contentPlainText.split(\"\\n\");\n const replyTarget = message.parentMessageId\n ? ` [reply to ${message.parentMessageId}]`\n : \"\";\n lines.push(`${indent}${author}: ${contentLines[0] ?? \"\"}${replyTarget}`);\n for (const contentLine of contentLines.slice(1))\n lines.push(`${indent} ${contentLine}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n// --- spaces footer --------------------------------------------------------\n\nexport function formatSpacesFooter(spaces: SpacesMap): string {\n if (!spaces || Object.keys(spaces).length === 0) return \"\";\n const lines = [\"\\nSpaces:\"];\n for (const [sid, s] of Object.entries(spaces)) {\n const members = (s.memberEmails ?? []).join(\", \");\n lines.push(` ${s.spaceName ?? sid} (${sid}) \u2014 members: ${members}`);\n }\n return lines.join(\"\\n\");\n}\n", "export interface EntityResolutionCandidate {\n _id: string;\n name: string;\n displayName?: string;\n type: string;\n}\n\nfunction normalized(value: string): string {\n return value.trim().toLowerCase();\n}\n\nexport function entityResolutionLabel(candidate: EntityResolutionCandidate): string {\n return candidate.displayName?.trim() || candidate.name;\n}\n\n/**\n * Resolve an already-fetched candidate set without guessing between duplicate\n * raw names. A parent-qualified display name is accepted when no raw entity\n * name matches the same input.\n */\nexport function resolveEntityCandidate(\n matches: EntityResolutionCandidate[],\n nameOrId: string,\n): string {\n if (matches.length === 0) throw new Error(`No entity found matching '${nameOrId}'.`);\n if (matches.length === 1) return matches[0]!._id;\n\n const input = normalized(nameOrId);\n const exactRaw = matches.filter((candidate) => normalized(candidate.name) === input);\n if (exactRaw.length === 1) return exactRaw[0]!._id;\n\n if (exactRaw.length === 0) {\n const exactDisplay = matches.filter(\n (candidate) => normalized(entityResolutionLabel(candidate)) === input,\n );\n if (exactDisplay.length === 1) return exactDisplay[0]!._id;\n }\n\n const ambiguousMatches = exactRaw.length > 1 ? exactRaw : matches;\n const listing = ambiguousMatches\n .slice(0, 5)\n .map((candidate) =>\n ` ${entityResolutionLabel(candidate)} (${candidate.type}) ${candidate._id}`\n )\n .join(\"\\n\");\n throw new Error(\n `Ambiguous match for '${nameOrId}':\\n${listing}\\nUse a parent-qualified entity name or the full entity ID to be specific.`,\n );\n}\n", "// Smart entity + space resolution \u2014 Convex-ID pass-through or fuzzy search.\n// Ports resolve.py. Takes an EnteClient so it stays free of transport details.\n\nimport type { EnteClient } from \"./client.ts\";\nimport { resolveEntityCandidate } from \"./entityResolution.ts\";\n\nconst ID_RE = /^[a-z]\\w{0,3}[0-9a-z]{28,}$/i;\n\nfunction looksLikeConvexId(value: string): boolean {\n return ID_RE.test(value) && value.length >= 20;\n}\n\n/** Resolve an entity name to its ID. Pass through if already an ID. */\nexport async function resolveEntity(client: EnteClient, nameOrId: string): Promise<string> {\n if (looksLikeConvexId(nameOrId)) return nameOrId;\n\n const res = await client.listEntities({ q: nameOrId, limit: \"10\" });\n const matches = res.data?.entities ?? [];\n return resolveEntityCandidate(matches.map(({ entity }) => entity), nameOrId);\n}\n\n/** Resolve a list of entity names/IDs (sequential \u2014 fuzzy search per item). */\nexport async function resolveEntities(client: EnteClient, inputs: string[]): Promise<string[]> {\n const ids: string[] = [];\n for (const i of inputs) ids.push(await resolveEntity(client, i));\n return ids;\n}\n\n/** Resolve a space name to its ID. Exact match first, then unique substring. */\nexport async function resolveSpaceByName(client: EnteClient, nameOrId: string): Promise<string> {\n if (looksLikeConvexId(nameOrId)) return nameOrId;\n\n const spaces = await client.listSpaces();\n const lower = nameOrId.toLowerCase();\n\n for (const [spaceId, space] of Object.entries(spaces)) {\n if ((space.spaceName ?? \"\").toLowerCase() === lower) return spaceId;\n }\n\n const partial = Object.entries(spaces).filter(([, s]) =>\n (s.spaceName ?? \"\").toLowerCase().includes(lower),\n );\n if (partial.length === 1) return partial[0]![0];\n if (partial.length > 1) {\n const listing = partial.map(([sid, s]) => ` ${s.spaceName ?? sid} ${sid}`).join(\"\\n\");\n throw new Error(\n `Ambiguous space match for '${nameOrId}':\\n${listing}\\nUse the full space ID to be specific.`,\n );\n }\n\n throw new Error(`No space found matching '${nameOrId}'.`);\n}\n", "// Branded command base. ClientCommand resolves an EnteClient from config (the\n// one place credentials are wired) and exposes it to network commands. It also\n// carries the two shared list routines (entity-list, activity-list) that more\n// than one command reuses \u2014 the TS equivalent of the Python module-level\n// run_entity_list / run_activity_list. Offline commands (guide) extend\n// BaseCommand directly.\n\nimport { Option } from \"clipanion\";\n\nimport { BaseCommand } from \"../core/command.ts\";\nimport type { QueryParams } from \"../core/transport.ts\";\nimport { parseAttrs } from \"./attrs.ts\";\nimport { ENTE_BRANDING } from \"./branding.ts\";\nimport { EnteClient } from \"./client.ts\";\nimport {\n formatActivityList,\n formatEntityList,\n formatSpacesFooter,\n formatTaskList,\n jsonWithSpaces,\n} from \"./format.ts\";\nimport { resolveEntity, resolveSpaceByName } from \"./resolve.ts\";\nimport type { Activity, SpacesMap } from \"./types.ts\";\n\nconst VALID_SORT = new Set([\"deadline\", \"created\"]);\nconst MAX_PAGINATED_ITEMS = 10_000;\nconst MAX_PAGES = 50;\n\nexport interface EntityListOpts {\n query?: string;\n typeFilter?: string;\n space?: string;\n limit?: number;\n archived?: boolean;\n}\n\nexport interface ActivityListOpts {\n entity?: string;\n typeFilter?: string;\n attrFilter?: string[];\n onlyOpen?: boolean;\n hours?: number;\n limit?: number;\n sort?: string;\n before?: number;\n after?: number;\n assignee?: string;\n}\n\nexport abstract class ProfileCommand extends BaseCommand {\n profile = Option.String(\"--profile\", {\n description: \"Use a named credential profile (or set ENTE_PROFILE)\",\n });\n\n async execute(): Promise<number> {\n if (this.profile === undefined) return super.execute();\n const previous = process.env[ENTE_BRANDING.profileEnvVar];\n process.env[ENTE_BRANDING.profileEnvVar] = this.profile;\n try {\n return await super.execute();\n } finally {\n if (previous === undefined) delete process.env[ENTE_BRANDING.profileEnvVar];\n else process.env[ENTE_BRANDING.profileEnvVar] = previous;\n }\n }\n}\n\nexport abstract class ClientCommand extends ProfileCommand {\n private _client?: EnteClient;\n\n /** Lazily build (and cache) the API client. Throws if not authenticated. */\n protected client(): EnteClient {\n if (!this._client) this._client = EnteClient.fromConfig(ENTE_BRANDING);\n return this._client;\n }\n\n /** Render `body` plus the spaces footer (mirrors the Python two-print form). */\n protected withFooter(body: string, spaces: SpacesMap): string {\n const footer = formatSpacesFooter(spaces);\n return footer ? `${body}\\n${footer}` : body;\n }\n\n // --- shared: entity list (used by `entity list` and `search`) -----------\n protected async runEntityList(opts: EntityListOpts): Promise<void> {\n const client = this.client();\n const params: QueryParams = { limit: String(opts.limit ?? 50) };\n if (opts.query) params.q = opts.query;\n if (opts.space) params.spaceId = await resolveSpaceByName(client, opts.space);\n if (opts.archived) params.archived = \"true\";\n\n const res = await client.listEntities(params);\n const data = res.data ?? { entities: [], spaces: {} };\n let entities = data.entities ?? [];\n const spaces = data.spaces ?? {};\n if (opts.typeFilter) entities = entities.filter((e) => e.entity.type === opts.typeFilter);\n\n this.emitText(jsonWithSpaces({ data: { ...data, entities } }, spaces), () =>\n this.withFooter(formatEntityList(entities, spaces), spaces),\n );\n }\n\n // --- shared: activity list (used by `activity list` and `tasks`) --------\n protected async runActivityList(opts: ActivityListOpts): Promise<void> {\n if (opts.sort && !VALID_SORT.has(opts.sort)) {\n throw new Error(`Invalid --sort value '${opts.sort}'. Allowed: deadline, created`);\n }\n const client = this.client();\n const entityId = opts.entity ? await resolveEntity(client, opts.entity) : undefined;\n const spaces = await client.listSpaces();\n\n // Task-specific path: richer /tasks endpoint.\n if (opts.typeFilter === \"task\" && opts.onlyOpen) {\n if (opts.before !== undefined || opts.after !== undefined) {\n throw new Error(\"--before/--after cannot be used with --type task --only-open.\");\n }\n const params: QueryParams = { onlyOpen: \"true\" };\n if (entityId) params.entityId = entityId;\n applyAssignee(params, opts.assignee);\n\n const res = await client.listTasks(params);\n let tasks = res.data ?? [];\n const users = res.users ?? {};\n\n if (opts.hours) {\n const cutoff = Date.now() - opts.hours * 3_600_000;\n tasks = tasks.filter((t) => (t.activity?.createdAt ?? 0) >= cutoff);\n }\n const attrDict = parseAttrs(opts.attrFilter);\n if (Object.keys(attrDict).length) {\n tasks = tasks.filter((t) =>\n Object.entries(attrDict).every(\n ([k, v]) => String(t.activity?.attributes?.[k] ?? \"\") === v,\n ),\n );\n }\n if (opts.sort === \"created\") {\n tasks.sort((a, b) => (b.activity?.createdAt ?? 0) - (a.activity?.createdAt ?? 0));\n } else {\n tasks.sort(\n (a, b) =>\n (a.activity?.deadline ?? Number.POSITIVE_INFINITY) -\n (b.activity?.deadline ?? Number.POSITIVE_INFINITY),\n );\n }\n if (opts.limit) tasks = tasks.slice(0, opts.limit);\n\n this.emitText(jsonWithSpaces({ data: tasks, users }, spaces), () =>\n this.withFooter(formatTaskList(tasks, users), spaces),\n );\n return;\n }\n\n // General activity-list path.\n const hasClientFilters = !!(\n opts.typeFilter ||\n opts.onlyOpen ||\n (opts.attrFilter && opts.attrFilter.length)\n );\n\n let activities: Activity[];\n let serverHasMore: boolean | undefined;\n\n if (hasClientFilters) {\n const hoursCutoff = opts.hours ? Date.now() - opts.hours * 3_600_000 : undefined;\n activities = [];\n let cursorBefore = opts.before;\n let opaqueCursor: string | undefined;\n let pages = 0;\n let hitCap = false;\n\n for (;;) {\n const page: QueryParams = { limit: \"10\" };\n if (entityId) page.entityId = entityId;\n if (opaqueCursor !== undefined) page.cursor = opaqueCursor;\n else if (cursorBefore !== undefined) page.before = String(cursorBefore);\n if (opts.after !== undefined) page.after = String(opts.after);\n\n const res = await client.listActivities(page);\n let pageData = res.data ?? [];\n\n if (hoursCutoff) {\n const filtered = pageData.filter((a) => (a.createdAt ?? 0) >= hoursCutoff);\n if (filtered.length < pageData.length) {\n activities.push(...filtered);\n break;\n }\n pageData = filtered;\n }\n\n activities.push(...pageData);\n pages += 1;\n\n if (!res.hasMore || pageData.length === 0) break;\n if (activities.length >= MAX_PAGINATED_ITEMS || pages >= MAX_PAGES) {\n hitCap = true;\n break;\n }\n if (res.nextCursor) opaqueCursor = res.nextCursor;\n else cursorBefore = pageData[pageData.length - 1]!.createdAt;\n }\n\n if (hitCap) {\n this.err(\n `Warning: pagination cap reached (${activities.length} items / ${pages} pages). ` +\n \"Results may be incomplete.\",\n );\n }\n } else {\n const params: QueryParams = {};\n if (entityId) params.entityId = entityId;\n if (opts.hours) params.hoursBack = String(opts.hours);\n if (opts.limit) params.limit = String(opts.limit);\n if (opts.before !== undefined) params.before = String(opts.before);\n if (opts.after !== undefined) params.after = String(opts.after);\n\n const res = await client.listActivities(params);\n activities = res.data ?? [];\n serverHasMore = res.hasMore;\n }\n\n if (opts.typeFilter) activities = activities.filter((a) => a.type === opts.typeFilter);\n if (opts.onlyOpen) activities = activities.filter((a) => !a.completed);\n\n const attrDict = parseAttrs(opts.attrFilter);\n if (Object.keys(attrDict).length) {\n activities = activities.filter((a) =>\n Object.entries(attrDict).every(([k, v]) => String(a.attributes?.[k] ?? \"\") === v),\n );\n }\n\n if (opts.sort === \"deadline\") {\n activities.sort(\n (a, b) =>\n (a.deadline ?? Number.POSITIVE_INFINITY) - (b.deadline ?? Number.POSITIVE_INFINITY),\n );\n } else if (opts.sort === \"created\") {\n activities.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));\n }\n\n if (hasClientFilters && opts.limit) activities = activities.slice(0, opts.limit);\n\n const hasMore = hasClientFilters ? undefined : serverHasMore;\n const jsonData: Record<string, unknown> = { data: activities };\n if (hasMore !== undefined) jsonData.hasMore = hasMore;\n\n this.emitText(jsonWithSpaces(jsonData, spaces), () => {\n let body = formatActivityList(activities);\n if (hasMore && activities.length) {\n const oldest = activities[activities.length - 1]!;\n body += `\\n\\n(more results available \u2014 use --before ${oldest.createdAt})`;\n }\n return this.withFooter(body, spaces);\n });\n }\n}\n\n/** Map a CLI assignee selector to the right query param. */\nexport function applyAssignee(params: QueryParams, assignee?: string): void {\n if (!assignee) return;\n if (assignee === \"me\" || assignee === \"meOrUnassigned\" || assignee === \"unassigned\") {\n params.assignee = assignee;\n } else if (assignee.includes(\"@\")) {\n params.assigneeEmail = assignee;\n } else {\n params.assigneeUserId = assignee;\n }\n}\n\nexport { BaseCommand };\n", "// ente wiring for the Convex transport: resolve stored credentials into the two\n// deployment origins a ConvexHttpClient needs, then build an authenticated\n// caller via the JWT bridge (see ../core/convex.ts).\n//\n// A Convex deployment exposes two origins for the sync/API surface and the\n// HTTP-actions (\"site\") surface. `ente auth login --url` stores either one; we\n// derive the sibling, so no config migration is needed. Two naming schemes:\n// \u2022 Managed cloud: <slug>.convex.cloud \u2194 <slug>.convex.site (suffix swap)\n// \u2022 Self-hosted (rdu/Traefik): convex.<rest> \u2194 site.<rest> (label swap)\n// \u2022 Local Convex: cloud port N \u2194 site port N+1\n// Anything else (e.g. a raw single-origin self-host) falls back to one origin\n// for both \u2014 a wrong guess fails loud at the /cli/token HTTP call, never silently.\n\nimport { createHash } from \"node:crypto\";\n\nimport { configDir } from \"../core/config.ts\";\nimport { makeCaller, type ConvexCaller } from \"../core/convex.ts\";\nimport { ENTE_BRANDING } from \"./branding.ts\";\nimport { loadCredentials } from \"../core/config.ts\";\n\nexport interface ConvexEndpoints {\n convexUrl: string;\n siteUrl: string;\n}\n\nexport function credentialCacheKey(apiUrl: string, apiKey: string): string {\n const { convexUrl } = resolveConvexEndpoints(apiUrl);\n const credentialFingerprint = createHash(\"sha256\")\n .update(apiKey)\n .digest(\"hex\")\n .slice(0, 16);\n return `${new URL(convexUrl).host}-${credentialFingerprint}`;\n}\n\n/** Derive the .cloud (API) and .site (HTTP-actions) origins from a stored URL. */\nexport function resolveConvexEndpoints(apiUrl: string): ConvexEndpoints {\n const trimmed = apiUrl.trim().replace(/\\/+$/, \"\");\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n throw new Error(`Stored API url is not a valid URL: ${apiUrl}`);\n }\n const host = url.hostname;\n const suffix = `${url.port ? `:${url.port}` : \"\"}`;\n const origin = (h: string) => `${url.protocol}//${h}${suffix}`;\n\n // Managed cloud: <slug>.convex.cloud (API) \u2194 <slug>.convex.site (HTTP actions).\n if (host.endsWith(\".convex.cloud\")) {\n return { convexUrl: origin(host), siteUrl: origin(host.replace(/\\.convex\\.cloud$/, \".convex.site\")) };\n }\n if (host.endsWith(\".convex.site\")) {\n return { siteUrl: origin(host), convexUrl: origin(host.replace(/\\.convex\\.site$/, \".convex.cloud\")) };\n }\n // Self-hosted behind rdu/Traefik: convex.<rest> (API) \u2194 site.<rest> (HTTP actions).\n if (host.startsWith(\"convex.\")) {\n return { convexUrl: origin(host), siteUrl: origin(host.replace(/^convex\\./, \"site.\")) };\n }\n if (host.startsWith(\"site.\")) {\n return { siteUrl: origin(host), convexUrl: origin(host.replace(/^site\\./, \"convex.\")) };\n }\n const isLoopback = host === \"localhost\" || host === \"127.0.0.1\" || host === \"[::1]\";\n const sitePort = Number(url.port);\n if (isLoopback && Number.isInteger(sitePort) && sitePort > 1) {\n const convexUrl = new URL(url.origin);\n convexUrl.port = String(sitePort - 1);\n return { siteUrl: url.origin, convexUrl: convexUrl.origin };\n }\n // Unknown host (raw single-origin self-host): API + HTTP actions share it.\n return { convexUrl: origin(host), siteUrl: origin(host) };\n}\n\n/** Resolve credentials + endpoints and build an authenticated Convex caller. */\nexport async function resolveCaller(): Promise<ConvexCaller> {\n const creds = loadCredentials(ENTE_BRANDING);\n const { convexUrl, siteUrl } = resolveConvexEndpoints(creds.apiUrl);\n return makeCaller({\n convexUrl,\n siteUrl,\n apiKey: creds.apiKey,\n cacheDir: configDir(ENTE_BRANDING),\n cacheKey: credentialCacheKey(creds.apiUrl, creds.apiKey),\n });\n}\n", "export const version = \"1.46.0\";\n", "/*\nhttps://github.com/beatgammit/base64-js/blob/88957c9943c7e2a0f03cdf73e71d579e433627d3/index.js\nCopyright (c) 2014 Jameson Little\nThe MIT License (MIT)\n*/\n\n// Vendored because this library has no ESM build, and some environments\n// (SvelteKit) are happiest when all dependencies are ESM.\n\nvar lookup: string[] = [];\nvar revLookup: number[] = [];\nvar Arr = Uint8Array;\n\nvar code = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup[\"-\".charCodeAt(0)] = 62;\nrevLookup[\"_\".charCodeAt(0)] = 63;\n\nfunction getLens(b64: string) {\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error(\"Invalid string. Length must be a multiple of 4\");\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf(\"=\");\n if (validLen === -1) validLen = len;\n\n var placeHoldersLen = validLen === len ? 0 : 4 - (validLen % 4);\n\n return [validLen, placeHoldersLen];\n}\n\n// base64 is 4/3 + up to two characters of the original data\n/** @public */\nexport function byteLength(b64: string): number {\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\nfunction _byteLength(_b64: string, validLen: number, placeHoldersLen: number) {\n return ((validLen + placeHoldersLen) * 3) / 4 - placeHoldersLen;\n}\n\n/** @public */\nexport function toByteArray(b64: string): Uint8Array {\n var tmp;\n var lens = getLens(b64);\n var validLen = lens[0];\n var placeHoldersLen = lens[1];\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen));\n\n var curByte = 0;\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0 ? validLen - 4 : validLen;\n\n var i;\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)];\n arr[curByte++] = (tmp >> 16) & 0xff;\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[curByte++] = tmp & 0xff;\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[curByte++] = (tmp >> 8) & 0xff;\n arr[curByte++] = tmp & 0xff;\n }\n\n return arr;\n}\n\nfunction tripletToBase64(num: number) {\n return (\n lookup[(num >> 18) & 0x3f] +\n lookup[(num >> 12) & 0x3f] +\n lookup[(num >> 6) & 0x3f] +\n lookup[num & 0x3f]\n );\n}\n\nfunction encodeChunk(uint8: Uint8Array, start: number, end: number) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xff0000) +\n ((uint8[i + 1] << 8) & 0xff00) +\n (uint8[i + 2] & 0xff);\n output.push(tripletToBase64(tmp));\n }\n return output.join(\"\");\n}\n\n/** @public */\nexport function fromByteArray(uint8: Uint8Array): string {\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(\n encodeChunk(\n uint8,\n i,\n i + maxChunkLength > len2 ? len2 : i + maxChunkLength,\n ),\n );\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n parts.push(lookup[tmp >> 2] + lookup[(tmp << 4) & 0x3f] + \"==\");\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1];\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3f] +\n lookup[(tmp << 2) & 0x3f] +\n \"=\",\n );\n }\n\n return parts.join(\"\");\n}\n\nexport function fromByteArrayUrlSafeNoPadding(uint8: Uint8Array): string {\n return fromByteArray(uint8)\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=/g, \"\");\n}\n", "import type { Value } from \"../values/value.js\";\n\n/**\n * Validate that the arguments to a Convex function are an object, defaulting\n * `undefined` to `{}`.\n */\nexport function parseArgs(\n args: Record<string, Value> | undefined,\n): Record<string, Value> {\n if (args === undefined) {\n return {};\n }\n if (!isSimpleObject(args)) {\n throw new Error(\n `The arguments to a Convex function must be an object. Received: ${\n args as any\n }`,\n );\n }\n return args;\n}\n\nexport function validateDeploymentUrl(deploymentUrl: string) {\n // Don't use things like `new URL(deploymentUrl).hostname` since these aren't\n // supported by React Native's JS environment\n if (typeof deploymentUrl === \"undefined\") {\n throw new Error(\n `Client created with undefined deployment address. If you used an environment variable, check that it's set.`,\n );\n }\n if (typeof deploymentUrl !== \"string\") {\n throw new Error(\n `Invalid deployment address: found ${deploymentUrl as any}\".`,\n );\n }\n if (\n !(deploymentUrl.startsWith(\"http:\") || deploymentUrl.startsWith(\"https:\"))\n ) {\n throw new Error(\n `Invalid deployment address: Must start with \"https://\" or \"http://\". Found \"${deploymentUrl}\".`,\n );\n }\n\n // Most clients should connect to \".convex.cloud\". But we also support localhost and\n // custom custom. We validate the deployment url is a valid url, which is the most\n // common failure pattern.\n try {\n new URL(deploymentUrl);\n } catch {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" is not a valid URL. If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n\n // If a user uses .convex.site, this is very likely incorrect.\n if (deploymentUrl.endsWith(\".convex.site\")) {\n throw new Error(\n `Invalid deployment address: \"${deploymentUrl}\" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \\`skipConvexDeploymentUrlCheck\\` option to bypass this.`,\n );\n }\n}\n\n/**\n * Check whether a value is a plain old JavaScript object.\n */\nexport function isSimpleObject(value: unknown) {\n const isObject = typeof value === \"object\";\n const prototype = Object.getPrototypeOf(value);\n const isSimple =\n prototype === null ||\n prototype === Object.prototype ||\n // Objects generated from other contexts (e.g. across Node.js `vm` modules) will not satisfy the previous\n // conditions but are still simple objects.\n prototype?.constructor?.name === \"Object\";\n return isObject && isSimple;\n}\n", "/**\n * Utilities for working with values stored in Convex.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n * @module\n */\nimport * as Base64 from \"./base64.js\";\nimport { isSimpleObject } from \"../common/index.js\";\n\nconst LITTLE_ENDIAN = true;\n// This code is used by code that may not have bigint literals.\nconst MIN_INT64 = BigInt(\"-9223372036854775808\");\nexport const MAX_INT64 = BigInt(\"9223372036854775807\");\nconst ZERO = BigInt(\"0\");\nconst EIGHT = BigInt(\"8\");\nconst TWOFIFTYSIX = BigInt(\"256\");\n\n/**\n * The type of JavaScript values serializable to JSON.\n *\n * @public\n */\nexport type JSONValue =\n | null\n | boolean\n | number\n | string\n | JSONValue[]\n | { [key: string]: JSONValue };\n\n/**\n * An identifier for a document in Convex.\n *\n * Convex documents are uniquely identified by their `Id`, which is accessible\n * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/database/document-ids).\n *\n * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.\n *\n * IDs are base 32 encoded strings which are URL safe.\n *\n * IDs are just strings at runtime, but this type can be used to distinguish them from other\n * strings at compile time.\n *\n * If you're using code generation, use the `Id` type generated for your data model in\n * `convex/_generated/dataModel.d.ts`.\n *\n * @typeParam TableName - A string literal type of the table name (like \"users\").\n *\n * @public\n */\nexport type Id<TableName extends string> = string & { __tableName: TableName };\n\n/**\n * A value supported by Convex.\n *\n * Values can be:\n * - stored inside of documents.\n * - used as arguments and return types to queries and mutation functions.\n *\n * You can see the full set of supported types at\n * [Types](https://docs.convex.dev/using/types).\n *\n * @public\n */\nexport type Value =\n | null\n | bigint\n | number\n | boolean\n | string\n | ArrayBuffer\n | CommitTsPlaceholder\n | Value[]\n | { [key: string]: undefined | Value };\n\n/**\n * The types of {@link Value} that can be used to represent numbers.\n *\n * @public\n */\nexport type NumericValue = bigint | number;\n\nconst COMMIT_TS_UNRESOLVED =\n \"This commit timestamp is unresolved: its value is assigned when the \" +\n \"mutation commits. Read the document after the mutation completes to get \" +\n \"its value.\";\n\n/**\n * The placeholder for a transaction's commit timestamp, which is not known\n * until the mutation commits. Write it into a document field via\n * `db.vars.commitTs` and it resolves to an int64 (`bigint`) at commit,\n * ordered by commit order. Reading the field back within the writing\n * mutation yields the placeholder, which cannot be used as a number.\n *\n * @public\n */\nexport class CommitTsPlaceholder {\n // A private member makes the class nominal: no structurally-similar object\n // type-checks as a placeholder.\n declare private readonly __isCommitTsPlaceholder: undefined;\n [Symbol.toPrimitive](hint: string): string {\n // Allow string conversion so logging a read-back document doesn't throw.\n if (hint === \"string\") {\n return this.toString();\n }\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n valueOf(): never {\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n toJSON(): never {\n throw new Error(COMMIT_TS_UNRESOLVED);\n }\n toString(): string {\n return \"[unresolved commit timestamp]\";\n }\n}\n\n/**\n * The placeholder for a commit timestamp that is not yet known, exposed as\n * `db.vars.commitTs`. A singleton so that a value read back within the\n * writing mutation compares equal to `db.vars.commitTs`.\n *\n * @internal\n */\nexport const commitTsPlaceholder = new CommitTsPlaceholder();\n\nfunction isSpecial(n: number) {\n return Number.isNaN(n) || !Number.isFinite(n) || Object.is(n, -0);\n}\n\nexport function slowBigIntToBase64(value: bigint): string {\n // the conversion is easy if we pretend it's unsigned\n if (value < ZERO) {\n value -= MIN_INT64 + MIN_INT64;\n }\n let hex = value.toString(16);\n if (hex.length % 2 === 1) hex = \"0\" + hex;\n\n const bytes = new Uint8Array(new ArrayBuffer(8));\n let i = 0;\n for (const hexByte of hex.match(/.{2}/g)!.reverse()) {\n bytes.set([parseInt(hexByte, 16)], i++);\n value >>= EIGHT;\n }\n return Base64.fromByteArray(bytes);\n}\n\nexport function slowBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n let value = ZERO;\n let power = ZERO;\n for (const byte of integerBytes) {\n value += BigInt(byte) * TWOFIFTYSIX ** power;\n power++;\n }\n if (value > MAX_INT64) {\n value += MIN_INT64 + MIN_INT64;\n }\n return value;\n}\n\nexport function modernBigIntToBase64(value: bigint): string {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setBigInt64(0, value, true);\n return Base64.fromByteArray(new Uint8Array(buffer));\n}\n\nexport function modernBase64ToBigInt(encoded: string): bigint {\n const integerBytes = Base64.toByteArray(encoded);\n if (integerBytes.byteLength !== 8) {\n throw new Error(\n `Received ${integerBytes.byteLength} bytes, expected 8 for $integer`,\n );\n }\n const intBytesView = new DataView(integerBytes.buffer);\n return intBytesView.getBigInt64(0, true);\n}\n\n// Fall back to a slower version on Safari 14 which lacks these APIs.\nexport const bigIntToBase64 = (DataView.prototype as any).setBigInt64\n ? modernBigIntToBase64\n : slowBigIntToBase64;\nexport const base64ToBigInt = (DataView.prototype as any).getBigInt64\n ? modernBase64ToBigInt\n : slowBase64ToBigInt;\n\nconst MAX_IDENTIFIER_LEN = 1024;\n\nfunction validateObjectField(k: string) {\n if (k.length > MAX_IDENTIFIER_LEN) {\n throw new Error(\n `Field name ${k} exceeds maximum field name length ${MAX_IDENTIFIER_LEN}.`,\n );\n }\n if (k.startsWith(\"$\")) {\n throw new Error(`Field name ${k} starts with a '$', which is reserved.`);\n }\n for (let i = 0; i < k.length; i += 1) {\n const charCode = k.charCodeAt(i);\n // Non-control ASCII characters\n if (charCode < 32 || charCode >= 127) {\n throw new Error(\n `Field name ${k} has invalid character '${k[i]}': Field names can only contain non-control ASCII characters`,\n );\n }\n }\n}\n\n/**\n * Parse a Convex value from its JSON representation.\n *\n * This function will deserialize serialized Int64s to `BigInt`s, Bytes to `ArrayBuffer`s etc.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - The JSON representation of a Convex value previously created with {@link convexToJson}.\n * @returns The JavaScript representation of the Convex value.\n *\n * @public\n */\nexport function jsonToConvex(value: JSONValue): Value {\n if (value === null) {\n return value;\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"number\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((value) => jsonToConvex(value));\n }\n if (typeof value !== \"object\") {\n throw new Error(`Unexpected type of ${value as any}`);\n }\n const entries = Object.entries(value);\n if (entries.length === 1) {\n const key = entries[0][0];\n if (key === \"$bytes\") {\n if (typeof value.$bytes !== \"string\") {\n throw new Error(`Malformed $bytes field on ${value as any}`);\n }\n return Base64.toByteArray(value.$bytes).buffer;\n }\n if (key === \"$integer\") {\n if (typeof value.$integer !== \"string\") {\n throw new Error(`Malformed $integer field on ${value as any}`);\n }\n return base64ToBigInt(value.$integer);\n }\n if (key === \"$float\") {\n if (typeof value.$float !== \"string\") {\n throw new Error(`Malformed $float field on ${value as any}`);\n }\n const floatBytes = Base64.toByteArray(value.$float);\n if (floatBytes.byteLength !== 8) {\n throw new Error(\n `Received ${floatBytes.byteLength} bytes, expected 8 for $float`,\n );\n }\n const floatBytesView = new DataView(floatBytes.buffer);\n const float = floatBytesView.getFloat64(0, LITTLE_ENDIAN);\n if (!isSpecial(float)) {\n throw new Error(`Float ${float} should be encoded as a number`);\n }\n return float;\n }\n if (key === \"$commitTs\") {\n if (value.$commitTs !== null) {\n throw new Error(`Malformed $commitTs field on ${value as any}`);\n }\n return commitTsPlaceholder;\n }\n if (key === \"$set\") {\n throw new Error(\n `Received a Set which is no longer supported as a Convex type.`,\n );\n }\n if (key === \"$map\") {\n throw new Error(\n `Received a Map which is no longer supported as a Convex type.`,\n );\n }\n }\n const out: { [key: string]: Value } = {};\n for (const [k, v] of Object.entries(value)) {\n validateObjectField(k);\n out[k] = jsonToConvex(v);\n }\n return out;\n}\n\nconst MAX_VALUE_FOR_ERROR_LEN = 16384;\n\nexport function stringifyValueForError(value: any) {\n const str = JSON.stringify(value, (_key, value) => {\n if (value === undefined) {\n // By default `JSON.stringify` converts undefined, functions, symbols,\n // Infinity, and NaN to null which produces a confusing error message.\n // We deal with `undefined` specifically because it's the most common.\n // Ideally we'd use a pretty-printing library that prints `undefined`\n // (no quotes), but it might not be worth the bundle size cost.\n return \"undefined\";\n }\n if (typeof value === \"bigint\") {\n // `JSON.stringify` throws on bigints by default.\n return `${value.toString()}n`;\n }\n return value;\n });\n if (str.length > MAX_VALUE_FOR_ERROR_LEN) {\n const rest = \"[...truncated]\";\n let truncateAt = MAX_VALUE_FOR_ERROR_LEN - rest.length;\n const codePoint = str.codePointAt(truncateAt - 1);\n if (codePoint !== undefined && codePoint > 0xffff) {\n // don't split a surrogate pair in half\n truncateAt -= 1;\n }\n return str.substring(0, truncateAt) + rest;\n }\n return str;\n}\n\nfunction convexToJsonInternal(\n value: Value,\n originalValue: Value,\n context: string,\n includeTopLevelUndefined: boolean,\n): JSONValue {\n if (value === undefined) {\n const contextText =\n context &&\n ` (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )})`;\n throw new Error(\n `undefined is not a valid Convex value${contextText}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`,\n );\n }\n if (value === null) {\n return value;\n }\n if (typeof value === \"bigint\") {\n if (value < MIN_INT64 || MAX_INT64 < value) {\n throw new Error(\n `BigInt ${value} does not fit into a 64-bit signed integer.`,\n );\n }\n return { $integer: bigIntToBase64(value) };\n }\n if (typeof value === \"number\") {\n if (isSpecial(value)) {\n const buffer = new ArrayBuffer(8);\n new DataView(buffer).setFloat64(0, value, LITTLE_ENDIAN);\n return { $float: Base64.fromByteArray(new Uint8Array(buffer)) };\n } else {\n return value;\n }\n }\n if (typeof value === \"boolean\") {\n return value;\n }\n if (typeof value === \"string\") {\n return value;\n }\n if (value instanceof ArrayBuffer) {\n return { $bytes: Base64.fromByteArray(new Uint8Array(value)) };\n }\n if (value instanceof CommitTsPlaceholder) {\n return { $commitTs: null };\n }\n if (Array.isArray(value)) {\n return value.map((value, i) =>\n convexToJsonInternal(value, originalValue, context + `[${i}]`, false),\n );\n }\n if (value instanceof Set) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Set\", [...value], originalValue),\n );\n }\n if (value instanceof Map) {\n throw new Error(\n errorMessageForUnsupportedType(context, \"Map\", [...value], originalValue),\n );\n }\n\n if (!isSimpleObject(value)) {\n const theType = value?.constructor?.name;\n const typeName = theType ? `${theType} ` : \"\";\n throw new Error(\n errorMessageForUnsupportedType(context, typeName, value, originalValue),\n );\n }\n\n const out: { [key: string]: JSONValue } = {};\n const entries = Object.entries(value);\n entries.sort(([k1, _v1], [k2, _v2]) => (k1 === k2 ? 0 : k1 < k2 ? -1 : 1));\n for (const [k, v] of entries) {\n if (v !== undefined) {\n validateObjectField(k);\n out[k] = convexToJsonInternal(v, originalValue, context + `.${k}`, false);\n } else if (includeTopLevelUndefined) {\n validateObjectField(k);\n out[k] = convexOrUndefinedToJsonInternal(\n v,\n originalValue,\n context + `.${k}`,\n );\n }\n }\n return out;\n}\n\nfunction errorMessageForUnsupportedType(\n context: string,\n typeName: string,\n value: any,\n originalValue: any,\n) {\n if (context) {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type (present at path ${context} in original object ${stringifyValueForError(\n originalValue,\n )}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`;\n } else {\n return `${typeName}${stringifyValueForError(\n value,\n )} is not a supported Convex type.`;\n }\n}\n\n// convexOrUndefinedToJsonInternal wrapper exists so we can pipe through the\n// `originalValue` and `context` through for better error messaging.\nfunction convexOrUndefinedToJsonInternal(\n value: Value | undefined,\n originalValue: Value | undefined,\n context: string,\n): JSONValue {\n if (value === undefined) {\n return { $undefined: null };\n } else {\n if (originalValue === undefined) {\n // This should not happen.\n throw new Error(\n `Programming error. Current value is ${stringifyValueForError(\n value,\n )} but original value is undefined`,\n );\n }\n return convexToJsonInternal(value, originalValue, context, false);\n }\n}\n\n/**\n * Convert a Convex value to its JSON representation.\n *\n * Use {@link jsonToConvex} to recreate the original value.\n *\n * To learn more about Convex values, see [Types](https://docs.convex.dev/using/types).\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n *\n * @public\n */\nexport function convexToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", false);\n}\n\n// Convert a Convex value or `undefined` into its JSON representation.\n// `undefined` is used in filters to represent a missing object field.\nexport function convexOrUndefinedToJson(value: Value | undefined): JSONValue {\n return convexOrUndefinedToJsonInternal(value, value, \"\");\n}\n\n/**\n * Similar to convexToJson but also serializes top level undefined fields\n * using convexOrUndefinedToJson().\n *\n * @param value - A Convex value to convert into JSON.\n * @returns The JSON representation of `value`.\n */\nexport function patchValueToJson(value: Value): JSONValue {\n return convexToJsonInternal(value, value, \"\", true);\n}\n", "import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport { GenericValidator, ObjectType } from \"./validator.js\";\nimport { CommitTsPlaceholder, JSONValue, convexToJson } from \"./value.js\";\n\ntype TableNameFromType<T> =\n T extends GenericId<infer TableName> ? TableName : string;\n\nconst UNDEFINED_VALIDATOR_ERROR_URL =\n \"https://docs.convex.dev/error#undefined-validator\";\n\nfunction throwUndefinedValidatorError(\n context: string,\n fieldName?: string,\n): never {\n const fieldInfo = fieldName !== undefined ? ` for field \"${fieldName}\"` : \"\";\n throw new Error(\n `A validator is undefined${fieldInfo} in ${context}. ` +\n `This is often caused by circular imports. ` +\n `See ${UNDEFINED_VALIDATOR_ERROR_URL} for details.`,\n );\n}\n\n/**\n * Avoid using `instanceof BaseValidator`; this is inheritence for code reuse\n * not type heirarchy.\n */\nabstract class BaseValidator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> {\n /**\n * Only for TypeScript, the TS type of the JS values validated\n * by this validator.\n */\n readonly type!: Type;\n /**\n * Only for TypeScript, if this an Object validator, then\n * this is the TS type of its property names.\n */\n readonly fieldPaths!: FieldPaths;\n\n /**\n * Whether this is an optional Object property value validator.\n */\n readonly isOptional: IsOptional;\n\n /**\n * Always `\"true\"`.\n */\n readonly isConvexValidator: true;\n\n constructor({ isOptional }: { isOptional: IsOptional }) {\n this.isOptional = isOptional;\n this.isConvexValidator = true;\n }\n /** @internal */\n abstract get json(): ValidatorJSON;\n /** @internal */\n abstract asOptional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n /** Allow this validated field to be absent. */\n abstract optional(): Validator<Type | undefined, \"optional\", FieldPaths>;\n}\n\n/**\n * The type of the `v.id(tableName)` validator.\n */\nexport class VId<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The name of the table that the validated IDs must belong to.\n */\n readonly tableName: TableNameFromType<Type>;\n\n /**\n * The kind of validator, `\"id\"`.\n */\n readonly kind = \"id\" as const;\n\n /**\n * Usually you'd use `v.id(tableName)` instead.\n */\n constructor({\n isOptional,\n tableName,\n }: {\n isOptional: IsOptional;\n tableName: TableNameFromType<Type>;\n }) {\n super({ isOptional });\n if (typeof tableName !== \"string\") {\n throw new Error(\"v.id(tableName) requires a string\");\n }\n this.tableName = tableName;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return { type: \"id\", tableName: this.tableName };\n }\n /** Allow this field to be validated as absent. */\n optional() {\n return new VId<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n tableName: this.tableName,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.float64()` validator.\n */\nexport class VFloat64<\n Type = number,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"float64\"`.\n */\n readonly kind = \"float64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `number` string instead of `float64`.\n return { type: \"number\" };\n }\n /** Allow this field to be validated as absent. */\n optional() {\n return new VFloat64<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.int64()` validator.\n */\nexport class VInt64<\n Type = bigint,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"int64\"`.\n */\n readonly kind = \"int64\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n // Server expects the old name `bigint`.\n return { type: \"bigint\" };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VInt64<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.commitTs()` validator.\n */\nexport class VCommitTs<\n Type = bigint | CommitTsPlaceholder,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"commitTs\"`.\n */\n readonly kind = \"commitTs\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VCommitTs<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.boolean()` validator.\n */\nexport class VBoolean<\n Type = boolean,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"boolean\"`.\n */\n readonly kind = \"boolean\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VBoolean<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.bytes()` validator.\n */\nexport class VBytes<\n Type = ArrayBuffer,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"bytes\"`.\n */\n readonly kind = \"bytes\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VBytes<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.string()` validator.\n */\nexport class VString<\n Type = string,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"string\"`.\n */\n readonly kind = \"string\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VString<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.null()` validator.\n */\nexport class VNull<\n Type = null,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The kind of validator, `\"null\"`.\n */\n readonly kind = \"null\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return { type: this.kind };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VNull<Type | undefined, \"optional\">({ isOptional: \"optional\" });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.any()` validator.\n */\nexport class VAny<\n Type = any,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The kind of validator, `\"any\"`.\n */\n readonly kind = \"any\" as const;\n\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VAny<Type | undefined, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.object()` validator.\n */\nexport class VObject<\n Type,\n Fields extends Record<string, GenericValidator>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = {\n [Property in keyof Fields]:\n | JoinFieldPaths<Property & string, Fields[Property][\"fieldPaths\"]>\n | Property;\n }[keyof Fields] &\n string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * An object with the validator for each property.\n */\n readonly fields: Fields;\n\n /**\n * The kind of validator, `\"object\"`.\n */\n readonly kind = \"object\" as const;\n\n /**\n * Usually you'd use `v.object({ ... })` instead.\n */\n constructor({\n isOptional,\n fields,\n }: {\n isOptional: IsOptional;\n fields: Fields;\n }) {\n super({ isOptional });\n globalThis.Object.entries(fields).forEach(([fieldName, validator]) => {\n if (validator === undefined) {\n throwUndefinedValidatorError(\"v.object()\", fieldName);\n }\n if (!validator.isConvexValidator) {\n throw new Error(\"v.object() entries must be validators\");\n }\n });\n this.fields = fields;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: globalThis.Object.fromEntries(\n globalThis.Object.entries(this.fields).map(([k, v]) => [\n k,\n {\n fieldType: v.json,\n optional: v.isOptional === \"optional\" ? true : false,\n },\n ]),\n ),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VObject<Type | undefined, Fields, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n fields: this.fields,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n\n /**\n * Create a new VObject with the specified fields omitted.\n * @param fields The field names to omit from this VObject.\n */\n omit<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<Expand<Omit<Type, K>>, Expand<Omit<Fields, K>>, IsOptional> {\n const newFields = { ...this.fields };\n for (const field of fields) {\n delete newFields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as any,\n });\n }\n\n /**\n * Create a new VObject with only the specified fields.\n * @param fields The field names to pick from this VObject.\n */\n pick<K extends keyof Fields & string>(\n ...fields: K[]\n ): VObject<\n Expand<Pick<Type, Extract<keyof Type, K>>>,\n Expand<Pick<Fields, K>>,\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const field of fields) {\n newFields[field] = this.fields[field];\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as Expand<Pick<Fields, K>>,\n });\n }\n\n /**\n * Create a new VObject with all fields marked as optional.\n */\n partial(): VObject<\n { [K in keyof Type]?: Type[K] },\n { [K in keyof Fields]: VOptional<Fields[K]> },\n IsOptional\n > {\n const newFields: Record<string, GenericValidator> = {};\n for (const [key, validator] of globalThis.Object.entries(this.fields)) {\n newFields[key] = validator.asOptional();\n }\n return new VObject({\n isOptional: this.isOptional,\n fields: newFields as {\n [K in keyof Fields]: VOptional<Fields[K]>;\n },\n });\n }\n\n /**\n * Create a new VObject with additional fields merged in.\n * @param fields An object with additional validators to merge into this VObject.\n */\n extend<NewFields extends Record<string, GenericValidator>>(\n fields: NewFields,\n ): VObject<\n Expand<Type & ObjectType<NewFields>>,\n Expand<Fields & NewFields>,\n IsOptional\n > {\n return new VObject({\n isOptional: this.isOptional,\n fields: { ...this.fields, ...fields } as Expand<Fields & NewFields>,\n });\n }\n}\n\n/**\n * The type of the `v.literal()` validator.\n */\nexport class VLiteral<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The value that the validated values must be equal to.\n */\n readonly value: Type;\n\n /**\n * The kind of validator, `\"literal\"`.\n */\n readonly kind = \"literal\" as const;\n\n /**\n * Usually you'd use `v.literal(value)` instead.\n */\n constructor({ isOptional, value }: { isOptional: IsOptional; value: Type }) {\n super({ isOptional });\n if (\n typeof value !== \"string\" &&\n typeof value !== \"boolean\" &&\n typeof value !== \"number\" &&\n typeof value !== \"bigint\"\n ) {\n throw new Error(\"v.literal(value) must be a string, number, or boolean\");\n }\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: convexToJson(this.value as string | boolean | number | bigint),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VLiteral<Type | undefined, \"optional\">({\n isOptional: \"optional\",\n value: this.value,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.array()` validator.\n */\nexport class VArray<\n Type,\n Element extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n> extends BaseValidator<Type, IsOptional> {\n /**\n * The validator for the elements of the array.\n */\n readonly element: Element;\n\n /**\n * The kind of validator, `\"array\"`.\n */\n readonly kind = \"array\" as const;\n\n /**\n * Usually you'd use `v.array(element)` instead.\n */\n constructor({\n isOptional,\n element,\n }: {\n isOptional: IsOptional;\n element: Element;\n }) {\n super({ isOptional });\n if (element === undefined) {\n throwUndefinedValidatorError(\"v.array()\");\n }\n this.element = element;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.element.json,\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VArray<Type | undefined, Element, \"optional\">({\n isOptional: \"optional\",\n element: this.element,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.record()` validator.\n */\nexport class VRecord<\n Type,\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = string,\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The validator for the keys of the record.\n */\n readonly key: Key;\n\n /**\n * The validator for the values of the record.\n */\n readonly value: Value;\n\n /**\n * The kind of validator, `\"record\"`.\n */\n readonly kind = \"record\" as const;\n\n /**\n * Usually you'd use `v.record(key, value)` instead.\n */\n constructor({\n isOptional,\n key,\n value,\n }: {\n isOptional: IsOptional;\n key: Key;\n value: Value;\n }) {\n super({ isOptional });\n if (key === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"key\");\n }\n if (value === undefined) {\n throwUndefinedValidatorError(\"v.record()\", \"value\");\n }\n if ((key.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional keys\");\n }\n if ((value.isOptional as OptionalProperty) === \"optional\") {\n throw new Error(\"Record validator cannot have optional values\");\n }\n if (!key.isConvexValidator || !value.isConvexValidator) {\n throw new Error(\"Key and value of v.record() but be validators\");\n }\n this.key = key;\n this.value = value;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n // This cast is needed because TypeScript thinks the key type is too wide\n keys: this.key.json as RecordKeyValidatorJSON,\n values: {\n fieldType: this.value.json,\n optional: false,\n },\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n key: this.key,\n value: this.value,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n/**\n * The type of the `v.union()` validator.\n */\nexport class VUnion<\n Type,\n T extends Validator<any, \"required\", any>[],\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = T[number][\"fieldPaths\"],\n> extends BaseValidator<Type, IsOptional, FieldPaths> {\n /**\n * The array of validators, one of which must match the value.\n */\n readonly members: T;\n\n /**\n * The kind of validator, `\"union\"`.\n */\n readonly kind = \"union\" as const;\n\n /**\n * Usually you'd use `v.union(...members)` instead.\n */\n constructor({ isOptional, members }: { isOptional: IsOptional; members: T }) {\n super({ isOptional });\n members.forEach((member, index) => {\n if (member === undefined) {\n throwUndefinedValidatorError(\"v.union()\", `member at index ${index}`);\n }\n if (!member.isConvexValidator) {\n throw new Error(\"All members of v.union() must be validators\");\n }\n });\n this.members = members;\n }\n /** @internal */\n get json(): ValidatorJSON {\n return {\n type: this.kind,\n value: this.members.map((v) => v.json),\n };\n }\n /** Allow this validated field to be absent. */\n optional() {\n return new VUnion<Type | undefined, T, \"optional\", FieldPaths>({\n isOptional: \"optional\",\n members: this.members,\n });\n }\n /** @internal */\n asOptional() {\n return this.optional();\n }\n}\n\n// prettier-ignore\nexport type VOptional<T extends Validator<any, OptionalProperty, any>> =\n T extends VId<infer Type, OptionalProperty> ? VId<Type | undefined, \"optional\">\n : T extends VString<infer Type, OptionalProperty>\n ? VString<Type | undefined, \"optional\">\n : T extends VFloat64<infer Type, OptionalProperty>\n ? VFloat64<Type | undefined, \"optional\">\n : T extends VInt64<infer Type, OptionalProperty>\n ? VInt64<Type | undefined, \"optional\">\n : T extends VCommitTs<infer Type, OptionalProperty>\n ? VCommitTs<Type | undefined, \"optional\">\n : T extends VBoolean<infer Type, OptionalProperty>\n ? VBoolean<Type | undefined, \"optional\">\n : T extends VNull<infer Type, OptionalProperty>\n ? VNull<Type | undefined, \"optional\">\n : T extends VAny<infer Type, OptionalProperty>\n ? VAny<Type | undefined, \"optional\">\n : T extends VLiteral<infer Type, OptionalProperty>\n ? VLiteral<Type | undefined, \"optional\">\n : T extends VBytes<infer Type, OptionalProperty>\n ? VBytes<Type | undefined, \"optional\">\n : T extends VObject< infer Type, infer Fields, OptionalProperty, infer FieldPaths>\n ? VObject<Type | undefined, Fields, \"optional\", FieldPaths>\n : T extends VArray<infer Type, infer Element, OptionalProperty>\n ? VArray<Type | undefined, Element, \"optional\">\n : T extends VRecord< infer Type, infer Key, infer Value, OptionalProperty, infer FieldPaths>\n ? VRecord<Type | undefined, Key, Value, \"optional\", FieldPaths>\n : T extends VUnion<infer Type, infer Members, OptionalProperty, infer FieldPaths>\n ? VUnion<Type | undefined, Members, \"optional\", FieldPaths>\n : never\n\n/**\n * Type representing whether a property in an object is optional or required.\n *\n * @public\n */\nexport type OptionalProperty = \"optional\" | \"required\";\n\n/**\n * A validator for a Convex value.\n *\n * This should be constructed using the validator builder, {@link v}.\n *\n * A validator encapsulates:\n * - The TypeScript type of this value.\n * - Whether this field should be optional if it's included in an object.\n * - The TypeScript type for the set of index field paths that can be used to\n * build indexes on this value.\n * - A JSON representation of the validator.\n *\n * Specific types of validators contain additional information: for example\n * an `ArrayValidator` contains an `element` property with the validator\n * used to validate each element of the list. Use the shared 'kind' property\n * to identity the type of validator.\n *\n * More validators can be added in future releases so an exhaustive\n * switch statement on validator `kind` should be expected to break\n * in future releases of Convex.\n *\n * @public\n */\nexport type Validator<\n Type,\n IsOptional extends OptionalProperty = \"required\",\n FieldPaths extends string = never,\n> =\n | VId<Type, IsOptional>\n | VString<Type, IsOptional>\n | VFloat64<Type, IsOptional>\n | VInt64<Type, IsOptional>\n | VCommitTs<Type, IsOptional>\n | VBoolean<Type, IsOptional>\n | VNull<Type, IsOptional>\n | VAny<Type, IsOptional>\n | VLiteral<Type, IsOptional>\n | VBytes<Type, IsOptional>\n | VObject<\n Type,\n Record<string, Validator<any, OptionalProperty, any>>,\n IsOptional,\n FieldPaths\n >\n | VArray<Type, Validator<any, \"required\", any>, IsOptional>\n | VRecord<\n Type,\n Validator<string, \"required\", any>,\n Validator<any, \"required\", any>,\n IsOptional,\n FieldPaths\n >\n | VUnion<Type, Validator<any, \"required\", any>[], IsOptional, FieldPaths>;\n\n/**\n * Join together two index field paths.\n *\n * This is used within the validator builder, {@link v}.\n * @public\n */\nexport type JoinFieldPaths<\n Start extends string,\n End extends string,\n> = `${Start}.${End}`;\n\nexport type ObjectFieldType = { fieldType: ValidatorJSON; optional: boolean };\n\nexport type ValidatorJSON =\n | { type: \"null\" }\n | { type: \"number\" }\n | { type: \"bigint\" }\n | { type: \"commitTs\" }\n | { type: \"boolean\" }\n | { type: \"string\" }\n | { type: \"bytes\" }\n | { type: \"any\" }\n | { type: \"literal\"; value: JSONValue }\n | { type: \"id\"; tableName: string }\n | { type: \"array\"; value: ValidatorJSON }\n | {\n type: \"record\";\n keys: RecordKeyValidatorJSON;\n values: RecordValueValidatorJSON;\n }\n | { type: \"object\"; value: Record<string, ObjectFieldType> }\n | { type: \"union\"; value: ValidatorJSON[] };\n\nexport type RecordKeyValidatorJSON =\n | { type: \"string\" }\n | { type: \"id\"; tableName: string }\n | { type: \"union\"; value: RecordKeyValidatorJSON[] };\n\nexport type RecordValueValidatorJSON = ObjectFieldType & { optional: false };\n", "import { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"./index.js\";\nimport {\n OptionalProperty,\n VAny,\n VArray,\n VBoolean,\n VBytes,\n VFloat64,\n VId,\n VCommitTs,\n VInt64,\n VLiteral,\n VNull,\n VObject,\n VOptional,\n VRecord,\n VString,\n VUnion,\n Validator,\n} from \"./validators.js\";\n\n/**\n * The type that all validators must extend.\n *\n * @public\n */\nexport type GenericValidator = Validator<any, any, any>;\n\nexport function isValidator(v: any): v is GenericValidator {\n // Check for the literal `true` marker: a field map can contain a field\n // *named* `isConvexValidator` whose value is a (truthy) validator object.\n return v?.isConvexValidator === true;\n}\n\n/**\n * Coerce an object with validators as properties to a validator.\n * If a validator is passed, return it.\n *\n * @public\n */\nexport function asObjectValidator<\n V extends Validator<any, any, any> | PropertyValidators,\n>(\n obj: V,\n): V extends Validator<any, any, any>\n ? V\n : V extends PropertyValidators\n ? Validator<ObjectType<V>>\n : never {\n if (isValidator(obj)) {\n return obj as any;\n } else {\n return v.object(obj as PropertyValidators) as any;\n }\n}\n\n/**\n * Coerce an object with validators as properties to a validator.\n * If a validator is passed, return it.\n *\n * @public\n */\nexport type AsObjectValidator<\n V extends Validator<any, any, any> | PropertyValidators,\n> =\n V extends Validator<any, any, any>\n ? V\n : V extends PropertyValidators\n ? Validator<ObjectType<V>>\n : never;\n\n/**\n * The validator builder.\n *\n * This builder allows you to build validators for Convex values. Validators\n * are used in two places:\n *\n * 1. **Schema definitions** - to define the shape of documents in your tables.\n * 2. **Function arguments and return values** - to validate inputs and outputs\n * of your Convex queries, mutations, and actions.\n *\n * Always include `args` and `returns` validators on all Convex functions. If a\n * function doesn't return a value, use `returns: v.null()`.\n *\n * **Convex type reference:**\n *\n * | Convex Type | JS/TS Type | Validator |\n * |-------------|---------------|--------------------------------|\n * | Id | `string` | `v.id(\"tableName\")` |\n * | Null | `null` | `v.null()` |\n * | Float64 | `number` | `v.number()` |\n * | Int64 | `bigint` | `v.int64()` |\n * | Boolean | `boolean` | `v.boolean()` |\n * | String | `string` | `v.string()` |\n * | Bytes | `ArrayBuffer` | `v.bytes()` |\n * | Array | `Array` | `v.array(element)` |\n * | Object | `Object` | `v.object({ field: value })` |\n * | Record | `Record` | `v.record(keys, values)` |\n *\n * **Modifiers and meta-types:**\n * - `v.union(member1, member2)` - a value matching at least one validator\n * - `v.literal(\"value\")` - a specific literal string, number, bigint, or boolean\n * - `v.optional(validator)` - makes a property optional in an object (`T | undefined`)\n *\n * **Important notes:**\n * - JavaScript's `undefined` is **not** a valid Convex value. Functions that\n * return `undefined` or have no return will return `null` to the client.\n * Objects with `undefined` values will strip those keys during serialization.\n * For arrays, use an explicit `null` instead.\n * - `v.bigint()` is deprecated, use `v.int64()` instead.\n * - `v.map()` and `v.set()` are not supported. Use `v.array()` of tuples or\n * `v.record()` as alternatives.\n *\n * @example\n * ```typescript\n * import { v } from \"convex/values\";\n *\n * // Use in function definition:\n * export const createUser = mutation({\n * args: {\n * name: v.string(),\n * email: v.string(),\n * age: v.optional(v.number()),\n * },\n * returns: v.id(\"users\"),\n * handler: async (ctx, args) => {\n * return await ctx.db.insert(\"users\", args);\n * },\n * });\n * ```\n *\n * @see https://docs.convex.dev/database/types\n * @see https://docs.convex.dev/functions/validation\n * @public\n */\nexport const v = {\n /**\n * Validates that the value is a document ID for the given table.\n *\n * IDs are strings at runtime but are typed as `Id<\"tableName\">` in\n * TypeScript for type safety.\n *\n * @example\n * ```typescript\n * args: { userId: v.id(\"users\") }\n * ```\n *\n * @param tableName The name of the table.\n */\n id: <TableName extends string>(tableName: TableName) => {\n return new VId<GenericId<TableName>>({\n isOptional: \"required\",\n tableName,\n });\n },\n\n /**\n * Validates that the value is `null`.\n *\n * Use `returns: v.null()` for functions that don't return a meaningful value.\n * JavaScript `undefined` is not a valid Convex value, it is automatically\n * converted to `null`.\n */\n null: () => {\n return new VNull({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is a JavaScript `number` (Convex Float64).\n *\n * Supports all IEEE-754 double-precision floating point numbers including\n * NaN and Infinity.\n *\n * Alias for `v.float64()`.\n */\n number: () => {\n return new VFloat64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is a JavaScript `number` (Convex Float64).\n *\n * Supports all IEEE-754 double-precision floating point numbers.\n */\n float64: () => {\n return new VFloat64({ isOptional: \"required\" });\n },\n\n /**\n * @deprecated Use `v.int64()` instead.\n */\n bigint: () => {\n return new VInt64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is a JavaScript `bigint` (Convex Int64).\n *\n * Supports BigInts between -2^63 and 2^63-1.\n *\n * @example\n * ```typescript\n * args: { timestamp: v.int64() }\n * // Usage: createDoc({ timestamp: 1234567890n })\n * ```\n */\n int64: () => {\n return new VInt64({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is a commit timestamp: an int64 (`bigint`)\n * assigned from the transaction's commit timestamp.\n *\n * An index on a field with this validator orders documents by commit order.\n * Accepts any int64 value; write `db.vars.commitTs` to have the field\n * resolve to the commit timestamp when the mutation commits.\n */\n commitTs: () => {\n return new VCommitTs({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is a `boolean`.\n */\n boolean: () => {\n return new VBoolean({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is a `string`.\n *\n * Strings are stored as UTF-8 and their storage size is calculated as their\n * UTF-8 encoded size.\n */\n string: () => {\n return new VString({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is an `ArrayBuffer` (Convex Bytes).\n *\n * Use for binary data.\n */\n bytes: () => {\n return new VBytes({ isOptional: \"required\" });\n },\n\n /**\n * Validates that the value is exactly equal to the given literal.\n *\n * Useful for discriminated unions and enum-like patterns.\n *\n * @example\n * ```typescript\n * // Discriminated union pattern:\n * v.union(\n * v.object({ kind: v.literal(\"error\"), message: v.string() }),\n * v.object({ kind: v.literal(\"success\"), value: v.number() }),\n * )\n * ```\n *\n * @param literal The literal value to compare against.\n */\n literal: <T extends string | number | bigint | boolean>(literal: T) => {\n return new VLiteral<T>({ isOptional: \"required\", value: literal });\n },\n\n /**\n * Validates that the value is an `Array` where every element matches the\n * given validator.\n *\n * Arrays can have at most 8192 elements.\n *\n * @example\n * ```typescript\n * args: { tags: v.array(v.string()) }\n * args: { coordinates: v.array(v.number()) }\n * args: { items: v.array(v.object({ name: v.string(), qty: v.number() })) }\n * ```\n *\n * @param element The validator for the elements of the array.\n */\n array: <T extends Validator<any, \"required\", any>>(element: T) => {\n return new VArray<T[\"type\"][], T>({ isOptional: \"required\", element });\n },\n\n /**\n * Validates that the value is an `Object` with the specified properties.\n *\n * Objects can have at most 1024 entries. Field names must be non-empty and\n * must not start with `\"$\"` or `\"_\"` (`_` is reserved for system fields\n * like `_id` and `_creationTime`; `$` is reserved for Convex internal use).\n *\n * @example\n * ```typescript\n * args: {\n * user: v.object({\n * name: v.string(),\n * email: v.string(),\n * age: v.optional(v.number()),\n * })\n * }\n * ```\n *\n * @param fields An object mapping property names to their validators.\n */\n object: <T extends PropertyValidators>(fields: T) => {\n return new VObject<ObjectType<T>, T>({ isOptional: \"required\", fields });\n },\n\n /**\n * Validates that the value is a `Record` (object with dynamic keys).\n *\n * Records are objects at runtime but allow dynamic keys, unlike `v.object()`\n * which requires known property names. Keys must be ASCII characters only,\n * non-empty, and not start with `\"$\"` or `\"_\"`.\n *\n * @example\n * ```typescript\n * // Map of user IDs to scores:\n * args: { scores: v.record(v.id(\"users\"), v.number()) }\n *\n * // Map of string keys to string values:\n * args: { metadata: v.record(v.string(), v.string()) }\n * ```\n *\n * @param keys The validator for the keys of the record.\n * @param values The validator for the values of the record.\n */\n record: <\n Key extends Validator<string, \"required\", any>,\n Value extends Validator<any, \"required\", any>,\n >(\n keys: Key,\n values: Value,\n ) => {\n return new VRecord<Record<Infer<Key>, Value[\"type\"]>, Key, Value>({\n isOptional: \"required\",\n key: keys,\n value: values,\n });\n },\n\n /**\n * Validates that the value matches at least one of the given validators.\n *\n * @example\n * ```typescript\n * // Allow string or number:\n * args: { value: v.union(v.string(), v.number()) }\n *\n * // Discriminated union (recommended pattern):\n * v.union(\n * v.object({ kind: v.literal(\"text\"), body: v.string() }),\n * v.object({ kind: v.literal(\"image\"), url: v.string() }),\n * )\n *\n * // Nullable value:\n * returns: v.union(v.object({ ... }), v.null())\n * ```\n *\n * @param members The validators to match against.\n */\n union: <T extends Validator<any, \"required\", any>[]>(...members: T) => {\n return new VUnion<T[number][\"type\"], T>({\n isOptional: \"required\",\n members,\n });\n },\n\n /**\n * A validator that accepts any Convex value without validation.\n *\n * Prefer using specific validators when possible for better type safety\n * and runtime validation.\n */\n any: () => {\n return new VAny({ isOptional: \"required\" });\n },\n\n /**\n * Makes a property optional in an object validator.\n *\n * An optional property can be omitted entirely when creating a document or\n * calling a function. This is different from `v.nullable()` which requires\n * the property to be present but allows `null`.\n *\n * @example\n * ```typescript\n * v.object({\n * name: v.string(), // required\n * nickname: v.optional(v.string()), // can be omitted\n * })\n *\n * // Valid: { name: \"Alice\" }\n * // Valid: { name: \"Alice\", nickname: \"Ali\" }\n * // Invalid: { name: \"Alice\", nickname: null } - use v.nullable() for this\n * ```\n *\n * @param value The property value validator to make optional.\n */\n optional: <T extends GenericValidator>(value: T) => {\n return value.asOptional() as VOptional<T>;\n },\n\n /**\n * Allows a value to be either the given type or `null`.\n *\n * This is shorthand for `v.union(value, v.null())`. Unlike `v.optional()`,\n * the property must still be present, but may be `null`.\n *\n * @example\n * ```typescript\n * v.object({\n * name: v.string(),\n * deletedAt: v.nullable(v.number()), // must be present, can be null\n * })\n *\n * // Valid: { name: \"Alice\", deletedAt: null }\n * // Valid: { name: \"Alice\", deletedAt: 1234567890 }\n * // Invalid: { name: \"Alice\" } - deletedAt is required\n * ```\n */\n nullable: <T extends Validator<any, \"required\", any>>(value: T) => {\n return v.union(value, v.null());\n },\n};\n\n/**\n * Validators for each property of an object.\n *\n * This is represented as an object mapping the property name to its\n * {@link Validator}.\n *\n * @public\n */\nexport type PropertyValidators = Record<\n string,\n Validator<any, OptionalProperty, any>\n>;\n\n/**\n * Compute the type of an object from {@link PropertyValidators}.\n *\n * @public\n */\nexport type ObjectType<Fields extends PropertyValidators> = Expand<\n // Map each key to the corresponding property validator's type making\n // the optional ones optional.\n {\n // This `Exclude<..., undefined>` does nothing unless\n // the tsconfig.json option `\"exactOptionalPropertyTypes\": true,`\n // is used. When it is it results in a more accurate type.\n // When it is not the `Exclude` removes `undefined` but it is\n // added again by the optional property.\n [Property in OptionalKeys<Fields>]?: Exclude<\n Infer<Fields[Property]>,\n undefined\n >;\n } & {\n [Property in RequiredKeys<Fields>]: Infer<Fields[Property]>;\n }\n>;\n\ntype OptionalKeys<PropertyValidators extends Record<string, GenericValidator>> =\n {\n [Property in keyof PropertyValidators]: PropertyValidators[Property][\"isOptional\"] extends \"optional\"\n ? Property\n : never;\n }[keyof PropertyValidators];\n\ntype RequiredKeys<PropertyValidators extends Record<string, GenericValidator>> =\n Exclude<keyof PropertyValidators, OptionalKeys<PropertyValidators>>;\n\n/**\n * Extract a TypeScript type from a validator.\n *\n * Example usage:\n * ```ts\n * const objectSchema = v.object({\n * property: v.string(),\n * });\n * type MyObject = Infer<typeof objectSchema>; // { property: string }\n * ```\n * @typeParam V - The type of a {@link Validator} constructed with {@link v}.\n *\n * @public\n */\nexport type Infer<T extends Validator<any, OptionalProperty, any>> = T[\"type\"];\n", "import { Value, stringifyValueForError } from \"./value.js\";\n\nconst IDENTIFYING_FIELD = Symbol.for(\"ConvexError\");\n\nexport class ConvexError<TData extends Value> extends Error {\n name = \"ConvexError\";\n data: TData;\n [IDENTIFYING_FIELD] = true;\n\n constructor(data: TData) {\n super(typeof data === \"string\" ? data : stringifyValueForError(data));\n this.data = data;\n }\n}\n", "/**\n * Taken from https://github.com/rocicorp/compare-utf8/blob/main/LICENSE\n * (Apache Version 2.0, January 2004)\n */\n\n/**\n * This is copied here instead of added as a dependency to avoid bundling issues.\n */\n\n/**\n * Compares two JavaScript strings as if they were UTF-8 encoded byte arrays.\n * @param {string} a\n * @param {string} b\n * @returns {number}\n */\nexport function compareUTF8(a: string, b: string): number {\n const aLength = a.length;\n const bLength = b.length;\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; ) {\n const aCodePoint = a.codePointAt(i)!;\n const bCodePoint = b.codePointAt(i)!;\n if (aCodePoint !== bCodePoint) {\n // Code points below 0x80 are represented the same way in UTF-8 as in\n // UTF-16.\n if (aCodePoint < 0x80 && bCodePoint < 0x80) {\n return aCodePoint - bCodePoint;\n }\n\n // get the UTF-8 bytes for the code points\n const aLength = utf8Bytes(aCodePoint, aBytes);\n const bLength = utf8Bytes(bCodePoint, bBytes);\n return compareArrays(aBytes, aLength, bBytes, bLength);\n }\n\n i += utf16LengthForCodePoint(aCodePoint);\n }\n\n return aLength - bLength;\n}\n\n/**\n * @param {number[]} a\n * @param {number} aLength\n * @param {number[]} b\n * @param {number} bLength\n * @returns {number}\n */\nfunction compareArrays(\n a: number[],\n aLength: number,\n b: number[],\n bLength: number,\n) {\n const length = Math.min(aLength, bLength);\n for (let i = 0; i < length; i++) {\n const aValue = a[i];\n const bValue = b[i];\n if (aValue !== bValue) {\n return aValue - bValue;\n }\n }\n return aLength - bLength;\n}\n\n/**\n * @param {number} aCodePoint\n * @returns {number}\n */\nexport function utf16LengthForCodePoint(aCodePoint: number) {\n return aCodePoint > 0xffff ? 2 : 1;\n}\n\n// 2 preallocated arrays for utf8Bytes.\nconst arr = () => Array.from({ length: 4 }, () => 0);\nconst aBytes = arr();\nconst bBytes = arr();\n\n/**\n * @param {number} codePoint\n * @param {number[]} bytes\n * @returns {number}\n */\nfunction utf8Bytes(codePoint: number, bytes: number[]) {\n if (codePoint < 0x80) {\n bytes[0] = codePoint;\n return 1;\n }\n\n let count;\n let offset;\n\n if (codePoint <= 0x07ff) {\n count = 1;\n offset = 0xc0;\n } else if (codePoint <= 0xffff) {\n count = 2;\n offset = 0xe0;\n } else if (codePoint <= 0x10ffff) {\n count = 3;\n offset = 0xf0;\n } else {\n throw new Error(\"Invalid code point\");\n }\n\n bytes[0] = (codePoint >> (6 * count)) + offset;\n let i = 1;\n for (; count > 0; count--) {\n const temp = codePoint >> (6 * (count - 1));\n bytes[i++] = 0x80 | (temp & 0x3f);\n }\n return i;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThan(a: string, b: string) {\n return compareUTF8(a, b) > 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function greaterThanEq(a: string, b: string) {\n return compareUTF8(a, b) >= 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThan(a: string, b: string) {\n return compareUTF8(a, b) < 0;\n}\n\n/**\n * @param {string} a\n * @param {string} b\n * @returns {boolean}\n */\nexport function lessThanEq(a: string, b: string) {\n return compareUTF8(a, b) <= 0;\n}\n", "/* eslint-disable no-console */ // This is the one file where we can `console.log` for the default logger implementation.\nimport { ConvexError, Value } from \"../values/index.js\";\nimport { FunctionFailure } from \"./sync/function_result.js\";\n\n// This is blue #9 from https://www.radix-ui.com/docs/colors/palette-composition/the-scales\n// It must look good in both light and dark mode.\nconst INFO_COLOR = \"color:rgb(0, 145, 255)\";\n\nexport type UdfType = \"query\" | \"mutation\" | \"action\" | \"any\";\n\nfunction prefix_for_source(source: UdfType) {\n switch (source) {\n case \"query\":\n return \"Q\";\n case \"mutation\":\n return \"M\";\n case \"action\":\n return \"A\";\n case \"any\":\n return \"?\";\n }\n}\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/**\n * A logger that can be used to log messages. By default, this is a wrapper\n * around `console`, but can be configured to not log at all or to log somewhere\n * else.\n */\nexport type Logger = {\n logVerbose(...args: any[]): void;\n log(...args: any[]): void;\n warn(...args: any[]): void;\n error(...args: any[]): void;\n};\n\nexport class DefaultLogger implements Logger {\n private _onLogLineFuncs: Record<\n string,\n (level: LogLevel, ...args: any[]) => void\n >;\n private _verbose: boolean;\n\n constructor(options: { verbose: boolean }) {\n this._onLogLineFuncs = {};\n this._verbose = options.verbose;\n }\n\n addLogLineListener(\n func: (level: LogLevel, ...args: any[]) => void,\n ): () => void {\n let id = Math.random().toString(36).substring(2, 15);\n for (let i = 0; i < 10; i++) {\n if (this._onLogLineFuncs[id] === undefined) {\n break;\n }\n id = Math.random().toString(36).substring(2, 15);\n }\n this._onLogLineFuncs[id] = func;\n return () => {\n delete this._onLogLineFuncs[id];\n };\n }\n\n logVerbose(...args: any[]) {\n if (this._verbose) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"debug\", `${new Date().toISOString()}`, ...args);\n }\n }\n }\n\n log(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"info\", ...args);\n }\n }\n\n warn(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"warn\", ...args);\n }\n }\n\n error(...args: any[]) {\n for (const func of Object.values(this._onLogLineFuncs)) {\n func(\"error\", ...args);\n }\n }\n}\n\nexport function instantiateDefaultLogger(options: {\n verbose: boolean;\n}): Logger {\n const logger = new DefaultLogger(options);\n logger.addLogLineListener((level, ...args) => {\n switch (level) {\n case \"debug\":\n console.debug(...args);\n break;\n case \"info\":\n console.log(...args);\n break;\n case \"warn\":\n console.warn(...args);\n break;\n case \"error\":\n console.error(...args);\n break;\n default: {\n level satisfies never;\n console.log(...args);\n }\n }\n });\n return logger;\n}\n\nexport function instantiateNoopLogger(options: { verbose: boolean }): Logger {\n return new DefaultLogger(options);\n}\n\nexport function logForFunction(\n logger: Logger,\n type: \"info\" | \"error\",\n source: UdfType,\n udfPath: string,\n message: string | { errorData: Value },\n) {\n const prefix = prefix_for_source(source);\n\n if (typeof message === \"object\") {\n message = `ConvexError ${JSON.stringify(message.errorData, null, 2)}`;\n }\n if (type === \"info\") {\n const match = message.match(/^\\[.*?\\] /);\n if (match === null) {\n logger.error(\n `[CONVEX ${prefix}(${udfPath})] Could not parse console.log`,\n );\n return;\n }\n const level = message.slice(1, match[0].length - 2);\n const args = message.slice(match[0].length);\n\n logger.log(`%c[CONVEX ${prefix}(${udfPath})] [${level}]`, INFO_COLOR, args);\n } else {\n logger.error(`[CONVEX ${prefix}(${udfPath})] ${message}`);\n }\n}\n\nexport function logFatalError(logger: Logger, message: string): Error {\n const errorMessage = `[CONVEX FATAL ERROR] ${message}`;\n logger.error(errorMessage);\n return new Error(errorMessage);\n}\n\nexport function createHybridErrorStacktrace(\n source: UdfType,\n udfPath: string,\n result: FunctionFailure,\n): string {\n const prefix = prefix_for_source(source);\n return `[CONVEX ${prefix}(${udfPath})] ${result.errorMessage}\\n Called by client`;\n}\n\nexport function forwardData(\n result: FunctionFailure,\n error: ConvexError<string>,\n) {\n (error as ConvexError<any>).data = result.errorData;\n return error;\n}\n", "/**\n * A symbol for accessing the name of a {@link FunctionReference} at runtime.\n */\nexport const functionName = Symbol.for(\"functionName\");\n", "import { functionName } from \"../functionName.js\";\n\nexport const toReferencePath = Symbol.for(\"toReferencePath\");\n\n// Multiple instances of the same Symbol.for() are equal at runtime but not\n// at type-time, so `[toReferencePath]` properties aren't used in types.\n// Use this function to set the property invisibly.\nexport function setReferencePath<T>(obj: T, value: string) {\n (obj as any)[toReferencePath] = value;\n}\n\nexport function extractReferencePath(reference: any): string | null {\n return reference[toReferencePath] ?? null;\n}\n\nexport function isFunctionHandle(s: string): boolean {\n return s.startsWith(\"function://\");\n}\n\nexport function getFunctionAddress(functionReference: any) {\n // The `run*` syscalls expect either a UDF path at \"name\" or a serialized\n // reference at \"reference\". Dispatch on `functionReference` to coerce\n // it to one or the other.\n let functionAddress;\n\n // Legacy path for passing in UDF paths directly as function references.\n if (typeof functionReference === \"string\") {\n if (isFunctionHandle(functionReference)) {\n functionAddress = { functionHandle: functionReference };\n } else {\n functionAddress = { name: functionReference };\n }\n }\n // Path for passing in a `FunctionReference`, either from `api` or directly\n // created from a UDF path with `makeFunctionReference`.\n else if (functionReference[functionName]) {\n functionAddress = { name: functionReference[functionName] };\n }\n // Reference to a component's function derived from `app` or `component`.\n else {\n const referencePath = extractReferencePath(functionReference);\n if (!referencePath) {\n throw new Error(`${functionReference} is not a functionReference`);\n }\n functionAddress = { reference: referencePath };\n }\n return functionAddress;\n}\n", "import {\n EmptyObject,\n DefaultFunctionArgs,\n FunctionVisibility,\n RegisteredAction,\n RegisteredMutation,\n RegisteredQuery,\n} from \"./registration.js\";\nimport { Expand, UnionToIntersection } from \"../type_utils.js\";\nimport { PaginationOptions, PaginationResult } from \"./pagination.js\";\nimport { functionName } from \"./functionName.js\";\nimport { getFunctionAddress } from \"./components/paths.js\";\n\n/**\n * The type of a Convex function.\n *\n * @public\n */\nexport type FunctionType = \"query\" | \"mutation\" | \"action\";\n\n/**\n * A reference to a registered Convex function.\n *\n * You can create a {@link FunctionReference} using the generated `api` utility:\n * ```js\n * import { api } from \"../convex/_generated/api\";\n *\n * const reference = api.myModule.myFunction;\n * ```\n *\n * If you aren't using code generation, you can create references using\n * {@link anyApi}:\n * ```js\n * import { anyApi } from \"convex/server\";\n *\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * Function references can be used to invoke functions from the client. For\n * example, in React you can pass references to the {@link react.useQuery} hook:\n * ```js\n * const result = useQuery(api.myModule.myFunction);\n * ```\n *\n * If you want to accept a `FunctionReference` as a callback argument, prefer\n * typing the callback parameter as {@link FunctionReference_future}.\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments to this function. This is an object mapping\n * argument names to their types.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n /**\n * To read the arguments for a `FunctionReference`, prefer\n * {@link FunctionArgs}.\n *\n * This slot will be removed in a future version.\n *\n * @deprecated\n */\n _args: Args;\n /**\n * To read the return type of a `FunctionReference`, prefer\n * {@link FunctionReturnType}.\n *\n * This slot will be removed in a future version.\n *\n * @deprecated\n */\n _returnType: ReturnType;\n _componentPath: ComponentPath;\n /**\n * To read the arguments or return type of a `FunctionReference`, prefer\n * {@link FunctionArgs} and {@link FunctionReturnType}.\n */\n // This phantom slot exists so that a `FunctionReference` can be checked\n // against a `FunctionReference_future`. It changes nothing about how two\n // `FunctionReference`s compare with each other.\n //\n // The slot models the function itself: it puts `Args` in a contravariant\n // position and `ReturnType` in a covariant one, so the slot alone is enough\n // to compare a reference the way TypeScript compares two functions.\n //\n // In that comparison the `keys` parameter has an important role. It carries\n // the keys of `Args`, so that checking a `FunctionReference` against a\n // `FunctionReference_future` also checks that every key the consumer passes\n // is a key the function declares. TypeScript treats a surplus property as\n // harmless, but a Convex argument validator rejects it, so this is what\n // makes the comparison match the runtime. See `FunctionReferenceArgKeys`.\n _fn?(args: Args, keys: FunctionReferenceArgKeys<Args>): ReturnType;\n};\n\n/**\n * The keys of a reference's arguments.\n *\n * `0 extends 1 & Args` holds only when `Args` is `any`. That maps to `any`\n * rather than `keyof any` so that an untyped reference neither imposes nor\n * fails the key check in either direction. Arguments with an index signature,\n * such as `EmptyObject` and `DefaultFunctionArgs`, map to `string`, which\n * accepts every key and leaves the decision to the first parameter.\n */\ntype ArgKeys<Args> = 0 extends 1 & Args ? any : keyof Args;\n\n/**\n * The second parameter of `FunctionReference._fn`.\n *\n * Wrapping the keys in a function of a function puts them two parameters deep,\n * so comparing this parameter contravariantly checks that every key the\n * consumer passes is one the function declares. That is the check a Convex\n * argument validator performs and an ordinary function-type comparison skips.\n *\n * The union with {@link UncheckedArgKeys} is what keeps two\n * `FunctionReference`s comparing as they did before this slot existed. Every\n * `FunctionReferenceArgKeys` is assignable to `UncheckedArgKeys`, so between\n * two `FunctionReference`s the keys always relate and only `_args` decides.\n * {@link FunctionReference_futureArgKeys} is not assignable to it, so a\n * `FunctionReference` compared against a `FunctionReference_future` has to\n * satisfy the real check.\n */\ntype FunctionReferenceArgKeys<Args> = 0 extends 1 & Args\n ? any\n : ((keys: (key: ArgKeys<Args>) => void) => void) | UncheckedArgKeys;\n\n/**\n * A keys parameter that every {@link FunctionReferenceArgKeys} is assignable\n * to, and that no {@link FunctionReference_futureArgKeys} is: `unknown` for\n * the second parameter accepts the former's missing parameter and rejects the\n * latter's `never`.\n */\ntype UncheckedArgKeys = (keys: never, unchecked?: unknown) => void;\n\n/**\n * The second parameter of `FunctionReference_future._fn`. The same shape as\n * {@link FunctionReferenceArgKeys} plus a `guard` parameter that keeps it out\n * of {@link UncheckedArgKeys}.\n */\ntype FunctionReference_futureArgKeys<Args> = 0 extends 1 & Args\n ? any\n : (keys: (key: ArgKeys<Args>) => void, guard?: never) => void;\n\n/**\n * A reference to a Convex function whose arguments are checked closer to the\n * way Convex checks them at runtime.\n *\n * Use this instead of {@link FunctionReference} when you accept someone else's\n * Convex function as a callback and know which arguments you will pass it.\n *\n * A plain `FunctionReference` gets a couple things backwards: it accepts a\n * function requiring arguments you never pass, and rejects a function\n * accepting broader values than you pass. An ordinary TypeScript function type\n * doesn't map perfectly either: it treats a surplus argument as harmless,\n * where a Convex validator rejects it.\n *\n * This type melds regular TypeScript function reference behavior with top\n * level checking of arguments to prevent surplus arguments from hitting\n * runtime validation errors. The caveat: a surplus key inside a nested object,\n * an array element, or one arm of a union passes the type check and fails the\n * validator at runtime.\n *\n * ```ts\n * import { FunctionReference_future } from \"convex/server\";\n *\n * declare function onComplete(\n * fn: FunctionReference_future<\n * \"mutation\",\n * \"internal\",\n * { taskId: string; force: boolean },\n * null\n * >,\n * ): void;\n *\n * // Takes exactly `{ taskId: string; force: boolean }`.\n * onComplete(internal.tasks.finish);\n * // Takes `{ taskId: string | number; force?: boolean }`: calling it is safe.\n * onComplete(internal.tasks.finishLoosely);\n * // Requires a `reason` argument that `onComplete` never passes.\n * onComplete(internal.tasks.finishWithReason);\n * // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ rejected\n * // Takes only `{ taskId: string }`: its validator would reject `force`.\n * onComplete(internal.tasks.finishById);\n * // ~~~~~~~~~~~~~~~~~~~~~~~~ rejected\n * ```\n *\n * A value of this type is usable with `ctx.runMutation`,\n * `ctx.scheduler.runAfter`, `createFunctionHandle`, and everything else in\n * this package that takes a reference, all of which accept either kind.\n *\n * It is *not* assignable to a plain `FunctionReference`. Code that wants to\n * accept both kinds should take\n * `FunctionReference<...> | FunctionReference_future<...>` and read arguments\n * and return types through {@link FunctionArgs} and {@link FunctionReturnType}.\n *\n * Argument checking here relies on `strictFunctionTypes` (implied by `strict`)\n * and is skipped for projects that disable it. Everything else about the\n * reference is compared exactly as `FunctionReference` compares it.\n *\n * @typeParam Type - The type of the function (\"query\", \"mutation\", or \"action\").\n * @typeParam Visibility - The visibility of the function (\"public\" or \"internal\").\n * @typeParam Args - The arguments the consumer of the reference will pass.\n * @typeParam ReturnType - The return type of this function.\n * @public\n */\nexport type FunctionReference_future<\n Type extends FunctionType,\n Visibility extends FunctionVisibility = \"public\",\n Args extends DefaultFunctionArgs = any,\n ReturnType = any,\n ComponentPath = string | undefined,\n> = {\n _type: Type;\n _visibility: Visibility;\n _componentPath: ComponentPath;\n // Declared as a *property* rather than a method: TypeScript compares method\n // parameters bivariantly and would not check anything. The explicit\n // `| undefined` is needed because an optional method on the source side\n // (`FunctionReference._fn`) carries a real `undefined` in its type, which\n // `exactOptionalPropertyTypes` would otherwise reject.\n //\n // Both parameters are compared contravariantly: the first checks that the\n // consumer's arguments satisfy the function's, the second that the consumer\n // passes no key the function does not declare. See\n // `FunctionReference_futureArgKeys`.\n _fn?:\n | ((args: Args, keys: FunctionReference_futureArgKeys<Args>) => ReturnType)\n | undefined;\n};\n\n/**\n * Get the name of a function from a {@link FunctionReference}.\n *\n * The name is a string like \"myDir/myModule:myFunction\". If the exported name\n * of the function is `\"default\"`, the function name is omitted\n * (e.g. \"myDir/myModule\").\n *\n * @param functionReference - A {@link FunctionReference} to get the name of.\n * @returns A string of the function's name.\n *\n * @public\n */\nexport function getFunctionName(\n functionReference:\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n): string {\n const address = getFunctionAddress(functionReference);\n\n if (address.name === undefined) {\n if (address.functionHandle !== undefined) {\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received function handle ${address.functionHandle}`,\n );\n } else if (address.reference !== undefined) {\n throw new Error(\n `Expected function reference in the current component like \"api.file.func\" or \"internal.file.func\", but received reference ${address.reference}`,\n );\n }\n throw new Error(\n `Expected function reference like \"api.file.func\" or \"internal.file.func\", but received ${JSON.stringify(address)}`,\n );\n }\n // Both a legacy thing and also a convenience for interactive use:\n // the types won't check but a string is always allowed at runtime.\n if (typeof functionReference === \"string\") return functionReference;\n\n // Two different runtime values for FunctionReference implement this\n // interface: api objects returned from `createApi()` and standalone\n // function reference objects returned from makeFunctionReference.\n const name = (functionReference as any)[functionName];\n if (!name) {\n throw new Error(`${functionReference as any} is not a functionReference`);\n }\n return name;\n}\n\n/**\n * FunctionReferences generally come from generated code, but in custom clients\n * it may be useful to be able to build one manually.\n *\n * Real function references are empty objects at runtime, but the same interface\n * can be implemented with an object for tests and clients which don't use\n * code generation.\n *\n * @param name - The identifier of the function. E.g. `path/to/file:functionName`\n * @public\n */\nexport function makeFunctionReference<\n type extends FunctionType,\n args extends DefaultFunctionArgs = any,\n ret = any,\n>(name: string): FunctionReference<type, \"public\", args, ret> {\n return { [functionName]: name } as unknown as FunctionReference<\n type,\n \"public\",\n args,\n ret\n >;\n}\n\n/**\n * Create a runtime API object that implements {@link AnyApi}.\n *\n * This allows accessing any path regardless of what directories, modules,\n * or functions are defined.\n *\n * @param pathParts - The path to the current node in the API.\n * @returns An {@link AnyApi}\n * @public\n */\nfunction createApi(pathParts: string[] = []): AnyApi {\n const handler: ProxyHandler<object> = {\n get(_, prop: string | symbol) {\n if (typeof prop === \"string\") {\n const newParts = [...pathParts, prop];\n return createApi(newParts);\n } else if (prop === functionName) {\n if (pathParts.length < 2) {\n const found = [\"api\", ...pathParts].join(\".\");\n throw new Error(\n `API path is expected to be of the form \\`api.moduleName.functionName\\`. Found: \\`${found}\\``,\n );\n }\n const path = pathParts.slice(0, -1).join(\"/\");\n const exportName = pathParts[pathParts.length - 1];\n if (exportName === \"default\") {\n return path;\n } else {\n return path + \":\" + exportName;\n }\n } else if (prop === Symbol.toStringTag) {\n return \"FunctionReference\";\n } else {\n return undefined;\n }\n },\n };\n\n return new Proxy({}, handler);\n}\n\n/**\n * Given an export from a module, convert it to a {@link FunctionReference}\n * if it is a Convex function.\n */\nexport type FunctionReferenceFromExport<Export> =\n Export extends RegisteredQuery<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"query\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredMutation<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"mutation\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : Export extends RegisteredAction<\n infer Visibility,\n infer Args,\n infer ReturnValue\n >\n ? FunctionReference<\n \"action\",\n Visibility,\n Args,\n ConvertReturnType<ReturnValue>\n >\n : never;\n\n/**\n * Given a module, convert all the Convex functions into\n * {@link FunctionReference}s and remove the other exports.\n *\n * BE CAREFUL WHEN EDITING THIS!\n *\n * This is written carefully to preserve jumping to function definitions using\n * cmd+click. If you edit it, please test that cmd+click still works.\n */\ntype FunctionReferencesInModule<Module extends Record<string, any>> = {\n -readonly [ExportName in keyof Module as Module[ExportName][\"isConvexFunction\"] extends true\n ? ExportName\n : never]: FunctionReferenceFromExport<Module[ExportName]>;\n};\n\n/**\n * Given a path to a module and it's type, generate an API type for this module.\n *\n * This is a nested object according to the module's path.\n */\ntype ApiForModule<\n ModulePath extends string,\n Module extends object,\n> = ModulePath extends `${infer First}/${infer Second}`\n ? {\n [_ in First]: ApiForModule<Second, Module>;\n }\n : { [_ in ModulePath]: FunctionReferencesInModule<Module> };\n\n/**\n * Given the types of all modules in the `convex/` directory, construct the type\n * of `api`.\n *\n * `api` is a utility for constructing {@link FunctionReference}s.\n *\n * @typeParam AllModules - A type mapping module paths (like `\"dir/myModule\"`) to\n * the types of the modules.\n * @public\n */\nexport type ApiFromModules<AllModules extends Record<string, object>> =\n FilterApi<\n ApiFromModulesAllowEmptyNodes<AllModules>,\n FunctionReference<any, any, any, any>\n >;\n\ntype ApiFromModulesAllowEmptyNodes<AllModules extends Record<string, object>> =\n ExpandModulesAndDirs<\n UnionToIntersection<\n {\n [ModulePath in keyof AllModules]: ApiForModule<\n ModulePath & string,\n AllModules[ModulePath]\n >;\n }[keyof AllModules]\n >\n >;\n\ntype FilterKeysInApi<key, API, Predicate> = API extends Predicate\n ? key\n : API extends FunctionReference<any, any, any, any>\n ? never\n : FilterApi<API, Predicate> extends Record<string, never>\n ? never\n : key;\n\n/**\n * @public\n *\n * Filter a Convex deployment api object for functions which meet criteria,\n * for example all public queries.\n */\nexport type FilterApi<API, Predicate> = Expand<{\n [mod in keyof API as FilterKeysInApi<\n mod,\n API[mod],\n Predicate\n >]: API[mod] extends Predicate ? API[mod] : FilterApi<API[mod], Predicate>;\n}>;\n\n/**\n * Given an api of type API and a FunctionReference subtype, return an api object\n * containing only the function references that match.\n *\n * ```ts\n * const q = filterApi<typeof api, FunctionReference<\"query\">>(api)\n * ```\n *\n * @public\n */\nexport function filterApi<API, Predicate>(api: API): FilterApi<API, Predicate> {\n return api as any;\n}\n\n// These just* API filter helpers require no type parameters so are useable from JavaScript.\n/** @public */\nexport function justInternal<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"internal\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPublic<API>(\n api: API,\n): FilterApi<API, FunctionReference<any, \"public\", any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justQueries<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"query\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justMutations<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justActions<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"action\", any, any, any>> {\n return api as any;\n}\n\n/** @public */\nexport function justPaginatedQueries<API>(\n api: API,\n): FilterApi<\n API,\n FunctionReference<\n \"query\",\n any,\n { paginationOpts: PaginationOptions },\n PaginationResult<any>\n >\n> {\n return api as any;\n}\n\n/** @public */\nexport function justSchedulable<API>(\n api: API,\n): FilterApi<API, FunctionReference<\"mutation\" | \"action\", any, any, any>> {\n return api as any;\n}\n\n/**\n * Like {@link Expand}, this simplifies how TypeScript displays object types.\n * The differences are:\n * 1. This version is recursive.\n * 2. This stops recursing when it hits a {@link FunctionReference}.\n */\ntype ExpandModulesAndDirs<ObjectType> = ObjectType extends AnyFunctionReference\n ? ObjectType\n : {\n [Key in keyof ObjectType]: ExpandModulesAndDirs<ObjectType[Key]>;\n };\n\n/**\n * A {@link FunctionReference} of any type and any visibility with any\n * arguments and any return type.\n *\n * @public\n */\nexport type AnyFunctionReference = FunctionReference<any, any>;\n\ntype AnyModuleDirOrFunc = {\n [key: string]: AnyModuleDirOrFunc;\n} & AnyFunctionReference;\n\n/**\n * The type that Convex api objects extend. If you were writing an api from\n * scratch it should extend this type.\n *\n * @public\n */\nexport type AnyApi = Record<string, Record<string, AnyModuleDirOrFunc>>;\n\n/**\n * Recursive partial API, useful for defining a subset of an API when mocking\n * or building custom api objects.\n *\n * @public\n */\nexport type PartialApi<API> = {\n [mod in keyof API]?: API[mod] extends FunctionReference<any, any, any, any>\n ? API[mod]\n : PartialApi<API[mod]>;\n};\n\n/**\n * A utility for constructing {@link FunctionReference}s in projects that\n * are not using code generation.\n *\n * You can create a reference to a function like:\n * ```js\n * const reference = anyApi.myModule.myFunction;\n * ```\n *\n * This supports accessing any path regardless of what directories and modules\n * are in your project. All function references are typed as\n * {@link AnyFunctionReference}.\n *\n *\n * If you're using code generation, use `api` from `convex/_generated/api`\n * instead. It will be more type-safe and produce better auto-complete\n * in your editor.\n *\n * @public\n */\nexport const anyApi: AnyApi = createApi() as any;\n\n/**\n * Given a {@link FunctionReference} or {@link FunctionReference_future}, get\n * the arguments of the function.\n *\n * This is represented as an object mapping argument names to values.\n *\n * @public\n */\nexport type FunctionArgs<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n> = ExtractSignature<FuncRef>[\"args\"];\n\n// The arguments and return type a reference declares. A `FunctionReference`\n// declares them in `_args` and `_returnType`, a `FunctionReference_future`\n// only in its `_fn` slot. Reading the named slots first also covers a\n// reference typed by an older copy of this package, which has no `_fn`.\ntype ExtractSignature<FuncRef> = FuncRef extends {\n _args: infer Args;\n _returnType: infer R;\n}\n ? { args: Args; returnType: R }\n : FuncRef extends {\n _fn?: ((args: infer Args, keys: never) => infer R) | undefined;\n }\n ? { args: Args; returnType: R }\n : { args: any; returnType: any };\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`.\n *\n * This type is used to make methods involving arguments type safe while allowing\n * skipping the arguments for functions that don't require arguments.\n *\n * @public\n */\nexport type OptionalRestArgs<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n> =\n FunctionArgs<FuncRef> extends EmptyObject\n ? [args?: EmptyObject]\n : [args: FunctionArgs<FuncRef>];\n\n/**\n * A tuple type of the (maybe optional) arguments to `FuncRef`, followed by an options\n * object of type `Options`.\n *\n * This type is used to make methods like `useQuery` type-safe while allowing\n * 1. Skipping arguments for functions that don't require arguments.\n * 2. Skipping the options object.\n * @public\n */\nexport type ArgsAndOptions<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n Options,\n> =\n FunctionArgs<FuncRef> extends EmptyObject\n ? [args?: EmptyObject, options?: Options]\n : [args: FunctionArgs<FuncRef>, options?: Options];\n\n/**\n * Given a {@link FunctionReference} or {@link FunctionReference_future}, get\n * the return type of the function.\n *\n * @public\n */\nexport type FunctionReturnType<\n FuncRef extends\n | FunctionReference<any, any>\n | FunctionReference_future<any, any>,\n> = ExtractSignature<FuncRef>[\"returnType\"];\n\ntype UndefinedToNull<T> = T extends void ? null : T;\n\ntype NullToUndefinedOrNull<T> = T extends null ? T | undefined | void : T;\n\n/**\n * Convert the return type of a function to it's client-facing format.\n *\n * This means:\n * - Converting `undefined` and `void` to `null`\n * - Removing all `Promise` wrappers\n */\nexport type ConvertReturnType<T> = UndefinedToNull<Awaited<T>>;\n\nexport type ValidatorTypeToReturnType<T> =\n | Promise<NullToUndefinedOrNull<T>>\n | NullToUndefinedOrNull<T>;\n", "// Implements an unsigned long.\n// This is a subset of https://github.com/dcodeIO/Long.js,\n// vendored to decrease bundle size.\n// Copyright Daniel Wirtz <dcode@dcode.io>\n// License: Apache Version 2.0\n/*\n\n Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\n TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n 1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n 2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n 3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n 4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n 5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n 6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n 7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n 8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n 9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\n END OF TERMS AND CONDITIONS\n\n APPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\n Copyright 2023 Daniel Wirtz <dcode@dcode.io>\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// This works... but don't try to compare one to a real Long.js Long!\n// For internal use only.\n// `| 0` assures the runtime that we are using integer arithmetic\nexport class Long {\n low: number;\n high: number;\n __isUnsignedLong__: boolean;\n\n static isLong(obj: Long) {\n return (obj && obj.__isUnsignedLong__) === true;\n }\n\n constructor(low: number, high: number) {\n this.low = low | 0;\n this.high = high | 0;\n this.__isUnsignedLong__ = true;\n }\n\n // prettier-ignore\n static fromBytesLE(bytes: number[]): Long {\n return new Long(\n bytes[0] |\n bytes[1] << 8 |\n bytes[2] << 16 |\n bytes[3] << 24,\n bytes[4] |\n bytes[5] << 8 |\n bytes[6] << 16 |\n bytes[7] << 24,\n );\n }\n\n // prettier-ignore\n toBytesLE() {\n const hi = this.high;\n const lo = this.low;\n return [\n lo & 0xff,\n lo >>> 8 & 0xff,\n lo >>> 16 & 0xff,\n lo >>> 24,\n hi & 0xff,\n hi >>> 8 & 0xff,\n hi >>> 16 & 0xff,\n hi >>> 24\n ];\n }\n\n static fromNumber(value: number) {\n if (isNaN(value)) return UZERO;\n if (value < 0) return UZERO;\n if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE;\n return new Long(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0);\n }\n\n toString() {\n return (\n BigInt(this.high) * BigInt(TWO_PWR_32_DBL) +\n BigInt(this.low)\n ).toString();\n }\n\n equals(other: Long) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.high >>> 31 === 1 && other.high >>> 31 === 1) return false;\n return this.high === other.high && this.low === other.low;\n }\n\n notEquals(other: Long) {\n return !this.equals(other);\n }\n\n comp(other: Long) {\n if (!Long.isLong(other)) other = Long.fromValue(other);\n if (this.equals(other)) return 0;\n return other.high >>> 0 > this.high >>> 0 ||\n (other.high === this.high && other.low >>> 0 > this.low >>> 0)\n ? -1\n : 1;\n }\n\n lessThanOrEqual(other: Long) {\n return this.comp(/* validates */ other) <= 0;\n }\n\n static fromValue(val: any) {\n if (typeof val === \"number\") return Long.fromNumber(val);\n // Throws for non-objects, converts non-instanceof Long:\n return new Long(val.low, val.high);\n }\n}\n\nconst UZERO = new Long(0, 0);\nconst TWO_PWR_16_DBL = 1 << 16;\nconst TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;\nconst TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;\nconst MAX_UNSIGNED_VALUE = new Long(0xffffffff | 0, 0xffffffff | 0);\n", "export interface JwtDecodeOptions {\n header?: boolean;\n}\n\nexport interface JwtHeader {\n typ?: string;\n alg?: string;\n kid?: string;\n}\n\nexport interface JwtPayload {\n iss?: string;\n sub?: string;\n aud?: string[] | string;\n exp?: number;\n nbf?: number;\n iat?: number;\n jti?: string;\n}\n\nexport class InvalidTokenError extends Error {}\n\nInvalidTokenError.prototype.name = \"InvalidTokenError\";\n\nfunction b64DecodeUnicode(str: string) {\n return decodeURIComponent(\n atob(str).replace(/(.)/g, (_m, p) => {\n let code = (p as string).charCodeAt(0).toString(16).toUpperCase();\n if (code.length < 2) {\n code = \"0\" + code;\n }\n return \"%\" + code;\n }),\n );\n}\n\nfunction base64UrlDecode(str: string) {\n let output = str.replace(/-/g, \"+\").replace(/_/g, \"/\");\n switch (output.length % 4) {\n case 0:\n break;\n case 2:\n output += \"==\";\n break;\n case 3:\n output += \"=\";\n break;\n default:\n throw new Error(\"base64 string is not of the correct length\");\n }\n\n try {\n return b64DecodeUnicode(output);\n } catch {\n return atob(output);\n }\n}\n\nexport function jwtDecode<T = JwtHeader>(\n token: string,\n options: JwtDecodeOptions & { header: true },\n): T;\nexport function jwtDecode<T = JwtPayload>(\n token: string,\n options?: JwtDecodeOptions,\n): T;\nexport function jwtDecode<T = JwtHeader | JwtPayload>(\n token: string,\n options?: JwtDecodeOptions,\n): T {\n if (typeof token !== \"string\") {\n throw new InvalidTokenError(\"Invalid token specified: must be a string\");\n }\n\n options ||= {};\n\n const pos = options.header === true ? 0 : 1;\n const part = token.split(\".\")[pos];\n\n if (typeof part !== \"string\") {\n throw new InvalidTokenError(\n `Invalid token specified: missing part #${pos + 1}`,\n );\n }\n\n let decoded: string;\n try {\n decoded = base64UrlDecode(part);\n } catch (e) {\n throw new InvalidTokenError(\n `Invalid token specified: invalid base64 for part #${pos + 1} (${(e as Error).message})`,\n );\n }\n\n try {\n return JSON.parse(decoded) as T;\n } catch (e) {\n throw new InvalidTokenError(\n `Invalid token specified: invalid json for part #${pos + 1} (${(e as Error).message})`,\n );\n }\n}\n", "import { Logger } from \"../logging.js\";\nimport { LocalSyncState } from \"./local_state.js\";\nimport { AuthError, IdentityVersion, Transition } from \"./protocol.js\";\nimport { jwtDecode } from \"../../vendor/jwt-decode/index.js\";\n\n// setTimout uses 32 bit integer, so it can only\n// schedule about 24 days in the future.\nconst MAXIMUM_REFRESH_DELAY = 20 * 24 * 60 * 60 * 1000; // 20 days\n\nconst MAX_TOKEN_CONFIRMATION_ATTEMPTS = 2;\n\n/**\n * An async function returning a JWT. Depending on the auth providers\n * configured in convex/auth.config.ts, this may be a JWT-encoded OpenID\n * Connect Identity Token or a traditional JWT.\n *\n * `forceRefreshToken` is `true` if the server rejected a previously\n * returned token or the token is anticipated to expiring soon\n * based on its `exp` time.\n *\n * See {@link ConvexReactClient.setAuth}.\n *\n * @public\n */\nexport type AuthTokenFetcher = (args: {\n forceRefreshToken: boolean;\n}) => Promise<string | null | undefined>;\n\n/**\n * What is provided to the client.\n */\ntype AuthConfig = {\n fetchToken: AuthTokenFetcher;\n onAuthChange: (isAuthenticated: boolean) => void;\n onRefreshChange?: ((isRefreshing: boolean) => void) | undefined;\n};\n\n/**\n * By default we take 3 steps:\n * 1. Fetch a possibly cached token and send it to the server\n * 2. Immediately fetch a fresh token without using a cache\n * 3. Repeat step 2 before the end of the fresh token's lifetime\n *\n * When `initialAuthTokenReuse` is enabled, step 2 is skipped: the\n * cached token is reused and a refetch is scheduled based on its\n * remaining lifetime (estimated via the server's clock skew). This\n * avoids a second Authenticate message that would cause the server\n * to re-execute all authenticated queries.\n *\n * If the server rejects a token before a scheduled refetch, we\n * immediately fetch a fresh token and retry.\n */\ntype AuthState =\n | { state: \"noAuth\" }\n | {\n state: \"waitingForServerConfirmationOfCachedToken\";\n config: AuthConfig;\n hasRetried: boolean;\n }\n | {\n state: \"initialRefetch\";\n config: AuthConfig;\n }\n | {\n state: \"waitingForServerConfirmationOfFreshToken\";\n config: AuthConfig;\n hadAuth: boolean;\n token: string;\n }\n | {\n state: \"waitingForScheduledRefetch\";\n config: AuthConfig;\n refetchTokenTimeoutId: ReturnType<typeof setTimeout>;\n }\n // Special/weird state when we got a valid token\n // but could not fetch a new one.\n | {\n state: \"notRefetching\";\n config: AuthConfig;\n };\n\n/**\n * Handles the state transitions for auth. The server is the source\n * of truth.\n */\nexport class AuthenticationManager {\n private authState: AuthState = { state: \"noAuth\" };\n // Used to detect races involving `setConfig` calls\n // while a token is being fetched.\n private configVersion = 0;\n // Shared by the BaseClient so that the auth manager can easily inspect it\n private readonly syncState: LocalSyncState;\n // Passed down by BaseClient, sends a message to the server\n private readonly authenticate: (token: string) => IdentityVersion;\n private readonly stopSocket: () => Promise<void>;\n private readonly tryRestartSocket: () => void;\n private readonly pauseSocket: () => void;\n private readonly resumeSocket: () => void;\n // Passed down by BaseClient, sends a message to the server\n private readonly clearAuth: () => void;\n private readonly logger: Logger;\n private readonly refreshTokenLeewaySeconds: number;\n private readonly initialAuthTokenReuse: boolean;\n // Track last value to avoid redundant calls\n private lastRefreshChange: boolean;\n // Number of times we have attempted to confirm the latest token. We retry up\n // to `MAX_TOKEN_CONFIRMATION_ATTEMPTS` times.\n private tokenConfirmationAttempts = 0;\n constructor(\n syncState: LocalSyncState,\n callbacks: {\n authenticate: (token: string) => IdentityVersion;\n stopSocket: () => Promise<void>;\n tryRestartSocket: () => void;\n pauseSocket: () => void;\n resumeSocket: () => void;\n clearAuth: () => void;\n },\n config: {\n refreshTokenLeewaySeconds: number;\n logger: Logger;\n initialAuthTokenReuse: boolean;\n },\n ) {\n this.syncState = syncState;\n this.authenticate = callbacks.authenticate;\n this.stopSocket = callbacks.stopSocket;\n this.tryRestartSocket = callbacks.tryRestartSocket;\n this.pauseSocket = callbacks.pauseSocket;\n this.resumeSocket = callbacks.resumeSocket;\n this.clearAuth = callbacks.clearAuth;\n this.logger = config.logger;\n this.refreshTokenLeewaySeconds = config.refreshTokenLeewaySeconds;\n this.initialAuthTokenReuse = config.initialAuthTokenReuse;\n this.lastRefreshChange = false;\n }\n\n private notifyRefreshChange(isRefreshing: boolean) {\n if (\n this.authState.state !== \"noAuth\" &&\n this.authState.state !== \"initialRefetch\" &&\n this.authState.config.onRefreshChange &&\n this.lastRefreshChange !== isRefreshing\n ) {\n this.lastRefreshChange = isRefreshing;\n this.authState.config.onRefreshChange(isRefreshing);\n }\n }\n\n async setConfig(\n fetchToken: AuthTokenFetcher,\n onChange: (isAuthenticated: boolean) => void,\n onRefreshChange?: (isRefreshing: boolean) => void,\n ) {\n this.resetAuthState();\n this._logVerbose(\"pausing WS for auth token fetch\");\n this.pauseSocket();\n const token = await this.fetchTokenAndGuardAgainstRace(fetchToken, {\n forceRefreshToken: false,\n });\n if (token.isFromOutdatedConfig) {\n return;\n }\n const config: AuthConfig = {\n fetchToken,\n onAuthChange: onChange,\n onRefreshChange,\n };\n if (token.value) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfCachedToken\",\n config,\n hasRetried: false,\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"initialRefetch\",\n config,\n });\n // Try again with `forceRefreshToken: true`\n await this.refetchToken();\n }\n this._logVerbose(\"resuming WS after auth token fetch\");\n this.resumeSocket();\n }\n\n onTransition(serverMessage: Transition) {\n if (\n !this.syncState.isCurrentOrNewerAuthVersion(\n serverMessage.endVersion.identity,\n )\n ) {\n // This is a stale transition - client has moved on to\n // a newer auth version.\n return;\n }\n if (\n serverMessage.endVersion.identity <= serverMessage.startVersion.identity\n ) {\n // This transition did not change auth - it is not a response to Authenticate.\n return;\n }\n\n this._logVerbose(\n `auth state is ${this.authState.state} when handling transition`,\n );\n\n // This transition advanced the auth version, which means the token used was valid\n // and the client and server auth states are in sync.\n this.syncState.markAuthCompletion();\n\n if (this.authState.state === \"waitingForServerConfirmationOfCachedToken\") {\n this._logVerbose(\"server confirmed auth token is valid\");\n const cachedToken = this.syncState.getAuth()?.value;\n if (this.initialAuthTokenReuse && cachedToken) {\n this.scheduleTokenRefetch(cachedToken, serverMessage.clientClockSkew);\n } else {\n void this.refetchToken();\n }\n this.authState.config.onAuthChange(true);\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this._logVerbose(\"server confirmed new auth token is valid\");\n this.notifyRefreshChange(false);\n this.scheduleTokenRefetch(this.authState.token);\n this.tokenConfirmationAttempts = 0;\n if (!this.authState.hadAuth) {\n this.authState.config.onAuthChange(true);\n }\n }\n }\n\n onAuthError(serverMessage: AuthError) {\n // If the AuthError is not due to updating the token, and we're currently\n // waiting on the result of a token update, ignore.\n if (\n serverMessage.authUpdateAttempted === false &&\n (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" ||\n this.authState.state === \"waitingForServerConfirmationOfCachedToken\")\n ) {\n this._logVerbose(\"ignoring non-auth token expired error\");\n return;\n }\n const { baseVersion } = serverMessage;\n // Versioned AuthErrors are ignored if the client advanced to\n // a newer auth identity\n // Error are reporting the previous version, since the server\n // didn't advance, hence `+ 1`.\n if (!this.syncState.isCurrentOrNewerAuthVersion(baseVersion + 1)) {\n this._logVerbose(\"ignoring auth error for previous auth attempt\");\n return;\n }\n void this.tryToReauthenticate(serverMessage);\n return;\n }\n\n // This is similar to `refetchToken` defined below, in fact we\n // don't represent them as different states, but it is different\n // in that we pause the WebSocket so that mutations\n // don't retry with bad auth.\n private async tryToReauthenticate(serverMessage: AuthError) {\n this._logVerbose(`attempting to reauthenticate: ${serverMessage.error}`);\n if (\n // No way to fetch another token, kaboom\n this.authState.state === \"noAuth\" ||\n // We failed on a fresh token. After a small number of retries, we give up\n // and clear the auth state to avoid infinite retries.\n (this.authState.state === \"waitingForServerConfirmationOfFreshToken\" &&\n this.tokenConfirmationAttempts >= MAX_TOKEN_CONFIRMATION_ATTEMPTS)\n ) {\n this.logger.error(\n `Failed to authenticate: \"${serverMessage.error}\", check your server auth config`,\n );\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n if (this.authState.state !== \"noAuth\") {\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n return;\n }\n if (this.authState.state === \"waitingForServerConfirmationOfFreshToken\") {\n this.tokenConfirmationAttempts++;\n this._logVerbose(\n `retrying reauthentication, ${MAX_TOKEN_CONFIRMATION_ATTEMPTS - this.tokenConfirmationAttempts} attempts remaining`,\n );\n }\n\n this.notifyRefreshChange(true);\n await this.stopSocket();\n if ((this.authState.state as AuthState[\"state\"]) === \"noAuth\") {\n // setConfig() or stop() ran during the await.\n return;\n }\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true,\n },\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n\n if (token.value && this.syncState.isNewAuth(token.value)) {\n this.authenticate(token.value);\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n config: this.authState.config,\n token: token.value,\n hadAuth:\n this.authState.state === \"notRefetching\" ||\n this.authState.state === \"waitingForScheduledRefetch\",\n });\n } else {\n this._logVerbose(\"reauthentication failed, could not fetch a new token\");\n if (this.syncState.hasAuth()) {\n this.syncState.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n this.tryRestartSocket();\n }\n\n // Force refetch the token and schedule another refetch\n // before the token expires - an active client should never\n // need to reauthenticate.\n private async refetchToken() {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n this._logVerbose(\"refetching auth token\");\n const token = await this.fetchTokenAndGuardAgainstRace(\n this.authState.config.fetchToken,\n {\n forceRefreshToken: true,\n },\n );\n if (token.isFromOutdatedConfig) {\n return;\n }\n\n if (token.value) {\n if (this.syncState.isNewAuth(token.value)) {\n this.setAuthState({\n state: \"waitingForServerConfirmationOfFreshToken\",\n hadAuth: this.syncState.hasAuth(),\n token: token.value,\n config: this.authState.config,\n });\n this.authenticate(token.value);\n } else {\n this.setAuthState({\n state: \"notRefetching\",\n config: this.authState.config,\n });\n }\n } else {\n this._logVerbose(\"refetching token failed\");\n if (this.syncState.hasAuth()) {\n this.clearAuth();\n }\n this.setAndReportAuthFailed(this.authState.config.onAuthChange);\n }\n // Restart in case this refetch was triggered via schedule during\n // a reauthentication attempt.\n this._logVerbose(\n \"restarting WS after auth token fetch (if currently stopped)\",\n );\n this.tryRestartSocket();\n }\n\n private scheduleTokenRefetch(token: string, clientClockSkewMs?: number) {\n if (this.authState.state === \"noAuth\") {\n return;\n }\n const decodedToken = this.decodeToken(token);\n if (!decodedToken) {\n // This is no longer really possible, because\n // we wait on server response before scheduling token refetch,\n // and the server currently requires JWT tokens.\n this.logger.error(\n \"Auth token is not a valid JWT, cannot refetch the token\",\n );\n return;\n }\n // iat: issued at time, UTC seconds timestamp at which the JWT was issued\n // exp: expiration time, UTC seconds timestamp at which the JWT will expire\n const { iat, exp } = decodedToken as { iat?: number; exp?: number };\n if (!iat || !exp) {\n this.logger.error(\n \"Auth token does not have required fields, cannot refetch the token\",\n );\n return;\n }\n const fullLifetimeSeconds = exp - iat;\n if (fullLifetimeSeconds <= 2) {\n this.logger.error(\n \"Auth token does not live long enough, cannot refetch the token\",\n );\n return;\n }\n let tokenValiditySeconds: number;\n if (clientClockSkewMs !== undefined) {\n // For cached tokens we use the server's clock skew estimate to\n // compute remaining lifetime. The server computes\n // clientClockSkew = clientTs - serverReceiveTs, so it's positive\n // when the client is ahead and negative when behind. To recover\n // server time: serverNow = Date.now() - clientClockSkew.\n // Both Date.now() and setTimeout use the same client clock, so\n // the scheduled delay is accurate regardless of absolute offset.\n // Connect latency inflates the skew toward \"client behind,\" which\n // is conservative \u2014 we schedule the refetch slightly early.\n const estimatedServerNowSeconds = (Date.now() - clientClockSkewMs) / 1000;\n tokenValiditySeconds = exp - estimatedServerNowSeconds;\n if (tokenValiditySeconds <= 0) {\n tokenValiditySeconds = 0;\n }\n } else {\n // For freshly-fetched tokens, `exp - iat` is the full lifetime\n // starting from now.\n tokenValiditySeconds = fullLifetimeSeconds;\n }\n // Attempt to refresh the token `refreshTokenLeewaySeconds` before it expires,\n // or immediately if the token is already expiring soon.\n let delay = Math.min(\n MAXIMUM_REFRESH_DELAY,\n (tokenValiditySeconds - this.refreshTokenLeewaySeconds) * 1000,\n );\n if (delay <= 0) {\n // Refetch immediately, but this might be due to configuring a `refreshTokenLeewaySeconds`\n // that is too large compared to the token's actual lifetime.\n this.logger.warn(\n `Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${tokenValiditySeconds}s`,\n );\n delay = 0;\n }\n const refetchTokenTimeoutId = setTimeout(() => {\n this._logVerbose(\"running scheduled token refetch\");\n void this.refetchToken();\n }, delay);\n this.setAuthState({\n state: \"waitingForScheduledRefetch\",\n refetchTokenTimeoutId,\n config: this.authState.config,\n });\n this._logVerbose(\n `scheduled preemptive auth token refetching in ${delay}ms`,\n );\n }\n\n // Protects against simultaneous calls to `setConfig`\n // while we're fetching a token\n private async fetchTokenAndGuardAgainstRace(\n fetchToken: AuthTokenFetcher,\n fetchArgs: {\n forceRefreshToken: boolean;\n },\n ) {\n const originalConfigVersion = ++this.configVersion;\n this._logVerbose(\n `fetching token with config version ${originalConfigVersion}`,\n );\n const token = await fetchToken(fetchArgs);\n if (this.configVersion !== originalConfigVersion) {\n // This is a stale config\n this._logVerbose(\n `stale config version, expected ${originalConfigVersion}, got ${this.configVersion}`,\n );\n return { isFromOutdatedConfig: true };\n }\n return { isFromOutdatedConfig: false, value: token };\n }\n\n stop() {\n this.resetAuthState();\n // Bump this in case we are mid-token-fetch when we get stopped\n this.configVersion++;\n this._logVerbose(`config version bumped to ${this.configVersion}`);\n }\n\n private setAndReportAuthFailed(\n onAuthChange: (authenticated: boolean) => void,\n ) {\n onAuthChange(false);\n this.resetAuthState();\n }\n\n // The sole path to `state === \"noAuth\"`; consumers rely on this firing\n // `notifyRefreshChange(false)` to pair any in-flight `(true)`. May run\n // when refresh state is already false.\n private resetAuthState() {\n this.notifyRefreshChange(false);\n this.setAuthState({ state: \"noAuth\" });\n }\n\n private setAuthState(newAuth: AuthState) {\n const authStateForLog =\n newAuth.state === \"waitingForServerConfirmationOfFreshToken\"\n ? {\n hadAuth: newAuth.hadAuth,\n state: newAuth.state,\n token: `...${newAuth.token.slice(-7)}`,\n }\n : { state: newAuth.state };\n this._logVerbose(\n `setting auth state to ${JSON.stringify(authStateForLog)}`,\n );\n switch (newAuth.state) {\n case \"waitingForScheduledRefetch\":\n case \"notRefetching\":\n case \"noAuth\":\n this.tokenConfirmationAttempts = 0;\n break;\n case \"waitingForServerConfirmationOfFreshToken\":\n case \"waitingForServerConfirmationOfCachedToken\":\n case \"initialRefetch\":\n break;\n default: {\n newAuth satisfies never;\n }\n }\n if (this.authState.state === \"waitingForScheduledRefetch\") {\n // TODO: this side-effect would be better situated with scheduling refetch\n clearTimeout(this.authState.refetchTokenTimeoutId);\n }\n this.authState = newAuth;\n }\n\n private decodeToken(token: string) {\n try {\n return jwtDecode(token);\n } catch (e) {\n this._logVerbose(\n `Error decoding token: ${e instanceof Error ? e.message : \"Unknown error\"}`,\n );\n return null;\n }\n }\n\n private _logVerbose(message: string) {\n this.logger.logVerbose(`${message} [v${this.configVersion}]`);\n }\n}\n", "import { validateDeploymentUrl } from \"../common/index.js\";\nimport {\n FunctionArgs,\n FunctionReturnType,\n PaginationResult,\n FunctionReference,\n FunctionReference_future,\n} from \"../server/index.js\";\nimport { getFunctionName } from \"../server/api.js\";\nimport { AuthTokenFetcher } from \"./sync/authentication_manager.js\";\nimport {\n BaseConvexClient,\n BaseConvexClientOptions,\n ConnectionState,\n MutationOptions,\n} from \"./sync/client.js\";\nimport {\n ExtendedTransition,\n PaginatedQueryClient,\n} from \"./sync/paginated_query_client.js\";\nimport { PaginatedQueryResult } from \"./sync/pagination.js\";\nimport { UserIdentityAttributes } from \"./sync/protocol.js\";\nimport {\n PaginatedQueryToken,\n QueryToken,\n serializedQueryTokenIsPaginated,\n} from \"./sync/udf_path_utils.js\";\n\n// In Node.js builds this points to a bundled WebSocket implementation. If no\n// WebSocket implementation is manually specified or globally available,\n// this one is used.\nlet defaultWebSocketConstructor: typeof WebSocket | undefined;\n\n/** internal */\nexport function setDefaultWebSocketConstructor(ws: typeof WebSocket) {\n defaultWebSocketConstructor = ws;\n}\n\nexport type ConvexClientOptions = BaseConvexClientOptions & {\n /**\n * `disabled` makes onUpdate callback registration a no-op and actions,\n * mutations and one-shot queries throw. Setting disabled to true may be\n * useful for server-side rendering, where subscriptions don't make sense.\n */\n disabled?: boolean;\n /**\n * Whether to prompt users in browsers about queued or in-flight mutations.\n * This only works in environments where `window.onbeforeunload` is available.\n *\n * Defaults to true when `window` is defined, otherwise false.\n */\n unsavedChangesWarning?: boolean;\n};\n\n/**\n * Stops callbacks from running.\n *\n * @public\n */\nexport type Unsubscribe<T> = {\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n (): void;\n /** Stop calling callback when query results changes. If this is the last listener on this query, stop received updates. */\n unsubscribe(): void;\n /** Get the last known value, possibly with local optimistic updates applied. */\n getCurrentValue(): T | undefined;\n /** @internal */\n getQueryLogs(): string[] | undefined;\n};\n\n/**\n * Subscribes to Convex query functions and executes mutations and actions over a WebSocket.\n *\n * Optimistic updates for mutations are not provided for this client.\n * Third party clients may choose to wrap {@link browser.BaseConvexClient} for additional control.\n *\n * ```ts\n * const client = new ConvexClient(\"https://happy-otter-123.convex.cloud\");\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages[0].body);\n * });\n * ```\n *\n * @public\n */\nexport class ConvexClient {\n private listeners: Set<QueryInfo>;\n private _client: BaseConvexClient | undefined;\n private _paginatedClient: PaginatedQueryClient | undefined;\n // A synthetic server event to run callbacks the first time\n private callNewListenersWithCurrentValuesTimer:\n | ReturnType<typeof setTimeout>\n | undefined;\n private _closed: boolean;\n private _disabled: boolean;\n /**\n * Once closed no registered callbacks will fire again.\n */\n get closed(): boolean {\n return this._closed;\n }\n get client(): BaseConvexClient {\n if (this._client) return this._client;\n throw new Error(\"ConvexClient is disabled\");\n }\n /**\n * @internal\n */\n get paginatedClient(): PaginatedQueryClient {\n if (this._paginatedClient) return this._paginatedClient;\n throw new Error(\"ConvexClient is disabled\");\n }\n get disabled(): boolean {\n return this._disabled;\n }\n\n /**\n * Construct a client and immediately initiate a WebSocket connection to the passed address.\n *\n * @public\n */\n constructor(address: string, options: ConvexClientOptions = {}) {\n if (options.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n const { disabled, ...baseOptions } = options;\n this._closed = false;\n this._disabled = !!disabled;\n if (\n defaultWebSocketConstructor &&\n !(\"webSocketConstructor\" in baseOptions) &&\n typeof WebSocket === \"undefined\"\n ) {\n baseOptions.webSocketConstructor = defaultWebSocketConstructor;\n }\n if (\n typeof window === \"undefined\" &&\n !(\"unsavedChangesWarning\" in baseOptions)\n ) {\n baseOptions.unsavedChangesWarning = false;\n }\n if (!this.disabled) {\n this._client = new BaseConvexClient(\n address,\n () => {}, // NOP, let the paginated query client do it all\n baseOptions,\n );\n this._paginatedClient = new PaginatedQueryClient(\n this._client,\n (transition) => this._transition(transition),\n );\n }\n this.listeners = new Set();\n }\n\n /**\n * Call a callback whenever a new result for a query is received. The callback\n * will run soon after being registered if a result for the query is already\n * in memory.\n *\n * The return value is an {@link Unsubscribe} object which is both a function\n * an an object with properties. Both of the patterns below work with this object:\n *\n *```ts\n * // call the return value as a function\n * const unsubscribe = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n * unsubscribe();\n *\n * // unpack the return value into its properties\n * const {\n * getCurrentValue,\n * unsubscribe,\n * } = client.onUpdate(api.messages.list, {}, (messages) => {\n * console.log(messages);\n * });\n *```\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n * If not provided, errors will be thrown instead of calling the callback.\n *\n * @return an {@link Unsubscribe} function to stop calling the onUpdate function.\n */\n onUpdate<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n callback: (result: FunctionReturnType<Query>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<FunctionReturnType<Query>> {\n if (this.disabled) {\n return this.createDisabledUnsubscribe<FunctionReturnType<Query>>();\n }\n\n // BaseConvexClient takes care of deduplicating queries subscriptions...\n const { queryToken, unsubscribe } = this.client.subscribe(\n getFunctionName(query),\n args,\n );\n\n // ...but we still need to bookkeep callbacks to actually call them.\n const queryInfo: QueryInfo = {\n queryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions: undefined,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n this.queryResultReady(queryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<FunctionReturnType<Query>>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => this.client.localQueryResultByToken(queryToken),\n getQueryLogs: () => this.client.localQueryLogs(queryToken),\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n FunctionReturnType<Query>\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n /**\n * Call a callback whenever a new result for a paginated query is received.\n *\n * This is an experimental preview: the final API may change.\n * In particular, caching behavior, page splitting, and required paginated query options\n * may change.\n *\n * @param query - A {@link server.FunctionReference} for the public query to run.\n * @param args - The arguments to run the query with.\n * @param options - Options for the paginated query including initialNumItems and id.\n * @param callback - Function to call when the query result updates.\n * @param onError - Function to call when the query result updates with an error.\n *\n * @return an {@link Unsubscribe} function to stop calling the callback.\n */\n onPaginatedUpdate_experimental<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n options: { initialNumItems: number },\n callback: (result: PaginationResult<FunctionReturnType<Query>>) => unknown,\n onError?: (e: Error) => unknown,\n ): Unsubscribe<PaginatedQueryResult<FunctionReturnType<Query>[]>> {\n if (this.disabled) {\n return this.createDisabledUnsubscribe<\n PaginatedQueryResult<FunctionReturnType<Query>>\n >();\n }\n\n const paginationOptions = {\n initialNumItems: options.initialNumItems,\n id: -1,\n };\n\n const { paginatedQueryToken, unsubscribe } = this.paginatedClient.subscribe(\n getFunctionName(query),\n args,\n // Simple client doesn't use IDs, there's no expectation that these queries remain separate.\n paginationOptions,\n );\n\n const queryInfo: QueryInfo = {\n queryToken: paginatedQueryToken,\n callback,\n onError,\n unsubscribe,\n hasEverRun: false,\n query,\n args,\n paginationOptions,\n };\n this.listeners.add(queryInfo);\n\n // If the callback is registered for a query with a result immediately available\n // schedule a fake transition to call the callback soon instead of waiting for\n // a new server update (which could take seconds or days).\n if (\n !!this.paginatedClient.localQueryResultByToken(paginatedQueryToken) &&\n this.callNewListenersWithCurrentValuesTimer === undefined\n ) {\n this.callNewListenersWithCurrentValuesTimer = setTimeout(\n () => this.callNewListenersWithCurrentValues(),\n 0,\n );\n }\n\n const unsubscribeProps: RemoveCallSignature<\n Unsubscribe<PaginatedQueryResult<FunctionReturnType<Query>[]>>\n > = {\n unsubscribe: () => {\n if (this.closed) {\n // all unsubscribes already ran\n return;\n }\n this.listeners.delete(queryInfo);\n unsubscribe();\n },\n getCurrentValue: () => {\n const result = this.paginatedClient.localQueryResult(\n getFunctionName(query),\n args,\n paginationOptions,\n );\n // cast to apply the specific function type\n return result as\n | PaginatedQueryResult<FunctionReturnType<Query>>\n | undefined;\n },\n getQueryLogs: () => [], // Paginated queries don't aggregate their logs\n };\n const ret = unsubscribeProps.unsubscribe as Unsubscribe<\n PaginatedQueryResult<FunctionReturnType<Query>>\n >;\n Object.assign(ret, unsubscribeProps);\n return ret;\n }\n\n // Run all callbacks that have never been run before if they have a query\n // result available now.\n private callNewListenersWithCurrentValues() {\n this.callNewListenersWithCurrentValuesTimer = undefined;\n this._transition({ queries: [], paginatedQueries: [] }, true);\n }\n\n private queryResultReady(queryToken: QueryToken): boolean {\n return this.client.hasLocalQueryResultByToken(queryToken);\n }\n\n private createDisabledUnsubscribe<T>(): Unsubscribe<T> {\n const disabledUnsubscribe = (() => {}) as Unsubscribe<T>;\n const unsubscribeProps: RemoveCallSignature<Unsubscribe<T>> = {\n unsubscribe: disabledUnsubscribe,\n getCurrentValue: () => undefined,\n getQueryLogs: () => undefined,\n };\n Object.assign(disabledUnsubscribe, unsubscribeProps);\n return disabledUnsubscribe;\n }\n\n async close() {\n if (this.disabled) return;\n // prevent pending updates\n this.listeners.clear();\n this._closed = true;\n if (this._paginatedClient) {\n this._paginatedClient = undefined;\n }\n return this.client.close();\n }\n\n /**\n * Get the current JWT auth token and decoded claims.\n */\n getAuth(): { token: string; decoded: Record<string, any> } | undefined {\n if (this.disabled) return;\n return this.client.getCurrentAuthClaims();\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n * `fetchToken` will be called automatically again if a token expires.\n * `fetchToken` should return `null` if the token cannot be retrieved, for example\n * when the user's rights were permanently revoked.\n * @param fetchToken - an async function returning the JWT (typically an OpenID Connect Identity Token)\n * @param onChange - a callback that will be called when the authentication status changes\n */\n setAuth(\n fetchToken: AuthTokenFetcher,\n onChange?: (isAuthenticated: boolean) => void,\n ) {\n if (this.disabled) return;\n this.client.setAuth(\n fetchToken,\n onChange ??\n (() => {\n // Do nothing\n }),\n );\n }\n\n /**\n * @internal\n */\n setAdminAuth(token: string, identity?: UserIdentityAttributes) {\n if (this.closed) {\n throw new Error(\"ConvexClient has already been closed.\");\n }\n if (this.disabled) return;\n this.client.setAdminAuth(token, identity);\n }\n\n /**\n * @internal\n */\n _transition(\n {\n queries,\n paginatedQueries,\n }: Pick<ExtendedTransition, \"queries\" | \"paginatedQueries\">,\n callNewListeners = false,\n ) {\n const updatedQueries = [\n ...queries.map((q) => q.token),\n ...paginatedQueries.map((q) => q.token),\n ];\n\n // Deduping subscriptions happens in the BaseConvexClient, so not much to do here.\n\n // Call all callbacks in the order they were registered\n for (const queryInfo of this.listeners) {\n const { callback, queryToken, onError, hasEverRun } = queryInfo;\n const isPaginatedQuery = serializedQueryTokenIsPaginated(queryToken);\n\n // What does it mean to have a paginated query result ready? I think it's\n // always going to fire immediately.\n const hasResultReady = isPaginatedQuery\n ? !!this.paginatedClient.localQueryResultByToken(queryToken)\n : this.client.hasLocalQueryResultByToken(queryToken);\n\n if (\n updatedQueries.includes(queryToken) ||\n (callNewListeners && !hasEverRun && hasResultReady)\n ) {\n queryInfo.hasEverRun = true;\n let newValue;\n try {\n if (isPaginatedQuery) {\n newValue = this.paginatedClient.localQueryResultByToken(queryToken);\n } else {\n newValue = this.client.localQueryResultByToken(queryToken);\n }\n } catch (error) {\n if (!(error instanceof Error)) throw error;\n if (onError) {\n onError(\n error,\n \"Second argument to onUpdate onError is reserved for later use\",\n );\n } else {\n // Make some noise without unsubscribing or failing to call other callbacks.\n void Promise.reject(error);\n }\n continue;\n }\n callback(\n newValue,\n \"Second argument to onUpdate callback is reserved for later use\",\n );\n }\n }\n }\n\n /**\n * Execute a mutation function.\n *\n * @param mutation - A {@link server.FunctionReference} for the public mutation\n * to run.\n * @param args - An arguments object for the mutation.\n * @param options - A {@link MutationOptions} options object for the mutation.\n * @returns A promise of the mutation's result.\n */\n async mutation<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n options?: MutationOptions,\n ): Promise<Awaited<FunctionReturnType<Mutation>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.mutation(getFunctionName(mutation), args, options);\n }\n\n /**\n * Execute an action function.\n *\n * @param action - A {@link server.FunctionReference} for the public action\n * to run.\n * @param args - An arguments object for the action.\n * @returns A promise of the action's result.\n */\n async action<\n Action extends\n | FunctionReference<\"action\">\n | FunctionReference_future<\"action\">,\n >(\n action: Action,\n args: FunctionArgs<Action>,\n ): Promise<Awaited<FunctionReturnType<Action>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return await this.client.action(getFunctionName(action), args);\n }\n\n /**\n * Fetch a query result once.\n *\n * @param query - A {@link server.FunctionReference} for the public query\n * to run.\n * @param args - An arguments object for the query.\n * @returns A promise of the query's result.\n */\n async query<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n args: FunctionArgs<Query>,\n ): Promise<Awaited<FunctionReturnType<Query>>> {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n const value = this.client.localQueryResult(getFunctionName(query), args) as\n | Awaited<FunctionReturnType<Query>>\n | undefined;\n if (value !== undefined) return Promise.resolve(value);\n\n return new Promise((resolve, reject) => {\n const { unsubscribe } = this.onUpdate(\n query,\n args,\n (value) => {\n unsubscribe();\n resolve(value);\n },\n (e: Error) => {\n unsubscribe();\n reject(e);\n },\n );\n });\n }\n\n /**\n * Get the current {@link ConnectionState} between the client and the Convex\n * backend.\n *\n * @returns The {@link ConnectionState} with the Convex backend.\n */\n connectionState(): ConnectionState {\n if (this.disabled) throw new Error(\"ConvexClient is disabled\");\n return this.client.connectionState();\n }\n\n /**\n * Subscribe to the {@link ConnectionState} between the client and the Convex\n * backend, calling a callback each time it changes.\n *\n * Subscribed callbacks will be called when any part of ConnectionState changes.\n * ConnectionState may grow in future versions (e.g. to provide a array of\n * inflight requests) in which case callbacks would be called more frequently.\n *\n * @returns An unsubscribe function to stop listening.\n */\n subscribeToConnectionState(\n cb: (connectionState: ConnectionState) => void,\n ): () => void {\n if (this.disabled) return () => {};\n return this.client.subscribeToConnectionState(cb);\n }\n}\n\n// internal information tracked about each registered callback\ntype QueryInfo = {\n callback: (result: any, meta: unknown) => unknown;\n onError: ((e: Error, meta: unknown) => unknown) | undefined;\n unsubscribe: () => void;\n queryToken: QueryToken | PaginatedQueryToken;\n hasEverRun: boolean;\n // query, args and paginationOptions are just here for debugging, the queryToken is authoritative\n query: FunctionReference<\"query\"> | FunctionReference_future<\"query\">;\n args: any;\n paginationOptions: { initialNumItems: number; id: number } | undefined;\n};\n\n// helps to construct objects with a call signature\ntype RemoveCallSignature<T> = Omit<T, never>;\n", "'use strict';\n\nconst BINARY_TYPES = ['nodebuffer', 'arraybuffer', 'fragments'];\nconst hasBlob = typeof Blob !== 'undefined';\n\nif (hasBlob) BINARY_TYPES.push('blob');\n\nmodule.exports = {\n BINARY_TYPES,\n CLOSE_TIMEOUT: 30000,\n EMPTY_BUFFER: Buffer.alloc(0),\n GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11',\n hasBlob,\n kForOnEventAttribute: Symbol('kIsForOnEventAttribute'),\n kListener: Symbol('kListener'),\n kStatusCode: Symbol('status-code'),\n kWebSocket: Symbol('websocket'),\n NOOP: () => {}\n};\n", "var fs = require('fs')\nvar path = require('path')\nvar os = require('os')\n\n// Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'\nvar runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\n\nvar vars = (process.config && process.config.variables) || {}\nvar prebuildsOnly = !!process.env.PREBUILDS_ONLY\nvar abi = process.versions.modules // TODO: support old node where this is undef\nvar runtime = isElectron() ? 'electron' : (isNwjs() ? 'node-webkit' : 'node')\n\nvar arch = process.env.npm_config_arch || os.arch()\nvar platform = process.env.npm_config_platform || os.platform()\nvar libc = process.env.LIBC || (isAlpine(platform) ? 'musl' : 'glibc')\nvar armv = process.env.ARM_VERSION || (arch === 'arm64' ? '8' : vars.arm_version) || ''\nvar uv = (process.versions.uv || '').split('.')[0]\n\nmodule.exports = load\n\nfunction load (dir) {\n return runtimeRequire(load.resolve(dir))\n}\n\nload.resolve = load.path = function (dir) {\n dir = path.resolve(dir || '.')\n\n try {\n var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')\n if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']\n } catch (err) {}\n\n if (!prebuildsOnly) {\n var release = getFirst(path.join(dir, 'build/Release'), matchBuild)\n if (release) return release\n\n var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)\n if (debug) return debug\n }\n\n var prebuild = resolve(dir)\n if (prebuild) return prebuild\n\n var nearby = resolve(path.dirname(process.execPath))\n if (nearby) return nearby\n\n var target = [\n 'platform=' + platform,\n 'arch=' + arch,\n 'runtime=' + runtime,\n 'abi=' + abi,\n 'uv=' + uv,\n armv ? 'armv=' + armv : '',\n 'libc=' + libc,\n 'node=' + process.versions.node,\n process.versions.electron ? 'electron=' + process.versions.electron : '',\n typeof __webpack_require__ === 'function' ? 'webpack=true' : '' // eslint-disable-line\n ].filter(Boolean).join(' ')\n\n throw new Error('No native build was found for ' + target + '\\n loaded from: ' + dir + '\\n')\n\n function resolve (dir) {\n // Find matching \"prebuilds/<platform>-<arch>\" directory\n var tuples = readdirSync(path.join(dir, 'prebuilds')).map(parseTuple)\n var tuple = tuples.filter(matchTuple(platform, arch)).sort(compareTuples)[0]\n if (!tuple) return\n\n // Find most specific flavor first\n var prebuilds = path.join(dir, 'prebuilds', tuple.name)\n var parsed = readdirSync(prebuilds).map(parseTags)\n var candidates = parsed.filter(matchTags(runtime, abi))\n var winner = candidates.sort(compareTags(runtime))[0]\n if (winner) return path.join(prebuilds, winner.file)\n }\n}\n\nfunction readdirSync (dir) {\n try {\n return fs.readdirSync(dir)\n } catch (err) {\n return []\n }\n}\n\nfunction getFirst (dir, filter) {\n var files = readdirSync(dir).filter(filter)\n return files[0] && path.join(dir, files[0])\n}\n\nfunction matchBuild (name) {\n return /\\.node$/.test(name)\n}\n\nfunction parseTuple (name) {\n // Example: darwin-x64+arm64\n var arr = name.split('-')\n if (arr.length !== 2) return\n\n var platform = arr[0]\n var architectures = arr[1].split('+')\n\n if (!platform) return\n if (!architectures.length) return\n if (!architectures.every(Boolean)) return\n\n return { name, platform, architectures }\n}\n\nfunction matchTuple (platform, arch) {\n return function (tuple) {\n if (tuple == null) return false\n if (tuple.platform !== platform) return false\n return tuple.architectures.includes(arch)\n }\n}\n\nfunction compareTuples (a, b) {\n // Prefer single-arch prebuilds over multi-arch\n return a.architectures.length - b.architectures.length\n}\n\nfunction parseTags (file) {\n var arr = file.split('.')\n var extension = arr.pop()\n var tags = { file: file, specificity: 0 }\n\n if (extension !== 'node') return\n\n for (var i = 0; i < arr.length; i++) {\n var tag = arr[i]\n\n if (tag === 'node' || tag === 'electron' || tag === 'node-webkit') {\n tags.runtime = tag\n } else if (tag === 'napi') {\n tags.napi = true\n } else if (tag.slice(0, 3) === 'abi') {\n tags.abi = tag.slice(3)\n } else if (tag.slice(0, 2) === 'uv') {\n tags.uv = tag.slice(2)\n } else if (tag.slice(0, 4) === 'armv') {\n tags.armv = tag.slice(4)\n } else if (tag === 'glibc' || tag === 'musl') {\n tags.libc = tag\n } else {\n continue\n }\n\n tags.specificity++\n }\n\n return tags\n}\n\nfunction matchTags (runtime, abi) {\n return function (tags) {\n if (tags == null) return false\n if (tags.runtime && tags.runtime !== runtime && !runtimeAgnostic(tags)) return false\n if (tags.abi && tags.abi !== abi && !tags.napi) return false\n if (tags.uv && tags.uv !== uv) return false\n if (tags.armv && tags.armv !== armv) return false\n if (tags.libc && tags.libc !== libc) return false\n\n return true\n }\n}\n\nfunction runtimeAgnostic (tags) {\n return tags.runtime === 'node' && tags.napi\n}\n\nfunction compareTags (runtime) {\n // Precedence: non-agnostic runtime, abi over napi, then by specificity.\n return function (a, b) {\n if (a.runtime !== b.runtime) {\n return a.runtime === runtime ? -1 : 1\n } else if (a.abi !== b.abi) {\n return a.abi ? -1 : 1\n } else if (a.specificity !== b.specificity) {\n return a.specificity > b.specificity ? -1 : 1\n } else {\n return 0\n }\n }\n}\n\nfunction isNwjs () {\n return !!(process.versions && process.versions.nw)\n}\n\nfunction isElectron () {\n if (process.versions && process.versions.electron) return true\n if (process.env.ELECTRON_RUN_AS_NODE) return true\n return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'\n}\n\nfunction isAlpine (platform) {\n return platform === 'linux' && fs.existsSync('/etc/alpine-release')\n}\n\n// Exposed for unit tests\n// TODO: move to lib\nload.parseTags = parseTags\nload.matchTags = matchTags\nload.compareTags = compareTags\nload.parseTuple = parseTuple\nload.matchTuple = matchTuple\nload.compareTuples = compareTuples\n", "const runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line\nif (typeof runtimeRequire.addon === 'function') { // if the platform supports native resolving prefer that\n module.exports = runtimeRequire.addon.bind(runtimeRequire)\n} else { // else use the runtime version here\n module.exports = require('./node-gyp-build.js')\n}\n", "'use strict';\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nconst mask = (source, mask, output, offset, length) => {\n for (var i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n};\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nconst unmask = (buffer, mask) => {\n // Required until https://github.com/nodejs/node/issues/9006 is resolved.\n const length = buffer.length;\n for (var i = 0; i < length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n};\n\nmodule.exports = { mask, unmask };\n", "'use strict';\n\ntry {\n module.exports = require('node-gyp-build')(__dirname);\n} catch (e) {\n module.exports = require('./fallback');\n}\n", "'use strict';\n\nconst { EMPTY_BUFFER } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\n\n/**\n * Merges an array of buffers into a new buffer.\n *\n * @param {Buffer[]} list The array of buffers to concat\n * @param {Number} totalLength The total length of buffers in the list\n * @return {Buffer} The resulting buffer\n * @public\n */\nfunction concat(list, totalLength) {\n if (list.length === 0) return EMPTY_BUFFER;\n if (list.length === 1) return list[0];\n\n const target = Buffer.allocUnsafe(totalLength);\n let offset = 0;\n\n for (let i = 0; i < list.length; i++) {\n const buf = list[i];\n target.set(buf, offset);\n offset += buf.length;\n }\n\n if (offset < totalLength) {\n return new FastBuffer(target.buffer, target.byteOffset, offset);\n }\n\n return target;\n}\n\n/**\n * Masks a buffer using the given mask.\n *\n * @param {Buffer} source The buffer to mask\n * @param {Buffer} mask The mask to use\n * @param {Buffer} output The buffer where to store the result\n * @param {Number} offset The offset at which to start writing\n * @param {Number} length The number of bytes to mask.\n * @public\n */\nfunction _mask(source, mask, output, offset, length) {\n for (let i = 0; i < length; i++) {\n output[offset + i] = source[i] ^ mask[i & 3];\n }\n}\n\n/**\n * Unmasks a buffer using the given mask.\n *\n * @param {Buffer} buffer The buffer to unmask\n * @param {Buffer} mask The mask to use\n * @public\n */\nfunction _unmask(buffer, mask) {\n for (let i = 0; i < buffer.length; i++) {\n buffer[i] ^= mask[i & 3];\n }\n}\n\n/**\n * Converts a buffer to an `ArrayBuffer`.\n *\n * @param {Buffer} buf The buffer to convert\n * @return {ArrayBuffer} Converted buffer\n * @public\n */\nfunction toArrayBuffer(buf) {\n if (buf.length === buf.buffer.byteLength) {\n return buf.buffer;\n }\n\n return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.length);\n}\n\n/**\n * Converts `data` to a `Buffer`.\n *\n * @param {*} data The data to convert\n * @return {Buffer} The buffer\n * @throws {TypeError}\n * @public\n */\nfunction toBuffer(data) {\n toBuffer.readOnly = true;\n\n if (Buffer.isBuffer(data)) return data;\n\n let buf;\n\n if (data instanceof ArrayBuffer) {\n buf = new FastBuffer(data);\n } else if (ArrayBuffer.isView(data)) {\n buf = new FastBuffer(data.buffer, data.byteOffset, data.byteLength);\n } else {\n buf = Buffer.from(data);\n toBuffer.readOnly = false;\n }\n\n return buf;\n}\n\nmodule.exports = {\n concat,\n mask: _mask,\n toArrayBuffer,\n toBuffer,\n unmask: _unmask\n};\n\n/* istanbul ignore else */\nif (!process.env.WS_NO_BUFFER_UTIL) {\n try {\n const bufferUtil = require('bufferutil');\n\n module.exports.mask = function (source, mask, output, offset, length) {\n if (length < 48) _mask(source, mask, output, offset, length);\n else bufferUtil.mask(source, mask, output, offset, length);\n };\n\n module.exports.unmask = function (buffer, mask) {\n if (buffer.length < 32) _unmask(buffer, mask);\n else bufferUtil.unmask(buffer, mask);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n", "'use strict';\n\nconst kDone = Symbol('kDone');\nconst kRun = Symbol('kRun');\n\n/**\n * A very simple job queue with adjustable concurrency. Adapted from\n * https://github.com/STRML/async-limiter\n */\nclass Limiter {\n /**\n * Creates a new `Limiter`.\n *\n * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed\n * to run concurrently\n */\n constructor(concurrency) {\n this[kDone] = () => {\n this.pending--;\n this[kRun]();\n };\n this.concurrency = concurrency || Infinity;\n this.jobs = [];\n this.pending = 0;\n }\n\n /**\n * Adds a job to the queue.\n *\n * @param {Function} job The job to run\n * @public\n */\n add(job) {\n this.jobs.push(job);\n this[kRun]();\n }\n\n /**\n * Removes a job from the queue and runs it if possible.\n *\n * @private\n */\n [kRun]() {\n if (this.pending === this.concurrency) return;\n\n if (this.jobs.length) {\n const job = this.jobs.shift();\n\n this.pending++;\n job(this[kDone]);\n }\n }\n}\n\nmodule.exports = Limiter;\n", "'use strict';\n\nconst zlib = require('zlib');\n\nconst bufferUtil = require('./buffer-util');\nconst Limiter = require('./limiter');\nconst { kStatusCode } = require('./constants');\n\nconst FastBuffer = Buffer[Symbol.species];\nconst TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]);\nconst kPerMessageDeflate = Symbol('permessage-deflate');\nconst kTotalLength = Symbol('total-length');\nconst kCallback = Symbol('callback');\nconst kBuffers = Symbol('buffers');\nconst kError = Symbol('error');\n\n//\n// We limit zlib concurrency, which prevents severe memory fragmentation\n// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913\n// and https://github.com/websockets/ws/issues/1202\n//\n// Intentionally global; it's the global thread pool that's an issue.\n//\nlet zlibLimiter;\n\n/**\n * permessage-deflate implementation.\n */\nclass PerMessageDeflate {\n /**\n * Creates a PerMessageDeflate instance.\n *\n * @param {Object} [options] Configuration options\n * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support\n * for, or request, a custom client window size\n * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/\n * acknowledge disabling of client context takeover\n * @param {Number} [options.concurrencyLimit=10] The number of concurrent\n * calls to zlib\n * @param {Boolean} [options.isServer=false] Create the instance in either\n * server or client mode\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the\n * use of a custom server window size\n * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept\n * disabling of server context takeover\n * @param {Number} [options.threshold=1024] Size (in bytes) below which\n * messages should not be compressed if context takeover is disabled\n * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on\n * deflate\n * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on\n * inflate\n */\n constructor(options) {\n this._options = options || {};\n this._threshold =\n this._options.threshold !== undefined ? this._options.threshold : 1024;\n this._maxPayload = this._options.maxPayload | 0;\n this._isServer = !!this._options.isServer;\n this._deflate = null;\n this._inflate = null;\n\n this.params = null;\n\n if (!zlibLimiter) {\n const concurrency =\n this._options.concurrencyLimit !== undefined\n ? this._options.concurrencyLimit\n : 10;\n zlibLimiter = new Limiter(concurrency);\n }\n }\n\n /**\n * @type {String}\n */\n static get extensionName() {\n return 'permessage-deflate';\n }\n\n /**\n * Create an extension negotiation offer.\n *\n * @return {Object} Extension parameters\n * @public\n */\n offer() {\n const params = {};\n\n if (this._options.serverNoContextTakeover) {\n params.server_no_context_takeover = true;\n }\n if (this._options.clientNoContextTakeover) {\n params.client_no_context_takeover = true;\n }\n if (this._options.serverMaxWindowBits) {\n params.server_max_window_bits = this._options.serverMaxWindowBits;\n }\n if (this._options.clientMaxWindowBits) {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n } else if (this._options.clientMaxWindowBits == null) {\n params.client_max_window_bits = true;\n }\n\n return params;\n }\n\n /**\n * Accept an extension negotiation offer/response.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Object} Accepted configuration\n * @public\n */\n accept(configurations) {\n configurations = this.normalizeParams(configurations);\n\n this.params = this._isServer\n ? this.acceptAsServer(configurations)\n : this.acceptAsClient(configurations);\n\n return this.params;\n }\n\n /**\n * Releases all resources used by the extension.\n *\n * @public\n */\n cleanup() {\n if (this._inflate) {\n this._inflate.close();\n this._inflate = null;\n }\n\n if (this._deflate) {\n const callback = this._deflate[kCallback];\n\n this._deflate.close();\n this._deflate = null;\n\n if (callback) {\n callback(\n new Error(\n 'The deflate stream was closed while data was being processed'\n )\n );\n }\n }\n }\n\n /**\n * Accept an extension negotiation offer.\n *\n * @param {Array} offers The extension negotiation offers\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsServer(offers) {\n const opts = this._options;\n const accepted = offers.find((params) => {\n if (\n (opts.serverNoContextTakeover === false &&\n params.server_no_context_takeover) ||\n (params.server_max_window_bits &&\n (opts.serverMaxWindowBits === false ||\n (typeof opts.serverMaxWindowBits === 'number' &&\n opts.serverMaxWindowBits > params.server_max_window_bits))) ||\n (typeof opts.clientMaxWindowBits === 'number' &&\n !params.client_max_window_bits)\n ) {\n return false;\n }\n\n return true;\n });\n\n if (!accepted) {\n throw new Error('None of the extension offers can be accepted');\n }\n\n if (opts.serverNoContextTakeover) {\n accepted.server_no_context_takeover = true;\n }\n if (opts.clientNoContextTakeover) {\n accepted.client_no_context_takeover = true;\n }\n if (typeof opts.serverMaxWindowBits === 'number') {\n accepted.server_max_window_bits = opts.serverMaxWindowBits;\n }\n if (typeof opts.clientMaxWindowBits === 'number') {\n accepted.client_max_window_bits = opts.clientMaxWindowBits;\n } else if (\n accepted.client_max_window_bits === true ||\n opts.clientMaxWindowBits === false\n ) {\n delete accepted.client_max_window_bits;\n }\n\n return accepted;\n }\n\n /**\n * Accept the extension negotiation response.\n *\n * @param {Array} response The extension negotiation response\n * @return {Object} Accepted configuration\n * @private\n */\n acceptAsClient(response) {\n const params = response[0];\n\n if (\n this._options.clientNoContextTakeover === false &&\n params.client_no_context_takeover\n ) {\n throw new Error('Unexpected parameter \"client_no_context_takeover\"');\n }\n\n if (!params.client_max_window_bits) {\n if (typeof this._options.clientMaxWindowBits === 'number') {\n params.client_max_window_bits = this._options.clientMaxWindowBits;\n }\n } else if (\n this._options.clientMaxWindowBits === false ||\n (typeof this._options.clientMaxWindowBits === 'number' &&\n params.client_max_window_bits > this._options.clientMaxWindowBits)\n ) {\n throw new Error(\n 'Unexpected or invalid parameter \"client_max_window_bits\"'\n );\n }\n\n return params;\n }\n\n /**\n * Normalize parameters.\n *\n * @param {Array} configurations The extension negotiation offers/reponse\n * @return {Array} The offers/response with normalized parameters\n * @private\n */\n normalizeParams(configurations) {\n configurations.forEach((params) => {\n Object.keys(params).forEach((key) => {\n let value = params[key];\n\n if (value.length > 1) {\n throw new Error(`Parameter \"${key}\" must have only a single value`);\n }\n\n value = value[0];\n\n if (key === 'client_max_window_bits') {\n if (value !== true) {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (!this._isServer) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else if (key === 'server_max_window_bits') {\n const num = +value;\n if (!Number.isInteger(num) || num < 8 || num > 15) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n value = num;\n } else if (\n key === 'client_no_context_takeover' ||\n key === 'server_no_context_takeover'\n ) {\n if (value !== true) {\n throw new TypeError(\n `Invalid value for parameter \"${key}\": ${value}`\n );\n }\n } else {\n throw new Error(`Unknown parameter \"${key}\"`);\n }\n\n params[key] = value;\n });\n });\n\n return configurations;\n }\n\n /**\n * Decompress data. Concurrency limited.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n decompress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._decompress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Compress data. Concurrency limited.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @public\n */\n compress(data, fin, callback) {\n zlibLimiter.add((done) => {\n this._compress(data, fin, (err, result) => {\n done();\n callback(err, result);\n });\n });\n }\n\n /**\n * Decompress data.\n *\n * @param {Buffer} data Compressed data\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _decompress(data, fin, callback) {\n const endpoint = this._isServer ? 'client' : 'server';\n\n if (!this._inflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._inflate = zlib.createInflateRaw({\n ...this._options.zlibInflateOptions,\n windowBits\n });\n this._inflate[kPerMessageDeflate] = this;\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n this._inflate.on('error', inflateOnError);\n this._inflate.on('data', inflateOnData);\n }\n\n this._inflate[kCallback] = callback;\n\n this._inflate.write(data);\n if (fin) this._inflate.write(TRAILER);\n\n this._inflate.flush(() => {\n const err = this._inflate[kError];\n\n if (err) {\n this._inflate.close();\n this._inflate = null;\n callback(err);\n return;\n }\n\n const data = bufferUtil.concat(\n this._inflate[kBuffers],\n this._inflate[kTotalLength]\n );\n\n if (this._inflate._readableState.endEmitted) {\n this._inflate.close();\n this._inflate = null;\n } else {\n this._inflate[kTotalLength] = 0;\n this._inflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._inflate.reset();\n }\n }\n\n callback(null, data);\n });\n }\n\n /**\n * Compress data.\n *\n * @param {(Buffer|String)} data Data to compress\n * @param {Boolean} fin Specifies whether or not this is the last fragment\n * @param {Function} callback Callback\n * @private\n */\n _compress(data, fin, callback) {\n const endpoint = this._isServer ? 'server' : 'client';\n\n if (!this._deflate) {\n const key = `${endpoint}_max_window_bits`;\n const windowBits =\n typeof this.params[key] !== 'number'\n ? zlib.Z_DEFAULT_WINDOWBITS\n : this.params[key];\n\n this._deflate = zlib.createDeflateRaw({\n ...this._options.zlibDeflateOptions,\n windowBits\n });\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n this._deflate.on('data', deflateOnData);\n }\n\n this._deflate[kCallback] = callback;\n\n this._deflate.write(data);\n this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {\n if (!this._deflate) {\n //\n // The deflate stream was closed while data was being processed.\n //\n return;\n }\n\n let data = bufferUtil.concat(\n this._deflate[kBuffers],\n this._deflate[kTotalLength]\n );\n\n if (fin) {\n data = new FastBuffer(data.buffer, data.byteOffset, data.length - 4);\n }\n\n //\n // Ensure that the callback will not be called again in\n // `PerMessageDeflate#cleanup()`.\n //\n this._deflate[kCallback] = null;\n\n this._deflate[kTotalLength] = 0;\n this._deflate[kBuffers] = [];\n\n if (fin && this.params[`${endpoint}_no_context_takeover`]) {\n this._deflate.reset();\n }\n\n callback(null, data);\n });\n }\n}\n\nmodule.exports = PerMessageDeflate;\n\n/**\n * The listener of the `zlib.DeflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction deflateOnData(chunk) {\n this[kBuffers].push(chunk);\n this[kTotalLength] += chunk.length;\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction inflateOnData(chunk) {\n this[kTotalLength] += chunk.length;\n\n if (\n this[kPerMessageDeflate]._maxPayload < 1 ||\n this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload\n ) {\n this[kBuffers].push(chunk);\n return;\n }\n\n this[kError] = new RangeError('Max payload size exceeded');\n this[kError].code = 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH';\n this[kError][kStatusCode] = 1009;\n this.removeListener('data', inflateOnData);\n\n //\n // The choice to employ `zlib.reset()` over `zlib.close()` is dictated by the\n // fact that in Node.js versions prior to 13.10.0, the callback for\n // `zlib.flush()` is not called if `zlib.close()` is used. Utilizing\n // `zlib.reset()` ensures that either the callback is invoked or an error is\n // emitted.\n //\n this.reset();\n}\n\n/**\n * The listener of the `zlib.InflateRaw` stream `'error'` event.\n *\n * @param {Error} err The emitted error\n * @private\n */\nfunction inflateOnError(err) {\n //\n // There is no need to call `Zlib#close()` as the handle is automatically\n // closed when an error is emitted.\n //\n this[kPerMessageDeflate]._inflate = null;\n\n if (this[kError]) {\n this[kCallback](this[kError]);\n return;\n }\n\n err[kStatusCode] = 1007;\n this[kCallback](err);\n}\n", "'use strict';\n\nconst { isUtf8 } = require('buffer');\n\nconst { hasBlob } = require('./constants');\n\n//\n// Allowed token characters:\n//\n// '!', '#', '$', '%', '&', ''', '*', '+', '-',\n// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~'\n//\n// tokenChars[32] === 0 // ' '\n// tokenChars[33] === 1 // '!'\n// tokenChars[34] === 0 // '\"'\n// ...\n//\n// prettier-ignore\nconst tokenChars = [\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15\n 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31\n 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63\n 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111\n 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127\n];\n\n/**\n * Checks if a status code is allowed in a close frame.\n *\n * @param {Number} code The status code\n * @return {Boolean} `true` if the status code is valid, else `false`\n * @public\n */\nfunction isValidStatusCode(code) {\n return (\n (code >= 1000 &&\n code <= 1014 &&\n code !== 1004 &&\n code !== 1005 &&\n code !== 1006) ||\n (code >= 3000 && code <= 4999)\n );\n}\n\n/**\n * Checks if a given buffer contains only correct UTF-8.\n * Ported from https://www.cl.cam.ac.uk/%7Emgk25/ucs/utf8_check.c by\n * Markus Kuhn.\n *\n * @param {Buffer} buf The buffer to check\n * @return {Boolean} `true` if `buf` contains only correct UTF-8, else `false`\n * @public\n */\nfunction _isValidUTF8(buf) {\n const len = buf.length;\n let i = 0;\n\n while (i < len) {\n if ((buf[i] & 0x80) === 0) {\n // 0xxxxxxx\n i++;\n } else if ((buf[i] & 0xe0) === 0xc0) {\n // 110xxxxx 10xxxxxx\n if (\n i + 1 === len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i] & 0xfe) === 0xc0 // Overlong\n ) {\n return false;\n }\n\n i += 2;\n } else if ((buf[i] & 0xf0) === 0xe0) {\n // 1110xxxx 10xxxxxx 10xxxxxx\n if (\n i + 2 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i] === 0xe0 && (buf[i + 1] & 0xe0) === 0x80) || // Overlong\n (buf[i] === 0xed && (buf[i + 1] & 0xe0) === 0xa0) // Surrogate (U+D800 - U+DFFF)\n ) {\n return false;\n }\n\n i += 3;\n } else if ((buf[i] & 0xf8) === 0xf0) {\n // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n if (\n i + 3 >= len ||\n (buf[i + 1] & 0xc0) !== 0x80 ||\n (buf[i + 2] & 0xc0) !== 0x80 ||\n (buf[i + 3] & 0xc0) !== 0x80 ||\n (buf[i] === 0xf0 && (buf[i + 1] & 0xf0) === 0x80) || // Overlong\n (buf[i] === 0xf4 && buf[i + 1] > 0x8f) ||\n buf[i] > 0xf4 // > U+10FFFF\n ) {\n return false;\n }\n\n i += 4;\n } else {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Determines whether a value is a `Blob`.\n *\n * @param {*} value The value to be tested\n * @return {Boolean} `true` if `value` is a `Blob`, else `false`\n * @private\n */\nfunction isBlob(value) {\n return (\n hasBlob &&\n typeof value === 'object' &&\n typeof value.arrayBuffer === 'function' &&\n typeof value.type === 'string' &&\n typeof value.stream === 'function' &&\n (value[Symbol.toStringTag] === 'Blob' ||\n value[Symbol.toStringTag] === 'File')\n );\n}\n\nmodule.exports = {\n isBlob,\n isValidStatusCode,\n isValidUTF8: _isValidUTF8,\n tokenChars\n};\n\nif (isUtf8) {\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 24 ? _isValidUTF8(buf) : isUtf8(buf);\n };\n} /* istanbul ignore else */ else if (!process.env.WS_NO_UTF_8_VALIDATE) {\n try {\n const isValidUTF8 = require('utf-8-validate');\n\n module.exports.isValidUTF8 = function (buf) {\n return buf.length < 32 ? _isValidUTF8(buf) : isValidUTF8(buf);\n };\n } catch (e) {\n // Continue regardless of the error.\n }\n}\n", "'use strict';\n\nconst { Writable } = require('stream');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst {\n BINARY_TYPES,\n EMPTY_BUFFER,\n kStatusCode,\n kWebSocket\n} = require('./constants');\nconst { concat, toArrayBuffer, unmask } = require('./buffer-util');\nconst { isValidStatusCode, isValidUTF8 } = require('./validation');\n\nconst FastBuffer = Buffer[Symbol.species];\n\nconst GET_INFO = 0;\nconst GET_PAYLOAD_LENGTH_16 = 1;\nconst GET_PAYLOAD_LENGTH_64 = 2;\nconst GET_MASK = 3;\nconst GET_DATA = 4;\nconst INFLATING = 5;\nconst DEFER_EVENT = 6;\n\n/**\n * HyBi Receiver implementation.\n *\n * @extends Writable\n */\nclass Receiver extends Writable {\n /**\n * Creates a Receiver instance.\n *\n * @param {Object} [options] Options object\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {String} [options.binaryType=nodebuffer] The type for binary data\n * @param {Object} [options.extensions] An object containing the negotiated\n * extensions\n * @param {Boolean} [options.isServer=false] Specifies whether to operate in\n * client or server mode\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message length\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n */\n constructor(options = {}) {\n super();\n\n this._allowSynchronousEvents =\n options.allowSynchronousEvents !== undefined\n ? options.allowSynchronousEvents\n : true;\n this._binaryType = options.binaryType || BINARY_TYPES[0];\n this._extensions = options.extensions || {};\n this._isServer = !!options.isServer;\n this._maxBufferedChunks = options.maxBufferedChunks | 0;\n this._maxFragments = options.maxFragments | 0;\n this._maxPayload = options.maxPayload | 0;\n this._skipUTF8Validation = !!options.skipUTF8Validation;\n this[kWebSocket] = undefined;\n\n this._bufferedBytes = 0;\n this._buffers = [];\n\n this._compressed = false;\n this._payloadLength = 0;\n this._mask = undefined;\n this._fragmented = 0;\n this._masked = false;\n this._fin = false;\n this._opcode = 0;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragments = [];\n\n this._errored = false;\n this._loop = false;\n this._state = GET_INFO;\n }\n\n /**\n * Implements `Writable.prototype._write()`.\n *\n * @param {Buffer} chunk The chunk of data to write\n * @param {String} encoding The character encoding of `chunk`\n * @param {Function} cb Callback\n * @private\n */\n _write(chunk, encoding, cb) {\n if (this._opcode === 0x08 && this._state == GET_INFO) return cb();\n\n if (\n this._maxBufferedChunks > 0 &&\n this._buffers.length >= this._maxBufferedChunks\n ) {\n cb(\n this.createError(\n RangeError,\n 'Too many buffered chunks',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n )\n );\n return;\n }\n\n this._bufferedBytes += chunk.length;\n this._buffers.push(chunk);\n this.startLoop(cb);\n }\n\n /**\n * Consumes `n` bytes from the buffered data.\n *\n * @param {Number} n The number of bytes to consume\n * @return {Buffer} The consumed bytes\n * @private\n */\n consume(n) {\n this._bufferedBytes -= n;\n\n if (n === this._buffers[0].length) return this._buffers.shift();\n\n if (n < this._buffers[0].length) {\n const buf = this._buffers[0];\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n\n return new FastBuffer(buf.buffer, buf.byteOffset, n);\n }\n\n const dst = Buffer.allocUnsafe(n);\n\n do {\n const buf = this._buffers[0];\n const offset = dst.length - n;\n\n if (n >= buf.length) {\n dst.set(this._buffers.shift(), offset);\n } else {\n dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);\n this._buffers[0] = new FastBuffer(\n buf.buffer,\n buf.byteOffset + n,\n buf.length - n\n );\n }\n\n n -= buf.length;\n } while (n > 0);\n\n return dst;\n }\n\n /**\n * Starts the parsing loop.\n *\n * @param {Function} cb Callback\n * @private\n */\n startLoop(cb) {\n this._loop = true;\n\n do {\n switch (this._state) {\n case GET_INFO:\n this.getInfo(cb);\n break;\n case GET_PAYLOAD_LENGTH_16:\n this.getPayloadLength16(cb);\n break;\n case GET_PAYLOAD_LENGTH_64:\n this.getPayloadLength64(cb);\n break;\n case GET_MASK:\n this.getMask();\n break;\n case GET_DATA:\n this.getData(cb);\n break;\n case INFLATING:\n case DEFER_EVENT:\n this._loop = false;\n return;\n }\n } while (this._loop);\n\n if (!this._errored) cb();\n }\n\n /**\n * Reads the first two bytes of a frame.\n *\n * @param {Function} cb Callback\n * @private\n */\n getInfo(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(2);\n\n if ((buf[0] & 0x30) !== 0x00) {\n const error = this.createError(\n RangeError,\n 'RSV2 and RSV3 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_2_3'\n );\n\n cb(error);\n return;\n }\n\n const compressed = (buf[0] & 0x40) === 0x40;\n\n if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n this._fin = (buf[0] & 0x80) === 0x80;\n this._opcode = buf[0] & 0x0f;\n this._payloadLength = buf[1] & 0x7f;\n\n if (this._opcode === 0x00) {\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fragmented) {\n const error = this.createError(\n RangeError,\n 'invalid opcode 0',\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._opcode = this._fragmented;\n } else if (this._opcode === 0x01 || this._opcode === 0x02) {\n if (this._fragmented) {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n this._compressed = compressed;\n } else if (this._opcode > 0x07 && this._opcode < 0x0b) {\n if (!this._fin) {\n const error = this.createError(\n RangeError,\n 'FIN must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_FIN'\n );\n\n cb(error);\n return;\n }\n\n if (compressed) {\n const error = this.createError(\n RangeError,\n 'RSV1 must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_RSV_1'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._payloadLength > 0x7d ||\n (this._opcode === 0x08 && this._payloadLength === 1)\n ) {\n const error = this.createError(\n RangeError,\n `invalid payload length ${this._payloadLength}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n } else {\n const error = this.createError(\n RangeError,\n `invalid opcode ${this._opcode}`,\n true,\n 1002,\n 'WS_ERR_INVALID_OPCODE'\n );\n\n cb(error);\n return;\n }\n\n if (!this._fin && !this._fragmented) this._fragmented = this._opcode;\n this._masked = (buf[1] & 0x80) === 0x80;\n\n if (this._isServer) {\n if (!this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be set',\n true,\n 1002,\n 'WS_ERR_EXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n } else if (this._masked) {\n const error = this.createError(\n RangeError,\n 'MASK must be clear',\n true,\n 1002,\n 'WS_ERR_UNEXPECTED_MASK'\n );\n\n cb(error);\n return;\n }\n\n if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16;\n else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64;\n else this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+16).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength16(cb) {\n if (this._bufferedBytes < 2) {\n this._loop = false;\n return;\n }\n\n this._payloadLength = this.consume(2).readUInt16BE(0);\n this.haveLength(cb);\n }\n\n /**\n * Gets extended payload length (7+64).\n *\n * @param {Function} cb Callback\n * @private\n */\n getPayloadLength64(cb) {\n if (this._bufferedBytes < 8) {\n this._loop = false;\n return;\n }\n\n const buf = this.consume(8);\n const num = buf.readUInt32BE(0);\n\n //\n // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned\n // if payload length is greater than this number.\n //\n if (num > Math.pow(2, 53 - 32) - 1) {\n const error = this.createError(\n RangeError,\n 'Unsupported WebSocket frame: payload length > 2^53 - 1',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);\n this.haveLength(cb);\n }\n\n /**\n * Payload length has been read.\n *\n * @param {Function} cb Callback\n * @private\n */\n haveLength(cb) {\n if (this._payloadLength && this._opcode < 0x08) {\n this._totalPayloadLength += this._payloadLength;\n if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n }\n\n if (this._masked) this._state = GET_MASK;\n else this._state = GET_DATA;\n }\n\n /**\n * Reads mask bytes.\n *\n * @private\n */\n getMask() {\n if (this._bufferedBytes < 4) {\n this._loop = false;\n return;\n }\n\n this._mask = this.consume(4);\n this._state = GET_DATA;\n }\n\n /**\n * Reads data bytes.\n *\n * @param {Function} cb Callback\n * @private\n */\n getData(cb) {\n let data = EMPTY_BUFFER;\n\n if (this._payloadLength) {\n if (this._bufferedBytes < this._payloadLength) {\n this._loop = false;\n return;\n }\n\n data = this.consume(this._payloadLength);\n\n if (\n this._masked &&\n (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0\n ) {\n unmask(data, this._mask);\n }\n }\n\n if (this._opcode > 0x07) {\n this.controlMessage(data, cb);\n return;\n }\n\n if (this._compressed) {\n this._state = INFLATING;\n this.decompress(data, cb);\n return;\n }\n\n if (data.length) {\n if (\n this._maxFragments > 0 &&\n this._fragments.length >= this._maxFragments\n ) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n //\n // This message is not compressed so its length is the sum of the payload\n // length of all fragments.\n //\n this._messageLength = this._totalPayloadLength;\n this._fragments.push(data);\n }\n\n this.dataMessage(cb);\n }\n\n /**\n * Decompresses data.\n *\n * @param {Buffer} data Compressed data\n * @param {Function} cb Callback\n * @private\n */\n decompress(data, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n perMessageDeflate.decompress(data, this._fin, (err, buf) => {\n if (err) return cb(err);\n\n if (buf.length) {\n this._messageLength += buf.length;\n if (this._messageLength > this._maxPayload && this._maxPayload > 0) {\n const error = this.createError(\n RangeError,\n 'Max payload size exceeded',\n false,\n 1009,\n 'WS_ERR_UNSUPPORTED_MESSAGE_LENGTH'\n );\n\n cb(error);\n return;\n }\n\n if (\n this._maxFragments > 0 &&\n this._fragments.length >= this._maxFragments\n ) {\n const error = this.createError(\n RangeError,\n 'Too many message fragments',\n false,\n 1008,\n 'WS_ERR_TOO_MANY_BUFFERED_PARTS'\n );\n\n cb(error);\n return;\n }\n\n this._fragments.push(buf);\n }\n\n this.dataMessage(cb);\n if (this._state === GET_INFO) this.startLoop(cb);\n });\n }\n\n /**\n * Handles a data message.\n *\n * @param {Function} cb Callback\n * @private\n */\n dataMessage(cb) {\n if (!this._fin) {\n this._state = GET_INFO;\n return;\n }\n\n const messageLength = this._messageLength;\n const fragments = this._fragments;\n\n this._totalPayloadLength = 0;\n this._messageLength = 0;\n this._fragmented = 0;\n this._fragments = [];\n\n if (this._opcode === 2) {\n let data;\n\n if (this._binaryType === 'nodebuffer') {\n data = concat(fragments, messageLength);\n } else if (this._binaryType === 'arraybuffer') {\n data = toArrayBuffer(concat(fragments, messageLength));\n } else if (this._binaryType === 'blob') {\n data = new Blob(fragments);\n } else {\n data = fragments;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit('message', data, true);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', data, true);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n } else {\n const buf = concat(fragments, messageLength);\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n if (this._state === INFLATING || this._allowSynchronousEvents) {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit('message', buf, false);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n }\n\n /**\n * Handles a control message.\n *\n * @param {Buffer} data Data to handle\n * @return {(Error|RangeError|undefined)} A possible error\n * @private\n */\n controlMessage(data, cb) {\n if (this._opcode === 0x08) {\n if (data.length === 0) {\n this._loop = false;\n this.emit('conclude', 1005, EMPTY_BUFFER);\n this.end();\n } else {\n const code = data.readUInt16BE(0);\n\n if (!isValidStatusCode(code)) {\n const error = this.createError(\n RangeError,\n `invalid status code ${code}`,\n true,\n 1002,\n 'WS_ERR_INVALID_CLOSE_CODE'\n );\n\n cb(error);\n return;\n }\n\n const buf = new FastBuffer(\n data.buffer,\n data.byteOffset + 2,\n data.length - 2\n );\n\n if (!this._skipUTF8Validation && !isValidUTF8(buf)) {\n const error = this.createError(\n Error,\n 'invalid UTF-8 sequence',\n true,\n 1007,\n 'WS_ERR_INVALID_UTF8'\n );\n\n cb(error);\n return;\n }\n\n this._loop = false;\n this.emit('conclude', code, buf);\n this.end();\n }\n\n this._state = GET_INFO;\n return;\n }\n\n if (this._allowSynchronousEvents) {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n } else {\n this._state = DEFER_EVENT;\n setImmediate(() => {\n this.emit(this._opcode === 0x09 ? 'ping' : 'pong', data);\n this._state = GET_INFO;\n this.startLoop(cb);\n });\n }\n }\n\n /**\n * Builds an error object.\n *\n * @param {function(new:Error|RangeError)} ErrorCtor The error constructor\n * @param {String} message The error message\n * @param {Boolean} prefix Specifies whether or not to add a default prefix to\n * `message`\n * @param {Number} statusCode The status code\n * @param {String} errorCode The exposed error code\n * @return {(Error|RangeError)} The error\n * @private\n */\n createError(ErrorCtor, message, prefix, statusCode, errorCode) {\n this._loop = false;\n this._errored = true;\n\n const err = new ErrorCtor(\n prefix ? `Invalid WebSocket frame: ${message}` : message\n );\n\n Error.captureStackTrace(err, this.createError);\n err.code = errorCode;\n err[kStatusCode] = statusCode;\n return err;\n }\n}\n\nmodule.exports = Receiver;\n", "/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex\" }] */\n\n'use strict';\n\nconst { Duplex } = require('stream');\nconst { randomFillSync } = require('crypto');\nconst {\n types: { isUint8Array }\n} = require('util');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst { EMPTY_BUFFER, kWebSocket, NOOP } = require('./constants');\nconst { isBlob, isValidStatusCode } = require('./validation');\nconst { mask: applyMask, toBuffer } = require('./buffer-util');\n\nconst kByteLength = Symbol('kByteLength');\nconst maskBuffer = Buffer.alloc(4);\nconst RANDOM_POOL_SIZE = 8 * 1024;\nlet randomPool;\nlet randomPoolPointer = RANDOM_POOL_SIZE;\n\nconst DEFAULT = 0;\nconst DEFLATING = 1;\nconst GET_BLOB_DATA = 2;\n\n/**\n * HyBi Sender implementation.\n */\nclass Sender {\n /**\n * Creates a Sender instance.\n *\n * @param {Duplex} socket The connection socket\n * @param {Object} [extensions] An object containing the negotiated extensions\n * @param {Function} [generateMask] The function used to generate the masking\n * key\n */\n constructor(socket, extensions, generateMask) {\n this._extensions = extensions || {};\n\n if (generateMask) {\n this._generateMask = generateMask;\n this._maskBuffer = Buffer.alloc(4);\n }\n\n this._socket = socket;\n\n this._firstFragment = true;\n this._compress = false;\n\n this._bufferedBytes = 0;\n this._queue = [];\n this._state = DEFAULT;\n this.onerror = NOOP;\n this[kWebSocket] = undefined;\n }\n\n /**\n * Frames a piece of data according to the HyBi WebSocket protocol.\n *\n * @param {(Buffer|String)} data The data to frame\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @return {(Buffer|String)[]} The framed data\n * @public\n */\n static frame(data, options) {\n let mask;\n let merge = false;\n let offset = 2;\n let skipMasking = false;\n\n if (options.mask) {\n mask = options.maskBuffer || maskBuffer;\n\n if (options.generateMask) {\n options.generateMask(mask);\n } else {\n if (randomPoolPointer === RANDOM_POOL_SIZE) {\n /* istanbul ignore else */\n if (randomPool === undefined) {\n //\n // This is lazily initialized because server-sent frames must not\n // be masked so it may never be used.\n //\n randomPool = Buffer.alloc(RANDOM_POOL_SIZE);\n }\n\n randomFillSync(randomPool, 0, RANDOM_POOL_SIZE);\n randomPoolPointer = 0;\n }\n\n mask[0] = randomPool[randomPoolPointer++];\n mask[1] = randomPool[randomPoolPointer++];\n mask[2] = randomPool[randomPoolPointer++];\n mask[3] = randomPool[randomPoolPointer++];\n }\n\n skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;\n offset = 6;\n }\n\n let dataLength;\n\n if (typeof data === 'string') {\n if (\n (!options.mask || skipMasking) &&\n options[kByteLength] !== undefined\n ) {\n dataLength = options[kByteLength];\n } else {\n data = Buffer.from(data);\n dataLength = data.length;\n }\n } else {\n dataLength = data.length;\n merge = options.mask && options.readOnly && !skipMasking;\n }\n\n let payloadLength = dataLength;\n\n if (dataLength >= 65536) {\n offset += 8;\n payloadLength = 127;\n } else if (dataLength > 125) {\n offset += 2;\n payloadLength = 126;\n }\n\n const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);\n\n target[0] = options.fin ? options.opcode | 0x80 : options.opcode;\n if (options.rsv1) target[0] |= 0x40;\n\n target[1] = payloadLength;\n\n if (payloadLength === 126) {\n target.writeUInt16BE(dataLength, 2);\n } else if (payloadLength === 127) {\n target[2] = target[3] = 0;\n target.writeUIntBE(dataLength, 4, 6);\n }\n\n if (!options.mask) return [target, data];\n\n target[1] |= 0x80;\n target[offset - 4] = mask[0];\n target[offset - 3] = mask[1];\n target[offset - 2] = mask[2];\n target[offset - 1] = mask[3];\n\n if (skipMasking) return [target, data];\n\n if (merge) {\n applyMask(data, mask, target, offset, dataLength);\n return [target];\n }\n\n applyMask(data, mask, data, 0, dataLength);\n return [target, data];\n }\n\n /**\n * Sends a close message to the other peer.\n *\n * @param {Number} [code] The status code component of the body\n * @param {(String|Buffer)} [data] The message component of the body\n * @param {Boolean} [mask=false] Specifies whether or not to mask the message\n * @param {Function} [cb] Callback\n * @public\n */\n close(code, data, mask, cb) {\n let buf;\n\n if (code === undefined) {\n buf = EMPTY_BUFFER;\n } else if (typeof code !== 'number' || !isValidStatusCode(code)) {\n throw new TypeError('First argument must be a valid error code number');\n } else if (data === undefined || !data.length) {\n buf = Buffer.allocUnsafe(2);\n buf.writeUInt16BE(code, 0);\n } else {\n const length = Buffer.byteLength(data);\n\n if (length > 123) {\n throw new RangeError('The message must not be greater than 123 bytes');\n }\n\n buf = Buffer.allocUnsafe(2 + length);\n buf.writeUInt16BE(code, 0);\n\n if (typeof data === 'string') {\n buf.write(data, 2);\n } else if (isUint8Array(data)) {\n buf.set(data, 2);\n } else {\n throw new TypeError('Second argument must be a string or a Uint8Array');\n }\n }\n\n const options = {\n [kByteLength]: buf.length,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x08,\n readOnly: false,\n rsv1: false\n };\n\n if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, buf, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(buf, options), cb);\n }\n }\n\n /**\n * Sends a ping message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n ping(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x09,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a pong message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Boolean} [mask=false] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback\n * @public\n */\n pong(data, mask, cb) {\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (byteLength > 125) {\n throw new RangeError('The data size must not be greater than 125 bytes');\n }\n\n const options = {\n [kByteLength]: byteLength,\n fin: true,\n generateMask: this._generateMask,\n mask,\n maskBuffer: this._maskBuffer,\n opcode: 0x0a,\n readOnly,\n rsv1: false\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, false, options, cb]);\n } else {\n this.getBlobData(data, false, options, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, false, options, cb]);\n } else {\n this.sendFrame(Sender.frame(data, options), cb);\n }\n }\n\n /**\n * Sends a data message to the other peer.\n *\n * @param {*} data The message to send\n * @param {Object} options Options object\n * @param {Boolean} [options.binary=false] Specifies whether `data` is binary\n * or text\n * @param {Boolean} [options.compress=false] Specifies whether or not to\n * compress `data`\n * @param {Boolean} [options.fin=false] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Function} [cb] Callback\n * @public\n */\n send(data, options, cb) {\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n let opcode = options.binary ? 2 : 1;\n let rsv1 = options.compress;\n\n let byteLength;\n let readOnly;\n\n if (typeof data === 'string') {\n byteLength = Buffer.byteLength(data);\n readOnly = false;\n } else if (isBlob(data)) {\n byteLength = data.size;\n readOnly = false;\n } else {\n data = toBuffer(data);\n byteLength = data.length;\n readOnly = toBuffer.readOnly;\n }\n\n if (this._firstFragment) {\n this._firstFragment = false;\n if (\n rsv1 &&\n perMessageDeflate &&\n perMessageDeflate.params[\n perMessageDeflate._isServer\n ? 'server_no_context_takeover'\n : 'client_no_context_takeover'\n ]\n ) {\n rsv1 = byteLength >= perMessageDeflate._threshold;\n }\n this._compress = rsv1;\n } else {\n rsv1 = false;\n opcode = 0;\n }\n\n if (options.fin) this._firstFragment = true;\n\n const opts = {\n [kByteLength]: byteLength,\n fin: options.fin,\n generateMask: this._generateMask,\n mask: options.mask,\n maskBuffer: this._maskBuffer,\n opcode,\n readOnly,\n rsv1\n };\n\n if (isBlob(data)) {\n if (this._state !== DEFAULT) {\n this.enqueue([this.getBlobData, data, this._compress, opts, cb]);\n } else {\n this.getBlobData(data, this._compress, opts, cb);\n }\n } else if (this._state !== DEFAULT) {\n this.enqueue([this.dispatch, data, this._compress, opts, cb]);\n } else {\n this.dispatch(data, this._compress, opts, cb);\n }\n }\n\n /**\n * Gets the contents of a blob as binary data.\n *\n * @param {Blob} blob The blob\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * the data\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n getBlobData(blob, compress, options, cb) {\n this._bufferedBytes += options[kByteLength];\n this._state = GET_BLOB_DATA;\n\n blob\n .arrayBuffer()\n .then((arrayBuffer) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while the blob was being read'\n );\n\n //\n // `callCallbacks` is called in the next tick to ensure that errors\n // that might be thrown in the callbacks behave like errors thrown\n // outside the promise chain.\n //\n process.nextTick(callCallbacks, this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n const data = toBuffer(arrayBuffer);\n\n if (!compress) {\n this._state = DEFAULT;\n this.sendFrame(Sender.frame(data, options), cb);\n this.dequeue();\n } else {\n this.dispatch(data, compress, options, cb);\n }\n })\n .catch((err) => {\n //\n // `onError` is called in the next tick for the same reason that\n // `callCallbacks` above is.\n //\n process.nextTick(onError, this, err, cb);\n });\n }\n\n /**\n * Dispatches a message.\n *\n * @param {(Buffer|String)} data The message to send\n * @param {Boolean} [compress=false] Specifies whether or not to compress\n * `data`\n * @param {Object} options Options object\n * @param {Boolean} [options.fin=false] Specifies whether or not to set the\n * FIN bit\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Boolean} [options.mask=false] Specifies whether or not to mask\n * `data`\n * @param {Buffer} [options.maskBuffer] The buffer used to store the masking\n * key\n * @param {Number} options.opcode The opcode\n * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be\n * modified\n * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the\n * RSV1 bit\n * @param {Function} [cb] Callback\n * @private\n */\n dispatch(data, compress, options, cb) {\n if (!compress) {\n this.sendFrame(Sender.frame(data, options), cb);\n return;\n }\n\n const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];\n\n this._bufferedBytes += options[kByteLength];\n this._state = DEFLATING;\n perMessageDeflate.compress(data, options.fin, (_, buf) => {\n if (this._socket.destroyed) {\n const err = new Error(\n 'The socket was closed while data was being compressed'\n );\n\n callCallbacks(this, err, cb);\n return;\n }\n\n this._bufferedBytes -= options[kByteLength];\n this._state = DEFAULT;\n options.readOnly = false;\n this.sendFrame(Sender.frame(buf, options), cb);\n this.dequeue();\n });\n }\n\n /**\n * Executes queued send operations.\n *\n * @private\n */\n dequeue() {\n while (this._state === DEFAULT && this._queue.length) {\n const params = this._queue.shift();\n\n this._bufferedBytes -= params[3][kByteLength];\n Reflect.apply(params[0], this, params.slice(1));\n }\n }\n\n /**\n * Enqueues a send operation.\n *\n * @param {Array} params Send operation parameters.\n * @private\n */\n enqueue(params) {\n this._bufferedBytes += params[3][kByteLength];\n this._queue.push(params);\n }\n\n /**\n * Sends a frame.\n *\n * @param {(Buffer | String)[]} list The frame to send\n * @param {Function} [cb] Callback\n * @private\n */\n sendFrame(list, cb) {\n if (list.length === 2) {\n this._socket.cork();\n this._socket.write(list[0]);\n this._socket.write(list[1], cb);\n this._socket.uncork();\n } else {\n this._socket.write(list[0], cb);\n }\n }\n}\n\nmodule.exports = Sender;\n\n/**\n * Calls queued callbacks with an error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error to call the callbacks with\n * @param {Function} [cb] The first callback\n * @private\n */\nfunction callCallbacks(sender, err, cb) {\n if (typeof cb === 'function') cb(err);\n\n for (let i = 0; i < sender._queue.length; i++) {\n const params = sender._queue[i];\n const callback = params[params.length - 1];\n\n if (typeof callback === 'function') callback(err);\n }\n}\n\n/**\n * Handles a `Sender` error.\n *\n * @param {Sender} sender The `Sender` instance\n * @param {Error} err The error\n * @param {Function} [cb] The first pending callback\n * @private\n */\nfunction onError(sender, err, cb) {\n callCallbacks(sender, err, cb);\n sender.onerror(err);\n}\n", "'use strict';\n\nconst { kForOnEventAttribute, kListener } = require('./constants');\n\nconst kCode = Symbol('kCode');\nconst kData = Symbol('kData');\nconst kError = Symbol('kError');\nconst kMessage = Symbol('kMessage');\nconst kReason = Symbol('kReason');\nconst kTarget = Symbol('kTarget');\nconst kType = Symbol('kType');\nconst kWasClean = Symbol('kWasClean');\n\n/**\n * Class representing an event.\n */\nclass Event {\n /**\n * Create a new `Event`.\n *\n * @param {String} type The name of the event\n * @throws {TypeError} If the `type` argument is not specified\n */\n constructor(type) {\n this[kTarget] = null;\n this[kType] = type;\n }\n\n /**\n * @type {*}\n */\n get target() {\n return this[kTarget];\n }\n\n /**\n * @type {String}\n */\n get type() {\n return this[kType];\n }\n}\n\nObject.defineProperty(Event.prototype, 'target', { enumerable: true });\nObject.defineProperty(Event.prototype, 'type', { enumerable: true });\n\n/**\n * Class representing a close event.\n *\n * @extends Event\n */\nclass CloseEvent extends Event {\n /**\n * Create a new `CloseEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {Number} [options.code=0] The status code explaining why the\n * connection was closed\n * @param {String} [options.reason=''] A human-readable string explaining why\n * the connection was closed\n * @param {Boolean} [options.wasClean=false] Indicates whether or not the\n * connection was cleanly closed\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kCode] = options.code === undefined ? 0 : options.code;\n this[kReason] = options.reason === undefined ? '' : options.reason;\n this[kWasClean] = options.wasClean === undefined ? false : options.wasClean;\n }\n\n /**\n * @type {Number}\n */\n get code() {\n return this[kCode];\n }\n\n /**\n * @type {String}\n */\n get reason() {\n return this[kReason];\n }\n\n /**\n * @type {Boolean}\n */\n get wasClean() {\n return this[kWasClean];\n }\n}\n\nObject.defineProperty(CloseEvent.prototype, 'code', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'reason', { enumerable: true });\nObject.defineProperty(CloseEvent.prototype, 'wasClean', { enumerable: true });\n\n/**\n * Class representing an error event.\n *\n * @extends Event\n */\nclass ErrorEvent extends Event {\n /**\n * Create a new `ErrorEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.error=null] The error that generated this event\n * @param {String} [options.message=''] The error message\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kError] = options.error === undefined ? null : options.error;\n this[kMessage] = options.message === undefined ? '' : options.message;\n }\n\n /**\n * @type {*}\n */\n get error() {\n return this[kError];\n }\n\n /**\n * @type {String}\n */\n get message() {\n return this[kMessage];\n }\n}\n\nObject.defineProperty(ErrorEvent.prototype, 'error', { enumerable: true });\nObject.defineProperty(ErrorEvent.prototype, 'message', { enumerable: true });\n\n/**\n * Class representing a message event.\n *\n * @extends Event\n */\nclass MessageEvent extends Event {\n /**\n * Create a new `MessageEvent`.\n *\n * @param {String} type The name of the event\n * @param {Object} [options] A dictionary object that allows for setting\n * attributes via object members of the same name\n * @param {*} [options.data=null] The message content\n */\n constructor(type, options = {}) {\n super(type);\n\n this[kData] = options.data === undefined ? null : options.data;\n }\n\n /**\n * @type {*}\n */\n get data() {\n return this[kData];\n }\n}\n\nObject.defineProperty(MessageEvent.prototype, 'data', { enumerable: true });\n\n/**\n * This provides methods for emulating the `EventTarget` interface. It's not\n * meant to be used directly.\n *\n * @mixin\n */\nconst EventTarget = {\n /**\n * Register an event listener.\n *\n * @param {String} type A string representing the event type to listen for\n * @param {(Function|Object)} handler The listener to add\n * @param {Object} [options] An options object specifies characteristics about\n * the event listener\n * @param {Boolean} [options.once=false] A `Boolean` indicating that the\n * listener should be invoked at most once after being added. If `true`,\n * the listener would be automatically removed when invoked.\n * @public\n */\n addEventListener(type, handler, options = {}) {\n for (const listener of this.listeners(type)) {\n if (\n !options[kForOnEventAttribute] &&\n listener[kListener] === handler &&\n !listener[kForOnEventAttribute]\n ) {\n return;\n }\n }\n\n let wrapper;\n\n if (type === 'message') {\n wrapper = function onMessage(data, isBinary) {\n const event = new MessageEvent('message', {\n data: isBinary ? data : data.toString()\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'close') {\n wrapper = function onClose(code, message) {\n const event = new CloseEvent('close', {\n code,\n reason: message.toString(),\n wasClean: this._closeFrameReceived && this._closeFrameSent\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'error') {\n wrapper = function onError(error) {\n const event = new ErrorEvent('error', {\n error,\n message: error.message\n });\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else if (type === 'open') {\n wrapper = function onOpen() {\n const event = new Event('open');\n\n event[kTarget] = this;\n callListener(handler, this, event);\n };\n } else {\n return;\n }\n\n wrapper[kForOnEventAttribute] = !!options[kForOnEventAttribute];\n wrapper[kListener] = handler;\n\n if (options.once) {\n this.once(type, wrapper);\n } else {\n this.on(type, wrapper);\n }\n },\n\n /**\n * Remove an event listener.\n *\n * @param {String} type A string representing the event type to remove\n * @param {(Function|Object)} handler The listener to remove\n * @public\n */\n removeEventListener(type, handler) {\n for (const listener of this.listeners(type)) {\n if (listener[kListener] === handler && !listener[kForOnEventAttribute]) {\n this.removeListener(type, listener);\n break;\n }\n }\n }\n};\n\nmodule.exports = {\n CloseEvent,\n ErrorEvent,\n Event,\n EventTarget,\n MessageEvent\n};\n\n/**\n * Call an event listener\n *\n * @param {(Function|Object)} listener The listener to call\n * @param {*} thisArg The value to use as `this`` when calling the listener\n * @param {Event} event The event to pass to the listener\n * @private\n */\nfunction callListener(listener, thisArg, event) {\n if (typeof listener === 'object' && listener.handleEvent) {\n listener.handleEvent.call(listener, event);\n } else {\n listener.call(thisArg, event);\n }\n}\n", "'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Adds an offer to the map of extension offers or a parameter to the map of\n * parameters.\n *\n * @param {Object} dest The map of extension offers or parameters\n * @param {String} name The extension or parameter name\n * @param {(Object|Boolean|String)} elem The extension parameters or the\n * parameter value\n * @private\n */\nfunction push(dest, name, elem) {\n if (dest[name] === undefined) dest[name] = [elem];\n else dest[name].push(elem);\n}\n\n/**\n * Parses the `Sec-WebSocket-Extensions` header into an object.\n *\n * @param {String} header The field value of the header\n * @return {Object} The parsed object\n * @public\n */\nfunction parse(header) {\n const offers = Object.create(null);\n let params = Object.create(null);\n let mustUnescape = false;\n let isEscaping = false;\n let inQuotes = false;\n let extensionName;\n let paramName;\n let start = -1;\n let code = -1;\n let end = -1;\n let i = 0;\n\n for (; i < header.length; i++) {\n code = header.charCodeAt(i);\n\n if (extensionName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b /* ';' */ || code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n const name = header.slice(start, end);\n if (code === 0x2c) {\n push(offers, name, params);\n params = Object.create(null);\n } else {\n extensionName = name;\n }\n\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (paramName === undefined) {\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x20 || code === 0x09) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n push(params, header.slice(start, end), true);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n start = end = -1;\n } else if (code === 0x3d /* '=' */ && start !== -1 && end === -1) {\n paramName = header.slice(start, i);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else {\n //\n // The value of a quoted-string after unescaping must conform to the\n // token ABNF, so only token characters are valid.\n // Ref: https://tools.ietf.org/html/rfc6455#section-9.1\n //\n if (isEscaping) {\n if (tokenChars[code] !== 1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n if (start === -1) start = i;\n else if (!mustUnescape) mustUnescape = true;\n isEscaping = false;\n } else if (inQuotes) {\n if (tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (code === 0x22 /* '\"' */ && start !== -1) {\n inQuotes = false;\n end = i;\n } else if (code === 0x5c /* '\\' */) {\n isEscaping = true;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) {\n inQuotes = true;\n } else if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (start !== -1 && (code === 0x20 || code === 0x09)) {\n if (end === -1) end = i;\n } else if (code === 0x3b || code === 0x2c) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n let value = header.slice(start, end);\n if (mustUnescape) {\n value = value.replace(/\\\\/g, '');\n mustUnescape = false;\n }\n push(params, paramName, value);\n if (code === 0x2c) {\n push(offers, extensionName, params);\n params = Object.create(null);\n extensionName = undefined;\n }\n\n paramName = undefined;\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n }\n\n if (start === -1 || inQuotes || code === 0x20 || code === 0x09) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n if (end === -1) end = i;\n const token = header.slice(start, end);\n if (extensionName === undefined) {\n push(offers, token, params);\n } else {\n if (paramName === undefined) {\n push(params, token, true);\n } else if (mustUnescape) {\n push(params, paramName, token.replace(/\\\\/g, ''));\n } else {\n push(params, paramName, token);\n }\n push(offers, extensionName, params);\n }\n\n return offers;\n}\n\n/**\n * Builds the `Sec-WebSocket-Extensions` header field value.\n *\n * @param {Object} extensions The map of extensions and parameters to format\n * @return {String} A string representing the given object\n * @public\n */\nfunction format(extensions) {\n return Object.keys(extensions)\n .map((extension) => {\n let configurations = extensions[extension];\n if (!Array.isArray(configurations)) configurations = [configurations];\n return configurations\n .map((params) => {\n return [extension]\n .concat(\n Object.keys(params).map((k) => {\n let values = params[k];\n if (!Array.isArray(values)) values = [values];\n return values\n .map((v) => (v === true ? k : `${k}=${v}`))\n .join('; ');\n })\n )\n .join('; ');\n })\n .join(', ');\n })\n .join(', ');\n}\n\nmodule.exports = { format, parse };\n", "/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex|Readable$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst https = require('https');\nconst http = require('http');\nconst net = require('net');\nconst tls = require('tls');\nconst { randomBytes, createHash } = require('crypto');\nconst { Duplex, Readable } = require('stream');\nconst { URL } = require('url');\n\nconst PerMessageDeflate = require('./permessage-deflate');\nconst Receiver = require('./receiver');\nconst Sender = require('./sender');\nconst { isBlob } = require('./validation');\n\nconst {\n BINARY_TYPES,\n CLOSE_TIMEOUT,\n EMPTY_BUFFER,\n GUID,\n kForOnEventAttribute,\n kListener,\n kStatusCode,\n kWebSocket,\n NOOP\n} = require('./constants');\nconst {\n EventTarget: { addEventListener, removeEventListener }\n} = require('./event-target');\nconst { format, parse } = require('./extension');\nconst { toBuffer } = require('./buffer-util');\n\nconst kAborted = Symbol('kAborted');\nconst protocolVersions = [8, 13];\nconst readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'];\nconst subprotocolRegex = /^[!#$%&'*+\\-.0-9A-Z^_`|a-z~]+$/;\n\n/**\n * Class representing a WebSocket.\n *\n * @extends EventEmitter\n */\nclass WebSocket extends EventEmitter {\n /**\n * Create a new `WebSocket`.\n *\n * @param {(String|URL)} address The URL to which to connect\n * @param {(String|String[])} [protocols] The subprotocols\n * @param {Object} [options] Connection options\n */\n constructor(address, protocols, options) {\n super();\n\n this._binaryType = BINARY_TYPES[0];\n this._closeCode = 1006;\n this._closeFrameReceived = false;\n this._closeFrameSent = false;\n this._closeMessage = EMPTY_BUFFER;\n this._closeTimer = null;\n this._errorEmitted = false;\n this._extensions = {};\n this._paused = false;\n this._protocol = '';\n this._readyState = WebSocket.CONNECTING;\n this._receiver = null;\n this._sender = null;\n this._socket = null;\n\n if (address !== null) {\n this._bufferedAmount = 0;\n this._isServer = false;\n this._redirects = 0;\n\n if (protocols === undefined) {\n protocols = [];\n } else if (!Array.isArray(protocols)) {\n if (typeof protocols === 'object' && protocols !== null) {\n options = protocols;\n protocols = [];\n } else {\n protocols = [protocols];\n }\n }\n\n initAsClient(this, address, protocols, options);\n } else {\n this._autoPong = options.autoPong;\n this._closeTimeout = options.closeTimeout;\n this._isServer = true;\n }\n }\n\n /**\n * For historical reasons, the custom \"nodebuffer\" type is used by the default\n * instead of \"blob\".\n *\n * @type {String}\n */\n get binaryType() {\n return this._binaryType;\n }\n\n set binaryType(type) {\n if (!BINARY_TYPES.includes(type)) return;\n\n this._binaryType = type;\n\n //\n // Allow to change `binaryType` on the fly.\n //\n if (this._receiver) this._receiver._binaryType = type;\n }\n\n /**\n * @type {Number}\n */\n get bufferedAmount() {\n if (!this._socket) return this._bufferedAmount;\n\n return this._socket._writableState.length + this._sender._bufferedBytes;\n }\n\n /**\n * @type {String}\n */\n get extensions() {\n return Object.keys(this._extensions).join();\n }\n\n /**\n * @type {Boolean}\n */\n get isPaused() {\n return this._paused;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onclose() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onerror() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onopen() {\n return null;\n }\n\n /**\n * @type {Function}\n */\n /* istanbul ignore next */\n get onmessage() {\n return null;\n }\n\n /**\n * @type {String}\n */\n get protocol() {\n return this._protocol;\n }\n\n /**\n * @type {Number}\n */\n get readyState() {\n return this._readyState;\n }\n\n /**\n * @type {String}\n */\n get url() {\n return this._url;\n }\n\n /**\n * Set up the socket and the internal resources.\n *\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Object} options Options object\n * @param {Boolean} [options.allowSynchronousEvents=false] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.maxBufferedChunks=0] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=0] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=0] The maximum allowed message size\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\n setSocket(socket, head, options) {\n const receiver = new Receiver({\n allowSynchronousEvents: options.allowSynchronousEvents,\n binaryType: this.binaryType,\n extensions: this._extensions,\n isServer: this._isServer,\n maxBufferedChunks: options.maxBufferedChunks,\n maxFragments: options.maxFragments,\n maxPayload: options.maxPayload,\n skipUTF8Validation: options.skipUTF8Validation\n });\n\n const sender = new Sender(socket, this._extensions, options.generateMask);\n\n this._receiver = receiver;\n this._sender = sender;\n this._socket = socket;\n\n receiver[kWebSocket] = this;\n sender[kWebSocket] = this;\n socket[kWebSocket] = this;\n\n receiver.on('conclude', receiverOnConclude);\n receiver.on('drain', receiverOnDrain);\n receiver.on('error', receiverOnError);\n receiver.on('message', receiverOnMessage);\n receiver.on('ping', receiverOnPing);\n receiver.on('pong', receiverOnPong);\n\n sender.onerror = senderOnError;\n\n //\n // These methods may not be available if `socket` is just a `Duplex`.\n //\n if (socket.setTimeout) socket.setTimeout(0);\n if (socket.setNoDelay) socket.setNoDelay();\n\n if (head.length > 0) socket.unshift(head);\n\n socket.on('close', socketOnClose);\n socket.on('data', socketOnData);\n socket.on('end', socketOnEnd);\n socket.on('error', socketOnError);\n\n this._readyState = WebSocket.OPEN;\n this.emit('open');\n }\n\n /**\n * Emit the `'close'` event.\n *\n * @private\n */\n emitClose() {\n if (!this._socket) {\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n return;\n }\n\n if (this._extensions[PerMessageDeflate.extensionName]) {\n this._extensions[PerMessageDeflate.extensionName].cleanup();\n }\n\n this._receiver.removeAllListeners();\n this._readyState = WebSocket.CLOSED;\n this.emit('close', this._closeCode, this._closeMessage);\n }\n\n /**\n * Start a closing handshake.\n *\n * +----------+ +-----------+ +----------+\n * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -\n * | +----------+ +-----------+ +----------+ |\n * +----------+ +-----------+ |\n * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING\n * +----------+ +-----------+ |\n * | | | +---+ |\n * +------------------------+-->|fin| - - - -\n * | +---+ | +---+\n * - - - - -|fin|<---------------------+\n * +---+\n *\n * @param {Number} [code] Status code explaining why the connection is closing\n * @param {(String|Buffer)} [data] The reason why the connection is\n * closing\n * @public\n */\n close(code, data) {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this.readyState === WebSocket.CLOSING) {\n if (\n this._closeFrameSent &&\n (this._closeFrameReceived || this._receiver._writableState.errorEmitted)\n ) {\n this._socket.end();\n }\n\n return;\n }\n\n this._readyState = WebSocket.CLOSING;\n this._sender.close(code, data, !this._isServer, (err) => {\n //\n // This error is handled by the `'error'` listener on the socket. We only\n // want to know if the close frame has been sent here.\n //\n if (err) return;\n\n this._closeFrameSent = true;\n\n if (\n this._closeFrameReceived ||\n this._receiver._writableState.errorEmitted\n ) {\n this._socket.end();\n }\n });\n\n setCloseTimer(this);\n }\n\n /**\n * Pause the socket.\n *\n * @public\n */\n pause() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = true;\n this._socket.pause();\n }\n\n /**\n * Send a ping.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the ping is sent\n * @public\n */\n ping(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.ping(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Send a pong.\n *\n * @param {*} [data] The data to send\n * @param {Boolean} [mask] Indicates whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when the pong is sent\n * @public\n */\n pong(data, mask, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof data === 'function') {\n cb = data;\n data = mask = undefined;\n } else if (typeof mask === 'function') {\n cb = mask;\n mask = undefined;\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n if (mask === undefined) mask = !this._isServer;\n this._sender.pong(data || EMPTY_BUFFER, mask, cb);\n }\n\n /**\n * Resume the socket.\n *\n * @public\n */\n resume() {\n if (\n this.readyState === WebSocket.CONNECTING ||\n this.readyState === WebSocket.CLOSED\n ) {\n return;\n }\n\n this._paused = false;\n if (!this._receiver._writableState.needDrain) this._socket.resume();\n }\n\n /**\n * Send a data message.\n *\n * @param {*} data The message to send\n * @param {Object} [options] Options object\n * @param {Boolean} [options.binary] Specifies whether `data` is binary or\n * text\n * @param {Boolean} [options.compress] Specifies whether or not to compress\n * `data`\n * @param {Boolean} [options.fin=true] Specifies whether the fragment is the\n * last one\n * @param {Boolean} [options.mask] Specifies whether or not to mask `data`\n * @param {Function} [cb] Callback which is executed when data is written out\n * @public\n */\n send(data, options, cb) {\n if (this.readyState === WebSocket.CONNECTING) {\n throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');\n }\n\n if (typeof options === 'function') {\n cb = options;\n options = {};\n }\n\n if (typeof data === 'number') data = data.toString();\n\n if (this.readyState !== WebSocket.OPEN) {\n sendAfterClose(this, data, cb);\n return;\n }\n\n const opts = {\n binary: typeof data !== 'string',\n mask: !this._isServer,\n compress: true,\n fin: true,\n ...options\n };\n\n if (!this._extensions[PerMessageDeflate.extensionName]) {\n opts.compress = false;\n }\n\n this._sender.send(data || EMPTY_BUFFER, opts, cb);\n }\n\n /**\n * Forcibly close the connection.\n *\n * @public\n */\n terminate() {\n if (this.readyState === WebSocket.CLOSED) return;\n if (this.readyState === WebSocket.CONNECTING) {\n const msg = 'WebSocket was closed before the connection was established';\n abortHandshake(this, this._req, msg);\n return;\n }\n\n if (this._socket) {\n this._readyState = WebSocket.CLOSING;\n this._socket.destroy();\n }\n }\n}\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} CONNECTING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CONNECTING', {\n enumerable: true,\n value: readyStates.indexOf('CONNECTING')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} OPEN\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'OPEN', {\n enumerable: true,\n value: readyStates.indexOf('OPEN')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSING\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSING', {\n enumerable: true,\n value: readyStates.indexOf('CLOSING')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket\n */\nObject.defineProperty(WebSocket, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n/**\n * @constant {Number} CLOSED\n * @memberof WebSocket.prototype\n */\nObject.defineProperty(WebSocket.prototype, 'CLOSED', {\n enumerable: true,\n value: readyStates.indexOf('CLOSED')\n});\n\n[\n 'binaryType',\n 'bufferedAmount',\n 'extensions',\n 'isPaused',\n 'protocol',\n 'readyState',\n 'url'\n].forEach((property) => {\n Object.defineProperty(WebSocket.prototype, property, { enumerable: true });\n});\n\n//\n// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes.\n// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface\n//\n['open', 'error', 'close', 'message'].forEach((method) => {\n Object.defineProperty(WebSocket.prototype, `on${method}`, {\n enumerable: true,\n get() {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) return listener[kListener];\n }\n\n return null;\n },\n set(handler) {\n for (const listener of this.listeners(method)) {\n if (listener[kForOnEventAttribute]) {\n this.removeListener(method, listener);\n break;\n }\n }\n\n if (typeof handler !== 'function') return;\n\n this.addEventListener(method, handler, {\n [kForOnEventAttribute]: true\n });\n }\n });\n});\n\nWebSocket.prototype.addEventListener = addEventListener;\nWebSocket.prototype.removeEventListener = removeEventListener;\n\nmodule.exports = WebSocket;\n\n/**\n * Initialize a WebSocket client.\n *\n * @param {WebSocket} websocket The client to initialize\n * @param {(String|URL)} address The URL to which to connect\n * @param {Array} protocols The subprotocols\n * @param {Object} [options] Connection options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether any\n * of the `'message'`, `'ping'`, and `'pong'` events can be emitted multiple\n * times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to wait\n * for the closing handshake to finish after `websocket.close()` is called\n * @param {Function} [options.finishRequest] A function which can be used to\n * customize the headers of each http request before it is sent\n * @param {Boolean} [options.followRedirects=false] Whether or not to follow\n * redirects\n * @param {Function} [options.generateMask] The function used to generate the\n * masking key\n * @param {Number} [options.handshakeTimeout] Timeout in milliseconds for the\n * handshake request\n * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=131072] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Number} [options.maxRedirects=10] The maximum number of redirects\n * allowed\n * @param {String} [options.origin] Value of the `Origin` or\n * `Sec-WebSocket-Origin` header\n * @param {(Boolean|Object)} [options.perMessageDeflate=true] Enable/disable\n * permessage-deflate\n * @param {Number} [options.protocolVersion=13] Value of the\n * `Sec-WebSocket-Version` header\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @private\n */\nfunction initAsClient(websocket, address, protocols, options) {\n const opts = {\n allowSynchronousEvents: true,\n autoPong: true,\n closeTimeout: CLOSE_TIMEOUT,\n protocolVersion: protocolVersions[1],\n maxBufferedChunks: 1024 * 1024,\n maxFragments: 128 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: true,\n followRedirects: false,\n maxRedirects: 10,\n ...options,\n socketPath: undefined,\n hostname: undefined,\n protocol: undefined,\n timeout: undefined,\n method: 'GET',\n host: undefined,\n path: undefined,\n port: undefined\n };\n\n websocket._autoPong = opts.autoPong;\n websocket._closeTimeout = opts.closeTimeout;\n\n if (!protocolVersions.includes(opts.protocolVersion)) {\n throw new RangeError(\n `Unsupported protocol version: ${opts.protocolVersion} ` +\n `(supported versions: ${protocolVersions.join(', ')})`\n );\n }\n\n let parsedUrl;\n\n if (address instanceof URL) {\n parsedUrl = address;\n } else {\n try {\n parsedUrl = new URL(address);\n } catch {\n throw new SyntaxError(`Invalid URL: ${address}`);\n }\n }\n\n if (parsedUrl.protocol === 'http:') {\n parsedUrl.protocol = 'ws:';\n } else if (parsedUrl.protocol === 'https:') {\n parsedUrl.protocol = 'wss:';\n }\n\n websocket._url = parsedUrl.href;\n\n const isSecure = parsedUrl.protocol === 'wss:';\n const isIpcUrl = parsedUrl.protocol === 'ws+unix:';\n let invalidUrlMessage;\n\n if (parsedUrl.protocol !== 'ws:' && !isSecure && !isIpcUrl) {\n invalidUrlMessage =\n 'The URL\\'s protocol must be one of \"ws:\", \"wss:\", ' +\n '\"http:\", \"https:\", or \"ws+unix:\"';\n } else if (isIpcUrl && !parsedUrl.pathname) {\n invalidUrlMessage = \"The URL's pathname is empty\";\n } else if (parsedUrl.hash) {\n invalidUrlMessage = 'The URL contains a fragment identifier';\n }\n\n if (invalidUrlMessage) {\n const err = new SyntaxError(invalidUrlMessage);\n\n if (websocket._redirects === 0) {\n throw err;\n } else {\n emitErrorAndClose(websocket, err);\n return;\n }\n }\n\n const defaultPort = isSecure ? 443 : 80;\n const key = randomBytes(16).toString('base64');\n const request = isSecure ? https.request : http.request;\n const protocolSet = new Set();\n let perMessageDeflate;\n\n opts.createConnection =\n opts.createConnection || (isSecure ? tlsConnect : netConnect);\n opts.defaultPort = opts.defaultPort || defaultPort;\n opts.port = parsedUrl.port || defaultPort;\n opts.host = parsedUrl.hostname.startsWith('[')\n ? parsedUrl.hostname.slice(1, -1)\n : parsedUrl.hostname;\n opts.headers = {\n ...opts.headers,\n 'Sec-WebSocket-Version': opts.protocolVersion,\n 'Sec-WebSocket-Key': key,\n Connection: 'Upgrade',\n Upgrade: 'websocket'\n };\n opts.path = parsedUrl.pathname + parsedUrl.search;\n opts.timeout = opts.handshakeTimeout;\n\n if (opts.perMessageDeflate) {\n perMessageDeflate = new PerMessageDeflate({\n ...opts.perMessageDeflate,\n isServer: false,\n maxPayload: opts.maxPayload\n });\n opts.headers['Sec-WebSocket-Extensions'] = format({\n [PerMessageDeflate.extensionName]: perMessageDeflate.offer()\n });\n }\n if (protocols.length) {\n for (const protocol of protocols) {\n if (\n typeof protocol !== 'string' ||\n !subprotocolRegex.test(protocol) ||\n protocolSet.has(protocol)\n ) {\n throw new SyntaxError(\n 'An invalid or duplicated subprotocol was specified'\n );\n }\n\n protocolSet.add(protocol);\n }\n\n opts.headers['Sec-WebSocket-Protocol'] = protocols.join(',');\n }\n if (opts.origin) {\n if (opts.protocolVersion < 13) {\n opts.headers['Sec-WebSocket-Origin'] = opts.origin;\n } else {\n opts.headers.Origin = opts.origin;\n }\n }\n if (parsedUrl.username || parsedUrl.password) {\n opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;\n }\n\n if (isIpcUrl) {\n const parts = opts.path.split(':');\n\n opts.socketPath = parts[0];\n opts.path = parts[1];\n }\n\n let req;\n\n if (opts.followRedirects) {\n if (websocket._redirects === 0) {\n websocket._originalIpc = isIpcUrl;\n websocket._originalSecure = isSecure;\n websocket._originalHostOrSocketPath = isIpcUrl\n ? opts.socketPath\n : parsedUrl.host;\n\n const headers = options && options.headers;\n\n //\n // Shallow copy the user provided options so that headers can be changed\n // without mutating the original object.\n //\n options = { ...options, headers: {} };\n\n if (headers) {\n for (const [key, value] of Object.entries(headers)) {\n options.headers[key.toLowerCase()] = value;\n }\n }\n } else if (websocket.listenerCount('redirect') === 0) {\n const isSameHost = isIpcUrl\n ? websocket._originalIpc\n ? opts.socketPath === websocket._originalHostOrSocketPath\n : false\n : websocket._originalIpc\n ? false\n : parsedUrl.host === websocket._originalHostOrSocketPath;\n\n if (!isSameHost || (websocket._originalSecure && !isSecure)) {\n //\n // Match curl 7.77.0 behavior and drop the following headers. These\n // headers are also dropped when following a redirect to a subdomain.\n //\n delete opts.headers.authorization;\n delete opts.headers.cookie;\n\n if (!isSameHost) delete opts.headers.host;\n\n opts.auth = undefined;\n }\n }\n\n //\n // Match curl 7.77.0 behavior and make the first `Authorization` header win.\n // If the `Authorization` header is set, then there is nothing to do as it\n // will take precedence.\n //\n if (opts.auth && !options.headers.authorization) {\n options.headers.authorization =\n 'Basic ' + Buffer.from(opts.auth).toString('base64');\n }\n\n req = websocket._req = request(opts);\n\n if (websocket._redirects) {\n //\n // Unlike what is done for the `'upgrade'` event, no early exit is\n // triggered here if the user calls `websocket.close()` or\n // `websocket.terminate()` from a listener of the `'redirect'` event. This\n // is because the user can also call `request.destroy()` with an error\n // before calling `websocket.close()` or `websocket.terminate()` and this\n // would result in an error being emitted on the `request` object with no\n // `'error'` event listeners attached.\n //\n websocket.emit('redirect', websocket.url, req);\n }\n } else {\n req = websocket._req = request(opts);\n }\n\n if (opts.timeout) {\n req.on('timeout', () => {\n abortHandshake(websocket, req, 'Opening handshake has timed out');\n });\n }\n\n req.on('error', (err) => {\n if (req === null || req[kAborted]) return;\n\n req = websocket._req = null;\n emitErrorAndClose(websocket, err);\n });\n\n req.on('response', (res) => {\n const location = res.headers.location;\n const statusCode = res.statusCode;\n\n if (\n location &&\n opts.followRedirects &&\n statusCode >= 300 &&\n statusCode < 400\n ) {\n if (++websocket._redirects > opts.maxRedirects) {\n abortHandshake(websocket, req, 'Maximum redirects exceeded');\n return;\n }\n\n req.abort();\n\n let addr;\n\n try {\n addr = new URL(location, address);\n } catch (e) {\n const err = new SyntaxError(`Invalid URL: ${location}`);\n emitErrorAndClose(websocket, err);\n return;\n }\n\n initAsClient(websocket, addr, protocols, options);\n } else if (!websocket.emit('unexpected-response', req, res)) {\n abortHandshake(\n websocket,\n req,\n `Unexpected server response: ${res.statusCode}`\n );\n }\n });\n\n req.on('upgrade', (res, socket, head) => {\n websocket.emit('upgrade', res);\n\n //\n // The user may have closed the connection from a listener of the\n // `'upgrade'` event.\n //\n if (websocket.readyState !== WebSocket.CONNECTING) return;\n\n req = websocket._req = null;\n\n const upgrade = res.headers.upgrade;\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n abortHandshake(websocket, socket, 'Invalid Upgrade header');\n return;\n }\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n if (res.headers['sec-websocket-accept'] !== digest) {\n abortHandshake(websocket, socket, 'Invalid Sec-WebSocket-Accept header');\n return;\n }\n\n const serverProt = res.headers['sec-websocket-protocol'];\n let protError;\n\n if (serverProt !== undefined) {\n if (!protocolSet.size) {\n protError = 'Server sent a subprotocol but none was requested';\n } else if (!protocolSet.has(serverProt)) {\n protError = 'Server sent an invalid subprotocol';\n }\n } else if (protocolSet.size) {\n protError = 'Server sent no subprotocol';\n }\n\n if (protError) {\n abortHandshake(websocket, socket, protError);\n return;\n }\n\n if (serverProt) websocket._protocol = serverProt;\n\n const secWebSocketExtensions = res.headers['sec-websocket-extensions'];\n\n if (secWebSocketExtensions !== undefined) {\n if (!perMessageDeflate) {\n const message =\n 'Server sent a Sec-WebSocket-Extensions header but no extension ' +\n 'was requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n let extensions;\n\n try {\n extensions = parse(secWebSocketExtensions);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n const extensionNames = Object.keys(extensions);\n\n if (\n extensionNames.length !== 1 ||\n extensionNames[0] !== PerMessageDeflate.extensionName\n ) {\n const message = 'Server indicated an extension that was not requested';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n try {\n perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Extensions header';\n abortHandshake(websocket, socket, message);\n return;\n }\n\n websocket._extensions[PerMessageDeflate.extensionName] =\n perMessageDeflate;\n }\n\n websocket.setSocket(socket, head, {\n allowSynchronousEvents: opts.allowSynchronousEvents,\n generateMask: opts.generateMask,\n maxBufferedChunks: opts.maxBufferedChunks,\n maxFragments: opts.maxFragments,\n maxPayload: opts.maxPayload,\n skipUTF8Validation: opts.skipUTF8Validation\n });\n });\n\n if (opts.finishRequest) {\n opts.finishRequest(req, websocket);\n } else {\n req.end();\n }\n}\n\n/**\n * Emit the `'error'` and `'close'` events.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {Error} The error to emit\n * @private\n */\nfunction emitErrorAndClose(websocket, err) {\n websocket._readyState = WebSocket.CLOSING;\n //\n // The following assignment is practically useless and is done only for\n // consistency.\n //\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n websocket.emitClose();\n}\n\n/**\n * Create a `net.Socket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {net.Socket} The newly created socket used to start the connection\n * @private\n */\nfunction netConnect(options) {\n options.path = options.socketPath;\n return net.connect(options);\n}\n\n/**\n * Create a `tls.TLSSocket` and initiate a connection.\n *\n * @param {Object} options Connection options\n * @return {tls.TLSSocket} The newly created socket used to start the connection\n * @private\n */\nfunction tlsConnect(options) {\n options.path = undefined;\n\n if (!options.servername && options.servername !== '') {\n options.servername = net.isIP(options.host) ? '' : options.host;\n }\n\n return tls.connect(options);\n}\n\n/**\n * Abort the handshake and emit an error.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {(http.ClientRequest|net.Socket|tls.Socket)} stream The request to\n * abort or the socket to destroy\n * @param {String} message The error message\n * @private\n */\nfunction abortHandshake(websocket, stream, message) {\n websocket._readyState = WebSocket.CLOSING;\n\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshake);\n\n if (stream.setHeader) {\n stream[kAborted] = true;\n stream.abort();\n\n if (stream.socket && !stream.socket.destroyed) {\n //\n // On Node.js >= 14.3.0 `request.abort()` does not destroy the socket if\n // called after the request completed. See\n // https://github.com/websockets/ws/issues/1869.\n //\n stream.socket.destroy();\n }\n\n process.nextTick(emitErrorAndClose, websocket, err);\n } else {\n stream.destroy(err);\n stream.once('error', websocket.emit.bind(websocket, 'error'));\n stream.once('close', websocket.emitClose.bind(websocket));\n }\n}\n\n/**\n * Handle cases where the `ping()`, `pong()`, or `send()` methods are called\n * when the `readyState` attribute is `CLOSING` or `CLOSED`.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @param {*} [data] The data to send\n * @param {Function} [cb] Callback\n * @private\n */\nfunction sendAfterClose(websocket, data, cb) {\n if (data) {\n const length = isBlob(data) ? data.size : toBuffer(data).length;\n\n //\n // The `_bufferedAmount` property is used only when the peer is a client and\n // the opening handshake fails. Under these circumstances, in fact, the\n // `setSocket()` method is not called, so the `_socket` and `_sender`\n // properties are set to `null`.\n //\n if (websocket._socket) websocket._sender._bufferedBytes += length;\n else websocket._bufferedAmount += length;\n }\n\n if (cb) {\n const err = new Error(\n `WebSocket is not open: readyState ${websocket.readyState} ` +\n `(${readyStates[websocket.readyState]})`\n );\n process.nextTick(cb, err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'conclude'` event.\n *\n * @param {Number} code The status code\n * @param {Buffer} reason The reason for closing\n * @private\n */\nfunction receiverOnConclude(code, reason) {\n const websocket = this[kWebSocket];\n\n websocket._closeFrameReceived = true;\n websocket._closeMessage = reason;\n websocket._closeCode = code;\n\n if (websocket._socket[kWebSocket] === undefined) return;\n\n websocket._socket.removeListener('data', socketOnData);\n process.nextTick(resume, websocket._socket);\n\n if (code === 1005) websocket.close();\n else websocket.close(code, reason);\n}\n\n/**\n * The listener of the `Receiver` `'drain'` event.\n *\n * @private\n */\nfunction receiverOnDrain() {\n const websocket = this[kWebSocket];\n\n if (!websocket.isPaused) websocket._socket.resume();\n}\n\n/**\n * The listener of the `Receiver` `'error'` event.\n *\n * @param {(RangeError|Error)} err The emitted error\n * @private\n */\nfunction receiverOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket._socket[kWebSocket] !== undefined) {\n websocket._socket.removeListener('data', socketOnData);\n\n //\n // On Node.js < 14.0.0 the `'error'` event is emitted synchronously. See\n // https://github.com/websockets/ws/issues/1940.\n //\n process.nextTick(resume, websocket._socket);\n\n websocket.close(err[kStatusCode]);\n }\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * The listener of the `Receiver` `'finish'` event.\n *\n * @private\n */\nfunction receiverOnFinish() {\n this[kWebSocket].emitClose();\n}\n\n/**\n * The listener of the `Receiver` `'message'` event.\n *\n * @param {Buffer|ArrayBuffer|Buffer[])} data The message\n * @param {Boolean} isBinary Specifies whether the message is binary or not\n * @private\n */\nfunction receiverOnMessage(data, isBinary) {\n this[kWebSocket].emit('message', data, isBinary);\n}\n\n/**\n * The listener of the `Receiver` `'ping'` event.\n *\n * @param {Buffer} data The data included in the ping frame\n * @private\n */\nfunction receiverOnPing(data) {\n const websocket = this[kWebSocket];\n\n if (websocket._autoPong) websocket.pong(data, !this._isServer, NOOP);\n websocket.emit('ping', data);\n}\n\n/**\n * The listener of the `Receiver` `'pong'` event.\n *\n * @param {Buffer} data The data included in the pong frame\n * @private\n */\nfunction receiverOnPong(data) {\n this[kWebSocket].emit('pong', data);\n}\n\n/**\n * Resume a readable stream\n *\n * @param {Readable} stream The readable stream\n * @private\n */\nfunction resume(stream) {\n stream.resume();\n}\n\n/**\n * The `Sender` error event handler.\n *\n * @param {Error} The error\n * @private\n */\nfunction senderOnError(err) {\n const websocket = this[kWebSocket];\n\n if (websocket.readyState === WebSocket.CLOSED) return;\n if (websocket.readyState === WebSocket.OPEN) {\n websocket._readyState = WebSocket.CLOSING;\n setCloseTimer(websocket);\n }\n\n //\n // `socket.end()` is used instead of `socket.destroy()` to allow the other\n // peer to finish sending queued data. There is no need to set a timer here\n // because `CLOSING` means that it is already set or not needed.\n //\n this._socket.end();\n\n if (!websocket._errorEmitted) {\n websocket._errorEmitted = true;\n websocket.emit('error', err);\n }\n}\n\n/**\n * Set a timer to destroy the underlying raw socket of a WebSocket.\n *\n * @param {WebSocket} websocket The WebSocket instance\n * @private\n */\nfunction setCloseTimer(websocket) {\n websocket._closeTimer = setTimeout(\n websocket._socket.destroy.bind(websocket._socket),\n websocket._closeTimeout\n );\n}\n\n/**\n * The listener of the socket `'close'` event.\n *\n * @private\n */\nfunction socketOnClose() {\n const websocket = this[kWebSocket];\n\n this.removeListener('close', socketOnClose);\n this.removeListener('data', socketOnData);\n this.removeListener('end', socketOnEnd);\n\n websocket._readyState = WebSocket.CLOSING;\n\n //\n // The close frame might not have been received or the `'end'` event emitted,\n // for example, if the socket was destroyed due to an error. Ensure that the\n // `receiver` stream is closed after writing any remaining buffered data to\n // it. If the readable side of the socket is in flowing mode then there is no\n // buffered data as everything has been already written. If instead, the\n // socket is paused, any possible buffered data will be read as a single\n // chunk.\n //\n if (\n !this._readableState.endEmitted &&\n !websocket._closeFrameReceived &&\n !websocket._receiver._writableState.errorEmitted &&\n this._readableState.length !== 0\n ) {\n const chunk = this.read(this._readableState.length);\n\n websocket._receiver.write(chunk);\n }\n\n websocket._receiver.end();\n\n this[kWebSocket] = undefined;\n\n clearTimeout(websocket._closeTimer);\n\n if (\n websocket._receiver._writableState.finished ||\n websocket._receiver._writableState.errorEmitted\n ) {\n websocket.emitClose();\n } else {\n websocket._receiver.on('error', receiverOnFinish);\n websocket._receiver.on('finish', receiverOnFinish);\n }\n}\n\n/**\n * The listener of the socket `'data'` event.\n *\n * @param {Buffer} chunk A chunk of data\n * @private\n */\nfunction socketOnData(chunk) {\n if (!this[kWebSocket]._receiver.write(chunk)) {\n this.pause();\n }\n}\n\n/**\n * The listener of the socket `'end'` event.\n *\n * @private\n */\nfunction socketOnEnd() {\n const websocket = this[kWebSocket];\n\n websocket._readyState = WebSocket.CLOSING;\n websocket._receiver.end();\n this.end();\n}\n\n/**\n * The listener of the socket `'error'` event.\n *\n * @private\n */\nfunction socketOnError() {\n const websocket = this[kWebSocket];\n\n this.removeListener('error', socketOnError);\n this.on('error', NOOP);\n\n if (websocket) {\n websocket._readyState = WebSocket.CLOSING;\n this.destroy();\n }\n}\n", "/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^WebSocket$\" }] */\n'use strict';\n\nconst WebSocket = require('./websocket');\nconst { Duplex } = require('stream');\n\n/**\n * Emits the `'close'` event on a stream.\n *\n * @param {Duplex} stream The stream.\n * @private\n */\nfunction emitClose(stream) {\n stream.emit('close');\n}\n\n/**\n * The listener of the `'end'` event.\n *\n * @private\n */\nfunction duplexOnEnd() {\n if (!this.destroyed && this._writableState.finished) {\n this.destroy();\n }\n}\n\n/**\n * The listener of the `'error'` event.\n *\n * @param {Error} err The error\n * @private\n */\nfunction duplexOnError(err) {\n this.removeListener('error', duplexOnError);\n this.destroy();\n if (this.listenerCount('error') === 0) {\n // Do not suppress the throwing behavior.\n this.emit('error', err);\n }\n}\n\n/**\n * Wraps a `WebSocket` in a duplex stream.\n *\n * @param {WebSocket} ws The `WebSocket` to wrap\n * @param {Object} [options] The options for the `Duplex` constructor\n * @return {Duplex} The duplex stream\n * @public\n */\nfunction createWebSocketStream(ws, options) {\n let terminateOnDestroy = true;\n\n const duplex = new Duplex({\n ...options,\n autoDestroy: false,\n emitClose: false,\n objectMode: false,\n writableObjectMode: false\n });\n\n ws.on('message', function message(msg, isBinary) {\n const data =\n !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;\n\n if (!duplex.push(data)) ws.pause();\n });\n\n ws.once('error', function error(err) {\n if (duplex.destroyed) return;\n\n // Prevent `ws.terminate()` from being called by `duplex._destroy()`.\n //\n // - If the `'error'` event is emitted before the `'open'` event, then\n // `ws.terminate()` is a noop as no socket is assigned.\n // - Otherwise, the error is re-emitted by the listener of the `'error'`\n // event of the `Receiver` object. The listener already closes the\n // connection by calling `ws.close()`. This allows a close frame to be\n // sent to the other peer. If `ws.terminate()` is called right after this,\n // then the close frame might not be sent.\n terminateOnDestroy = false;\n duplex.destroy(err);\n });\n\n ws.once('close', function close() {\n if (duplex.destroyed) return;\n\n duplex.push(null);\n });\n\n duplex._destroy = function (err, callback) {\n if (ws.readyState === ws.CLOSED) {\n callback(err);\n process.nextTick(emitClose, duplex);\n return;\n }\n\n let called = false;\n\n ws.once('error', function error(err) {\n called = true;\n callback(err);\n });\n\n ws.once('close', function close() {\n if (!called) callback(err);\n process.nextTick(emitClose, duplex);\n });\n\n if (terminateOnDestroy) ws.terminate();\n };\n\n duplex._final = function (callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._final(callback);\n });\n return;\n }\n\n // If the value of the `_socket` property is `null` it means that `ws` is a\n // client websocket and the handshake failed. In fact, when this happens, a\n // socket is never assigned to the websocket. Wait for the `'error'` event\n // that will be emitted by the websocket.\n if (ws._socket === null) return;\n\n if (ws._socket._writableState.finished) {\n callback();\n if (duplex._readableState.endEmitted) duplex.destroy();\n } else {\n ws._socket.once('finish', function finish() {\n // `duplex` is not destroyed here because the `'end'` event will be\n // emitted on `duplex` after this `'finish'` event. The EOF signaling\n // `null` chunk is, in fact, pushed when the websocket emits `'close'`.\n callback();\n });\n ws.close();\n }\n };\n\n duplex._read = function () {\n if (ws.isPaused) ws.resume();\n };\n\n duplex._write = function (chunk, encoding, callback) {\n if (ws.readyState === ws.CONNECTING) {\n ws.once('open', function open() {\n duplex._write(chunk, encoding, callback);\n });\n return;\n }\n\n ws.send(chunk, callback);\n };\n\n duplex.on('end', duplexOnEnd);\n duplex.on('error', duplexOnError);\n return duplex;\n}\n\nmodule.exports = createWebSocketStream;\n", "'use strict';\n\nconst { tokenChars } = require('./validation');\n\n/**\n * Parses the `Sec-WebSocket-Protocol` header into a set of subprotocol names.\n *\n * @param {String} header The field value of the header\n * @return {Set} The subprotocol names\n * @public\n */\nfunction parse(header) {\n const protocols = new Set();\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (i; i < header.length; i++) {\n const code = header.charCodeAt(i);\n\n if (end === -1 && tokenChars[code] === 1) {\n if (start === -1) start = i;\n } else if (\n i !== 0 &&\n (code === 0x20 /* ' ' */ || code === 0x09) /* '\\t' */\n ) {\n if (end === -1 && start !== -1) end = i;\n } else if (code === 0x2c /* ',' */) {\n if (start === -1) {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n\n if (end === -1) end = i;\n\n const protocol = header.slice(start, end);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n start = end = -1;\n } else {\n throw new SyntaxError(`Unexpected character at index ${i}`);\n }\n }\n\n if (start === -1 || end !== -1) {\n throw new SyntaxError('Unexpected end of input');\n }\n\n const protocol = header.slice(start, i);\n\n if (protocols.has(protocol)) {\n throw new SyntaxError(`The \"${protocol}\" subprotocol is duplicated`);\n }\n\n protocols.add(protocol);\n return protocols;\n}\n\nmodule.exports = { parse };\n", "/* eslint no-unused-vars: [\"error\", { \"varsIgnorePattern\": \"^Duplex$\", \"caughtErrors\": \"none\" }] */\n\n'use strict';\n\nconst EventEmitter = require('events');\nconst http = require('http');\nconst { Duplex } = require('stream');\nconst { createHash } = require('crypto');\n\nconst extension = require('./extension');\nconst PerMessageDeflate = require('./permessage-deflate');\nconst subprotocol = require('./subprotocol');\nconst WebSocket = require('./websocket');\nconst { CLOSE_TIMEOUT, GUID, kWebSocket } = require('./constants');\n\nconst keyRegex = /^[+/0-9A-Za-z]{22}==$/;\n\nconst RUNNING = 0;\nconst CLOSING = 1;\nconst CLOSED = 2;\n\n/**\n * Class representing a WebSocket server.\n *\n * @extends EventEmitter\n */\nclass WebSocketServer extends EventEmitter {\n /**\n * Create a `WebSocketServer` instance.\n *\n * @param {Object} options Configuration options\n * @param {Boolean} [options.allowSynchronousEvents=true] Specifies whether\n * any of the `'message'`, `'ping'`, and `'pong'` events can be emitted\n * multiple times in the same tick\n * @param {Boolean} [options.autoPong=true] Specifies whether or not to\n * automatically send a pong in response to a ping\n * @param {Number} [options.backlog=511] The maximum length of the queue of\n * pending connections\n * @param {Boolean} [options.clientTracking=true] Specifies whether or not to\n * track clients\n * @param {Number} [options.closeTimeout=30000] Duration in milliseconds to\n * wait for the closing handshake to finish after `websocket.close()` is\n * called\n * @param {Function} [options.handleProtocols] A hook to handle protocols\n * @param {String} [options.host] The hostname where to bind the server\n * @param {Number} [options.maxBufferedChunks=1048576] The maximum number of\n * buffered data chunks\n * @param {Number} [options.maxFragments=131072] The maximum number of message\n * fragments\n * @param {Number} [options.maxPayload=104857600] The maximum allowed message\n * size\n * @param {Boolean} [options.noServer=false] Enable no server mode\n * @param {String} [options.path] Accept only connections matching this path\n * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable\n * permessage-deflate\n * @param {Number} [options.port] The port where to bind the server\n * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S\n * server to use\n * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or\n * not to skip UTF-8 validation for text and close messages\n * @param {Function} [options.verifyClient] A hook to reject connections\n * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`\n * class to use. It must be the `WebSocket` class or class that extends it\n * @param {Function} [callback] A listener for the `listening` event\n */\n constructor(options, callback) {\n super();\n\n options = {\n allowSynchronousEvents: true,\n autoPong: true,\n maxBufferedChunks: 1024 * 1024,\n maxFragments: 128 * 1024,\n maxPayload: 100 * 1024 * 1024,\n skipUTF8Validation: false,\n perMessageDeflate: false,\n handleProtocols: null,\n clientTracking: true,\n closeTimeout: CLOSE_TIMEOUT,\n verifyClient: null,\n noServer: false,\n backlog: null, // use default (511 as implemented in net.js)\n server: null,\n host: null,\n path: null,\n port: null,\n WebSocket,\n ...options\n };\n\n if (\n (options.port == null && !options.server && !options.noServer) ||\n (options.port != null && (options.server || options.noServer)) ||\n (options.server && options.noServer)\n ) {\n throw new TypeError(\n 'One and only one of the \"port\", \"server\", or \"noServer\" options ' +\n 'must be specified'\n );\n }\n\n if (options.port != null) {\n this._server = http.createServer((req, res) => {\n const body = http.STATUS_CODES[426];\n\n res.writeHead(426, {\n 'Content-Length': body.length,\n 'Content-Type': 'text/plain'\n });\n res.end(body);\n });\n this._server.listen(\n options.port,\n options.host,\n options.backlog,\n callback\n );\n } else if (options.server) {\n this._server = options.server;\n }\n\n if (this._server) {\n const emitConnection = this.emit.bind(this, 'connection');\n\n this._removeListeners = addListeners(this._server, {\n listening: this.emit.bind(this, 'listening'),\n error: this.emit.bind(this, 'error'),\n upgrade: (req, socket, head) => {\n this.handleUpgrade(req, socket, head, emitConnection);\n }\n });\n }\n\n if (options.perMessageDeflate === true) options.perMessageDeflate = {};\n if (options.clientTracking) {\n this.clients = new Set();\n this._shouldEmitClose = false;\n }\n\n this.options = options;\n this._state = RUNNING;\n }\n\n /**\n * Returns the bound address, the address family name, and port of the server\n * as reported by the operating system if listening on an IP socket.\n * If the server is listening on a pipe or UNIX domain socket, the name is\n * returned as a string.\n *\n * @return {(Object|String|null)} The address of the server\n * @public\n */\n address() {\n if (this.options.noServer) {\n throw new Error('The server is operating in \"noServer\" mode');\n }\n\n if (!this._server) return null;\n return this._server.address();\n }\n\n /**\n * Stop the server from accepting new connections and emit the `'close'` event\n * when all existing connections are closed.\n *\n * @param {Function} [cb] A one-time listener for the `'close'` event\n * @public\n */\n close(cb) {\n if (this._state === CLOSED) {\n if (cb) {\n this.once('close', () => {\n cb(new Error('The server is not running'));\n });\n }\n\n process.nextTick(emitClose, this);\n return;\n }\n\n if (cb) this.once('close', cb);\n\n if (this._state === CLOSING) return;\n this._state = CLOSING;\n\n if (this.options.noServer || this.options.server) {\n if (this._server) {\n this._removeListeners();\n this._removeListeners = this._server = null;\n }\n\n if (this.clients) {\n if (!this.clients.size) {\n process.nextTick(emitClose, this);\n } else {\n this._shouldEmitClose = true;\n }\n } else {\n process.nextTick(emitClose, this);\n }\n } else {\n const server = this._server;\n\n this._removeListeners();\n this._removeListeners = this._server = null;\n\n //\n // The HTTP/S server was created internally. Close it, and rely on its\n // `'close'` event.\n //\n server.close(() => {\n emitClose(this);\n });\n }\n }\n\n /**\n * See if a given request should be handled by this server instance.\n *\n * @param {http.IncomingMessage} req Request object to inspect\n * @return {Boolean} `true` if the request is valid, else `false`\n * @public\n */\n shouldHandle(req) {\n if (this.options.path) {\n const index = req.url.indexOf('?');\n const pathname = index !== -1 ? req.url.slice(0, index) : req.url;\n\n if (pathname !== this.options.path) return false;\n }\n\n return true;\n }\n\n /**\n * Handle a HTTP Upgrade request.\n *\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @public\n */\n handleUpgrade(req, socket, head, cb) {\n socket.on('error', socketOnError);\n\n const key = req.headers['sec-websocket-key'];\n const upgrade = req.headers.upgrade;\n const version = +req.headers['sec-websocket-version'];\n\n if (req.method !== 'GET') {\n const message = 'Invalid HTTP method';\n abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);\n return;\n }\n\n if (upgrade === undefined || upgrade.toLowerCase() !== 'websocket') {\n const message = 'Invalid Upgrade header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (key === undefined || !keyRegex.test(key)) {\n const message = 'Missing or invalid Sec-WebSocket-Key header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n\n if (version !== 13 && version !== 8) {\n const message = 'Missing or invalid Sec-WebSocket-Version header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {\n 'Sec-WebSocket-Version': '13, 8'\n });\n return;\n }\n\n if (!this.shouldHandle(req)) {\n abortHandshake(socket, 400);\n return;\n }\n\n const secWebSocketProtocol = req.headers['sec-websocket-protocol'];\n let protocols = new Set();\n\n if (secWebSocketProtocol !== undefined) {\n try {\n protocols = subprotocol.parse(secWebSocketProtocol);\n } catch (err) {\n const message = 'Invalid Sec-WebSocket-Protocol header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n const secWebSocketExtensions = req.headers['sec-websocket-extensions'];\n const extensions = {};\n\n if (\n this.options.perMessageDeflate &&\n secWebSocketExtensions !== undefined\n ) {\n const perMessageDeflate = new PerMessageDeflate({\n ...this.options.perMessageDeflate,\n isServer: true,\n maxPayload: this.options.maxPayload\n });\n\n try {\n const offers = extension.parse(secWebSocketExtensions);\n\n if (offers[PerMessageDeflate.extensionName]) {\n perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);\n extensions[PerMessageDeflate.extensionName] = perMessageDeflate;\n }\n } catch (err) {\n const message =\n 'Invalid or unacceptable Sec-WebSocket-Extensions header';\n abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);\n return;\n }\n }\n\n //\n // Optionally call external client verification handler.\n //\n if (this.options.verifyClient) {\n const info = {\n origin:\n req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`],\n secure: !!(req.socket.authorized || req.socket.encrypted),\n req\n };\n\n if (this.options.verifyClient.length === 2) {\n this.options.verifyClient(info, (verified, code, message, headers) => {\n if (!verified) {\n return abortHandshake(socket, code || 401, message, headers);\n }\n\n this.completeUpgrade(\n extensions,\n key,\n protocols,\n req,\n socket,\n head,\n cb\n );\n });\n return;\n }\n\n if (!this.options.verifyClient(info)) return abortHandshake(socket, 401);\n }\n\n this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);\n }\n\n /**\n * Upgrade the connection to WebSocket.\n *\n * @param {Object} extensions The accepted extensions\n * @param {String} key The value of the `Sec-WebSocket-Key` header\n * @param {Set} protocols The subprotocols\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The network socket between the server and client\n * @param {Buffer} head The first packet of the upgraded stream\n * @param {Function} cb Callback\n * @throws {Error} If called more than once with the same socket\n * @private\n */\n completeUpgrade(extensions, key, protocols, req, socket, head, cb) {\n //\n // Destroy the socket if the client has already sent a FIN packet.\n //\n if (!socket.readable || !socket.writable) return socket.destroy();\n\n if (socket[kWebSocket]) {\n throw new Error(\n 'server.handleUpgrade() was called more than once with the same ' +\n 'socket, possibly due to a misconfiguration'\n );\n }\n\n if (this._state > RUNNING) return abortHandshake(socket, 503);\n\n const digest = createHash('sha1')\n .update(key + GUID)\n .digest('base64');\n\n const headers = [\n 'HTTP/1.1 101 Switching Protocols',\n 'Upgrade: websocket',\n 'Connection: Upgrade',\n `Sec-WebSocket-Accept: ${digest}`\n ];\n\n const ws = new this.options.WebSocket(null, undefined, this.options);\n\n if (protocols.size) {\n //\n // Optionally call external protocol selection handler.\n //\n const protocol = this.options.handleProtocols\n ? this.options.handleProtocols(protocols, req)\n : protocols.values().next().value;\n\n if (protocol) {\n headers.push(`Sec-WebSocket-Protocol: ${protocol}`);\n ws._protocol = protocol;\n }\n }\n\n if (extensions[PerMessageDeflate.extensionName]) {\n const params = extensions[PerMessageDeflate.extensionName].params;\n const value = extension.format({\n [PerMessageDeflate.extensionName]: [params]\n });\n headers.push(`Sec-WebSocket-Extensions: ${value}`);\n ws._extensions = extensions;\n }\n\n //\n // Allow external modification/inspection of handshake headers.\n //\n this.emit('headers', headers, req);\n\n socket.write(headers.concat('\\r\\n').join('\\r\\n'));\n socket.removeListener('error', socketOnError);\n\n ws.setSocket(socket, head, {\n allowSynchronousEvents: this.options.allowSynchronousEvents,\n maxBufferedChunks: this.options.maxBufferedChunks,\n maxFragments: this.options.maxFragments,\n maxPayload: this.options.maxPayload,\n skipUTF8Validation: this.options.skipUTF8Validation\n });\n\n if (this.clients) {\n this.clients.add(ws);\n ws.on('close', () => {\n this.clients.delete(ws);\n\n if (this._shouldEmitClose && !this.clients.size) {\n process.nextTick(emitClose, this);\n }\n });\n }\n\n cb(ws, req);\n }\n}\n\nmodule.exports = WebSocketServer;\n\n/**\n * Add event listeners on an `EventEmitter` using a map of <event, listener>\n * pairs.\n *\n * @param {EventEmitter} server The event emitter\n * @param {Object.<String, Function>} map The listeners to add\n * @return {Function} A function that will remove the added listeners when\n * called\n * @private\n */\nfunction addListeners(server, map) {\n for (const event of Object.keys(map)) server.on(event, map[event]);\n\n return function removeListeners() {\n for (const event of Object.keys(map)) {\n server.removeListener(event, map[event]);\n }\n };\n}\n\n/**\n * Emit a `'close'` event on an `EventEmitter`.\n *\n * @param {EventEmitter} server The event emitter\n * @private\n */\nfunction emitClose(server) {\n server._state = CLOSED;\n server.emit('close');\n}\n\n/**\n * Handle socket errors.\n *\n * @private\n */\nfunction socketOnError() {\n this.destroy();\n}\n\n/**\n * Close the connection when preconditions are not fulfilled.\n *\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} [message] The HTTP response body\n * @param {Object} [headers] Additional HTTP response headers\n * @private\n */\nfunction abortHandshake(socket, code, message, headers) {\n //\n // The socket is writable unless the user destroyed or ended it before calling\n // `server.handleUpgrade()` or in the `verifyClient` function, which is a user\n // error. Handling this does not make much sense as the worst that can happen\n // is that some of the data written by the user might be discarded due to the\n // call to `socket.end()` below, which triggers an `'error'` event that in\n // turn causes the socket to be destroyed.\n //\n message = message || http.STATUS_CODES[code];\n headers = {\n Connection: 'close',\n 'Content-Type': 'text/html',\n 'Content-Length': Buffer.byteLength(message),\n ...headers\n };\n\n socket.once('finish', socket.destroy);\n\n socket.end(\n `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\\r\\n` +\n Object.keys(headers)\n .map((h) => `${h}: ${headers[h]}`)\n .join('\\r\\n') +\n '\\r\\n\\r\\n' +\n message\n );\n}\n\n/**\n * Emit a `'wsClientError'` event on a `WebSocketServer` if there is at least\n * one listener for it, otherwise call `abortHandshake()`.\n *\n * @param {WebSocketServer} server The WebSocket server\n * @param {http.IncomingMessage} req The request object\n * @param {Duplex} socket The socket of the upgrade request\n * @param {Number} code The HTTP response status code\n * @param {String} message The HTTP response body\n * @param {Object} [headers] The HTTP response headers\n * @private\n */\nfunction abortHandshakeOrEmitwsClientError(\n server,\n req,\n socket,\n code,\n message,\n headers\n) {\n if (server.listenerCount('wsClientError')) {\n const err = new Error(message);\n Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);\n\n server.emit('wsClientError', err, socket, req);\n } else {\n abortHandshake(socket, code, message, headers);\n }\n}\n", "import {\n ConvexClient,\n setDefaultWebSocketConstructor,\n} from \"./simple_client.js\";\n\n// This file is compiled with `bundle: true` with an exception for\n// `./simple_client.js` so this \"ws\" import will be inlined.\nimport ws from \"ws\";\nconst nodeWebSocket = ws as unknown as typeof WebSocket;\n\nsetDefaultWebSocketConstructor(nodeWebSocket);\n\nexport { ConvexClient };\n", "import createWebSocketStream from './lib/stream.js';\nimport extension from './lib/extension.js';\nimport PerMessageDeflate from './lib/permessage-deflate.js';\nimport Receiver from './lib/receiver.js';\nimport Sender from './lib/sender.js';\nimport subprotocol from './lib/subprotocol.js';\nimport WebSocket from './lib/websocket.js';\nimport WebSocketServer from './lib/websocket-server.js';\n\nexport {\n createWebSocketStream,\n extension,\n PerMessageDeflate,\n Receiver,\n Sender,\n subprotocol,\n WebSocket,\n WebSocketServer\n};\n\nexport default WebSocket;\n", "import {\n FunctionReturnType,\n OptionalRestArgs,\n getFunctionName,\n FunctionReference,\n FunctionReference_future,\n} from \"../server/api.js\";\nimport { parseArgs, validateDeploymentUrl } from \"../common/index.js\";\nimport { version } from \"../index.js\";\nimport {\n ConvexError,\n JSONValue,\n convexToJson,\n jsonToConvex,\n} from \"../values/index.js\";\nimport {\n instantiateDefaultLogger,\n instantiateNoopLogger,\n logForFunction,\n Logger,\n} from \"./logging.js\";\nimport {\n ArgsAndOptions,\n FunctionArgs,\n UserIdentityAttributes,\n} from \"../server/index.js\";\n\nexport const STATUS_CODE_OK = 200;\nexport const STATUS_CODE_BAD_REQUEST = 400;\n// Special custom 5xx HTTP status code to mean that the UDF returned an error.\n//\n// Must match the constant of the same name in the backend.\nexport const STATUS_CODE_UDF_FAILED = 560;\n\n// Allow fetch to be shimmed in for Node.js < 18\nlet specifiedFetch: typeof globalThis.fetch | undefined = undefined;\nexport function setFetch(f: typeof globalThis.fetch) {\n specifiedFetch = f;\n}\n\nexport type HttpMutationOptions = {\n /**\n * Skip the default queue of mutations and run this immediately.\n *\n * This allows the same HttpConvexClient to be used to request multiple\n * mutations in parallel, something not possible with WebSocket-based clients.\n */\n skipQueue: boolean;\n};\n\n/**\n * A Convex client that runs queries and mutations over HTTP.\n *\n * This client is stateful (it has user credentials and queues mutations)\n * so take care to avoid sharing it between requests in a server.\n *\n * This is appropriate for server-side code (like Netlify Lambdas) or non-reactive\n * webapps.\n *\n * @public\n */\nexport class ConvexHttpClient {\n private readonly address: string;\n private auth: string | undefined;\n private adminAuth: string | undefined;\n private encodedTsPromise?: Promise<string>;\n private debug: boolean;\n private fetchOptions?: FetchOptions;\n private fetch?: typeof globalThis.fetch | undefined;\n private logger: Logger;\n private mutationQueue: Array<{\n mutation:\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">;\n args: FunctionArgs<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }> = [];\n private isProcessingQueue: boolean = false;\n\n /**\n * Create a new {@link ConvexHttpClient}.\n *\n * @param address - The url of your Convex deployment, often provided\n * by an environment variable. E.g. `https://small-mouse-123.convex.cloud`.\n * @param options - An object of options.\n * - `skipConvexDeploymentUrlCheck` - Skip validating that the Convex deployment URL looks like\n * `https://happy-animal-123.convex.cloud` or localhost. This can be useful if running a self-hosted\n * Convex backend that uses a different URL.\n * - `logger` - A logger or a boolean. If not provided, logs to the console.\n * You can construct your own logger to customize logging to log elsewhere\n * or not log at all, or use `false` as a shorthand for a no-op logger.\n * A logger is an object with 4 methods: log(), warn(), error(), and logVerbose().\n * These methods can receive multiple arguments of any types, like console.log().\n * - `auth` - A JWT containing identity claims accessible in Convex functions.\n * This identity may expire so it may be necessary to call `setAuth()` later,\n * but for short-lived clients it's convenient to specify this value here.\n * - `fetch` - A custom fetch implementation to use for all HTTP requests made by this client.\n */\n constructor(\n address: string,\n options?: {\n skipConvexDeploymentUrlCheck?: boolean;\n logger?: Logger | boolean;\n auth?: string;\n fetch?: typeof globalThis.fetch;\n },\n ) {\n if (typeof options === \"boolean\") {\n throw new Error(\n \"skipConvexDeploymentUrlCheck as the second argument is no longer supported. Please pass an options object, `{ skipConvexDeploymentUrlCheck: true }`.\",\n );\n }\n const opts = options ?? {};\n if (opts.skipConvexDeploymentUrlCheck !== true) {\n validateDeploymentUrl(address);\n }\n this.logger =\n options?.logger === false\n ? instantiateNoopLogger({ verbose: false })\n : options?.logger !== true && options?.logger\n ? options.logger\n : instantiateDefaultLogger({ verbose: false });\n this.address = address;\n this.debug = true;\n this.auth = undefined;\n this.adminAuth = undefined;\n this.fetch = options?.fetch;\n if (options?.auth) {\n this.setAuth(options.auth);\n }\n }\n\n /**\n * Obtain the {@link ConvexHttpClient}'s URL to its backend.\n * @deprecated Use url, which returns the url without /api at the end.\n *\n * @returns The URL to the Convex backend, including the client's API version.\n */\n backendUrl(): string {\n return `${this.address}/api`;\n }\n\n /**\n * Return the address for this client, useful for creating a new client.\n *\n * Not guaranteed to match the address with which this client was constructed:\n * it may be canonicalized.\n */\n get url() {\n return this.address;\n }\n\n /**\n * Set the authentication token to be used for subsequent queries and mutations.\n *\n * Should be called whenever the token changes (i.e. due to expiration and refresh).\n *\n * @param value - JWT-encoded OpenID Connect identity token.\n */\n setAuth(value: string) {\n this.clearAuth();\n this.auth = value;\n }\n\n /**\n * Set admin auth token to allow calling internal queries, mutations, and actions\n * and acting as an identity.\n *\n * @internal\n */\n setAdminAuth(token: string, actingAsIdentity?: UserIdentityAttributes) {\n this.clearAuth();\n if (actingAsIdentity !== undefined) {\n // Encode the identity to a base64 string\n const bytes = new TextEncoder().encode(JSON.stringify(actingAsIdentity));\n const actingAsIdentityEncoded = btoa(String.fromCodePoint(...bytes));\n this.adminAuth = `${token}:${actingAsIdentityEncoded}`;\n } else {\n this.adminAuth = token;\n }\n }\n\n /**\n * Clear the current authentication token if set.\n */\n clearAuth() {\n this.auth = undefined;\n this.adminAuth = undefined;\n }\n\n /**\n * Sets whether the result log lines should be printed on the console or not.\n *\n * @internal\n */\n setDebug(debug: boolean) {\n this.debug = debug;\n }\n\n /**\n * Used to customize the fetch behavior in some runtimes.\n *\n * @internal\n */\n setFetchOptions(fetchOptions: FetchOptions) {\n this.fetchOptions = fetchOptions;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Execute a Convex query function at the same timestamp as every other\n * consistent query execution run by this HTTP client.\n *\n * This doesn't make sense for long-lived ConvexHttpClients as Convex\n * backends can read a limited amount into the past: beyond 30 seconds\n * in the past may not be available.\n *\n * Create a new client to use a consistent time.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n *\n * @deprecated This API is experimental: it may change or disappear.\n */\n async consistentQuery<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n\n const timestampPromise = this.getTimestamp();\n return await this.queryInner(query, queryArgs, { timestampPromise });\n }\n\n private async getTimestamp() {\n if (this.encodedTsPromise) {\n return this.encodedTsPromise;\n }\n return (this.encodedTsPromise = this.getTimestampInner());\n }\n\n private async getTimestampInner() {\n const localFetch = this.fetch || specifiedFetch || fetch;\n\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n const response = await localFetch(`${this.address}/api/query_ts`, {\n ...this.fetchOptions,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok) {\n throw new Error(await response.text());\n }\n const { ts } = (await response.json()) as { ts: string };\n return ts;\n }\n\n /**\n * Execute a Convex query function.\n *\n * @param name - The name of the query.\n * @param args - The arguments object for the query. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the query's result.\n */\n async query<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n ...args: OptionalRestArgs<Query>\n ): Promise<FunctionReturnType<Query>> {\n const queryArgs = parseArgs(args[0]);\n return await this.queryInner(query, queryArgs, {});\n }\n\n private async queryInner<\n Query extends\n | FunctionReference<\"query\">\n | FunctionReference_future<\"query\">,\n >(\n query: Query,\n queryArgs: FunctionArgs<Query>,\n options: { timestampPromise?: Promise<string> },\n ): Promise<FunctionReturnType<Query>> {\n const name = getFunctionName(query);\n const args = [convexToJson(queryArgs)];\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n\n const timestamp = options.timestampPromise\n ? await options.timestampPromise\n : undefined;\n\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args,\n ...(timestamp ? { ts: timestamp } : {}),\n });\n const endpoint = timestamp\n ? `${this.address}/api/query_at_ts`\n : `${this.address}/api/query`;\n\n const response = await localFetch(endpoint, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"query\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async mutationInner<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n mutationArgs: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n const name = getFunctionName(mutation);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(mutationArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/mutation`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"mutation\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n private async processMutationQueue() {\n if (this.isProcessingQueue) {\n return;\n }\n\n this.isProcessingQueue = true;\n while (this.mutationQueue.length > 0) {\n const { mutation, args, resolve, reject } = this.mutationQueue.shift()!;\n try {\n const result = await this.mutationInner(mutation, args);\n resolve(result);\n } catch (error) {\n reject(error);\n }\n }\n this.isProcessingQueue = false;\n }\n\n private enqueueMutation<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n args: FunctionArgs<Mutation>,\n ): Promise<FunctionReturnType<Mutation>> {\n return new Promise((resolve, reject) => {\n this.mutationQueue.push({ mutation, args, resolve, reject });\n void this.processMutationQueue();\n });\n }\n\n /**\n * Execute a Convex mutation function. Mutations are queued by default.\n *\n * @param name - The name of the mutation.\n * @param args - The arguments object for the mutation. If this is omitted,\n * the arguments will be `{}`.\n * @param options - An optional object containing\n * @returns A promise of the mutation's result.\n */\n async mutation<\n Mutation extends\n | FunctionReference<\"mutation\">\n | FunctionReference_future<\"mutation\">,\n >(\n mutation: Mutation,\n ...args: ArgsAndOptions<Mutation, HttpMutationOptions>\n ): Promise<FunctionReturnType<Mutation>> {\n const [fnArgs, options] = args;\n const mutationArgs = parseArgs(fnArgs);\n const queued = !options?.skipQueue;\n\n if (queued) {\n return await this.enqueueMutation(mutation, mutationArgs);\n } else {\n return await this.mutationInner(mutation, mutationArgs);\n }\n }\n\n /**\n * Execute a Convex action function. Actions are not queued.\n *\n * @param name - The name of the action.\n * @param args - The arguments object for the action. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the action's result.\n */\n async action<\n Action extends\n | FunctionReference<\"action\">\n | FunctionReference_future<\"action\">,\n >(\n action: Action,\n ...args: OptionalRestArgs<Action>\n ): Promise<FunctionReturnType<Action>> {\n const actionArgs = parseArgs(args[0]);\n const name = getFunctionName(action);\n const body = JSON.stringify({\n path: name,\n format: \"convex_encoded_json\",\n args: [convexToJson(actionArgs)],\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/action`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"action\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n\n /**\n * Execute a Convex function of an unknown type. These function calls are not queued.\n *\n * @param name - The name of the function.\n * @param args - The arguments object for the function. If this is omitted,\n * the arguments will be `{}`.\n * @returns A promise of the function's result.\n *\n * @internal\n */\n async function<\n AnyFunction extends\n | FunctionReference<\"query\" | \"mutation\" | \"action\">\n | FunctionReference_future<\"query\" | \"mutation\" | \"action\">,\n >(\n anyFunction: AnyFunction | string,\n componentPath?: string,\n ...args: OptionalRestArgs<AnyFunction>\n ): Promise<FunctionReturnType<AnyFunction>> {\n const functionArgs = parseArgs(args[0]);\n const name =\n typeof anyFunction === \"string\"\n ? anyFunction\n : getFunctionName(anyFunction);\n const body = JSON.stringify({\n componentPath: componentPath,\n path: name,\n format: \"convex_encoded_json\",\n args: convexToJson(functionArgs),\n });\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n \"Convex-Client\": `npm-${version}`,\n };\n if (this.adminAuth) {\n headers[\"Authorization\"] = `Convex ${this.adminAuth}`;\n } else if (this.auth) {\n headers[\"Authorization\"] = `Bearer ${this.auth}`;\n }\n const localFetch = this.fetch || specifiedFetch || fetch;\n const response = await localFetch(`${this.address}/api/function`, {\n ...this.fetchOptions,\n body,\n method: \"POST\",\n headers: headers,\n });\n if (!response.ok && response.status !== STATUS_CODE_UDF_FAILED) {\n throw new Error(await response.text());\n }\n const respJSON = await response.json();\n if (this.debug) {\n for (const line of respJSON.logLines ?? []) {\n logForFunction(this.logger, \"info\", \"any\", name, line);\n }\n }\n switch (respJSON.status) {\n case \"success\":\n return jsonToConvex(respJSON.value);\n case \"error\":\n if (respJSON.errorData !== undefined) {\n throw forwardErrorData(\n respJSON.errorData,\n new ConvexError(respJSON.errorMessage),\n );\n }\n throw new Error(respJSON.errorMessage);\n default:\n throw new Error(`Invalid response: ${JSON.stringify(respJSON)}`);\n }\n }\n}\n\nfunction forwardErrorData(errorData: JSONValue, error: ConvexError<string>) {\n (error as ConvexError<any>).data = jsonToConvex(errorData);\n return error;\n}\n\n/**\n * @internal\n */\ntype FetchOptions = { cache: \"force-cache\" | \"no-store\" };\n", "// Convex transport for the CLI. Unlike a hand-rolled REST client, this talks to\n// the deployment the way the frontend does: a `ConvexHttpClient` calling `api.*`\n// functions directly. Auth is the JWT bridge \u2014 the persistent `ente_\u2026` API key\n// is exchanged at `POST ${siteUrl}/cli/token` for a short-lived RS256 JWT that\n// Convex verifies via its customJwt provider, so every call lands as the real\n// authenticated user and the same permission gates apply. Brand-neutral.\n\nimport { ConvexHttpClient } from \"convex/browser\";\nimport type { FunctionReference, FunctionReturnType, OptionalRestArgs } from \"convex/server\";\n\nimport { loadJwt, storeJwt } from \"./jwt-cache.ts\";\n\nconst DEFAULT_TTL_MS = 15 * 60 * 1000;\n\n/** Exchange the persistent API key for a short-lived JWT at /cli/token. */\nexport async function exchangeToken(\n siteUrl: string,\n apiKey: string,\n): Promise<{ jwt: string; expiresAt: number }> {\n const url = `${siteUrl.replace(/\\/+$/, \"\")}/cli/token`;\n let resp: Response;\n try {\n resp = await fetch(url, { method: \"POST\", headers: { Authorization: `Bearer ${apiKey}` } });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(`Could not reach ${url}: ${msg}`);\n }\n if (resp.status === 401) {\n throw new Error(\n \"API key rejected (401) at /cli/token \u2014 generate a fresh key in the web app under \" +\n \"Settings \u2192 API Keys and re-run 'ente auth login'.\",\n );\n }\n if (!resp.ok) {\n throw new Error(`/cli/token exchange failed (${resp.status} ${resp.statusText}).`);\n }\n const body = (await resp.json()) as { token?: string; expiresAt?: number };\n if (!body.token) throw new Error(\"/cli/token returned no token.\");\n return { jwt: body.token, expiresAt: body.expiresAt ?? Date.now() + DEFAULT_TTL_MS };\n}\n\n/** Heuristic: does a Convex call error look like an auth failure worth a JWT refresh? */\nexport function isAuthError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return /\\b(401|403|unauthenticated|unauthorized|not authenticated)\\b/i.test(msg);\n}\n\nexport interface CallerOptions {\n /** The deployment API origin (\u2026convex.cloud) \u2014 the ConvexHttpClient target. */\n convexUrl: string;\n /** The deployment HTTP-actions origin (\u2026convex.site) \u2014 hosts /cli/token. */\n siteUrl: string;\n /** The persistent `ente_\u2026` API key. */\n apiKey: string;\n /** Directory for the on-disk JWT cache. */\n cacheDir: string;\n /** Cache key (per deployment), e.g. the convexUrl host. */\n cacheKey: string;\n}\n\nexport interface ConvexCaller {\n query<Q extends FunctionReference<\"query\">>(\n ref: Q,\n ...args: OptionalRestArgs<Q>\n ): Promise<FunctionReturnType<Q>>;\n mutation<M extends FunctionReference<\"mutation\">>(\n ref: M,\n ...args: OptionalRestArgs<M>\n ): Promise<FunctionReturnType<M>>;\n action<A extends FunctionReference<\"action\">>(\n ref: A,\n ...args: OptionalRestArgs<A>\n ): Promise<FunctionReturnType<A>>;\n readonly convexUrl: string;\n}\n\nasync function mintAndCache(opts: CallerOptions): Promise<string> {\n const { jwt, expiresAt } = await exchangeToken(opts.siteUrl, opts.apiKey);\n storeJwt(opts.cacheDir, opts.cacheKey, jwt, expiresAt);\n return jwt;\n}\n\n/** Build a Convex caller authenticated via the JWT bridge. */\nexport async function makeCaller(opts: CallerOptions): Promise<ConvexCaller> {\n const client = new ConvexHttpClient(opts.convexUrl);\n const cached = loadJwt(opts.cacheDir, opts.cacheKey);\n const jwt = cached ?? (await mintAndCache(opts));\n client.setAuth(jwt);\n\n // On an auth error, re-exchange the JWT once and retry \u2014 handles a cached JWT\n // that expired mid-session.\n async function withRetry<R>(fn: () => Promise<R>): Promise<R> {\n try {\n return await fn();\n } catch (err) {\n if (!isAuthError(err)) throw err;\n client.setAuth(await mintAndCache(opts));\n return fn();\n }\n }\n\n return {\n convexUrl: opts.convexUrl,\n query: (ref, ...args) => withRetry(() => client.query(ref, ...args)),\n mutation: (ref, ...args) => withRetry(() => client.mutation(ref, ...args)),\n action: (ref, ...args) => withRetry(() => client.action(ref, ...args)),\n };\n}\n", "import { createHash, randomBytes, randomInt } from \"node:crypto\";\nimport { existsSync, readFileSync, rmSync, writeFileSync } from \"node:fs\";\nimport { Command, Option } from \"clipanion\";\n\nimport {\n configPath,\n normalizeProfileName,\n saveCredentials,\n} from \"../../core/config.ts\";\nimport { BaseCommand } from \"../command.ts\";\nimport { ENTE_BRANDING } from \"../branding.ts\";\n\ntype PairSpec = {\n profile: string;\n agentId?: string;\n access?: \"read\" | \"write\";\n};\n\ntype PendingPair = {\n spec: PairSpec;\n key: string;\n keyHash: string;\n keyPrefix: string;\n};\n\nfunction parseManifest(file: string): PairSpec[] {\n const parsed: unknown = JSON.parse(readFileSync(file, \"utf8\"));\n if (!Array.isArray(parsed)) throw new Error(\"Pairing manifest must be a JSON array\");\n return parsed.map((item: unknown) => {\n if (!item || typeof item !== \"object\" || Array.isArray(item)) {\n throw new Error(\"Each pairing entry needs a profile and optional agentId/access\");\n }\n const value = item as Record<string, unknown>;\n if (typeof value.profile !== \"string\"\n || value.agentId !== undefined && typeof value.agentId !== \"string\"\n || value.access !== undefined && value.access !== \"read\" && value.access !== \"write\"\n || Object.keys(value).some((key) => ![\"profile\", \"agentId\", \"access\"].includes(key))) {\n throw new Error(\"Invalid pairing manifest entry\");\n }\n return {\n profile: value.profile,\n ...(value.agentId !== undefined ? { agentId: value.agentId } : {}),\n ...(value.access ? { access: value.access } : {}),\n } as PairSpec;\n });\n}\n\nexport function validatePairSpecs(specs: PairSpec[]): PairSpec[] {\n if (specs.length < 1 || specs.length > 10) {\n throw new Error(\"Pair 1 to 10 profiles at a time\");\n }\n const names = new Set<string>();\n return specs.map((spec) => {\n if (!spec.profile.trim()) throw new Error(\"Pairing profile name cannot be empty\");\n const profile = normalizeProfileName(spec.profile) ?? \"default\";\n if (names.has(profile) || profile === \"default\" && specs.length > 1) {\n throw new Error(\"Pairing profiles must be distinct; batch profiles must be named\");\n }\n names.add(profile);\n if (spec.agentId === undefined && spec.access === \"read\") {\n throw new Error(\"Account profiles have full API access; use an agent ID to choose agent and inbox permissions\");\n }\n if (spec.agentId !== undefined && !/^[a-z0-9]{20,64}$/.test(spec.agentId)) {\n throw new Error(`Invalid agent ID for profile '${profile}'`);\n }\n return { ...spec, profile, access: spec.agentId !== undefined ? spec.access ?? \"read\" : \"write\" };\n });\n}\n\nfunction createPendingPair(spec: PairSpec): PendingPair {\n const key = `ente_${randomBytes(32).toString(\"hex\")}`;\n return {\n spec,\n key,\n keyHash: createHash(\"sha256\").update(key).digest(\"hex\"),\n keyPrefix: `${key.slice(0, 13)}...`,\n };\n}\n\ntype SavedPairProfile = { profile: string; key: string; previous: Buffer | null };\n\nclass PairingHttpError extends Error {\n constructor(readonly status: number) {\n super(status === 409\n ? \"Pairing approval is no longer eligible; check the agent inbox and start again\"\n : `Pairing service returned ${status}`);\n }\n}\n\nfunction restoreProfiles(saved: SavedPairProfile[], forceLast = false): void {\n for (const [index, item] of [...saved].reverse().entries()) {\n const file = configPath(ENTE_BRANDING, item.profile);\n // Another process may have changed this profile after pairing wrote it.\n if (existsSync(file)) {\n if (!forceLast || index > 0) {\n if (!readFileSync(file, \"utf8\").includes(`api_key = \"${item.key}\"`)) continue;\n }\n rmSync(file);\n }\n if (item.previous !== null) writeFileSync(file, item.previous, { mode: 0o600 });\n }\n}\n\nfunction saveApprovedProfiles(pending: PendingPair[], url: string, replace: boolean): SavedPairProfile[] {\n const saved: SavedPairProfile[] = [];\n try {\n for (const item of pending) {\n const file = configPath(ENTE_BRANDING, item.spec.profile);\n const previous = replace && existsSync(file) ? readFileSync(file) : null;\n if (replace) saved.push({ profile: item.spec.profile, key: item.key, previous });\n saveCredentials(ENTE_BRANDING, url, item.key, item.spec.profile, { ifAbsent: !replace });\n if (!replace) saved.push({ profile: item.spec.profile, key: item.key, previous: null });\n }\n return saved;\n } catch (error) {\n restoreProfiles(saved, replace);\n throw error;\n }\n}\n\nasync function postJson(url: string, body: unknown): Promise<Record<string, unknown>> {\n const response = await fetch(url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(15_000),\n });\n if (!response.ok) throw new PairingHttpError(response.status);\n const result: unknown = await response.json();\n if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n throw new Error(\"Invalid pairing service response\");\n }\n return result as Record<string, unknown>;\n}\n\nasync function verifyCredential(url: string, key: string): Promise<Response> {\n return await fetch(`${url}/api/external/auth-context`, {\n headers: { Authorization: `Bearer ${key}` },\n signal: AbortSignal.timeout(15_000),\n });\n}\n\nexport class AuthPair extends BaseCommand {\n static paths = [[\"auth\", \"pair\"]];\n static usage = Command.Usage({\n category: \"Auth\",\n description: \"Connect CLI profiles through browser approval without copying API keys\",\n });\n\n url = Option.String(\"--url\", { required: true, description: \"Convex site URL\" });\n email = Option.String(\"--email\", { required: true, description: \"Ente account email that will approve the connection\" });\n manifest = Option.String(\"--manifest\", { description: \"JSON file with up to 10 profile and agentId entries\" });\n profile = Option.String(\"--profile\", { description: \"Single profile name (default: default)\" });\n agent = Option.String(\"--agent\", { description: \"Agent ID to bind the single profile to\" });\n access = Option.String(\"--access\", { description: \"Agent access: read or write (default: read)\" });\n replace = Option.Boolean(\"--replace\", false, { description: \"Replace existing local profiles after approval\" });\n\n async run(): Promise<number | void> {\n if (this.manifest && (this.profile || this.agent || this.access)) {\n throw new Error(\"Use either --manifest or single-profile options\");\n }\n if (this.access && this.access !== \"read\" && this.access !== \"write\") {\n throw new Error(\"--access must be read or write\");\n }\n const specs = validatePairSpecs(this.manifest\n ? parseManifest(this.manifest)\n : [{ profile: this.profile ?? \"default\", agentId: this.agent, access: this.access as \"read\" | \"write\" | undefined }]);\n if (!this.replace) {\n const existing = specs.find((spec) => existsSync(configPath(ENTE_BRANDING, spec.profile)));\n if (existing) throw new Error(`Profile '${existing.profile}' already exists; use --replace to replace it`);\n }\n const cleanUrl = this.url.replace(/\\/+$/, \"\");\n const pending = specs.map(createPendingPair);\n const requestId = randomBytes(32).toString(\"hex\");\n const pollToken = randomBytes(32).toString(\"hex\");\n const userCode = String(randomInt(1_000_000)).padStart(6, \"0\");\n const started = await postJson(`${cleanUrl}/api/credential-pair/start`, {\n requestId,\n pollToken,\n userCode,\n email: this.email,\n entries: pending.map(({ spec, keyHash, keyPrefix }) => ({\n profile: spec.profile,\n kind: spec.agentId !== undefined ? \"agent\" : \"account\",\n ...(spec.agentId !== undefined ? { agentId: spec.agentId } : {}),\n access: spec.access,\n keyHash,\n keyPrefix,\n })),\n });\n if (typeof started.reviewUrl !== \"string\" || typeof started.expiresAt !== \"number\") {\n throw new Error(\"Invalid pairing response\");\n }\n this.out(`Review and approve ${pending.length} profile${pending.length === 1 ? \"\" : \"s\"}:`);\n this.out(started.reviewUrl);\n this.out(`Code: ${userCode}`);\n this.out(\"Waiting for approval. Keys remain in this process and are not printed.\");\n\n let pollErrors = 0;\n while (Date.now() < started.expiresAt) {\n await new Promise((resolve) => setTimeout(resolve, 2_000));\n let polled: Record<string, unknown>;\n try {\n polled = await postJson(`${cleanUrl}/api/credential-pair/poll`, { requestId, pollToken });\n pollErrors = 0;\n } catch (error) {\n if (error instanceof PairingHttpError && error.status < 500) throw error;\n if (++pollErrors < 5) continue;\n throw error;\n }\n if (polled.status === \"pending\") continue;\n if (polled.status !== \"approved\") {\n throw new Error(`Pairing ${String(polled.status ?? \"failed\")}; no profiles saved`);\n }\n const saved = saveApprovedProfiles(pending, cleanUrl, this.replace);\n let completed: Record<string, unknown>;\n try {\n completed = await postJson(`${cleanUrl}/api/credential-pair/poll`, {\n requestId, pollToken, finalize: true,\n });\n } catch (error) {\n if (error instanceof PairingHttpError && error.status === 409) {\n restoreProfiles(saved);\n throw error;\n }\n // The request may have reached the server. Keep the secrets recoverable\n // if activation succeeded but the response was lost.\n throw new Error(`Profiles saved; activation status is unknown. Check 'ente auth status' for each profile. ${String(error)}`);\n }\n if (completed.status !== \"completed\") {\n restoreProfiles(saved);\n throw new Error(`Pairing ${String(completed.status ?? \"failed\")}; prior profiles restored`);\n }\n for (const item of pending) {\n const response = await verifyCredential(cleanUrl, item.key);\n if (!response.ok) {\n throw new Error(`Profile '${item.spec.profile}' saved but verification failed (${response.status})`);\n }\n this.out(`Verified: ${item.spec.profile}`);\n }\n return;\n }\n throw new Error(\"Pairing expired; no profiles saved\");\n }\n}\n", "// Authentication commands \u2014 login, status, logout. Offline (no API client):\n// they read/write the credential file directly. Ports commands/auth.py.\n\nimport { Command, Option } from \"clipanion\";\n\nimport {\n configDir,\n configPath,\n deleteCredentials,\n listStoredProfiles,\n readEnvCredentials,\n readStoredCredentials,\n saveCredentials,\n selectedProfile,\n} from \"../../core/config.ts\";\nimport { deleteJwt } from \"../../core/jwt-cache.ts\";\nimport { BaseCommand } from \"../command.ts\";\nimport { ENTE_BRANDING } from \"../branding.ts\";\nimport { credentialCacheKey } from \"../convexClient.ts\";\nimport { AuthPair } from \"./authPair.ts\";\n\nconst AUTH_CONTEXT_PATH = \"/api/external/auth-context\";\nconst LEGACY_AUTH_PROBE_PATH = \"/api/external/entities\";\n\nexport function readCredentialsForCleanup(\n profile: string | undefined,\n reader: typeof readStoredCredentials = readStoredCredentials,\n) {\n try {\n return reader(ENTE_BRANDING, profile);\n } catch {\n // Login and logout are recovery paths. A malformed config must not prevent\n // replacement or removal; it only means its old JWT cache key is unknown.\n return null;\n }\n}\n\n/**\n * Validate any external key without assuming it has a product-data scope.\n * Older deployments do not expose auth-context, so retain the historical\n * entities probe as a 404-only compatibility fallback.\n */\nexport async function validateExternalCredential(\n cleanUrl: string,\n key: string,\n signal?: AbortSignal,\n): Promise<Response> {\n const headers = { Authorization: `Bearer ${key}` };\n const authContext = await fetch(`${cleanUrl}${AUTH_CONTEXT_PATH}`, { headers, signal });\n if (authContext.status !== 404) return authContext;\n\n const legacyUrl = new URL(`${cleanUrl}${LEGACY_AUTH_PROBE_PATH}`);\n legacyUrl.searchParams.set(\"limit\", \"1\");\n return fetch(legacyUrl, { headers, signal });\n}\n\nclass AuthLogin extends BaseCommand {\n static paths = [[\"auth\", \"login\"]];\n static usage = Command.Usage({\n category: \"Auth\",\n description: \"Authenticate with an ente deployment\",\n });\n\n url = Option.String(\"--url\", {\n required: true,\n description: \"Convex site URL (e.g. https://your-deployment.convex.site)\",\n });\n key = Option.String(\"--key\", { description: \"API key (prefer --key-stdin to keep it out of command arguments)\" });\n keyStdin = Option.Boolean(\"--key-stdin\", false, { description: \"Read the API key from standard input\" });\n profile = Option.String(\"--profile\", {\n description: \"Store credentials in a named profile\",\n });\n\n async run(): Promise<number | void> {\n if (Boolean(this.key) === this.keyStdin) {\n throw new Error(\"Provide exactly one of --key or --key-stdin\");\n }\n let key = this.key ?? \"\";\n if (this.keyStdin) {\n for await (const chunk of this.context.stdin) {\n key += chunk.toString();\n if (key.length > 4096) throw new Error(\"API key input is too long\");\n }\n key = key.trim();\n }\n if (!key || /[\\r\\n]/u.test(key)) throw new Error(\"Provide one non-empty API key\");\n const cleanUrl = this.url.replace(/\\/+$/, \"\");\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), 10_000);\n let resp: Response;\n try {\n resp = await validateExternalCredential(cleanUrl, key, controller.signal);\n } catch {\n this.err(`Could not reach ${cleanUrl}`);\n return 1;\n } finally {\n clearTimeout(timer);\n }\n\n if (resp.status >= 400) {\n this.err(`Authentication failed: ${resp.status} ${resp.statusText}`);\n return 1;\n }\n\n const previous = readCredentialsForCleanup(this.profile);\n if (previous) {\n deleteJwt(\n configDir(ENTE_BRANDING),\n credentialCacheKey(previous.apiUrl, previous.apiKey),\n );\n }\n saveCredentials(ENTE_BRANDING, cleanUrl, key, this.profile);\n this.out(\"Authenticated successfully\");\n this.out(` Profile: ${selectedProfile(ENTE_BRANDING, this.profile) ?? \"default\"}`);\n this.out(` Config saved to ${configPath(ENTE_BRANDING, this.profile)}`);\n }\n}\n\nclass AuthStatus extends BaseCommand {\n static paths = [[\"auth\", \"status\"]];\n static usage = Command.Usage({\n category: \"Auth\",\n description: \"Show current authentication status\",\n });\n profile = Option.String(\"--profile\", {\n description: \"Inspect a named credential profile\",\n });\n\n async run(): Promise<number | void> {\n const profile = selectedProfile(ENTE_BRANDING, this.profile);\n const credentials = readEnvCredentials(ENTE_BRANDING, this.profile)\n ?? readStoredCredentials(ENTE_BRANDING, this.profile);\n const status = {\n configured: credentials !== null,\n verified: false,\n profile: profile ?? \"default\",\n source: credentials?.source ?? null,\n url: credentials?.apiUrl ?? null,\n };\n this.emitText(status, () => credentials\n ? `Profile: ${status.profile}\\nSource: ${status.source}\\nURL: ${status.url}\\nCredentials configured; run a read-only command to verify server access.`\n : `Profile '${status.profile}' is not authenticated.\\nSee https://ente.fast/cli.md for local login.`);\n\n }\n}\n\nclass AuthLogout extends BaseCommand {\n static paths = [[\"auth\", \"logout\"]];\n static usage = Command.Usage({ category: \"Auth\", description: \"Remove stored credentials\" });\n profile = Option.String(\"--profile\", {\n description: \"Remove credentials from a named profile\",\n });\n\n async run(): Promise<number | void> {\n const profile = selectedProfile(ENTE_BRANDING, this.profile) ?? \"default\";\n const stored = readCredentialsForCleanup(this.profile);\n const removed = deleteCredentials(ENTE_BRANDING, this.profile);\n if (stored) {\n deleteJwt(\n configDir(ENTE_BRANDING),\n credentialCacheKey(stored.apiUrl, stored.apiKey),\n );\n }\n this.out(removed\n ? `Credentials and cached session removed from profile '${profile}'`\n : `No stored credentials found for profile '${profile}'`);\n }\n}\n\nclass AuthProfiles extends BaseCommand {\n static paths = [[\"auth\", \"profiles\"]];\n static usage = Command.Usage({\n category: \"Auth\",\n description: \"List stored credential profiles\",\n });\n\n async run(): Promise<number | void> {\n const profiles = listStoredProfiles(ENTE_BRANDING);\n const selected = selectedProfile(ENTE_BRANDING) ?? \"default\";\n this.print({ selected, profiles }, (data) => data.profiles.map((profile) => ({\n Profile: profile,\n Selected: profile === data.selected ? \"yes\" : \"\",\n })));\n }\n}\n\nexport const AUTH_COMMANDS = [AuthLogin, AuthPair, AuthStatus, AuthLogout, AuthProfiles];\n", "import { v } from \"../values/validator.js\";\nimport type { Validator } from \"../values/validators.js\";\nimport type { Value } from \"../values/value.js\";\n\n/**\n * An opaque identifier used for paginating a database query.\n *\n * Cursors are returned from {@link OrderedQuery.paginate} and represent the\n * point of the query where the page of results ended.\n *\n * To continue paginating, pass the cursor back into\n * {@link OrderedQuery.paginate} in the {@link PaginationOptions} object to\n * fetch another page of results.\n *\n * Note: Cursors can only be passed to _exactly_ the same database query that\n * they were generated from. You may not reuse a cursor between different\n * database queries.\n *\n * @public\n */\nexport type Cursor = string;\n\n/**\n * The result of paginating using {@link OrderedQuery.paginate}.\n *\n * @public\n */\nexport interface PaginationResult<T> {\n /**\n * The page of results.\n */\n page: T[];\n\n /**\n * Have we reached the end of the results?\n */\n isDone: boolean;\n\n /**\n * A {@link Cursor} to continue loading more results.\n */\n continueCursor: Cursor;\n\n /**\n * A {@link Cursor} to split the page into two, so the page from\n * (cursor, continueCursor] can be replaced by two pages (cursor, splitCursor]\n * and (splitCursor, continueCursor].\n */\n splitCursor?: Cursor | null;\n\n /**\n * When a query reads too much data, it may return 'SplitRecommended' to\n * indicate that the page should be split into two with `splitCursor`.\n * When a query reads so much data that `page` might be incomplete, its status\n * becomes 'SplitRequired'.\n */\n pageStatus?: \"SplitRecommended\" | \"SplitRequired\" | null;\n}\n\n/**\n * The options passed to {@link OrderedQuery.paginate}.\n *\n * To use this type in [argument validation](https://docs.convex.dev/functions/validation),\n * use the {@link paginationOptsValidator}.\n *\n * @public\n */\nexport interface PaginationOptions {\n /**\n * Number of items to load in this page of results.\n *\n * Note: This is only an initial value!\n *\n * If you are running this paginated query in a reactive query function, you\n * may receive more or less items than this if items were added to or removed\n * from the query range.\n */\n numItems: number;\n\n /**\n * A {@link Cursor} representing the start of this page or `null` to start\n * at the beginning of the query results.\n */\n cursor: Cursor | null;\n\n /**\n * A {@link Cursor} representing the end of this page or `null | undefined` to\n * use `numItems` instead.\n *\n * This explicitly sets the range of documents the query will return, from\n * `cursor` to `endCursor`. It's used by reactive pagination clients to ensure\n * there are no gaps between pages when data changes, and to split pages when\n * `pageStatus` indicates a split is recommended or required.\n *\n * When splitting a page, use the returned `splitCursor` as `endCursor` for the\n * first half and as `cursor` for the second half.\n */\n endCursor?: Cursor | null;\n\n /**\n * The maximum number of rows to read from the database during pagination.\n *\n * This limits rows entering the query pipeline before filters are applied.\n * Use this when filtering for rare items, where low `numItems` won't bound\n * execution time because the query scans many rows to find matches.\n *\n * Currently this is not enforced for search queries.\n */\n maximumRowsRead?: number;\n\n /**\n * The maximum number of bytes to read from the database during pagination.\n *\n * This limits bytes entering the query pipeline before filters are applied.\n * Use this to control bandwidth usage when documents are large.\n * If the limit is reached, the query may return an incomplete page and\n * require a page split.\n *\n * Currently this is not enforced for search queries.\n */\n maximumBytesRead?: number;\n}\n\n/**\n * A {@link values.Validator} for {@link PaginationOptions}.\n *\n * Use this as the args validator in paginated query functions so that clients\n * can pass pagination options.\n *\n * @example\n * ```typescript\n * import { query } from \"./_generated/server\";\n * import { paginationOptsValidator } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export const listMessages = query({\n * args: {\n * channelId: v.id(\"channels\"),\n * paginationOpts: paginationOptsValidator,\n * },\n * handler: async (ctx, args) => {\n * return await ctx.db\n * .query(\"messages\")\n * .withIndex(\"by_channel\", (q) => q.eq(\"channelId\", args.channelId))\n * .order(\"desc\")\n * .paginate(args.paginationOpts);\n * },\n * });\n * ```\n *\n * On the client, use `usePaginatedQuery` from `\"convex/react\"`:\n * ```tsx\n * const { results, status, loadMore } = usePaginatedQuery(\n * api.messages.listMessages,\n * { channelId },\n * { initialNumItems: 25 },\n * );\n * ```\n *\n * @see https://docs.convex.dev/database/pagination\n * @public\n */\nexport const paginationOptsValidator = v.object({\n numItems: v.number(),\n cursor: v.union(v.string(), v.null()),\n endCursor: v.optional(v.union(v.string(), v.null())),\n id: v.optional(v.number()),\n maximumRowsRead: v.optional(v.number()),\n maximumBytesRead: v.optional(v.number()),\n});\n\n/**\n * A {@link values.Validator} factory for {@link PaginationResult}.\n *\n * Create a validator for the result of calling {@link OrderedQuery.paginate}\n * with a given item validator.\n *\n * For example:\n * ```ts\n * const paginationResultValidator = paginationResultValidator(v.object({\n * _id: v.id(\"users\"),\n * _creationTime: v.number(),\n * name: v.string(),\n * }));\n * ```\n *\n * @param itemValidator - A validator for the items in the page\n * @returns A validator for the pagination result\n *\n * @public\n */\nexport function paginationResultValidator<\n T extends Validator<Value, \"required\", string>,\n>(itemValidator: T) {\n return v.object({\n page: v.array(itemValidator),\n continueCursor: v.string(),\n isDone: v.boolean(),\n splitCursor: v.optional(v.union(v.string(), v.null())),\n pageStatus: v.optional(\n v.union(\n v.literal(\"SplitRecommended\"),\n v.literal(\"SplitRequired\"),\n v.null(),\n ),\n ),\n });\n}\n", "const REQUEST_ID = Symbol(\"var.requestId\");\nconst IP = Symbol(\"var.ip\");\nconst USER_AGENT = Symbol(\"var.userAgent\");\nconst NOW = Symbol(\"var.now\");\nconst CONVEX_ACTOR = Symbol(\"var.convexActor\");\n\nexport type LogVar =\n | typeof REQUEST_ID\n | typeof IP\n | typeof USER_AGENT\n | typeof NOW\n | typeof CONVEX_ACTOR;\n\nexport const varNames: Record<symbol, string> = {\n [REQUEST_ID]: \"requestId\",\n [IP]: \"ip\",\n [USER_AGENT]: \"userAgent\",\n [NOW]: \"now\",\n [CONVEX_ACTOR]: \"convexActor\",\n};\n\nexport const vars = {\n /** Resolved to the request ID. */\n requestId: REQUEST_ID,\n /** Resolved to the client's IP address. */\n ip: IP,\n /** Resolved to the client's User-Agent header. */\n userAgent: USER_AGENT,\n /**\n * Resolved to the current server timestamp, as milliseconds from the\n * Unix epoch.\n */\n now: NOW,\n /**\n * If the function was invoked using admin auth (either directly or while\n * acting as an end user, e.g. from the dashboard), resolved to information\n * about the admin. Otherwise, resolved to `null`.\n */\n convexActor: CONVEX_ACTOR,\n} as const;\n", "/**\n * Utilities for defining the schema of your Convex project.\n *\n * ## Usage\n *\n * Schemas should be placed in a `schema.ts` file in your `convex/` directory.\n *\n * Schema definitions should be built using {@link defineSchema},\n * {@link defineTable}, and {@link values.v}. Make sure to export the schema as the\n * default export.\n *\n * ```ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * messages: defineTable({\n * body: v.string(),\n * user: v.id(\"users\"),\n * }),\n * users: defineTable({\n * name: v.string(),\n * }),\n * });\n * ```\n *\n * To learn more about schemas, see [Defining a Schema](https://docs.convex.dev/using/schemas).\n * @module\n */\nimport {\n AnyDataModel,\n GenericDataModel,\n GenericTableIndexes,\n GenericTableSearchIndexes,\n GenericTableVectorIndexes,\n TableNamesInDataModel,\n} from \"../server/data_model.js\";\nimport {\n IdField,\n IndexTiebreakerField,\n SystemFields,\n SystemIndexes,\n} from \"../server/system_fields.js\";\nimport { Expand } from \"../type_utils.js\";\nimport { GenericId } from \"../values/index.js\";\nimport {\n GenericValidator,\n ObjectType,\n isValidator,\n v,\n} from \"../values/validator.js\";\nimport {\n VFloat64,\n VId,\n VObject,\n VUnion,\n Validator,\n} from \"../values/validators.js\";\n\n/**\n * Extract all of the index field paths within a {@link Validator}.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractFieldPaths<T extends Validator<any, any, any>> =\n // Add in the system fields available in index definitions.\n // This should be everything except for `_id` because thats added to indexes\n // automatically.\n T[\"fieldPaths\"] | keyof SystemFields;\n\n/**\n * Extract the {@link GenericDocument} within a {@link Validator} and\n * add on the system fields.\n *\n * This is used within {@link defineTable}.\n * @public\n */\ntype ExtractDocument<T extends Validator<any, any, any>> =\n // Add the system fields to `Value` (except `_id` because it depends on\n //the table name) and trick TypeScript into expanding them.\n Expand<SystemFields & T[\"type\"]>;\n\nexport interface DbIndexConfig<\n FirstFieldPath extends string,\n RestFieldPaths extends string[],\n> {\n /**\n * The fields to index, in order. Must specify at least one field.\n */\n fields: [FirstFieldPath, ...RestFieldPaths];\n}\n\n/**\n * The configuration for a full text search index.\n *\n * @public\n */\nexport interface SearchIndexConfig<\n SearchField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for full text search.\n *\n * This must be a field of type `string`.\n */\n searchField: SearchField;\n\n /**\n * Additional fields to index for fast filtering when running search queries.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * The configuration for a vector index.\n *\n * @public\n */\nexport interface VectorIndexConfig<\n VectorField extends string,\n FilterFields extends string,\n> {\n /**\n * The field to index for vector search.\n *\n * This must be a field of type `v.array(v.float64())` (or a union)\n */\n vectorField: VectorField;\n /**\n * The length of the vectors indexed. This must be between 2 and 2048 inclusive.\n */\n dimensions: number;\n /**\n * Additional fields to index for fast filtering when running vector searches.\n */\n filterFields?: FilterFields[];\n}\n\n/**\n * @internal\n */\nexport type VectorIndex = {\n indexDescriptor: string;\n vectorField: string;\n dimensions: number;\n filterFields: string[];\n};\n\n/**\n * @internal\n */\nexport type Index = {\n indexDescriptor: string;\n fields: string[];\n};\n\n/**\n * @internal\n */\nexport type SearchIndex = {\n indexDescriptor: string;\n searchField: string;\n filterFields: string[];\n};\n\n/**\n * Options for defining an index.\n *\n * @public\n */\nexport interface IndexOptions {\n /**\n * Whether the index should be staged.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n */\n staged?: boolean;\n}\n\n/**\n * The definition of a table within a schema.\n *\n * This should be produced by using {@link defineTable}.\n * @public\n */\nexport class TableDefinition<\n DocumentType extends Validator<any, any, any> = Validator<any, any, any>,\n Indexes extends GenericTableIndexes = {},\n SearchIndexes extends GenericTableSearchIndexes = {},\n VectorIndexes extends GenericTableVectorIndexes = {},\n> {\n private indexes: Index[];\n private stagedDbIndexes: Index[];\n private searchIndexes: SearchIndex[];\n private stagedSearchIndexes: SearchIndex[];\n private vectorIndexes: VectorIndex[];\n private stagedVectorIndexes: VectorIndex[];\n // The type of documents stored in this table.\n validator: DocumentType;\n // The proposed next validator for this table, validated against existing\n // documents in the background while `validator` remains enforced.\n private stagedValidator: Validator<any, any, any> | undefined;\n\n /**\n * @internal\n */\n constructor(documentType: DocumentType) {\n this.indexes = [];\n this.stagedDbIndexes = [];\n this.searchIndexes = [];\n this.stagedSearchIndexes = [];\n this.vectorIndexes = [];\n this.stagedVectorIndexes = [];\n this.validator = documentType;\n }\n\n /**\n * This API is experimental: it may change or disappear.\n *\n * Returns indexes defined on this table.\n * Intended for the advanced use cases of dynamically deciding which index to use for a query.\n * If you think you need this, please chime in on ths issue in the Convex JS GitHub repo.\n * https://github.com/get-convex/convex-js/issues/49\n */\n \" indexes\"(): { indexDescriptor: string; fields: string[] }[] {\n return this.indexes;\n }\n\n /**\n * Define an index on this table.\n *\n * Indexes speed up queries by allowing efficient lookups on specific fields.\n * Use `.withIndex()` in your queries to leverage them.\n *\n * Index fields must be queried in the same order they are defined. If you\n * need to query by `field2` then `field1`, create a separate index with\n * that field order.\n *\n * @example\n * ```ts\n * defineTable({\n * userId: v.id(\"users\"),\n * status: v.string(),\n * updatedAt: v.number(),\n * })\n * // Name indexes after their fields:\n * .index(\"by_userId\", [\"userId\"])\n * .index(\"by_status_updatedAt\", [\"status\", \"updatedAt\"])\n * ```\n *\n * **Best practice:** Always include all index fields in the index name\n * (e.g., `\"by_field1_and_field2\"`).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n *\n * @see https://docs.convex.dev/database/reading-data/indexes\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define an index on this table.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/database/reading-data/indexes).\n *\n * @param name - The name of the index.\n * @param fields - The fields to index, in order. Must specify at least one\n * field.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n fields: [FirstFieldPath, ...RestFieldPaths],\n ): TableDefinition<\n DocumentType,\n Expand<\n Indexes &\n Record<\n IndexName,\n [FirstFieldPath, ...RestFieldPaths, IndexTiebreakerField]\n >\n >,\n SearchIndexes,\n VectorIndexes\n >;\n\n /**\n * Define a staged index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about indexes, see [Defining Indexes](https://docs.convex.dev/using/indexes).\n *\n * @param name - The name of the index.\n * @param indexConfig - The index configuration object.\n * @returns A {@link TableDefinition} with this index included.\n */\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig: Expand<\n DbIndexConfig<FirstFieldPath, RestFieldPaths> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n index<\n IndexName extends string,\n FirstFieldPath extends ExtractFieldPaths<DocumentType>,\n RestFieldPaths extends ExtractFieldPaths<DocumentType>[],\n >(\n name: IndexName,\n indexConfig:\n | Expand<DbIndexConfig<FirstFieldPath, RestFieldPaths> & IndexOptions>\n | [FirstFieldPath, ...RestFieldPaths],\n ) {\n if (Array.isArray(indexConfig)) {\n // indexConfig is [FirstFieldPath, ...RestFieldPaths]\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig,\n });\n } else if (indexConfig.staged) {\n // indexConfig is object with fields and staged: true\n this.stagedDbIndexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n } else {\n // indexConfig is object with fields (and maybe staged: false/undefined)\n this.indexes.push({\n indexDescriptor: name,\n fields: indexConfig.fields,\n });\n }\n return this;\n }\n\n /**\n * Define a search index on this table.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n // Update `SearchIndexes` to include the new index and use `Expand` to make\n // the types look pretty in editors.\n Expand<\n SearchIndexes &\n Record<\n IndexName,\n {\n searchField: SearchField;\n filterFields: FilterFields;\n }\n >\n >,\n VectorIndexes\n >;\n\n /**\n * Define a staged search index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about search indexes, see [Search](https://docs.convex.dev/text-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The search index configuration object.\n * @returns A {@link TableDefinition} with this search index included.\n */\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n searchIndex<\n IndexName extends string,\n SearchField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n SearchIndexConfig<SearchField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedSearchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.searchIndexes.push({\n indexDescriptor: name,\n searchField: indexConfig.searchField,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Define a vector index on this table.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged?: false }\n >,\n ): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n Expand<\n VectorIndexes &\n Record<\n IndexName,\n {\n vectorField: VectorField;\n dimensions: number;\n filterFields: FilterFields;\n }\n >\n >\n >;\n\n /**\n * Define a staged vector index on this table.\n *\n * For large tables, index backfill can be slow. Staging an index allows you\n * to push the schema and enable the index later.\n *\n * If `staged` is `true`, the index will be staged and will not be enabled\n * until the staged flag is removed. Staged indexes do not block push\n * completion. Staged indexes cannot be used in queries.\n *\n * To learn about vector indexes, see [Vector Search](https://docs.convex.dev/vector-search).\n *\n * @param name - The name of the index.\n * @param indexConfig - The vector index configuration object.\n * @returns A {@link TableDefinition} with this vector index included.\n */\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> &\n IndexOptions & { staged: true }\n >,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes>;\n\n vectorIndex<\n IndexName extends string,\n VectorField extends ExtractFieldPaths<DocumentType>,\n FilterFields extends ExtractFieldPaths<DocumentType> = never,\n >(\n name: IndexName,\n indexConfig: Expand<\n VectorIndexConfig<VectorField, FilterFields> & IndexOptions\n >,\n ) {\n if (indexConfig.staged) {\n this.stagedVectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n } else {\n this.vectorIndexes.push({\n indexDescriptor: name,\n vectorField: indexConfig.vectorField,\n dimensions: indexConfig.dimensions,\n filterFields: indexConfig.filterFields || [],\n });\n }\n return this;\n }\n\n /**\n * Stage a new document validator for this table.\n *\n * Convex validates the staged validator against the table's existing\n * documents in the background, while the validator passed to\n * {@link defineTable} remains the one enforced on reads and writes. Once\n * the background validation succeeds, make the staged validator the\n * table's validator and remove `.staged()`.\n *\n * ```ts\n * defineTable({\n * author: v.string(),\n * }).staged({\n * author: v.array(v.string()),\n * })\n * ```\n *\n * TODO: link a worked staged-schema example from the docs once one exists.\n *\n * @param documentSchema - The proposed next type of documents stored in\n * this table, as an object of field validators or a schema validator.\n * @returns A {@link TableDefinition} with the staged validator attached.\n *\n * @internal\n */\n staged(\n documentSchema:\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator>,\n ): TableDefinition<DocumentType, Indexes, SearchIndexes, VectorIndexes> {\n if (this.stagedValidator !== undefined) {\n throw new Error(\"Table cannot have more than one staged validator.\");\n }\n this.stagedValidator = isValidator(documentSchema)\n ? documentSchema\n : v.object(documentSchema);\n return this.self();\n }\n\n /**\n * Work around for https://github.com/microsoft/TypeScript/issues/57035\n */\n protected self(): TableDefinition<\n DocumentType,\n Indexes,\n SearchIndexes,\n VectorIndexes\n > {\n return this;\n }\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export() {\n const documentType = this.validator.json;\n if (typeof documentType !== \"object\") {\n throw new Error(\n \"Invalid validator: please make sure that the parameter of `defineTable` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n\n let stagedDocumentType = undefined;\n if (this.stagedValidator !== undefined) {\n stagedDocumentType = this.stagedValidator.json;\n if (typeof stagedDocumentType !== \"object\") {\n throw new Error(\n \"Invalid staged validator: please make sure that the parameter of `.staged()` is valid (see https://docs.convex.dev/database/schemas)\",\n );\n }\n }\n\n return {\n indexes: this.indexes,\n stagedDbIndexes: this.stagedDbIndexes,\n searchIndexes: this.searchIndexes,\n stagedSearchIndexes: this.stagedSearchIndexes,\n vectorIndexes: this.vectorIndexes,\n stagedVectorIndexes: this.stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n };\n }\n}\n\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Validator<Record<string, any>, \"required\", any>,\n>(documentSchema: DocumentSchema): TableDefinition<DocumentSchema>;\n/**\n * Define a table in a schema.\n *\n * You can either specify the schema of your documents as an object like\n * ```ts\n * defineTable({\n * field: v.string()\n * });\n * ```\n *\n * or as a schema type like\n * ```ts\n * defineTable(\n * v.union(\n * v.object({...}),\n * v.object({...})\n * )\n * );\n * ```\n *\n * @param documentSchema - The type of documents stored in this table.\n * @returns A {@link TableDefinition} for the table.\n *\n * @public\n */\nexport function defineTable<\n DocumentSchema extends Record<string, GenericValidator>,\n>(\n documentSchema: DocumentSchema,\n): TableDefinition<VObject<ObjectType<DocumentSchema>, DocumentSchema>>;\nexport function defineTable<\n DocumentSchema extends\n | Validator<Record<string, any>, \"required\", any>\n | Record<string, GenericValidator>,\n>(documentSchema: DocumentSchema): TableDefinition<any, any, any> {\n if (isValidator(documentSchema)) {\n return new TableDefinition(documentSchema);\n } else {\n return new TableDefinition(v.object(documentSchema));\n }\n}\n\n/**\n * The validators for the system fields Convex adds to every document.\n *\n * @public\n */\nexport type SystemFieldValidators<TableName extends string> = {\n _id: VId<GenericId<TableName>>;\n _creationTime: VFloat64<number>;\n};\n\n/**\n * Add the system field validators to an object validator, leaving any other\n * validator untouched.\n */\ntype WithSystemFieldValidators<\n TableName extends string,\n DocumentType extends Validator<any, any, any>,\n> =\n DocumentType extends VObject<infer Type, infer Fields, any, any>\n ? VObject<\n Expand<IdField<TableName> & SystemFields & Type>,\n Expand<SystemFieldValidators<TableName> & Fields>\n >\n : DocumentType;\n\n/**\n * The validator for whole documents of a table: the table's own validator with\n * the `_id` and `_creationTime` system fields added.\n *\n * For a table defined with a union, the system fields are added to each member\n * of the union.\n *\n * @public\n */\nexport type DocValidator<\n TableName extends string,\n DocumentType extends Validator<any, any, any>,\n> =\n DocumentType extends VUnion<any, infer Members, any, any>\n ? {\n [Index in keyof Members]: WithSystemFieldValidators<\n TableName,\n Members[Index]\n >;\n } extends infer NewMembers extends Validator<any, \"required\", any>[]\n ? VUnion<\n WithSystemFieldValidators<TableName, Members[number]>[\"type\"],\n NewMembers\n >\n : never\n : WithSystemFieldValidators<TableName, DocumentType>;\n\nfunction addSystemFields(\n tableName: string,\n validator: GenericValidator,\n): GenericValidator {\n switch (validator.kind) {\n case \"object\":\n return validator.extend({\n _id: v.id(tableName),\n _creationTime: v.number(),\n });\n case \"union\":\n return v.union(\n ...validator.members.map((member) =>\n addSystemFields(tableName, member),\n ),\n );\n // `v.any()` already permits the system fields.\n case \"any\":\n return validator;\n default:\n throw new Error(\n `Invalid validator for table \"${tableName}\": a table's documents must be objects, or a union of objects (see https://docs.convex.dev/database/schemas)`,\n );\n }\n}\n\n/**\n * Build the validator for whole documents of a table, by adding the `_id` and\n * `_creationTime` system fields to the table's own validator.\n *\n * Prefer {@link SchemaDefinition.doc} when you have the schema in hand: it\n * checks the table name against the schema.\n *\n * @example\n * ```ts\n * const messageDoc = docValidator(\"messages\", schema.tables.messages);\n *\n * export const get = query({\n * args: { id: v.id(\"messages\") },\n * returns: v.union(messageDoc, v.null()),\n * handler: (ctx, args) => ctx.db.get(args.id),\n * });\n * ```\n *\n * @param tableName - The name of the table, used for the `_id` validator.\n * @param table - The {@link TableDefinition} for that table.\n * @returns A validator matching documents of the table.\n *\n * @public\n */\nexport function docValidator<\n TableName extends string,\n Table extends TableDefinition<any, any, any, any>,\n>(\n tableName: TableName,\n table: Table,\n): DocValidator<TableName, Table[\"validator\"]> {\n return addSystemFields(tableName, table.validator) as DocValidator<\n TableName,\n Table[\"validator\"]\n >;\n}\n\n/**\n * A type describing the schema of a Convex project.\n *\n * This should be constructed using {@link defineSchema}, {@link defineTable},\n * and {@link v}.\n * @public\n */\nexport type GenericSchema = Record<string, TableDefinition>;\n\nfunction tableInSchema<\n Schema extends GenericSchema,\n TableName extends keyof Schema & string,\n>(\n schema: SchemaDefinition<Schema, boolean>,\n tableName: TableName,\n): Schema[TableName] {\n const table = schema.tables[tableName];\n if (table === undefined) {\n throw new Error(\n `Table \"${tableName}\" is not in this schema. Tables in this schema: ${Object.keys(\n schema.tables,\n ).join(\", \")}`,\n );\n }\n return table;\n}\n\n/**\n *\n * The definition of a Convex project schema.\n *\n * This should be produced by using {@link defineSchema}.\n * @public\n */\nexport class SchemaDefinition<\n Schema extends GenericSchema,\n StrictTableTypes extends boolean,\n> {\n public tables: Schema;\n public strictTableNameTypes!: StrictTableTypes;\n public readonly schemaValidation: boolean;\n\n /**\n * @internal\n */\n constructor(tables: Schema, options?: DefineSchemaOptions<StrictTableTypes>) {\n this.tables = tables;\n this.schemaValidation =\n options?.schemaValidation === undefined ? true : options.schemaValidation;\n }\n\n /**\n * The validator for whole documents of a table in this schema: the table's\n * own validator with the `_id` and `_creationTime` system fields added.\n *\n * @example\n * ```ts\n * export const get = query({\n * args: { id: schema.id(\"messages\") },\n * returns: v.union(schema.doc(\"messages\"), v.null()),\n * handler: (ctx, args) => ctx.db.get(args.id),\n * });\n * ```\n *\n * @param tableName - The name of a table in this schema.\n * @returns A validator matching documents of that table.\n */\n doc<TableName extends keyof Schema & string>(\n tableName: TableName,\n ): DocValidator<TableName, Schema[TableName][\"validator\"]> {\n return docValidator(tableName, tableInSchema(this, tableName));\n }\n\n /**\n * The validator for IDs of a table in this schema.\n *\n * Same as `v.id(tableName)`, but only accepts tables in this schema.\n *\n * @param tableName - The name of a table in this schema.\n * @returns A validator matching IDs of that table.\n */\n id<TableName extends keyof Schema & string>(\n tableName: TableName,\n ): VId<GenericId<TableName>> {\n tableInSchema(this, tableName);\n return v.id(tableName);\n }\n\n /**\n * Export the contents of this definition.\n *\n * This is called internally by the Convex framework.\n * @internal\n */\n export(): string {\n return JSON.stringify({\n tables: Object.entries(this.tables).map(([tableName, definition]) => {\n const {\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n } = definition.export();\n return {\n tableName,\n indexes,\n stagedDbIndexes,\n searchIndexes,\n stagedSearchIndexes,\n vectorIndexes,\n stagedVectorIndexes,\n documentType,\n stagedDocumentType,\n };\n }),\n schemaValidation: this.schemaValidation,\n });\n }\n}\n\n/**\n * Options for {@link defineSchema}.\n *\n * @public\n */\nexport interface DefineSchemaOptions<StrictTableNameTypes extends boolean> {\n /**\n * Whether Convex should validate at runtime that all documents match\n * your schema.\n *\n * If `schemaValidation` is `true`, Convex will:\n * 1. Check that all existing documents match your schema when your schema\n * is pushed.\n * 2. Check that all insertions and updates match your schema during mutations.\n *\n * If `schemaValidation` is `false`, Convex will not validate that new or\n * existing documents match your schema. You'll still get schema-specific\n * TypeScript types, but there will be no validation at runtime that your\n * documents match those types.\n *\n * By default, `schemaValidation` is `true`.\n */\n schemaValidation?: boolean;\n\n /**\n * Whether the TypeScript types should allow accessing tables not in the schema.\n *\n * If `strictTableNameTypes` is `true`, using tables not listed in the schema\n * will generate a TypeScript compilation error.\n *\n * If `strictTableNameTypes` is `false`, you'll be able to access tables not\n * listed in the schema and their document type will be `any`.\n *\n * `strictTableNameTypes: false` is useful for rapid prototyping.\n *\n * Regardless of the value of `strictTableNameTypes`, your schema will only\n * validate documents in the tables listed in the schema. You can still create\n * and modify other tables on the dashboard or in JavaScript mutations.\n *\n * By default, `strictTableNameTypes` is `true`.\n */\n strictTableNameTypes?: StrictTableNameTypes;\n}\n\n/**\n * Define the schema of this Convex project.\n *\n * This should be exported as the default export from a `schema.ts` file in\n * your `convex/` directory. The schema enables runtime validation of documents\n * and provides end-to-end TypeScript type safety.\n *\n * Every document in Convex automatically has two system fields:\n * - `_id` - a unique document ID with validator `v.id(\"tableName\")`\n * - `_creationTime` - a creation timestamp with validator `v.number()`\n *\n * You do not need to include these in your schema definition, they are added\n * automatically.\n *\n * @example\n * ```ts\n * // convex/schema.ts\n * import { defineSchema, defineTable } from \"convex/server\";\n * import { v } from \"convex/values\";\n *\n * export default defineSchema({\n * users: defineTable({\n * name: v.string(),\n * email: v.string(),\n * }).index(\"by_email\", [\"email\"]),\n *\n * messages: defineTable({\n * body: v.string(),\n * userId: v.id(\"users\"),\n * channelId: v.id(\"channels\"),\n * }).index(\"by_channel\", [\"channelId\"]),\n *\n * channels: defineTable({\n * name: v.string(),\n * }),\n *\n * // Discriminated union table:\n * results: defineTable(\n * v.union(\n * v.object({ kind: v.literal(\"error\"), message: v.string() }),\n * v.object({ kind: v.literal(\"success\"), value: v.number() }),\n * )\n * ),\n * });\n * ```\n *\n * **Best practice:** Always include all index fields in the index name. For\n * example, an index on `[\"field1\", \"field2\"]` should be named\n * `\"by_field1_field2\"`.\n *\n * @param schema - A map from table name to {@link TableDefinition} for all of\n * the tables in this project.\n * @param options - Optional configuration. See {@link DefineSchemaOptions} for\n * a full description.\n * @returns The schema.\n *\n * @see https://docs.convex.dev/database/schemas\n * @public\n */\nexport function defineSchema<\n Schema extends GenericSchema,\n StrictTableNameTypes extends boolean = true,\n>(\n schema: Schema,\n options?: DefineSchemaOptions<StrictTableNameTypes>,\n): SchemaDefinition<Schema, StrictTableNameTypes> {\n return new SchemaDefinition(schema, options);\n}\n\n/**\n * Internal type used in Convex code generation!\n *\n * Convert a {@link SchemaDefinition} into a {@link server.GenericDataModel}.\n *\n * @public\n */\nexport type DataModelFromSchemaDefinition<\n SchemaDef extends SchemaDefinition<any, boolean>,\n> = MaybeMakeLooseDataModel<\n {\n [TableName in keyof SchemaDef[\"tables\"] &\n string]: SchemaDef[\"tables\"][TableName] extends TableDefinition<\n infer DocumentType,\n infer Indexes,\n infer SearchIndexes,\n infer VectorIndexes\n >\n ? {\n // We've already added all of the system fields except for `_id`.\n // Add that here.\n document: Expand<IdField<TableName> & ExtractDocument<DocumentType>>;\n fieldPaths:\n | keyof IdField<TableName>\n | ExtractFieldPaths<DocumentType>;\n indexes: Expand<Indexes & SystemIndexes>;\n searchIndexes: SearchIndexes;\n vectorIndexes: VectorIndexes;\n }\n : never;\n },\n SchemaDef[\"strictTableNameTypes\"]\n>;\n\ntype MaybeMakeLooseDataModel<\n DataModel extends GenericDataModel,\n StrictTableNameTypes extends boolean,\n> = StrictTableNameTypes extends true\n ? DataModel\n : Expand<DataModel & AnyDataModel>;\n\nconst _systemSchema = defineSchema({\n _scheduled_functions: defineTable({\n name: v.string(),\n args: v.array(v.any()),\n scheduledTime: v.float64(),\n completedTime: v.optional(v.float64()),\n state: v.union(\n v.object({ kind: v.literal(\"pending\") }),\n v.object({ kind: v.literal(\"inProgress\") }),\n v.object({ kind: v.literal(\"success\") }),\n v.object({ kind: v.literal(\"failed\"), error: v.string() }),\n v.object({ kind: v.literal(\"canceled\") }),\n ),\n }),\n _storage: defineTable({\n sha256: v.string(),\n size: v.float64(),\n contentType: v.optional(v.string()),\n }),\n});\n\nexport interface SystemDataModel extends DataModelFromSchemaDefinition<\n typeof _systemSchema\n> {}\n\nexport type SystemTableNames = TableNamesInDataModel<SystemDataModel>;\n", "// Convex-transport entity/space/assignee resolution \u2014 the Convex-caller\n// equivalent of resolve.ts (which resolves through the REST `EnteClient`).\n// Used by every migrated (non-REST) command. The REST-staying commands\n// (`task list`, `tasks`, `activity list`, `entity list`, `search`) keep using\n// resolve.ts + ClientCommand unchanged.\n\nimport { makeFunctionReference } from \"convex/server\";\n\nimport type { ConvexCaller } from \"../core/convex.ts\";\nimport { formatSpacesFooter } from \"./format.ts\";\nimport { resolveEntityCandidate } from \"./entityResolution.ts\";\nimport type { SpacesMap } from \"./types.ts\";\n\n// Same heuristic as resolve.ts's ID_RE \u2014 duplicated rather than imported so\n// this module stays independent of the REST resolver.\nconst ID_RE = /^[a-z]\\w{0,3}[0-9a-z]{28,}$/i;\n\nexport function looksLikeConvexId(value: string): boolean {\n return ID_RE.test(value) && value.length >= 20;\n}\n\n// --- entity resolution ------------------------------------------------------\n\ninterface EntitySearchResult {\n _id: string;\n name: string;\n displayName?: string;\n type: string;\n [key: string]: unknown;\n}\n\nconst entitiesSearch = makeFunctionReference<\n \"query\",\n { query: string; limit?: number },\n EntitySearchResult[]\n>(\"entities:search\");\n\n/** Resolve an entity name to its ID via `entities:search`. Pass through if already an ID. */\nexport async function resolveEntityC(caller: ConvexCaller, nameOrId: string): Promise<string> {\n if (looksLikeConvexId(nameOrId)) return nameOrId;\n\n const matches = await caller.query(entitiesSearch, { query: nameOrId, limit: 10 });\n return resolveEntityCandidate(matches, nameOrId);\n}\n\n/** Resolve a list of entity names/IDs (sequential \u2014 fuzzy search per item). */\nexport async function resolveEntitiesC(caller: ConvexCaller, inputs: string[]): Promise<string[]> {\n const ids: string[] = [];\n for (const i of inputs) ids.push(await resolveEntityC(caller, i));\n return ids;\n}\n\n// --- space + membership resolution ------------------------------------------\n\nexport interface MembershipRow {\n membership: { _id: string; userId: string; spaceId: string; role: \"owner\" | \"admin\" | \"member\" };\n space: { _id: string; name: string; color: string; [key: string]: unknown } | null;\n}\n\nexport interface MemberRow {\n membership: { _id: string; userId: string; spaceId: string; role: \"owner\" | \"admin\" | \"member\" };\n user: { _id: string; name?: string; email?: string; [key: string]: unknown } | null;\n}\n\nexport const membershipsListForCurrentUser = makeFunctionReference<\n \"query\",\n Record<string, never>,\n MembershipRow[]\n>(\"memberships:listForCurrentUser\");\n\nexport const membershipsListForSpace = makeFunctionReference<\n \"query\",\n { spaceId: string },\n MemberRow[]\n>(\"memberships:listForSpace\");\n\n/** Resolve a space name to its ID. Exact match first, then unique substring. */\nexport async function resolveSpaceByNameC(caller: ConvexCaller, nameOrId: string): Promise<string> {\n if (looksLikeConvexId(nameOrId)) return nameOrId;\n\n const rows = await caller.query(membershipsListForCurrentUser, {});\n const lower = nameOrId.toLowerCase();\n\n for (const row of rows) {\n if (row.space && row.space.name.toLowerCase() === lower) return row.space._id;\n }\n\n const partial = rows.filter((r) => r.space && r.space.name.toLowerCase().includes(lower));\n if (partial.length === 1) return partial[0]!.space!._id;\n if (partial.length > 1) {\n const listing = partial.map((r) => ` ${r.space!.name} ${r.space!._id}`).join(\"\\n\");\n throw new Error(\n `Ambiguous space match for '${nameOrId}':\\n${listing}\\nUse the full space ID to be specific.`,\n );\n }\n\n throw new Error(`No space found matching '${nameOrId}'.`);\n}\n\n/** Any space the caller belongs to \u2014 used where the backend requires *some*\n * membership-checked spaceId but the actual search scope is all-spaces. */\nexport async function anyMembershipSpaceId(caller: ConvexCaller): Promise<string> {\n const rows = await caller.query(membershipsListForCurrentUser, {});\n const spaceId = rows.find((r) => r.space)?.space?._id;\n if (!spaceId) throw new Error(\"You don't belong to any space yet.\");\n return spaceId;\n}\n\n/** Build the `SpacesMap` (id \u2192 {spaceName, memberEmails}) footer data from the\n * caller's memberships, fetching each space's member emails via\n * `memberships:listForSpace`. Mirrors `EnteClient.listSpaces()`'s footer shape. */\nexport async function spacesFooterFromMemberships(caller: ConvexCaller): Promise<SpacesMap> {\n const rows = await caller.query(membershipsListForCurrentUser, {});\n const spaces: SpacesMap = {};\n for (const row of rows) {\n if (!row.space) continue;\n const members = await caller.query(membershipsListForSpace, { spaceId: row.space._id });\n const memberEmails = members.map((m) => m.user?.email).filter((e): e is string => !!e);\n spaces[row.space._id] = { spaceName: row.space.name, memberEmails };\n }\n return spaces;\n}\n\n/** Render `body` plus the spaces footer (BaseCommand has no `withFooter` \u2014 only\n * ClientCommand does \u2014 so migrated commands use this free function instead). */\nexport function withFooter(body: string, spaces: SpacesMap): string {\n const footer = formatSpacesFooter(spaces);\n return footer ? `${body}\\n${footer}` : body;\n}\n\n/** Resolve assignee emails to user IDs via that space's membership list. Throws\n * loud on any email with no matching member (no silent drops). */\nexport async function resolveAssigneeEmailsToIds(\n caller: ConvexCaller,\n spaceId: string,\n emails: string[],\n): Promise<string[]> {\n if (emails.length === 0) return [];\n const members = await caller.query(membershipsListForSpace, { spaceId });\n const ids: string[] = [];\n for (const email of emails) {\n const match = members.find((m) => (m.user?.email ?? \"\").toLowerCase() === email.toLowerCase());\n if (!match || !match.user) throw new Error(`No member with email '${email}' found in this space.`);\n ids.push(match.user._id);\n }\n return ids;\n}\n", "export function normalizePinRoleOption(role: string | undefined): string | undefined {\n const normalized = role?.trim().replace(/\\s+/g, \" \");\n return normalized || undefined;\n}\n", "import { readFileSync } from \"node:fs\";\n\nimport { makeFunctionReference } from \"convex/server\";\n\nimport type { ConvexCaller } from \"../core/convex.ts\";\n\nexport interface HtmlBlockSummary {\n blockId: string;\n artifactId: string;\n versionId: string;\n version: number;\n title: string;\n height: number;\n sourceHash: string;\n byteSize: number;\n provenance: \"user\" | \"agent\" | \"external\";\n createdAt: number;\n}\n\nexport interface HtmlBlock extends HtmlBlockSummary {\n source: string;\n}\n\nexport interface CreatedHtmlBlock {\n artifactId: string;\n versionId: string;\n version: number;\n title: string;\n height: number;\n}\n\nconst htmlArtifactsList = makeFunctionReference<\n \"query\",\n { documentId: string },\n HtmlBlockSummary[]\n>(\"htmlArtifacts:list\");\nconst htmlArtifactsGet = makeFunctionReference<\n \"query\",\n { documentId: string; blockId: string },\n HtmlBlock | null\n>(\"htmlArtifacts:get\");\nconst htmlArtifactsAppend = makeFunctionReference<\n \"mutation\",\n { documentId: string; title: string; source: string; height: number },\n CreatedHtmlBlock\n>(\"htmlArtifacts:append\");\nconst htmlArtifactsUpdate = makeFunctionReference<\n \"mutation\",\n {\n documentId: string;\n blockId: string;\n artifactId: string;\n expectedVersionId: string;\n title: string;\n source: string;\n height: number;\n },\n CreatedHtmlBlock\n>(\"htmlArtifacts:update\");\n\nexport function readHtmlSource(value: string): string {\n return value === \"-\" ? readFileSync(0, \"utf8\") : readFileSync(value, \"utf8\");\n}\n\nexport async function listHtmlBlocks(caller: ConvexCaller, documentId: string) {\n return await caller.query(htmlArtifactsList, { documentId });\n}\n\nexport async function getHtmlBlock(\n caller: ConvexCaller,\n documentId: string,\n blockId: string,\n) {\n return await caller.query(htmlArtifactsGet, { documentId, blockId });\n}\n\nexport async function addHtmlBlock(\n caller: ConvexCaller,\n args: { documentId: string; title: string; source: string; height: number },\n) {\n return await caller.mutation(htmlArtifactsAppend, args);\n}\n\nexport async function updateHtmlBlock(\n caller: ConvexCaller,\n args: {\n documentId: string;\n blockId: string;\n source: string;\n title?: string;\n height?: number;\n },\n) {\n const current = await getHtmlBlock(caller, args.documentId, args.blockId);\n if (!current) throw new Error(`HTML block not found: ${args.blockId}`);\n return await caller.mutation(htmlArtifactsUpdate, {\n documentId: args.documentId,\n blockId: args.blockId,\n artifactId: current.artifactId,\n expectedVersionId: current.versionId,\n title: args.title ?? current.title,\n source: args.source,\n height: args.height ?? current.height,\n });\n}\n\nexport function formatHtmlBlockList(blocks: HtmlBlockSummary[]): string {\n return blocks.length\n ? blocks.map((block) => `${block.blockId} v${block.version} ${block.title} ${block.height}px`).join(\"\\n\")\n : \"No interactive HTML blocks.\";\n}\n", "// `ente pins list <entity>` \u2014 show the entities pinned to a source entity,\n// aggregated across every space the caller can access. Complements\n// `entity pin` / `entity unpin` (entity.ts). Like every migrated command this\n// calls the SAME public `api.pins.*` functions the web app uses, via the JWT\n// bridge (see ../convexClient.ts) \u2014 no per-capability REST endpoint.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { resolveEntityC, spacesFooterFromMemberships, withFooter } from \"../convexResolve.ts\";\nimport { formatPinsList, jsonWithSpaces } from \"../format.ts\";\nimport { normalizePinRoleOption } from \"../pinRole.ts\";\nimport type { PinSummary } from \"../types.ts\";\n\ninterface PinTargetEntity {\n _id: string;\n name: string;\n type: string;\n [key: string]: unknown;\n}\n\ninterface PinBySourceRow {\n _id: string;\n targetEntityId: string;\n role?: string;\n targetEntity: PinTargetEntity | null;\n}\n\n// Typed function references \u2014 the wire contract with convex/pins.ts. Shared\n// with entity.ts (entity pin/unpin), which imports these.\nexport const pinsListBySource = makeFunctionReference<\n \"query\",\n { sourceEntityId: string },\n PinBySourceRow[]\n>(\"pins:listBySource\");\n\nexport const pinsCreate = makeFunctionReference<\n \"mutation\",\n {\n sourceEntityId: string;\n targetEntityId: string;\n role?: string;\n grantMissingParentAccess?: boolean;\n parentSpaceGrantFingerprint?: string;\n },\n string\n>(\"pins:create\");\n\nexport const pinsRemove = makeFunctionReference<\"mutation\", { pinId: string }, null>(\"pins:remove\");\n\n/** Adapt a `pins:listBySource` row to the REST-era `PinSummary` shape so the\n * existing `formatPinsList` renderer works unchanged. */\nexport function toPinSummaries(rows: PinBySourceRow[]): PinSummary[] {\n return rows.map((r) => ({\n entityId: r.targetEntityId,\n name: r.targetEntity?.name,\n type: r.targetEntity?.type,\n role: r.role,\n }));\n}\n\nclass PinsList extends ProfileCommand {\n static paths = [[\"pins\", \"list\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"List pins for an entity\" });\n\n nameOrId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n const rows = await caller.query(pinsListBySource, { sourceEntityId: entityId });\n const pins = toPinSummaries(rows);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: pins }, spaces), () =>\n withFooter(formatPinsList(pins), spaces),\n );\n }\n}\n\nexport const PINS_COMMANDS = [PinsList];\n", "// Entity commands \u2014 list, create, get, update, rename, archive, restore, pin,\n// unpin, remove-from-space, add-to-space. Ports commands/entity.py.\n//\n// `entity list` stays on the REST transport (ClientCommand) \u2014 see search.ts /\n// list.ts for the sibling REST-staying commands. Every other command here\n// calls the SAME public `api.entities.*` / `api.pins.*` functions the web app\n// uses, via the JWT bridge (see ../convexClient.ts) \u2014 no per-capability REST\n// endpoint, and no more rich 422 `space_entity_mismatch` explainer (that was a\n// REST-only affordance); errors from the backend just bubble to ProfileCommand's\n// error boundary.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ExitWithCode } from \"../../core/errors.ts\";\nimport { errorMessage } from \"../../core/output.ts\";\nimport { parseAttrs } from \"../attrs.ts\";\nimport { ClientCommand, ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport {\n resolveEntitiesC,\n resolveEntityC,\n resolveSpaceByNameC,\n spacesFooterFromMemberships,\n withFooter,\n} from \"../convexResolve.ts\";\nimport { formatEntityDetail, jsonWithSpaces } from \"../format.ts\";\nimport { normalizePinRoleOption } from \"../pinRole.ts\";\nimport type { Activity, Entity, EntityDetail, OpenTaskRef } from \"../types.ts\";\nimport {\n addHtmlBlock,\n formatHtmlBlockList,\n getHtmlBlock,\n listHtmlBlocks,\n readHtmlSource,\n updateHtmlBlock,\n} from \"../htmlBlocks.ts\";\nimport { pinsCreate, pinsListBySource, pinsRemove } from \"./pins.ts\";\n\n// --- entity doc + rich-activity shapes (wire contract with convex/*.ts) -----\n\ninterface EntityDoc {\n _id: string;\n name: string;\n type: string;\n tags?: string[];\n aliases?: string[];\n attributes?: Record<string, unknown>;\n hiddenFromGraph?: boolean;\n descriptionPlainText?: string;\n archived: boolean;\n [key: string]: unknown;\n}\n\ninterface ActivityDoc {\n _id: string;\n type: string;\n title?: string;\n contentPlainText?: string;\n createdAt: number;\n deadline?: number;\n completed?: boolean;\n shortId?: number;\n deletedAt?: number;\n [key: string]: unknown;\n}\n\ninterface EntityRefLite {\n _id: string;\n name: string;\n [key: string]: unknown;\n}\n\ninterface ActivityRich extends ActivityDoc {\n entityDetails: Array<EntityRefLite | null>;\n}\n\n// --- typed function references (convex/entities.ts + convex/activities.ts) -\n\nconst entitiesCreate = makeFunctionReference<\n \"mutation\",\n { spaceId: string; name?: string; type?: string },\n string\n>(\"entities:create\");\nconst entitiesFindById = makeFunctionReference<\"query\", { id: string }, EntityDoc | null>(\n \"entities:findById\",\n);\nconst entitiesUpdateName = makeFunctionReference<\"mutation\", { id: string; name: string }, null>(\n \"entities:updateName\",\n);\nconst entitiesAddTag = makeFunctionReference<\"mutation\", { id: string; tag: string }, null>(\n \"entities:addTag\",\n);\nconst entitiesRemoveTag = makeFunctionReference<\"mutation\", { id: string; tag: string }, null>(\n \"entities:removeTag\",\n);\nconst entitiesAddAlias = makeFunctionReference<\"mutation\", { id: string; alias: string }, null>(\n \"entities:addAlias\",\n);\nconst entitiesRemoveAlias = makeFunctionReference<\"mutation\", { id: string; alias: string }, null>(\n \"entities:removeAlias\",\n);\nconst entitiesSetAttribute = makeFunctionReference<\n \"mutation\",\n { id: string; key: string; value: unknown },\n null\n>(\"entities:setAttribute\");\nconst entitiesSetDescriptionFromMarkdown = makeFunctionReference<\n \"mutation\",\n { entityId: string; markdown: string },\n null\n>(\"entities:setDescriptionFromMarkdown\");\nconst entitiesDeleteEntity = makeFunctionReference<\"mutation\", { entityId: string }, null>(\n \"entities:deleteEntity\",\n);\nconst entitiesRestoreEntity = makeFunctionReference<\n \"mutation\",\n {\n entityId: string;\n grantMissingParentAccess?: boolean;\n parentSpaceGrantFingerprint?: string;\n },\n null\n>(\n \"entities:restoreEntity\",\n);\nconst entitiesCreateEntitySpaceLink = makeFunctionReference<\n \"mutation\",\n {\n entityId: string;\n spaceId: string;\n grantMissingParentAccess?: boolean;\n parentSpaceGrantFingerprint?: string;\n },\n null\n>(\"entities:createEntitySpaceLink\");\nconst entitiesRemoveFromSpace = makeFunctionReference<\n \"mutation\",\n { entityId: string; spaceId: string; removeFromActivities?: boolean },\n null\n>(\"entities:removeFromSpace\");\nconst activitiesListTasksForEntity = makeFunctionReference<\n \"query\",\n { entityId: string },\n ActivityDoc[]\n>(\"activities:listTasksForEntity\");\nconst activitiesListForEntity = makeFunctionReference<\n \"query\",\n { entityId: string },\n ActivityRich[]\n>(\"activities:listForEntity\");\n\nfunction toEntityView(doc: EntityDoc): Entity {\n return {\n _id: doc._id,\n name: doc.name,\n type: doc.type as Entity[\"type\"],\n aliases: doc.aliases,\n tags: doc.tags,\n attributes: doc.attributes,\n hiddenFromGraph: doc.hiddenFromGraph,\n };\n}\n\nfunction toActivityView(rich: ActivityDoc): Activity {\n return {\n _id: rich._id,\n type: rich.type,\n title: rich.title,\n contentPlainText: rich.contentPlainText,\n createdAt: rich.createdAt,\n deadline: rich.deadline,\n completed: rich.completed,\n shortId: rich.shortId,\n };\n}\n\n// --- entity list (stays on REST) --------------------------------------------\n\nclass EntityList extends ClientCommand {\n static paths = [[\"entity\", \"list\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"List or search entities\" });\n\n query = Option.String(\"--query\", { description: \"Fuzzy name search\" });\n type = Option.String(\"--type\", { description: \"Filter by type (person, org, project, topic)\" });\n space = Option.String(\"--space\", { description: \"Filter by space (name or ID)\" });\n limit = Option.String(\"--limit\", { description: \"Max results (default: 50)\" });\n archived = Option.Boolean(\"--archived\", false, {\n description: \"Show archived (trashed) entities instead of active ones\",\n });\n\n async run(): Promise<number | void> {\n await this.runEntityList({\n query: this.query,\n typeFilter: this.type,\n space: this.space,\n limit: this.limit ? Number(this.limit) : undefined,\n archived: this.archived,\n });\n }\n}\n\n// --- migrated (Convex) commands ---------------------------------------------\n\nclass EntityCreate extends ProfileCommand {\n static paths = [[\"entity\", \"create\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Create a new entity\" });\n\n name = Option.String();\n type = Option.String(\"--type\", { required: true, description: \"Entity type (person, org, project, topic)\" });\n space = Option.String(\"--space\", { required: true, description: \"Space to create in (name or ID)\" });\n pin = Option.Array(\"--pin\", { description: \"Pin to other entities (resolved by name)\" });\n shareParents = Option.Boolean(\"--share-parents\", false, {\n description: \"Share pinned parents and ancestors into this entity's space when required\",\n });\n parentSpaceGrantFingerprint = Option.String(\"--parent-space-grant-fingerprint\", {\n description: \"Exact grantFingerprint returned by the confirmation-required error\",\n });\n alias = Option.Array(\"--alias\", { description: \"Alternative names\" });\n attr = Option.Array(\"--attr\", { description: \"Attributes as key=value pairs\" });\n tag = Option.Array(\"--tag\", { description: \"Tags (repeatable)\" });\n description = Option.String(\"--description\", { description: \"Description text\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const spaceId = await resolveSpaceByNameC(caller, this.space);\n const attributes = parseAttrs(this.attr);\n\n const entityId = await caller.mutation(entitiesCreate, {\n spaceId,\n name: this.name,\n type: this.type,\n });\n\n if (this.alias) for (const a of this.alias) await caller.mutation(entitiesAddAlias, { id: entityId, alias: a });\n if (this.tag) for (const t of this.tag) await caller.mutation(entitiesAddTag, { id: entityId, tag: t });\n for (const [key, value] of Object.entries(attributes)) {\n await caller.mutation(entitiesSetAttribute, { id: entityId, key, value });\n }\n if (this.description) {\n await caller.mutation(entitiesSetDescriptionFromMarkdown, { entityId, markdown: this.description });\n }\n\n // Pin targets \u2014 collect failures rather than aborting on the first, so a\n // single bad target doesn't block the rest. The entity already exists, so\n // we always report its id (prevents na\u00EFve retries creating duplicates).\n const pinFailures: Array<[string, string]> = [];\n const pinSucceeded: string[] = [];\n if (this.pin && this.pin.length) {\n let pinIds: string[] = [];\n try {\n pinIds = await resolveEntitiesC(caller, this.pin);\n } catch (exc) {\n for (const target of this.pin) pinFailures.push([target, `could not resolve target: ${errorMessage(exc)}`]);\n }\n for (let i = 0; i < pinIds.length; i++) {\n const targetLabel = this.pin[i]!;\n try {\n await caller.mutation(pinsCreate, {\n sourceEntityId: entityId,\n targetEntityId: pinIds[i]!,\n ...(this.shareParents ? {\n grantMissingParentAccess: true,\n ...(this.parentSpaceGrantFingerprint\n ? { parentSpaceGrantFingerprint: this.parentSpaceGrantFingerprint }\n : {}),\n } : {}),\n });\n pinSucceeded.push(targetLabel);\n } catch (exc) {\n pinFailures.push([targetLabel, errorMessage(exc)]);\n }\n }\n }\n\n const spaces = await spacesFooterFromMemberships(caller);\n const jsonOut: Record<string, unknown> = { data: { entityId } };\n if (pinFailures.length) {\n jsonOut.data = {\n entityId,\n pinFailures: pinFailures.map(([target, error]) => ({ target, error })),\n pinSucceeded,\n };\n }\n\n this.emitText(jsonWithSpaces(jsonOut, spaces), () => {\n let body = `Created ${this.type} '${this.name}' (${entityId})`;\n if (pinSucceeded.length) body += `\\nPinned to: ${pinSucceeded.join(\", \")}`;\n return withFooter(body, spaces);\n });\n\n if (pinFailures.length) {\n // Partial-success summary on stderr, separate from stdout, so JSON/pipe\n // consumers still see the success line. Exit 2 distinguishes this from a\n // generic failure.\n this.err(\"\");\n this.err(\n `\u26A0 Entity '${this.name}' (${entityId}) created, but ${pinFailures.length} ` +\n `of ${pinFailures.length + pinSucceeded.length} pin(s) failed:`,\n );\n for (const [target, msg] of pinFailures) {\n this.err(` - '${target}': ${msg}`);\n this.err(` retry: ente entity pin ${entityId} \"${target}\"`);\n }\n throw new ExitWithCode(2);\n }\n }\n}\n\nclass EntityGet extends ProfileCommand {\n static paths = [[\"entity\", \"get\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Get entity details\" });\n\n nameOrId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n const doc = await caller.query(entitiesFindById, { id: entityId });\n if (!doc) throw new Error(`Entity not found or not accessible: ${entityId}`);\n\n const [allTasks, activityRows, pinRows] = await Promise.all([\n caller.query(activitiesListTasksForEntity, { entityId }),\n caller.query(activitiesListForEntity, { entityId }),\n caller.query(pinsListBySource, { sourceEntityId: entityId }),\n ]);\n\n const openTasks: OpenTaskRef[] = allTasks\n .filter((t) => !t.completed && !t.deletedAt)\n .map((t) => ({ shortId: t.shortId, activityId: t._id, title: t.title }));\n\n const activities: Activity[] = [...activityRows]\n .sort((a, b) => b.createdAt - a.createdAt)\n .map(toActivityView);\n\n const pins = pinRows.map((p) => ({\n entityId: p.targetEntityId,\n name: p.targetEntity?.name,\n type: p.targetEntity?.type,\n }));\n\n const detail: EntityDetail = {\n entity: toEntityView(doc),\n descriptionPlainText: doc.descriptionPlainText,\n pins,\n openTasks,\n activities,\n };\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: detail }, spaces), () =>\n withFooter(formatEntityDetail(detail), spaces),\n );\n }\n}\n\nclass EntityUpdate extends ProfileCommand {\n static paths = [[\"entity\", \"update\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Update an entity\" });\n\n nameOrId = Option.String();\n name = Option.String(\"--name\", { description: \"Rename the entity\" });\n aliasAdd = Option.String(\"--alias-add\", { description: \"Add an alias\" });\n aliasRemove = Option.String(\"--alias-remove\", { description: \"Remove an alias\" });\n attr = Option.Array(\"--attr\", { description: \"Set attributes as key=value pairs\" });\n tag = Option.Array(\"--tag\", { description: \"Replace the tag set (repeatable)\" });\n description = Option.String(\"--description\", { description: \"Update description\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n\n const newAttrs = parseAttrs(this.attr);\n const needsCurrent = !!this.aliasAdd || !!this.aliasRemove || (this.tag && this.tag.length > 0);\n const current = needsCurrent ? await caller.query(entitiesFindById, { id: entityId }) : undefined;\n if (needsCurrent && !current) throw new Error(`Entity not found: ${entityId}`);\n\n let didSomething = false;\n\n if (this.name !== undefined) {\n await caller.mutation(entitiesUpdateName, { id: entityId, name: this.name });\n didSomething = true;\n }\n if (this.aliasAdd) {\n await caller.mutation(entitiesAddAlias, { id: entityId, alias: this.aliasAdd });\n didSomething = true;\n }\n if (this.aliasRemove) {\n await caller.mutation(entitiesRemoveAlias, { id: entityId, alias: this.aliasRemove });\n didSomething = true;\n }\n if (Object.keys(newAttrs).length) {\n for (const [key, value] of Object.entries(newAttrs)) {\n await caller.mutation(entitiesSetAttribute, { id: entityId, key, value });\n }\n didSomething = true;\n }\n if (this.tag && this.tag.length) {\n // `--tag` replaces the whole tag set (REST semantics) \u2014 diff against the\n // current tags since the backend only exposes addTag/removeTag.\n const currentTags = current?.tags ?? [];\n const nextTags = new Set(this.tag);\n for (const t of currentTags) if (!nextTags.has(t)) await caller.mutation(entitiesRemoveTag, { id: entityId, tag: t });\n for (const t of this.tag) if (!currentTags.includes(t)) await caller.mutation(entitiesAddTag, { id: entityId, tag: t });\n didSomething = true;\n }\n if (this.description !== undefined) {\n await caller.mutation(entitiesSetDescriptionFromMarkdown, { entityId, markdown: this.description });\n didSomething = true;\n }\n if (!didSomething) {\n this.err(\n \"Nothing to update. Specify --name, --alias-add, --alias-remove, --attr, --tag, or --description.\",\n );\n return 1;\n }\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, entityId } }, spaces), () =>\n withFooter(`Updated entity ${entityId}`, spaces),\n );\n }\n}\n\nclass EntityRename extends ProfileCommand {\n static paths = [[\"entity\", \"rename\"]];\n static usage = Command.Usage({\n category: \"Entity\",\n description: \"Rename an entity (changes its display name)\",\n });\n\n nameOrId = Option.String();\n newName = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n await caller.mutation(entitiesUpdateName, { id: entityId, name: this.newName });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(\n jsonWithSpaces({ data: { success: true, entityId, name: this.newName } }, spaces),\n () => withFooter(`Renamed entity ${entityId} \u2192 \"${this.newName}\"`, spaces),\n );\n }\n}\n\nclass EntityArchive extends ProfileCommand {\n static paths = [[\"entity\", \"archive\"]];\n static usage = Command.Usage({\n category: \"Entity\",\n description: \"Move an entity to the trash (soft delete). Its exclusive activities are also trashed.\",\n });\n\n nameOrId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n await caller.mutation(entitiesDeleteEntity, { entityId });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, entityId } }, spaces), () =>\n withFooter(`Archived entity ${entityId}`, spaces),\n );\n }\n}\n\nclass EntityRestore extends ProfileCommand {\n static paths = [[\"entity\", \"restore\"]];\n static usage = Command.Usage({\n category: \"Entity\",\n description: \"Restore an entity (and its cascade-trashed activities) from the trash\",\n });\n\n nameOrId = Option.String();\n shareParents = Option.Boolean(\"--share-parents\", false, {\n description: \"Confirm parent and ancestor grants required to reactivate the entity\",\n });\n parentSpaceGrantFingerprint = Option.String(\"--parent-space-grant-fingerprint\", {\n description: \"Exact grantFingerprint returned by the confirmation-required error\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n await caller.mutation(entitiesRestoreEntity, {\n entityId,\n ...(this.shareParents ? {\n grantMissingParentAccess: true,\n ...(this.parentSpaceGrantFingerprint\n ? { parentSpaceGrantFingerprint: this.parentSpaceGrantFingerprint }\n : {}),\n } : {}),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, entityId } }, spaces), () =>\n withFooter(`Restored entity ${entityId}`, spaces),\n );\n }\n}\n\nclass EntityPin extends ProfileCommand {\n static paths = [[\"entity\", \"pin\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Pin target entity to source entity\" });\n\n source = Option.String();\n target = Option.String();\n role = Option.String(\"--role\", {\n description: \"Optional child role at the parent (for example: student)\",\n });\n shareParents = Option.Boolean(\"--share-parents\", false, {\n description: \"Confirm sharing the parent and its ancestors into missing child spaces\",\n });\n parentSpaceGrantFingerprint = Option.String(\"--parent-space-grant-fingerprint\", {\n description: \"Exact grantFingerprint returned by the confirmation-required error\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const sourceId = await resolveEntityC(caller, this.source);\n const targetId = await resolveEntityC(caller, this.target);\n\n const existing = await caller.query(pinsListBySource, { sourceEntityId: sourceId });\n const alreadyExists = existing.some((p) => p.targetEntityId === targetId);\n const normalizedRole = normalizePinRoleOption(this.role);\n await caller.mutation(pinsCreate, {\n sourceEntityId: sourceId,\n targetEntityId: targetId,\n ...(this.role !== undefined ? { role: normalizedRole ?? \"\" } : {}),\n ...(this.shareParents ? {\n grantMissingParentAccess: true,\n ...(this.parentSpaceGrantFingerprint\n ? { parentSpaceGrantFingerprint: this.parentSpaceGrantFingerprint }\n : {}),\n } : {}),\n });\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({\n data: {\n alreadyExists,\n ...(normalizedRole ? { role: normalizedRole } : {}),\n },\n }, spaces), () =>\n withFooter(\n alreadyExists\n ? (this.role !== undefined ? \"Pin role updated.\" : \"Pin already exists.\")\n : \"Pin added.\",\n spaces,\n ),\n );\n }\n}\n\nclass EntityUnpin extends ProfileCommand {\n static paths = [[\"entity\", \"unpin\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Remove pin between entities\" });\n\n source = Option.String();\n target = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const sourceId = await resolveEntityC(caller, this.source);\n const targetId = await resolveEntityC(caller, this.target);\n\n const existing = await caller.query(pinsListBySource, { sourceEntityId: sourceId });\n const match = existing.find((p) => p.targetEntityId === targetId);\n if (match) await caller.mutation(pinsRemove, { pinId: match._id });\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true } }, spaces), () =>\n withFooter(\"Pin removed.\", spaces),\n );\n }\n}\n\nclass EntityRemoveFromSpace extends ProfileCommand {\n static paths = [[\"entity\", \"remove-from-space\"]];\n static usage = Command.Usage({\n category: \"Entity\",\n description: \"Remove an entity from a space (must remain in at least one other space)\",\n });\n\n nameOrId = Option.String();\n space = Option.String(\"--space\", { required: true, description: \"Space to remove from (name or ID)\" });\n removeFromActivities = Option.Boolean(\"--remove-from-activities\", false, {\n description: \"Also remove the entity from activities in this space when another owner remains\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n const spaceId = await resolveSpaceByNameC(caller, this.space);\n await caller.mutation(entitiesRemoveFromSpace, {\n entityId,\n spaceId,\n ...(this.removeFromActivities ? { removeFromActivities: true } : {}),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true } }, spaces), () =>\n withFooter(\"Removed entity from space.\", spaces),\n );\n }\n}\n\nclass EntityAddToSpace extends ProfileCommand {\n static paths = [[\"entity\", \"add-to-space\"]];\n static usage = Command.Usage({\n category: \"Entity\",\n description: \"Add an entity to an additional space\",\n });\n\n nameOrId = Option.String();\n space = Option.String(\"--space\", { required: true, description: \"Space to add to (name or ID)\" });\n shareParents = Option.Boolean(\"--share-parents\", false, {\n description: \"Confirm sharing this entity's parents and ancestors into the target space\",\n });\n parentSpaceGrantFingerprint = Option.String(\"--parent-space-grant-fingerprint\", {\n description: \"Exact grantFingerprint returned by the confirmation-required error\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const entityId = await resolveEntityC(caller, this.nameOrId);\n const spaceId = await resolveSpaceByNameC(caller, this.space);\n await caller.mutation(entitiesCreateEntitySpaceLink, {\n entityId,\n spaceId,\n ...(this.shareParents ? {\n grantMissingParentAccess: true,\n ...(this.parentSpaceGrantFingerprint\n ? { parentSpaceGrantFingerprint: this.parentSpaceGrantFingerprint }\n : {}),\n } : {}),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true } }, spaces), () =>\n withFooter(\"Added entity to space.\", spaces),\n );\n }\n}\n\nasync function entityDescriptionDocumentId(\n caller: Awaited<ReturnType<typeof resolveCaller>>,\n nameOrId: string,\n) {\n return `entity-desc:${await resolveEntityC(caller, nameOrId)}`;\n}\n\nclass EntityHtmlList extends ProfileCommand {\n static paths = [[\"entity\", \"html\", \"list\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"List interactive HTML blocks in an entity description\" });\n\n nameOrId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await listHtmlBlocks(caller, await entityDescriptionDocumentId(caller, this.nameOrId));\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(formatHtmlBlockList(data), spaces));\n }\n}\n\nclass EntityHtmlGet extends ProfileCommand {\n static paths = [[\"entity\", \"html\", \"get\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Read one entity HTML block including source\" });\n\n nameOrId = Option.String();\n blockId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await getHtmlBlock(\n caller,\n await entityDescriptionDocumentId(caller, this.nameOrId),\n this.blockId,\n );\n if (!data) throw new Error(`HTML block not found: ${this.blockId}`);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(data.source, spaces));\n }\n}\n\nclass EntityHtmlAdd extends ProfileCommand {\n static paths = [[\"entity\", \"html\", \"add\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Append an interactive HTML block to an entity description\" });\n\n nameOrId = Option.String();\n htmlFile = Option.String({ required: false, name: \"htmlFile\" });\n htmlFileFlag = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - or omit for stdin\" });\n title = Option.String(\"--title\", { required: true, description: \"Block title\" });\n height = Option.String(\"--height\", \"480\", { description: \"Block height in pixels\" });\n\n async run(): Promise<number | void> {\n if (this.htmlFile !== undefined && this.htmlFileFlag !== undefined)\n throw new Error(\"Pass a positional HTML file or --html-file, not both.\");\n const caller = await resolveCaller();\n const data = await addHtmlBlock(caller, {\n documentId: await entityDescriptionDocumentId(caller, this.nameOrId),\n title: this.title,\n source: readHtmlSource(this.htmlFileFlag ?? this.htmlFile ?? \"-\"),\n height: Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Added interactive HTML '${data.title}' (${data.artifactId})`,\n spaces,\n ));\n }\n}\n\nclass EntityHtmlUpdate extends ProfileCommand {\n static paths = [[\"entity\", \"html\", \"update\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Surgically update one entity HTML block\" });\n\n nameOrId = Option.String();\n blockId = Option.String();\n htmlFile = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - for stdin\" });\n html = Option.String(\"--html\", { description: \"Inline complete HTML source\" });\n title = Option.String(\"--title\", { description: \"Replacement title\" });\n height = Option.String(\"--height\", { description: \"Replacement height in pixels\" });\n\n async run(): Promise<number | void> {\n if ((this.htmlFile === undefined) === (this.html === undefined))\n throw new Error(\"Use exactly one of --html or --html-file.\");\n const caller = await resolveCaller();\n const data = await updateHtmlBlock(caller, {\n documentId: await entityDescriptionDocumentId(caller, this.nameOrId),\n blockId: this.blockId,\n source: this.html ?? readHtmlSource(this.htmlFile!),\n title: this.title,\n height: this.height === undefined ? undefined : Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Updated interactive HTML '${data.title}' to v${data.version}`,\n spaces,\n ));\n }\n}\n\nexport const ENTITY_COMMANDS = [\n EntityList,\n EntityCreate,\n EntityGet,\n EntityUpdate,\n EntityRename,\n EntityArchive,\n EntityRestore,\n EntityPin,\n EntityUnpin,\n EntityRemoveFromSpace,\n EntityAddToSpace,\n EntityHtmlList,\n EntityHtmlGet,\n EntityHtmlAdd,\n EntityHtmlUpdate,\n];\n", "// Activity commands \u2014 list, create, search, get, update, delete, restore,\n// attachment upload. Ports commands/activity.py.\n//\n// `activity list` stays on the REST transport (ClientCommand). Every other\n// command here calls the SAME public `api.activities.*` / `api.storage.*`\n// functions the web app uses, via the JWT bridge (see ../convexClient.ts) \u2014 no\n// per-capability REST endpoint. The old 422 `space_entity_mismatch` explainer\n// (`surfaceSpaceMismatch`) was a REST-only affordance; it's kept exported here\n// for any REST-staying caller, but the migrated create path below just lets\n// backend errors bubble to ProfileCommand's error boundary.\n\nimport { readFileSync } from \"node:fs\";\nimport { basename } from \"node:path\";\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ApiError } from \"../../core/errors.ts\";\nimport { ENTE_BRANDING } from \"../branding.ts\";\nimport { ProfileCommand, ClientCommand } from \"../command.ts\";\nimport { readContentOption } from \"../content.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport {\n anyMembershipSpaceId,\n resolveEntitiesC,\n resolveEntityC,\n resolveSpaceByNameC,\n spacesFooterFromMemberships,\n withFooter,\n} from \"../convexResolve.ts\";\nimport { formatActivityDetail, formatActivityList, jsonWithSpaces } from \"../format.ts\";\nimport { mimeTypeForPath } from \"../fileAttachments.ts\";\nimport {\n addHtmlBlock,\n formatHtmlBlockList,\n getHtmlBlock,\n listHtmlBlocks,\n readHtmlSource,\n updateHtmlBlock,\n} from \"../htmlBlocks.ts\";\nimport { parseSourceCreatedAt, type SourceCreatedAt } from \"../source-created-at.ts\";\nimport type {\n Activity,\n ActivityAgendaPoint,\n ActivityAttachment,\n ActivityMessage,\n SpaceEntityMismatch,\n} from \"../types.ts\";\n\nconst MAX_ACTIVITY_ATTACHMENT_BYTES = 20 * 1024 * 1024;\n\n// --- rich-activity shape (wire contract with convex/activities.ts) ---------\n\ninterface EntityRefLite {\n _id: string;\n name: string;\n [key: string]: unknown;\n}\n\ninterface ActivityRich {\n _id: string;\n type: string;\n title?: string;\n contentPlainText?: string;\n createdAt: number;\n deadline?: number;\n completed?: boolean;\n shortId?: number;\n attributes?: Record<string, unknown>;\n tags?: string[];\n assigneeIds?: string[];\n spaceId: string;\n revisionCount?: number;\n attachments?: ActivityAttachment[];\n agendaPoints?: ActivityAgendaPoint[];\n messages?: ActivityMessage[];\n entityDetails: Array<EntityRefLite | null>;\n [key: string]: unknown;\n}\n\ntype ActivityRevisionSource = \"user\" | \"agent\" | \"recording\";\n\ninterface ActivityRevisionSummary {\n _id: string;\n activityId: string;\n title?: string;\n contentPlainText?: string;\n source: ActivityRevisionSource;\n authorId: string;\n authorName?: string;\n agentThreadId?: string;\n agentRunId?: string;\n summary?: string;\n createdAt: number;\n updatedAt: number;\n}\n\ninterface ActivityRevisionFull extends ActivityRevisionSummary {\n snapshot: string;\n}\n\ntype ActivityContentEditOperation =\n | { type: \"replaceBlock\" | \"insertBefore\" | \"insertAfter\"; target: string; markdown: string }\n | { type: \"deleteBlock\"; target: string }\n | { type: \"replaceText\"; target: string; oldText: string; newText: string }\n | { type: \"append\"; markdown: string };\n\ninterface ActivityContentReadResult {\n activityId: string;\n contentVersion: number | null;\n blocks: Array<{\n target: string;\n blockType: string;\n format: \"markdown\" | \"plain_text\";\n content: string;\n start: number;\n end: number;\n totalCharacters: number;\n canReplaceText: boolean;\n }>;\n nextCursor?: string;\n}\n\ninterface ActivityContentEditResult {\n activityId: string;\n contentVersion: number | null;\n changed: boolean;\n}\n\nfunction toActivity(rich: ActivityRich): Activity {\n return {\n _id: rich._id,\n type: rich.type,\n title: rich.title,\n contentPlainText: rich.contentPlainText,\n createdAt: rich.createdAt,\n deadline: rich.deadline,\n completed: rich.completed,\n shortId: rich.shortId,\n attributes: rich.attributes,\n tags: rich.tags,\n entityIds: rich.entityDetails.map((e) => e?._id).filter((id): id is string => !!id),\n assigneeIds: rich.assigneeIds,\n attachments: rich.attachments,\n agendaPoints: rich.agendaPoints ?? [],\n messages: rich.messages ?? [],\n };\n}\n\n// --- typed function references (convex/activities.ts + convex/storage.ts) --\n\nconst activitiesCreate = makeFunctionReference<\n \"mutation\",\n {\n entityId?: string;\n additionalEntities?: string[];\n ownerSpaceId: string;\n grantMissingEntityAccess?: boolean;\n entitySpaceGrantFingerprint?: string;\n type: string;\n title?: string;\n contentMarkdown?: string;\n tags?: string[];\n },\n string\n>(\"activities:create\");\nconst activitiesGetCompleteByIdRich = makeFunctionReference<\n \"query\",\n { activityId: string },\n ActivityRich | null\n>(\"activities:getCompleteByIdRich\");\nconst activitiesGetByIdRich = makeFunctionReference<\n \"query\",\n { activityId: string },\n ActivityRich | null\n>(\"activities:getByIdRich\");\nconst activitiesSearchRich = makeFunctionReference<\n \"query\",\n { spaceId: string; query: string; type?: string; limit?: number },\n ActivityRich[]\n>(\"activities:searchRich\");\nconst activitiesUpdateTitle = makeFunctionReference<\n \"mutation\",\n { activityId: string; title?: string },\n null\n>(\"activities:updateTitle\");\nconst activitiesSetContentFromMarkdown = makeFunctionReference<\n \"mutation\",\n { activityId: string; markdown: string },\n null\n>(\"activities:setContentFromMarkdown\");\nconst activitiesReadContent = makeFunctionReference<\n \"query\",\n {\n activityId: string;\n cursor?: string;\n maxBlocks?: number;\n maxCharacters?: number;\n expectedContentVersion?: number | null;\n },\n ActivityContentReadResult\n>(\"activities:readContent\");\nconst activitiesEditContent = makeFunctionReference<\n \"mutation\",\n {\n activityId: string;\n expectedContentVersion: number | null;\n operations: ActivityContentEditOperation[];\n },\n ActivityContentEditResult\n>(\"activities:editContent\");\nconst activitiesUpdateEntities = makeFunctionReference<\n \"mutation\",\n {\n activityId: string;\n entities: string[];\n grantMissingEntityAccess?: boolean;\n entitySpaceGrantFingerprint?: string;\n },\n null\n>(\"activities:updateEntities\");\nconst activitiesUpdateCreatedAt = makeFunctionReference<\n \"mutation\",\n { activityId: string; sourceCreatedAt: SourceCreatedAt },\n null\n>(\"activities:updateCreatedAt\");\nconst activitiesDeleteActivity = makeFunctionReference<\"mutation\", { activityId: string }, null>(\n \"activities:deleteActivity\",\n);\nconst activitiesRestoreActivity = makeFunctionReference<\"mutation\", { activityId: string }, null>(\n \"activities:restoreActivity\",\n);\nconst activitiesAddAttachment = makeFunctionReference<\n \"mutation\",\n { activityId: string; storageId: string; name: string; mimeType: string },\n null\n>(\"activities:addAttachment\");\nconst activitiesCreateAttachmentAccessUrls = makeFunctionReference<\n \"mutation\",\n { activityId: string },\n { expiresAt: number; attachments: ActivityAttachment[] }\n>(\"activities:createAttachmentAccessUrls\");\nconst storageGenerateUploadUrl = makeFunctionReference<\"mutation\", Record<string, never>, string>(\n \"storage:generateUploadUrl\",\n);\nconst activitiesListRevisions = makeFunctionReference<\n \"query\",\n { activityId: string },\n ActivityRevisionSummary[]\n>(\"activities:listActivityRevisions\");\nconst activitiesGetRevision = makeFunctionReference<\n \"query\",\n { revisionId: string },\n ActivityRevisionFull | null\n>(\"activities:getActivityRevision\");\nconst activitiesRestoreRevision = makeFunctionReference<\n \"mutation\",\n { revisionId: string },\n { activityId: string }\n>(\"activities:restoreActivityRevision\");\nconst messagesCreateFromMarkdown = makeFunctionReference<\n \"mutation\",\n { activityId: string; markdown: string },\n string\n>(\"messages:createFromMarkdown\");\nfunction formatRevisionTimestamp(ms: number): string {\n return new Date(ms).toISOString().replace(\"T\", \" \").slice(0, 16);\n}\n\nfunction formatRevisionLine(rev: ActivityRevisionSummary): string {\n const who = rev.authorName ?? rev.authorId;\n const label = rev.summary ? ` (${rev.summary})` : \"\";\n const thread = rev.agentThreadId ? ` thread:${rev.agentThreadId}` : \"\";\n return `${formatRevisionTimestamp(rev.createdAt)} [${rev.source}] ${who}${label}${thread} ${rev._id}`;\n}\n\n// --- activity list (stays on REST) ------------------------------------------\n\nclass ActivityList extends ClientCommand {\n static paths = [[\"activity\", \"list\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"List activities\" });\n\n entity = Option.String(\"--entity\", { description: \"Filter by entity (name or ID)\" });\n type = Option.String(\"--type\", { description: \"Filter by type (task, call, note, message, conversation, meeting)\" });\n attr = Option.Array(\"--attr\", { description: \"Filter by attribute key=value\" });\n onlyOpen = Option.Boolean(\"--only-open\", false, { description: \"Only show non-completed activities\" });\n hours = Option.String(\"--hours\", { description: \"Only from the last N hours\" });\n limit = Option.String(\"--limit\", { description: \"Max results\" });\n sort = Option.String(\"--sort\", { description: \"Sort by: deadline, created\" });\n before = Option.String(\"--before\", { description: \"Only activities before this timestamp (ms)\" });\n after = Option.String(\"--after\", { description: \"Only activities after this timestamp (ms)\" });\n archived = Option.Boolean(\"--archived\", false, {\n description: \"Show archived (trashed) activities instead of active ones\",\n });\n\n async run(): Promise<number | void> {\n if (this.archived) {\n const client = this.client();\n const params: Record<string, string> = { archived: \"true\" };\n if (this.limit) params.limit = this.limit;\n const res = await client.listActivities(params);\n const spaces = await client.listSpaces();\n this.emitText(jsonWithSpaces(res, spaces), () =>\n this.withFooter(formatActivityList(res.data ?? []), spaces),\n );\n return;\n }\n\n await this.runActivityList({\n entity: this.entity,\n typeFilter: this.type,\n attrFilter: this.attr,\n onlyOpen: this.onlyOpen,\n hours: this.hours ? Number(this.hours) : undefined,\n limit: this.limit ? Number(this.limit) : undefined,\n sort: this.sort,\n before: this.before !== undefined ? Number(this.before) : undefined,\n after: this.after !== undefined ? Number(this.after) : undefined,\n });\n }\n}\n\n// --- migrated (Convex) commands ---------------------------------------------\n\nclass ActivityCreate extends ProfileCommand {\n static paths = [[\"activity\", \"create\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Create an activity\" });\n\n type = Option.String(\"--type\", { required: true, description: \"Activity type (note, conversation, meeting, call, message, task)\" });\n title = Option.String(\"--title\", { required: true, description: \"Activity title\" });\n entity = Option.Array(\"--entity\", { required: true, description: \"Linked entities (resolved by name)\" });\n space = Option.String(\"--space\", { required: true, description: \"Space to create in (name or ID)\" });\n content = Option.String(\"--content\", { description: \"Activity content\" });\n contentFile = Option.String(\"--content-file\", { description: \"Read content from a markdown/text file\" });\n sourceCreatedAt = Option.String(\"--source-created-at\", {\n description: \"Import/backfill timestamp: YYYY-MM-DD or YYYY-MM-DDTHH:mm\",\n });\n sourceCreatedAtTimezone = Option.String(\"--source-created-at-timezone\", \"Europe/Berlin\", {\n description: \"IANA timezone for --source-created-at\",\n });\n tag = Option.Array(\"--tag\", { description: \"Tags (repeatable)\" });\n autoLink = Option.Boolean(\"--auto-link\", false, { description: \"Auto-link entities not in target space\" });\n entitySpaceGrantFingerprint = Option.String(\"--entity-space-grant-fingerprint\", {\n description: \"Exact grant fingerprint returned by the confirmation-required error\",\n });\n\n async run(): Promise<number | void> {\n const content = readContentOption(this.content, this.contentFile);\n const caller = await resolveCaller();\n const entityIds = await resolveEntitiesC(caller, this.entity);\n const spaceId = await resolveSpaceByNameC(caller, this.space);\n\n const activityId = await caller.mutation(activitiesCreate, {\n entityId: entityIds[0],\n additionalEntities: entityIds.slice(1),\n ownerSpaceId: spaceId,\n grantMissingEntityAccess: this.autoLink,\n ...(this.entitySpaceGrantFingerprint\n ? { entitySpaceGrantFingerprint: this.entitySpaceGrantFingerprint }\n : {}),\n type: this.type,\n title: this.title,\n ...(content !== undefined ? { contentMarkdown: content } : {}),\n ...(this.tag && this.tag.length ? { tags: this.tag } : {}),\n });\n\n if (this.sourceCreatedAt) {\n const sourceCreatedAt = parseSourceCreatedAt(this.sourceCreatedAt, this.sourceCreatedAtTimezone);\n await caller.mutation(activitiesUpdateCreatedAt, { activityId, sourceCreatedAt });\n }\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { activityId } }, spaces), () =>\n withFooter(`Created ${this.type} '${this.title}' (${activityId})`, spaces),\n );\n }\n}\n\nclass ActivitySearch extends ProfileCommand {\n static paths = [[\"activity\", \"search\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Search activities by title or content\" });\n\n query = Option.String();\n entity = Option.String(\"--entity\", { description: \"Filter by entity (name or ID)\" });\n type = Option.String(\"--type\", { description: \"Filter by activity type\" });\n limit = Option.String(\"--limit\", { description: \"Max results\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n // searchRich requires *some* membership-checked spaceId, but the actual\n // search scope (lensSpaceId omitted) is every space the caller can access.\n const spaceId = await anyMembershipSpaceId(caller);\n let results = await caller.query(activitiesSearchRich, {\n spaceId,\n query: this.query,\n ...(this.type ? { type: this.type } : {}),\n ...(this.limit ? { limit: Number(this.limit) } : {}),\n });\n\n if (this.entity) {\n const entityId = await resolveEntityC(caller, this.entity);\n results = results.filter((r) => r.entityDetails.some((e) => e?._id === entityId));\n }\n\n const activities = results.map(toActivity);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: activities }, spaces), () =>\n withFooter(formatActivityList(activities), spaces),\n );\n }\n}\n\nclass ActivityGet extends ProfileCommand {\n static paths = [[\"activity\", \"get\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Get a single activity by ID\" });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rich = await caller.query(activitiesGetCompleteByIdRich, { activityId: this.id });\n if (!rich) throw new Error(`Activity not found or not accessible: ${this.id}`);\n const accessGrant = rich.attachments?.length\n ? await caller.mutation(activitiesCreateAttachmentAccessUrls, { activityId: this.id })\n : null;\n const urlByStorageId = new Map(\n (accessGrant?.attachments ?? []).map((attachment) => [attachment.storageId, attachment.url]),\n );\n const activity = toActivity({\n ...rich,\n attachments: rich.attachments?.map((attachment) => ({\n ...attachment,\n url: urlByStorageId.get(attachment.storageId) ?? attachment.url,\n })),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n const revisionCount = rich.revisionCount ?? 0;\n this.emitText(jsonWithSpaces({ data: { ...activity, revisionCount } }, spaces), () => {\n const detail = withFooter(formatActivityDetail(activity), spaces);\n // Always show the latest content; surface that older versions are available.\n if (revisionCount > 1) {\n return `${detail}\\n\\n${revisionCount} versions available \u2014 view with: ente activity revisions ${this.id}`;\n }\n return detail;\n });\n }\n}\n\nclass ActivityRevisions extends ProfileCommand {\n static paths = [[\"activity\", \"revisions\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"List an activity's version history (newest first)\",\n });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const revisions = await caller.query(activitiesListRevisions, { activityId: this.id });\n this.emitText({ data: revisions }, () => {\n if (revisions.length === 0) return \"No versions recorded yet.\";\n const lines = revisions.map(formatRevisionLine);\n return [\n `${revisions.length} version(s) \u2014 newest first:`,\n ...lines,\n \"\",\n `View one: ente activity revision ${this.id} <revisionId>`,\n `Restore one: ente activity restore-revision ${this.id} <revisionId>`,\n ].join(\"\\n\");\n });\n }\n}\n\nclass ActivityRevisionShow extends ProfileCommand {\n static paths = [[\"activity\", \"revision\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Show a single past version of an activity (read-only)\",\n });\n\n activityId = Option.String();\n revisionId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rev = await caller.query(activitiesGetRevision, { revisionId: this.revisionId });\n if (!rev) throw new Error(`Revision not found or not accessible: ${this.revisionId}`);\n if (rev.activityId !== this.activityId) {\n throw new Error(`Revision ${this.revisionId} does not belong to activity ${this.activityId}.`);\n }\n this.emitText({ data: rev }, () =>\n [\n `Version of activity ${rev.activityId}`,\n `Captured: ${formatRevisionTimestamp(rev.createdAt)} [${rev.source}] ${rev.authorName ?? rev.authorId}`,\n rev.agentThreadId ? `Agent thread: ${rev.agentThreadId}${rev.agentRunId ? ` run: ${rev.agentRunId}` : \"\"}` : null,\n rev.summary ? `Note: ${rev.summary}` : null,\n \"\",\n rev.title ? `# ${rev.title}` : null,\n rev.contentPlainText && rev.contentPlainText.length ? rev.contentPlainText : \"(empty body)\",\n ]\n .filter((line) => line !== null)\n .join(\"\\n\"),\n );\n }\n}\n\nclass ActivityRestoreRevision extends ProfileCommand {\n static paths = [[\"activity\", \"restore-revision\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Restore an activity's body + title to a past version\",\n });\n\n activityId = Option.String();\n revisionId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rev = await caller.query(activitiesGetRevision, { revisionId: this.revisionId });\n if (!rev) throw new Error(`Revision not found or not accessible: ${this.revisionId}`);\n if (rev.activityId !== this.activityId) {\n throw new Error(`Revision ${this.revisionId} does not belong to activity ${this.activityId}.`);\n }\n const result = await caller.mutation(activitiesRestoreRevision, { revisionId: this.revisionId });\n this.emitText({ data: { ok: true, ...result } }, () =>\n `Restored activity ${result.activityId} to the version from ${formatRevisionTimestamp(rev.createdAt)}. A new \"restored\" version was recorded.`,\n );\n }\n}\n\nclass ActivityUpdate extends ProfileCommand {\n static paths = [[\"activity\", \"update\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Update an activity\" });\n\n id = Option.String();\n content = Option.String(\"--content\", { description: \"Update content\" });\n contentFile = Option.String(\"--content-file\", { description: \"Read updated content from a markdown/text file\" });\n title = Option.String(\"--title\", { description: \"Update title\" });\n entityAdd = Option.Array(\"--entity-add\", { description: \"Link additional entities\" });\n entityRemove = Option.Array(\"--entity-remove\", { description: \"Unlink entities\" });\n\n async run(): Promise<number | void> {\n const content = readContentOption(this.content, this.contentFile);\n const hasEntityChange = !!((this.entityAdd && this.entityAdd.length) || (this.entityRemove && this.entityRemove.length));\n if (this.content === undefined && this.contentFile === undefined && this.title === undefined && !hasEntityChange) {\n this.err(\"Nothing to update. Specify --content, --title, --entity-add, or --entity-remove.\");\n return 1;\n }\n\n const caller = await resolveCaller();\n\n if (this.title !== undefined) await caller.mutation(activitiesUpdateTitle, { activityId: this.id, title: this.title });\n\n if (content !== undefined) await caller.mutation(activitiesSetContentFromMarkdown, { activityId: this.id, markdown: content });\n\n if (hasEntityChange) {\n const rich = await caller.query(activitiesGetByIdRich, { activityId: this.id });\n if (!rich) throw new Error(`Activity not found or not accessible: ${this.id}`);\n const currentIds = rich.entityDetails.map((e) => e?._id).filter((x): x is string => !!x);\n const addIds = this.entityAdd ? await resolveEntitiesC(caller, this.entityAdd) : [];\n const removeIds = this.entityRemove ? await resolveEntitiesC(caller, this.entityRemove) : [];\n const removeSet = new Set(removeIds);\n\n const newIds = currentIds.filter((eid) => !removeSet.has(eid));\n for (const eid of addIds) if (!currentIds.includes(eid)) newIds.push(eid);\n\n if (newIds.length === 0) {\n this.err(\"Cannot remove all entities \u2014 an activity must have at least one.\");\n return 1;\n }\n await caller.mutation(activitiesUpdateEntities, { activityId: this.id, entities: newIds });\n }\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, activityId: this.id } }, spaces), () =>\n withFooter(`Updated activity ${this.id}`, spaces),\n );\n }\n}\n\nfunction parseContentVersion(value: string): number | null {\n if (value === \"null\") return null;\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed < 0)\n throw new Error(\"Content version must be a non-negative integer or 'null'.\");\n return parsed;\n}\n\nfunction parseOptionalPositiveInteger(value: string | undefined, label: string) {\n if (value === undefined) return undefined;\n const parsed = Number(value);\n if (!Number.isInteger(parsed) || parsed < 1)\n throw new Error(`${label} must be a positive integer.`);\n return parsed;\n}\n\nclass ActivityContentRead extends ProfileCommand {\n static paths = [[\"activity\", \"content\", \"read\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Read a bounded, versioned activity body for partial editing\",\n });\n\n id = Option.String();\n cursor = Option.String(\"--cursor\", { description: \"Opaque nextCursor from the preceding page\" });\n expectedVersion = Option.String(\"--expected-version\", {\n description: \"contentVersion from the preceding page\",\n });\n maxBlocks = Option.String(\"--max-blocks\", { description: \"Maximum block windows (max 50)\" });\n maxCharacters = Option.String(\"--max-characters\", { description: \"Maximum characters (max 50000)\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await caller.query(activitiesReadContent, {\n activityId: this.id,\n cursor: this.cursor,\n expectedContentVersion: this.expectedVersion === undefined\n ? undefined\n : parseContentVersion(this.expectedVersion),\n maxBlocks: parseOptionalPositiveInteger(this.maxBlocks, \"--max-blocks\"),\n maxCharacters: parseOptionalPositiveInteger(this.maxCharacters, \"--max-characters\"),\n });\n this.emitText({ data }, () => {\n const lines = [\n `Activity ${data.activityId} contentVersion=${String(data.contentVersion)}`,\n ...data.blocks.flatMap((block) => [\n `\\n[${block.target} ${block.blockType} ${block.format} ${block.start}:${block.end}/${block.totalCharacters}]`,\n block.content,\n ]),\n ];\n if (data.nextCursor)\n lines.push(`\\nNext: --cursor ${data.nextCursor} --expected-version ${String(data.contentVersion)}`);\n return lines.join(\"\\n\");\n });\n }\n}\n\nclass ActivityContentEdit extends ProfileCommand {\n static paths = [[\"activity\", \"content\", \"edit\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Apply an atomic, version-guarded partial activity-body edit\",\n });\n\n id = Option.String();\n expectedVersion = Option.String(\"--expected-version\", {\n required: true,\n description: \"Exact contentVersion returned by activity content read\",\n });\n operationsFile = Option.String(\"--operations-file\", {\n required: true,\n description: \"JSON file containing an operation array or {operations:[...]}\",\n });\n\n async run(): Promise<number | void> {\n const raw = JSON.parse(readFileSync(this.operationsFile, \"utf8\")) as unknown;\n const operations = Array.isArray(raw)\n ? raw\n : raw && typeof raw === \"object\" && \"operations\" in raw\n ? (raw as { operations: unknown }).operations\n : null;\n if (!Array.isArray(operations))\n throw new Error(\"Operations file must contain a JSON array or an object with an operations array.\");\n const caller = await resolveCaller();\n const data = await caller.mutation(activitiesEditContent, {\n activityId: this.id,\n expectedContentVersion: parseContentVersion(this.expectedVersion),\n operations: operations as ActivityContentEditOperation[],\n });\n this.emitText({ data }, () =>\n `${data.changed ? \"Updated\" : \"No change to\"} activity ${data.activityId}; contentVersion=${String(data.contentVersion)}`,\n );\n }\n}\n\nclass ActivityDelete extends ProfileCommand {\n static paths = [[\"activity\", \"delete\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Move an activity to the trash (soft delete). Use `activity restore` to undo.\",\n });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n await caller.mutation(activitiesDeleteActivity, { activityId: this.id });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, activityId: this.id } }, spaces), () =>\n withFooter(`Trashed activity ${this.id}`, spaces),\n );\n }\n}\n\nclass ActivityRestore extends ProfileCommand {\n static paths = [[\"activity\", \"restore\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Restore a trashed activity\" });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n await caller.mutation(activitiesRestoreActivity, { activityId: this.id });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, activityId: this.id } }, spaces), () =>\n withFooter(`Restored activity ${this.id}`, spaces),\n );\n }\n}\n\nclass ActivityAttachmentUpload extends ProfileCommand {\n static paths = [[\"activity\", \"attachment\", \"upload\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Upload a file and attach it to an activity\",\n });\n\n id = Option.String();\n file = Option.String();\n name = Option.String(\"--name\", { description: \"Stored filename (defaults to the file's basename)\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const bytes = readFileSync(this.file);\n if (bytes.byteLength > MAX_ACTIVITY_ATTACHMENT_BYTES) {\n throw new Error(\"Activity attachments must be 20 MB or smaller.\");\n }\n const name = this.name ?? basename(this.file);\n const mimeType = mimeTypeForPath(this.file);\n\n const uploadUrl = await caller.mutation(storageGenerateUploadUrl, {});\n const uploadRes = await fetch(uploadUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": mimeType },\n body: bytes,\n });\n if (!uploadRes.ok) {\n throw new Error(`Attachment upload failed: ${uploadRes.status} ${uploadRes.statusText}`);\n }\n const { storageId } = (await uploadRes.json()) as { storageId: string };\n\n await caller.mutation(activitiesAddAttachment, { activityId: this.id, storageId, name, mimeType });\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { storageId } }, spaces), () =>\n withFooter(`Attached '${name}' to activity ${this.id} (${storageId})`, spaces),\n );\n }\n}\n\nclass ActivityMessageAdd extends ProfileCommand {\n static paths = [[\"activity\", \"message\", \"add\"]];\n static usage = Command.Usage({\n category: \"Activity\",\n description: \"Append a chronological message to an activity\",\n });\n\n id = Option.String();\n content = Option.String(\"--content\", { description: \"Message content in markdown\" });\n contentFile = Option.String(\"--content-file\", {\n description: \"Read message content from a markdown/text file\",\n });\n\n async run(): Promise<number | void> {\n const markdown = readContentOption(this.content, this.contentFile);\n if (!markdown?.trim()) {\n this.err(\"Message content is required. Specify --content or --content-file.\");\n return 1;\n }\n\n const caller = await resolveCaller();\n const messageId = await caller.mutation(messagesCreateFromMarkdown, {\n activityId: this.id,\n markdown,\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { activityId: this.id, messageId } }, spaces), () =>\n withFooter(`Added message ${messageId} to activity ${this.id}`, spaces),\n );\n }\n}\n\nclass ActivityHtmlList extends ProfileCommand {\n static paths = [[\"activity\", \"html\", \"list\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"List interactive HTML blocks in an activity\" });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await listHtmlBlocks(caller, this.id);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n formatHtmlBlockList(data),\n spaces,\n ));\n }\n}\n\nclass ActivityHtmlGet extends ProfileCommand {\n static paths = [[\"activity\", \"html\", \"get\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Read one interactive HTML block including source\" });\n\n id = Option.String();\n blockId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await getHtmlBlock(caller, this.id, this.blockId);\n if (!data) throw new Error(`HTML block not found: ${this.blockId}`);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(data.source, spaces));\n }\n}\n\nclass ActivityHtmlAdd extends ProfileCommand {\n static paths = [[\"activity\", \"html\", \"add\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Append an interactive HTML block to an activity\" });\n\n id = Option.String();\n htmlFile = Option.String({ required: false, name: \"htmlFile\" });\n htmlFileFlag = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - or omit for stdin\" });\n title = Option.String(\"--title\", { required: true, description: \"Block title\" });\n height = Option.String(\"--height\", \"480\", { description: \"Block height in pixels\" });\n\n async run(): Promise<number | void> {\n if (this.htmlFile !== undefined && this.htmlFileFlag !== undefined)\n throw new Error(\"Pass a positional HTML file or --html-file, not both.\");\n const htmlFile = this.htmlFileFlag ?? this.htmlFile ?? \"-\";\n const source = readHtmlSource(htmlFile);\n const caller = await resolveCaller();\n const data = await addHtmlBlock(caller, {\n documentId: this.id,\n title: this.title,\n source,\n height: Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Added interactive HTML '${data.title}' (${data.artifactId})`,\n spaces,\n ));\n }\n}\n\nclass ActivityHtmlUpdate extends ProfileCommand {\n static paths = [[\"activity\", \"html\", \"update\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Surgically update one interactive HTML block\" });\n\n id = Option.String();\n blockId = Option.String();\n htmlFile = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - for stdin\" });\n html = Option.String(\"--html\", { description: \"Inline complete HTML source\" });\n title = Option.String(\"--title\", { description: \"Replacement title\" });\n height = Option.String(\"--height\", { description: \"Replacement height in pixels\" });\n\n async run(): Promise<number | void> {\n if ((this.htmlFile === undefined) === (this.html === undefined))\n throw new Error(\"Use exactly one of --html or --html-file.\");\n const caller = await resolveCaller();\n const source = this.html !== undefined\n ? this.html\n : readHtmlSource(this.htmlFile!);\n const data = await updateHtmlBlock(caller, {\n documentId: this.id,\n blockId: this.blockId,\n source,\n title: this.title,\n height: this.height === undefined ? undefined : Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Updated interactive HTML '${data.title}' to v${data.version}`,\n spaces,\n ));\n }\n}\n\nclass ActivityMessageHtmlList extends ProfileCommand {\n static paths = [[\"activity\", \"message\", \"html\", \"list\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"List interactive HTML blocks in an activity message\" });\n\n messageId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await listHtmlBlocks(caller, `message:${this.messageId}`);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n formatHtmlBlockList(data),\n spaces,\n ));\n }\n}\n\nclass ActivityMessageHtmlGet extends ProfileCommand {\n static paths = [[\"activity\", \"message\", \"html\", \"get\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Read one activity-message HTML block including source\" });\n\n messageId = Option.String();\n blockId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await getHtmlBlock(caller, `message:${this.messageId}`, this.blockId);\n if (!data) throw new Error(`HTML block not found: ${this.blockId}`);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(data.source, spaces));\n }\n}\n\nclass ActivityMessageHtmlAdd extends ProfileCommand {\n static paths = [[\"activity\", \"message\", \"html\", \"add\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Append an interactive HTML block to an activity message\" });\n\n messageId = Option.String();\n htmlFile = Option.String({ required: false, name: \"htmlFile\" });\n htmlFileFlag = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - or omit for stdin\" });\n title = Option.String(\"--title\", { required: true, description: \"Block title\" });\n height = Option.String(\"--height\", \"480\", { description: \"Block height in pixels\" });\n\n async run(): Promise<number | void> {\n if (this.htmlFile !== undefined && this.htmlFileFlag !== undefined)\n throw new Error(\"Pass a positional HTML file or --html-file, not both.\");\n const htmlFile = this.htmlFileFlag ?? this.htmlFile ?? \"-\";\n const source = readHtmlSource(htmlFile);\n const caller = await resolveCaller();\n const data = await addHtmlBlock(caller, {\n documentId: `message:${this.messageId}`,\n title: this.title,\n source,\n height: Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Added interactive HTML '${data.title}' (${data.artifactId})`,\n spaces,\n ));\n }\n}\n\nclass ActivityMessageHtmlUpdate extends ProfileCommand {\n static paths = [[\"activity\", \"message\", \"html\", \"update\"]];\n static usage = Command.Usage({ category: \"Activity\", description: \"Surgically update one activity-message HTML block\" });\n\n messageId = Option.String();\n blockId = Option.String();\n htmlFile = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - for stdin\" });\n html = Option.String(\"--html\", { description: \"Inline complete HTML source\" });\n title = Option.String(\"--title\", { description: \"Replacement title\" });\n height = Option.String(\"--height\", { description: \"Replacement height in pixels\" });\n\n async run(): Promise<number | void> {\n if ((this.htmlFile === undefined) === (this.html === undefined))\n throw new Error(\"Use exactly one of --html or --html-file.\");\n const caller = await resolveCaller();\n const source = this.html !== undefined\n ? this.html\n : readHtmlSource(this.htmlFile!);\n const data = await updateHtmlBlock(caller, {\n documentId: `message:${this.messageId}`,\n blockId: this.blockId,\n source,\n title: this.title,\n height: this.height === undefined ? undefined : Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Updated interactive HTML '${data.title}' to v${data.version}`,\n spaces,\n ));\n }\n}\n\n/**\n * If `exc` is a cross-space mismatch, print the entity names + the spaces they\n * ARE in, plus a UI link to add them, and return true. Otherwise return false\n * so the caller rethrows. REST-only affordance \u2014 kept for any REST-staying\n * caller (the migrated `activity create` / `task create` above no longer throw\n * `ApiError`; backend errors just bubble to ProfileCommand's boundary).\n */\nexport async function surfaceSpaceMismatch(\n err: (line: string) => void,\n client: import(\"../client.ts\").EnteClient,\n exc: ApiError,\n noun = \"Activity\",\n): Promise<boolean> {\n const error = exc.error as SpaceEntityMismatch;\n const kind = String(error.kind ?? \"\").toLowerCase();\n if (exc.statusCode !== 422 || kind !== \"space_entity_mismatch\") return false;\n const invalid = error.invalidEntities ?? [];\n if (invalid.length === 0) return false;\n\n const spaces = await client.listSpaces();\n const targetSpaceId = error.targetSpaceId;\n const targetSpaceName =\n (targetSpaceId ? spaces[targetSpaceId]?.spaceName : undefined) ?? targetSpaceId ?? \"target space\";\n\n err(\n `\u2717 ${noun} not created \u2014 ${invalid.length} ${invalid.length === 1 ? \"entity is\" : \"entities are\"} ` +\n `not in '${targetSpaceName}':`,\n );\n for (const item of invalid) {\n const availNames = (item.availableInSpaceIds ?? []).map((sid) => spaces[sid]?.spaceName ?? sid);\n const availStr = availNames.length ? availNames.join(\", \") : \"(no shared space)\";\n err(` - ${item.name ?? \"?\"} (${item.entityId ?? \"\"}) \u2014 currently in: ${availStr}`);\n if (item.entityId) err(` Add via UI: ${ENTE_BRANDING.webUiBase}/entity/${item.entityId}`);\n }\n err(\n \" Tip: confirm the exact grant set, then retry with --auto-link --entity-space-grant-fingerprint <token>.\",\n );\n return true;\n}\n\nexport const ACTIVITY_COMMANDS = [\n ActivityList,\n ActivityCreate,\n ActivitySearch,\n ActivityGet,\n ActivityRevisions,\n ActivityRevisionShow,\n ActivityRestoreRevision,\n ActivityUpdate,\n ActivityContentRead,\n ActivityContentEdit,\n ActivityDelete,\n ActivityRestore,\n ActivityMessageAdd,\n ActivityHtmlList,\n ActivityHtmlGet,\n ActivityHtmlAdd,\n ActivityHtmlUpdate,\n ActivityMessageHtmlList,\n ActivityMessageHtmlGet,\n ActivityMessageHtmlAdd,\n ActivityMessageHtmlUpdate,\n ActivityAttachmentUpload,\n];\n", "// Shared handling of the `--content` / `--content-file` option pair: the body\n// of an activity or list row as markdown, given inline or read from a file.\n\nimport { readFileSync } from \"node:fs\";\n\n/** Resolve `--content` / `--content-file` to one markdown string, or undefined when neither was given. */\nexport function readContentOption(\n content: string | undefined,\n contentFile: string | undefined,\n): string | undefined {\n if (content !== undefined && contentFile !== undefined) {\n throw new Error(\"Use either --content or --content-file, not both.\");\n }\n if (content !== undefined) return content;\n if (contentFile !== undefined) return readFileSync(contentFile, \"utf8\");\n return undefined;\n}\n", "import { readFileSync } from \"node:fs\";\nimport { basename, extname } from \"node:path\";\nimport type { NotificationEmailAttachmentInput } from \"./types.ts\";\n\nconst MIME_TYPES: Record<string, string> = {\n \".pdf\": \"application/pdf\",\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n \".svg\": \"image/svg+xml\",\n \".txt\": \"text/plain\",\n \".md\": \"text/markdown\",\n \".csv\": \"text/csv\",\n \".json\": \"application/json\",\n \".html\": \"text/html\",\n \".htm\": \"text/html\",\n \".zip\": \"application/zip\",\n \".doc\": \"application/msword\",\n \".docx\": \"application/vnd.openxmlformats-officedocument.wordprocessingml.document\",\n \".xls\": \"application/vnd.ms-excel\",\n \".xlsx\": \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\",\n};\n\nexport function mimeTypeForPath(filePath: string): string {\n return MIME_TYPES[extname(filePath).toLowerCase()] ?? \"application/octet-stream\";\n}\n\nfunction startsWith(\n bytes: Uint8Array,\n signature: readonly number[],\n offset = 0,\n): boolean {\n return signature.every((byte, index) => bytes[offset + index] === byte);\n}\n\nexport function detectImageMimeType(bytes: Uint8Array): string | undefined {\n if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))\n return \"image/png\";\n if (startsWith(bytes, [0xff, 0xd8, 0xff])) return \"image/jpeg\";\n if (\n startsWith(bytes, [0x47, 0x49, 0x46, 0x38, 0x37, 0x61])\n || startsWith(bytes, [0x47, 0x49, 0x46, 0x38, 0x39, 0x61])\n ) return \"image/gif\";\n if (\n startsWith(bytes, [0x52, 0x49, 0x46, 0x46])\n && startsWith(bytes, [0x57, 0x45, 0x42, 0x50], 8)\n ) return \"image/webp\";\n return undefined;\n}\n\nexport function parseInlineImageSpecs(\n specs: readonly string[],\n options: { maxContentIdLength: number; commandLabel: string },\n): Array<{ contentId: string; path: string }> {\n const contentIds = new Set<string>();\n return specs.map((spec) => {\n const separator = spec.indexOf(\"=\");\n if (separator <= 0 || separator === spec.length - 1) {\n throw new Error(`${options.commandLabel}: --inline-image must use CONTENT_ID=PATH.`);\n }\n const contentId = spec.slice(0, separator).trim();\n if (contentId.length > options.maxContentIdLength\n || !/^[A-Za-z0-9][A-Za-z0-9._@-]*$/u.test(contentId)) {\n throw new Error(`${options.commandLabel}: inline image Content-ID must start with a letter or number and use only letters, numbers, ., _, @, or - (maximum ${options.maxContentIdLength} characters).`);\n }\n if (contentIds.has(contentId)) {\n throw new Error(`${options.commandLabel}: duplicate inline image Content-ID '${contentId}'.`);\n }\n contentIds.add(contentId);\n return { contentId, path: spec.slice(separator + 1) };\n });\n}\n\nexport function readOutgoingEmailAttachment(\n path: string,\n options: {\n maxBytes: number;\n maxFilenameLength: number;\n contentId?: string;\n requireImage?: boolean;\n commandLabel: string;\n },\n): NotificationEmailAttachmentInput {\n let bytes: Buffer;\n try {\n bytes = readFileSync(path);\n } catch (error) {\n const detail = error instanceof Error ? error.message : String(error);\n throw new Error(`${options.commandLabel}: could not read attachment '${path}': ${detail}`);\n }\n if (bytes.byteLength > options.maxBytes) {\n throw new Error(\n `${options.commandLabel}: attachment '${path}' must be ${options.maxBytes} bytes or smaller.`,\n );\n }\n const detectedImageMimeType = detectImageMimeType(bytes);\n if (options.requireImage && !detectedImageMimeType) {\n throw new Error(\n `${options.commandLabel}: image '${path}' must be PNG, JPEG, GIF, or WebP.`,\n );\n }\n const filename = basename(path);\n if (!filename || filename.length > options.maxFilenameLength) {\n throw new Error(\n `${options.commandLabel}: attachment filename must be 1-${options.maxFilenameLength} characters.`,\n );\n }\n const hasAsciiControlCharacter = Array.from(filename).some((character) => {\n const code = character.charCodeAt(0);\n return code < 0x20 || code === 0x7f;\n });\n if (hasAsciiControlCharacter || /[/\\\\]/.test(filename)) {\n throw new Error(\n `${options.commandLabel}: attachment filename must not contain ASCII control characters or path separators.`,\n );\n }\n return {\n filename,\n mimeType: detectedImageMimeType ?? mimeTypeForPath(path),\n data: bytes.toString(\"base64\"),\n ...(options.contentId ? { contentId: options.contentId } : {}),\n };\n}\n", "// Readable sourceCreatedAt parsing for activity/task backfill. Ports\n// source_created_at.py.\n\nexport interface SourceCreatedAt {\n date: string;\n time: string | null;\n timezone: string;\n}\n\nconst DATE_ONLY = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\nconst DATE_TIME = /^(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2})$/;\n\nfunction valid(year: number, month: number, day: number, hour = 0, minute = 0): boolean {\n if (month < 1 || month > 12 || day < 1 || day > 31 || hour > 23 || minute > 59) return false;\n const d = new Date(Date.UTC(year, month - 1, day));\n return d.getUTCFullYear() === year && d.getUTCMonth() + 1 === month && d.getUTCDate() === day;\n}\n\nexport function parseSourceCreatedAt(value: string, timezone = \"Europe/Berlin\"): SourceCreatedAt {\n const dt = DATE_TIME.exec(value);\n if (dt) {\n const [year, month, day, hour, minute] = dt.slice(1).map(Number) as [number, number, number, number, number];\n if (!valid(year, month, day, hour, minute)) throw new Error(`Invalid --source-created-at value: ${value}`);\n return {\n date: `${dt[1]}-${dt[2]}-${dt[3]}`,\n time: `${dt[4]}:${dt[5]}`,\n timezone,\n };\n }\n\n const d = DATE_ONLY.exec(value);\n if (d) {\n const [year, month, day] = d.slice(1).map(Number) as [number, number, number];\n if (!valid(year, month, day)) throw new Error(`Invalid --source-created-at value: ${value}`);\n return { date: `${d[1]}-${d[2]}-${d[3]}`, time: null, timezone };\n }\n\n throw new Error(\"--source-created-at must be YYYY-MM-DD or YYYY-MM-DDTHH:mm\");\n}\n", "// Human-friendly deadline parsing \u2192 epoch milliseconds. All bare dates/times are\n// interpreted in Europe/Berlin. Ports deadline.py 1:1.\n\nimport { berlinToEpochMs, berlinToday } from \"./datetime.ts\";\n\nconst DEFAULT_HOUR = 22;\nconst DEFAULT_MINUTE = 0;\n\nfunction addDaysToBerlinToday(days: number): { year: number; month: number; day: number } {\n const t = berlinToday();\n const dt = new Date(Date.UTC(t.year, t.month - 1, t.day) + days * 86_400_000);\n return { year: dt.getUTCFullYear(), month: dt.getUTCMonth() + 1, day: dt.getUTCDate() };\n}\n\nfunction parseTimeOrDefault(s: string): [number, number] {\n if (!s) return [DEFAULT_HOUR, DEFAULT_MINUTE];\n const m = /^(\\d{1,2}):(\\d{2})$/.exec(s);\n if (!m) throw new Error(`Invalid time format: '${s}'. Use HH:MM (e.g. 14:00).`);\n const hour = Number(m[1]);\n const minute = Number(m[2]);\n if (hour > 23 || minute > 59) throw new Error(`Invalid time format: '${s}'.`);\n return [hour, minute];\n}\n\nfunction validateDate(year: number, month: number, day: number, original: string): void {\n if (month < 1 || month > 12 || day < 1 || day > 31) {\n throw new Error(`Invalid date: '${original}'.`);\n }\n const d = new Date(Date.UTC(year, month - 1, day));\n if (d.getUTCFullYear() !== year || d.getUTCMonth() + 1 !== month || d.getUTCDate() !== day) {\n throw new Error(`Invalid date: '${original}' \u2014 day ${day} does not exist in month ${month}.`);\n }\n}\n\n/** Parse a human-friendly deadline string to epoch milliseconds. */\nexport function parseDeadline(input: string): number {\n const trimmed = input.trim().toLowerCase();\n\n if (trimmed.startsWith(\"tomorrow\")) {\n const [hour, minute] = parseTimeOrDefault(trimmed.slice(\"tomorrow\".length).trim());\n const t = addDaysToBerlinToday(1);\n return berlinToEpochMs(t.year, t.month, t.day, hour, minute);\n }\n\n if (trimmed.startsWith(\"today\")) {\n const [hour, minute] = parseTimeOrDefault(trimmed.slice(\"today\".length).trim());\n const t = addDaysToBerlinToday(0);\n return berlinToEpochMs(t.year, t.month, t.day, hour, minute);\n }\n\n const rel = /^\\+(\\d+)\\s*(days?|weeks?)$/.exec(trimmed);\n if (rel) {\n const n = Number(rel[1]);\n const days = rel[2]!.startsWith(\"week\") ? n * 7 : n;\n const t = addDaysToBerlinToday(days);\n return berlinToEpochMs(t.year, t.month, t.day, DEFAULT_HOUR, DEFAULT_MINUTE);\n }\n\n const iso = /^(\\d{4})-(\\d{2})-(\\d{2})t(\\d{2}):(\\d{2})(?::(\\d{2}))?(?:z|([+-])(\\d{2}):(\\d{2}))$/.exec(\n trimmed,\n );\n if (iso) {\n const year = Number(iso[1]);\n const month = Number(iso[2]);\n const day = Number(iso[3]);\n const hour = Number(iso[4]);\n const minute = Number(iso[5]);\n const second = iso[6] ? Number(iso[6]) : 0;\n validateDate(year, month, day, input);\n if (hour > 23 || minute > 59 || second > 59) throw new Error(`Invalid time in deadline: '${input}'.`);\n let offsetMs = 0;\n if (iso[7]) {\n const sign = iso[7] === \"-\" ? -1 : 1;\n offsetMs = sign * (Number(iso[8]) * 60 + Number(iso[9])) * 60_000;\n }\n return Date.UTC(year, month - 1, day, hour, minute, second) - offsetMs;\n }\n\n const date = /^(\\d{4})-(\\d{2})-(\\d{2})(?:\\s+(\\d{1,2}):(\\d{2}))?$/.exec(trimmed);\n if (date) {\n const year = Number(date[1]);\n const month = Number(date[2]);\n const day = Number(date[3]);\n validateDate(year, month, day, input);\n const hour = date[4] ? Number(date[4]) : DEFAULT_HOUR;\n const minute = date[5] ? Number(date[5]) : DEFAULT_MINUTE;\n if (hour > 23 || minute > 59) throw new Error(`Invalid time in deadline: '${input}'.`);\n return berlinToEpochMs(year, month, day, hour, minute);\n }\n\n throw new Error(\n `Cannot parse deadline '${input}'. ` +\n 'Accepted: \"tomorrow\", \"today\", \"+3 days\", \"+1 week\", ' +\n '\"2026-03-15\", \"2026-03-15 14:00\", \"2026-03-15T14:00:00+01:00\"',\n );\n}\n\n/** Default deadline: tomorrow 22:00 Berlin. */\nexport function defaultDeadline(): number {\n const t = addDaysToBerlinToday(1);\n return berlinToEpochMs(t.year, t.month, t.day, DEFAULT_HOUR, DEFAULT_MINUTE);\n}\n", "// Task commands \u2014 list, get, create, update, done, assign, unassign,\n// set-assignees, clear-assignees. Ports commands/task.py. Tasks are activities\n// with type \"task\"; they carry a deadline, completion, short-id (#N), assignees.\n//\n// `task list` / `tasks` stay on the REST transport (ClientCommand). Every\n// other command here calls the SAME public `api.activities.*` functions the\n// web app uses, via the JWT bridge (see ../convexClient.ts) \u2014 no\n// per-capability REST endpoint, and no more rich 422 explainer (REST-only\n// affordance); backend errors just bubble to ProfileCommand's error boundary.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { applyAssignee, ProfileCommand, ClientCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport type { ConvexCaller } from \"../../core/convex.ts\";\nimport { endOfTodayBerlin } from \"../datetime.ts\";\nimport { defaultDeadline, parseDeadline } from \"../deadline.ts\";\nimport { formatTaskDetail, formatTaskList, jsonWithSpaces } from \"../format.ts\";\nimport { resolveEntity } from \"../resolve.ts\";\nimport {\n membershipsListForSpace,\n resolveAssigneeEmailsToIds,\n resolveEntitiesC,\n resolveSpaceByNameC,\n spacesFooterFromMemberships,\n withFooter,\n} from \"../convexResolve.ts\";\nimport { parseAttrs } from \"../attrs.ts\";\nimport { parseSourceCreatedAt, type SourceCreatedAt } from \"../source-created-at.ts\";\nimport type { TaskItem, UsersMap } from \"../types.ts\";\n\n// --- rich-activity shape (wire contract with convex/activities.ts) ---------\n\ninterface EntityRefLite {\n _id: string;\n name: string;\n [key: string]: unknown;\n}\n\ninterface ActivityRich {\n _id: string;\n type: string;\n title?: string;\n contentPlainText?: string;\n createdAt: number;\n deadline?: number;\n completed?: boolean;\n shortId?: number;\n attributes?: Record<string, unknown>;\n tags?: string[];\n assigneeIds?: string[];\n spaceId: string;\n entityDetails: Array<EntityRefLite | null>;\n [key: string]: unknown;\n}\n\nfunction toTaskItem(rich: ActivityRich): TaskItem {\n return {\n activity: {\n _id: rich._id,\n type: rich.type,\n title: rich.title,\n contentPlainText: rich.contentPlainText,\n createdAt: rich.createdAt,\n deadline: rich.deadline,\n completed: rich.completed,\n shortId: rich.shortId,\n attributes: rich.attributes,\n tags: rich.tags,\n entityIds: rich.entityDetails.map((e) => e?._id).filter((id): id is string => !!id),\n assigneeIds: rich.assigneeIds,\n },\n entities: rich.entityDetails.filter((e): e is EntityRefLite => e !== null).map((e) => ({ name: e.name, _id: e._id })),\n };\n}\n\nasync function usersMapForAssignees(caller: ConvexCaller, rich: ActivityRich): Promise<UsersMap> {\n if (!rich.assigneeIds || rich.assigneeIds.length === 0) return {};\n const members = await caller.query(membershipsListForSpace, { spaceId: rich.spaceId });\n const users: UsersMap = {};\n for (const m of members) {\n if (m.user) users[m.user._id] = { name: m.user.name, email: m.user.email };\n }\n return users;\n}\n\n// --- typed function references (convex/activities.ts) -----------------------\n\nconst activitiesFindTaskByShortId = makeFunctionReference<\"query\", { shortId: number }, string | null>(\n \"activities:findTaskByShortId\",\n);\nconst activitiesGetByIdRich = makeFunctionReference<\n \"query\",\n { activityId: string },\n ActivityRich | null\n>(\"activities:getByIdRich\");\nconst activitiesCreate = makeFunctionReference<\n \"mutation\",\n {\n entityId?: string;\n additionalEntities?: string[];\n ownerSpaceId: string;\n grantMissingEntityAccess?: boolean;\n entitySpaceGrantFingerprint?: string;\n type: string;\n title?: string;\n deadline?: number;\n assigneeIds?: string[];\n contentMarkdown?: string;\n tags?: string[];\n },\n string\n>(\"activities:create\");\nconst activitiesSetAttribute = makeFunctionReference<\n \"mutation\",\n { activityId: string; key: string; value: string },\n null\n>(\"activities:setAttribute\");\nconst activitiesUpdateCreatedAt = makeFunctionReference<\n \"mutation\",\n { activityId: string; sourceCreatedAt: SourceCreatedAt },\n null\n>(\"activities:updateCreatedAt\");\nconst activitiesUpdateTitle = makeFunctionReference<\n \"mutation\",\n { activityId: string; title?: string },\n null\n>(\"activities:updateTitle\");\nconst activitiesSetContentFromMarkdown = makeFunctionReference<\n \"mutation\",\n { activityId: string; markdown: string },\n null\n>(\"activities:setContentFromMarkdown\");\nconst activitiesUpdateDeadline = makeFunctionReference<\n \"mutation\",\n { activityId: string; deadline?: number },\n null\n>(\"activities:updateDeadline\");\nconst activitiesSetCompleted = makeFunctionReference<\n \"mutation\",\n { activityId: string; completed: boolean },\n null\n>(\"activities:setCompleted\");\nconst activitiesUpdateAssignees = makeFunctionReference<\n \"mutation\",\n { activityId: string; assigneeIds: string[] },\n null\n>(\"activities:updateAssignees\");\n\nfunction parseShortId(idStr: string): number | null {\n const cleaned = idStr.replace(/^#/, \"\");\n return /^\\d+$/.test(cleaned) ? Number(cleaned) : null;\n}\n\n/** Resolve a shortId (#N, open tasks only) or pass a raw activity ID through. */\nasync function resolveTaskIdC(caller: ConvexCaller, idStr: string): Promise<string> {\n const num = parseShortId(idStr);\n if (num === null) return idStr;\n const activityId = await caller.query(activitiesFindTaskByShortId, { shortId: num });\n if (!activityId) throw new Error(`No open task found with short ID #${num}.`);\n return activityId;\n}\n\nasync function getRichTask(caller: ConvexCaller, idStr: string): Promise<ActivityRich> {\n const activityId = await resolveTaskIdC(caller, idStr);\n const rich = await caller.query(activitiesGetByIdRich, { activityId });\n if (!rich) throw new Error(`No task found with ID \"${idStr}\".`);\n return rich;\n}\n\n// --- task list / tasks alias (stay on REST) ---------------------------------\n\nclass TaskListCmd extends ClientCommand {\n static paths = [[\"task\", \"list\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"List open tasks\" });\n\n due = Option.String(\"--due\", { description: \"Filter: today, overdue, all\" });\n entity = Option.String(\"--entity\", { description: \"Filter by entity (name or ID)\" });\n assignee = Option.String(\"--assignee\", {\n description: \"Filter by assignee: me, meOrUnassigned, unassigned, user ID, or email\",\n });\n\n async run(): Promise<number | void> {\n const client = this.client();\n const params: Record<string, string> = { onlyOpen: \"true\" };\n if (this.entity) params.entityId = await resolveEntity(client, this.entity);\n applyAssignee(params, this.assignee);\n\n if (this.due === \"all\") params.onlyOpen = \"false\";\n else if (this.due === \"today\") params.dueBy = String(endOfTodayBerlin());\n else if (this.due === \"overdue\") params.dueBy = String(Date.now());\n else if (this.due) {\n this.err(`Unknown --due value: '${this.due}'. Use: today, overdue, or all.`);\n return 1;\n }\n\n const res = await client.listTasks(params);\n const tasks = (res.data ?? []).slice();\n const users = res.users ?? {};\n const spaces = await client.listSpaces();\n tasks.sort(\n (a, b) =>\n (a.activity?.deadline ?? Number.POSITIVE_INFINITY) -\n (b.activity?.deadline ?? Number.POSITIVE_INFINITY),\n );\n\n this.emitText(jsonWithSpaces(res, spaces), () =>\n this.withFooter(formatTaskList(tasks, users), spaces),\n );\n }\n}\n\n// Top-level `ente tasks` \u2014 open tasks sorted by deadline (alias).\nclass TasksAlias extends ClientCommand {\n static paths = [[\"tasks\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"List open tasks sorted by deadline\" });\n\n assignee = Option.String(\"--assignee\", {\n description: \"Filter by assignee: me, meOrUnassigned, unassigned, user ID, or email\",\n });\n\n async run(): Promise<number | void> {\n await this.runActivityList({\n typeFilter: \"task\",\n onlyOpen: true,\n sort: \"deadline\",\n assignee: this.assignee,\n });\n }\n}\n\n// --- migrated (Convex) commands ---------------------------------------------\n\nclass TaskGet extends ProfileCommand {\n static paths = [[\"task\", \"get\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Get task by shortId (#N) or activity ID\" });\n\n id = Option.String();\n space = Option.String(\"--space\", { description: \"Filter by space to disambiguate shortIds\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n if (this.space) {\n this.err(\n \"Note: --space is not used with the Convex-backed task lookup (short IDs resolve across all your spaces).\",\n );\n }\n const rich = await getRichTask(caller, this.id);\n const taskItem = toTaskItem(rich);\n const users = await usersMapForAssignees(caller, rich);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: taskItem, users }, spaces), () =>\n withFooter(formatTaskDetail(taskItem, users), spaces),\n );\n }\n}\n\nclass TaskCreate extends ProfileCommand {\n static paths = [[\"task\", \"create\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Create a task\" });\n\n title = Option.String();\n entity = Option.Array(\"--entity\", { required: true, description: \"Linked entities (resolved by name)\" });\n space = Option.String(\"--space\", { required: true, description: \"Space to create in (name or ID)\" });\n deadline = Option.String(\"--deadline\", { description: \"Deadline (human-friendly)\" });\n noDeadline = Option.Boolean(\"--no-deadline\", false, {\n description: \"Create the task with no deadline (skip the default of tomorrow 22:00)\",\n });\n tag = Option.Array(\"--tag\", { description: \"Tags (repeatable)\" });\n attr = Option.Array(\"--attr\", { description: \"Attributes as key=value pairs\" });\n content = Option.String(\"--content\", { description: \"Task content/description\" });\n sourceCreatedAt = Option.String(\"--source-created-at\", {\n description: \"Import/backfill timestamp: YYYY-MM-DD or YYYY-MM-DDTHH:mm\",\n });\n sourceCreatedAtTimezone = Option.String(\"--source-created-at-timezone\", \"Europe/Berlin\", {\n description: \"IANA timezone for --source-created-at\",\n });\n assignee = Option.Array(\"--assignee\", { description: \"Assignee user IDs or emails\" });\n assigneeEmail = Option.Array(\"--assignee-email\", { description: \"Assignee emails\" });\n autoLink = Option.Boolean(\"--auto-link\", false, { description: \"Auto-link entities not in target space\" });\n entitySpaceGrantFingerprint = Option.String(\"--entity-space-grant-fingerprint\", {\n description: \"Exact grant fingerprint returned by the confirmation-required error\",\n });\n\n async run(): Promise<number | void> {\n if (this.noDeadline && this.deadline) {\n throw new Error(\"Use either --deadline or --no-deadline, not both.\");\n }\n const caller = await resolveCaller();\n const entityIds = await resolveEntitiesC(caller, this.entity);\n const spaceId = await resolveSpaceByNameC(caller, this.space);\n const deadline = this.noDeadline\n ? undefined\n : this.deadline\n ? parseDeadline(this.deadline)\n : defaultDeadline();\n const attributes = parseAttrs(this.attr);\n\n const directAssigneeIds = (this.assignee ?? []).filter((v) => !v.includes(\"@\"));\n const emailAssignees = [\n ...(this.assignee ?? []).filter((v) => v.includes(\"@\")),\n ...(this.assigneeEmail ?? []),\n ];\n const resolvedFromEmails = await resolveAssigneeEmailsToIds(caller, spaceId, emailAssignees);\n const assigneeIds = [...new Set([...directAssigneeIds, ...resolvedFromEmails])];\n\n const activityId = await caller.mutation(activitiesCreate, {\n entityId: entityIds[0],\n additionalEntities: entityIds.slice(1),\n ownerSpaceId: spaceId,\n grantMissingEntityAccess: this.autoLink,\n ...(this.entitySpaceGrantFingerprint\n ? { entitySpaceGrantFingerprint: this.entitySpaceGrantFingerprint }\n : {}),\n type: \"task\",\n title: this.title,\n ...(deadline !== undefined ? { deadline } : {}),\n ...(assigneeIds.length ? { assigneeIds } : {}),\n ...(this.tag && this.tag.length ? { tags: this.tag } : {}),\n ...(this.content !== undefined ? { contentMarkdown: this.content } : {}),\n });\n\n for (const [key, value] of Object.entries(attributes)) {\n await caller.mutation(activitiesSetAttribute, { activityId, key, value });\n }\n if (this.sourceCreatedAt) {\n const sourceCreatedAt = parseSourceCreatedAt(this.sourceCreatedAt, this.sourceCreatedAtTimezone);\n await caller.mutation(activitiesUpdateCreatedAt, { activityId, sourceCreatedAt });\n }\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { activityId } }, spaces), () =>\n withFooter(`Created task '${this.title}' (${activityId})`, spaces),\n );\n }\n}\n\nclass TaskUpdate extends ProfileCommand {\n static paths = [[\"task\", \"update\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Update a task\" });\n\n id = Option.String();\n title = Option.String(\"--title\", { description: \"Update title\" });\n content = Option.String(\"--content\", { description: \"Update content\" });\n attr = Option.Array(\"--attr\", { description: \"Set attributes as key=value pairs\" });\n deadline = Option.String(\"--deadline\", { description: \"Update deadline (human-friendly)\" });\n\n async run(): Promise<number | void> {\n const attributes = parseAttrs(this.attr);\n if (\n this.title === undefined &&\n this.content === undefined &&\n this.deadline === undefined &&\n Object.keys(attributes).length === 0\n ) {\n this.err(\"Nothing to update. Specify --title, --content, --attr, or --deadline.\");\n return 1;\n }\n\n const caller = await resolveCaller();\n const activityId = await resolveTaskIdC(caller, this.id);\n\n if (this.title !== undefined) await caller.mutation(activitiesUpdateTitle, { activityId, title: this.title });\n if (this.content !== undefined) await caller.mutation(activitiesSetContentFromMarkdown, { activityId, markdown: this.content });\n if (this.deadline) await caller.mutation(activitiesUpdateDeadline, { activityId, deadline: parseDeadline(this.deadline) });\n for (const [key, value] of Object.entries(attributes)) {\n await caller.mutation(activitiesSetAttribute, { activityId, key, value });\n }\n\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, activityId } }, spaces), () =>\n withFooter(`Updated task ${this.id}`, spaces),\n );\n }\n}\n\nclass TaskDone extends ProfileCommand {\n static paths = [[\"task\", \"done\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Mark task as completed\" });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const activityId = await resolveTaskIdC(caller, this.id);\n await caller.mutation(activitiesSetCompleted, { activityId, completed: true });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, activityId } }, spaces), () =>\n withFooter(`Task ${this.id} marked as done.`, spaces),\n );\n }\n}\n\nclass TaskAssign extends ProfileCommand {\n static paths = [[\"task\", \"assign\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Add assignee to task\" });\n\n id = Option.String();\n userId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rich = await getRichTask(caller, this.id);\n const activityId = rich._id;\n const current = rich.assigneeIds ?? [];\n\n let newUserId = this.userId;\n if (this.userId.includes(\"@\")) {\n const [resolved] = await resolveAssigneeEmailsToIds(caller, rich.spaceId, [this.userId]);\n newUserId = resolved!;\n }\n\n if (current.includes(newUserId)) {\n this.out(\"User is already assigned.\");\n return;\n }\n\n const updated = [...current, newUserId];\n await caller.mutation(activitiesUpdateAssignees, { activityId, assigneeIds: updated });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(\n jsonWithSpaces({ data: { success: true, activityId, assigneeIds: updated } }, spaces),\n () => withFooter(`Assigned ${this.userId} to task ${this.id}.`, spaces),\n );\n }\n}\n\nclass TaskUnassign extends ProfileCommand {\n static paths = [[\"task\", \"unassign\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Remove assignee from task\" });\n\n id = Option.String();\n userId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rich = await getRichTask(caller, this.id);\n const activityId = rich._id;\n const current = rich.assigneeIds ?? [];\n\n let targetId = this.userId;\n if (this.userId.includes(\"@\")) {\n const members = await caller.query(membershipsListForSpace, { spaceId: rich.spaceId });\n const match = members.find((m) => (m.user?.email ?? \"\").toLowerCase() === this.userId.toLowerCase());\n if (!match || !match.user || !current.includes(match.user._id)) {\n this.out(\"User is not assigned to this task.\");\n return;\n }\n targetId = match.user._id;\n } else if (!current.includes(this.userId)) {\n this.out(\"User is not assigned to this task.\");\n return;\n }\n\n const updated = current.filter((uid) => uid !== targetId);\n await caller.mutation(activitiesUpdateAssignees, { activityId, assigneeIds: updated });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(\n jsonWithSpaces({ data: { success: true, activityId, assigneeIds: updated } }, spaces),\n () => withFooter(`Unassigned ${this.userId} from task ${this.id}.`, spaces),\n );\n }\n}\n\nclass TaskSetAssignees extends ProfileCommand {\n static paths = [[\"task\", \"set-assignees\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Replace all assignees on a task\" });\n\n id = Option.String();\n assignee = Option.Array(\"--assignee\", { description: \"Assignee user IDs or emails\" });\n assigneeEmail = Option.Array(\"--assignee-email\", { description: \"Assignee emails\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rich = await getRichTask(caller, this.id);\n const activityId = rich._id;\n\n const values = this.assignee ?? [];\n const directIds = values.filter((v) => !v.includes(\"@\"));\n const emails = [...values.filter((v) => v.includes(\"@\")), ...(this.assigneeEmail ?? [])];\n const resolvedIds = await resolveAssigneeEmailsToIds(caller, rich.spaceId, emails);\n const assigneeIds = [...new Set([...directIds, ...resolvedIds])];\n\n await caller.mutation(activitiesUpdateAssignees, { activityId, assigneeIds });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data: { success: true, activityId } }, spaces), () =>\n withFooter(`Updated assignees for task ${this.id}.`, spaces),\n );\n }\n}\n\nclass TaskClearAssignees extends ProfileCommand {\n static paths = [[\"task\", \"clear-assignees\"]];\n static usage = Command.Usage({ category: \"Task\", description: \"Clear all assignees from a task\" });\n\n id = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const activityId = await resolveTaskIdC(caller, this.id);\n await caller.mutation(activitiesUpdateAssignees, { activityId, assigneeIds: [] });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(\n jsonWithSpaces({ data: { success: true, activityId, assigneeIds: [] } }, spaces),\n () => withFooter(`Cleared assignees for task ${this.id}.`, spaces),\n );\n }\n}\n\nexport const TASK_COMMANDS = [\n TaskListCmd,\n TaskGet,\n TaskCreate,\n TaskUpdate,\n TaskDone,\n TaskAssign,\n TaskUnassign,\n TaskSetAssignees,\n TaskClearAssignees,\n TasksAlias,\n];\n", "// `ente list \u2026` \u2014 Notion-style database lists. A list is an entity (topic or\n// project) carrying a `databaseView` (columns/filters/sorts); each row is an\n// activity linked to that entity, its column values stored in the activity's\n// attributes. Like every migrated command this calls the SAME public `api.*`\n// functions the web \"database\" tab uses (entities.create/updateDatabaseView,\n// activities.create/setAttributeValue/listEntityDatabaseRowsPaginated) via the\n// JWT bridge \u2014 no per-capability REST endpoint. Name\u2192ID resolution reuses the\n// REST resolvers (this.client()).\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { parseAttrs } from \"../attrs.ts\";\nimport { ClientCommand } from \"../command.ts\";\nimport { readContentOption } from \"../content.ts\";\nimport { parseDeadline } from \"../deadline.ts\";\nimport { resolveEntity, resolveSpaceByName } from \"../resolve.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\n\n// --- databaseView shapes (mirror convex/schema/shared.ts) -----------------\nconst COLUMN_TYPES = [\"text\", \"number\", \"boolean\", \"single-select\", \"multi-select\"] as const;\ntype ColumnType = (typeof COLUMN_TYPES)[number];\nconst SELECT_TYPES = new Set<ColumnType>([\"single-select\", \"multi-select\"]);\n\ninterface SelectOption {\n value: string;\n label?: string;\n color?: string;\n}\ninterface Column {\n key: string;\n label?: string;\n type: ColumnType;\n options?: SelectOption[];\n}\ninterface DatabaseView {\n version: 1;\n columns: Column[];\n filters: unknown[];\n sorts: unknown[];\n}\n/** A database list opens on its table; the activity feed stays one tap away. */\nconst DATABASE_LIST_TABS = [\"database\", \"activities\"];\ntype DbValue = string | number | boolean | string[] | null;\n\ninterface EntityDoc {\n _id: string;\n name: string;\n type: string;\n databaseView?: { version?: 1; columns?: Column[]; filters?: unknown[]; sorts?: unknown[] } | null;\n}\ninterface SpaceDoc {\n _id: string;\n name: string;\n}\ninterface RowActivity {\n _id: string;\n title?: string | null;\n type: string;\n attributes?: Record<string, DbValue> | null;\n}\n\n// --- public function references (wire contract with convex/*.ts) ----------\nconst entitiesCreate = makeFunctionReference<\n \"mutation\",\n { spaceId: string; name?: string; type?: string },\n string\n>(\"entities:create\");\nconst updateDatabaseView = makeFunctionReference<\n \"mutation\",\n { id: string; databaseView: DatabaseView },\n null\n>(\"entities:updateDatabaseView\");\nconst setDescriptionFromMarkdown = makeFunctionReference<\n \"mutation\",\n { entityId: string; markdown: string },\n null\n>(\"entities:setDescriptionFromMarkdown\");\nconst setEnabledTabs = makeFunctionReference<\n \"mutation\",\n { entityId: string; enabledTabs: string[] },\n null\n>(\"entities:setEnabledTabs\");\nconst setCustomIcon = makeFunctionReference<\n \"mutation\",\n { id: string; icon: string | null },\n null\n>(\"entities:setCustomIcon\");\nconst removeDatabaseColumn = makeFunctionReference<\n \"mutation\",\n { id: string; key: string; databaseView: DatabaseView },\n null\n>(\"entities:removeDatabaseColumn\");\nconst findById = makeFunctionReference<\"query\", { id: string }, EntityDoc | null>(\n \"entities:findById\",\n);\nconst listSpacesForEntity = makeFunctionReference<\"query\", { entityId: string }, SpaceDoc[]>(\n \"entities:listSpacesForEntity\",\n);\nconst activitiesCreate = makeFunctionReference<\n \"mutation\",\n {\n entityId?: string;\n ownerSpaceId: string;\n type: string;\n title?: string;\n deadline?: number;\n contentMarkdown?: string;\n },\n string\n>(\"activities:create\");\nconst setAttributeValue = makeFunctionReference<\n \"mutation\",\n { activityId: string; key: string; value: DbValue },\n null\n>(\"activities:setAttributeValue\");\nconst listRows = makeFunctionReference<\n \"query\",\n { entityId: string; paginationOpts: { numItems: number; cursor: string | null } },\n { page: RowActivity[]; isDone: boolean; continueCursor: string }\n>(\"activities:listEntityDatabaseRowsPaginated\");\n\n/**\n * Parse a `--column key[=Label]:type[:opt1,opt2,\u2026]` spec. The key is the\n * attribute name stored on every row (ascii, stable); the optional label is\n * what the table header shows and may carry umlauts, spaces, units.\n */\nfunction parseColumn(spec: string): Column {\n const parts = spec.split(\":\");\n const keyPart = (parts[0] ?? \"\").trim();\n const typeRaw = (parts[1] ?? \"\").trim();\n const optsCsv = parts.slice(2).join(\":\").trim();\n const eq = keyPart.indexOf(\"=\");\n const key = (eq === -1 ? keyPart : keyPart.slice(0, eq)).trim();\n const label = eq === -1 ? \"\" : keyPart.slice(eq + 1).trim();\n if (!key) throw new Error(`Invalid --column '${spec}': missing key.`);\n if (!/^[a-z0-9_-]+$/.test(key))\n throw new Error(`Invalid column key '${key}': use lowercase letters, numbers, '_' or '-'.`);\n if (eq !== -1 && !label) throw new Error(`Invalid --column '${spec}': empty label after '='.`);\n if (!COLUMN_TYPES.includes(typeRaw as ColumnType))\n throw new Error(`Invalid --column '${spec}': type must be one of ${COLUMN_TYPES.join(\", \")}.`);\n const type = typeRaw as ColumnType;\n const col: Column = { key, type };\n if (label) col.label = label;\n if (SELECT_TYPES.has(type)) {\n if (!optsCsv)\n throw new Error(`--column '${spec}': ${type} requires options, e.g. key:${type}:opt1,opt2.`);\n col.options = optsCsv\n .split(\",\")\n .map((v) => ({ value: v.trim() }))\n .filter((o) => o.value.length > 0);\n }\n return col;\n}\n\n/** Coerce a raw `--attr` string to the value type of its column. */\nfunction coerceValue(type: ColumnType, raw: string): DbValue {\n switch (type) {\n case \"number\": {\n const n = Number(raw);\n if (Number.isNaN(n)) throw new Error(`Value '${raw}' is not a number.`);\n return n;\n }\n case \"boolean\":\n return [\"true\", \"yes\", \"1\", \"on\"].includes(raw.trim().toLowerCase());\n case \"multi-select\":\n return raw\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n default:\n return raw;\n }\n}\n\nclass ListCreate extends ClientCommand {\n static paths = [[\"list\", \"create\"]];\n static usage = Command.Usage({\n category: \"List\",\n description:\n \"Create a database list (an entity with a databaseView; opens on its database view by default)\",\n examples: [\n [\n \"A Sarah-ideas list with a category column\",\n 'ente list create \"Sarah \u2013 Ideen\" --space Personal --column \"kategorie:single-select:Aktivit\u00E4t,Essen,Geschenk,Film\"',\n ],\n [\n \"A recipe collection with labelled columns and an icon\",\n 'ente list create Rezepte --space \"ivo&sarah\" --icon book-open --column \"protein_g=Protein (g):number\" --column \"vegan:boolean\"',\n ],\n ],\n });\n\n name = Option.String();\n space = Option.String(\"--space\", { required: true, description: \"Space to create in (name or ID)\" });\n type = Option.String(\"--type\", \"topic\", { description: \"Entity type: topic (default) or project\" });\n column = Option.Array(\"--column\", {\n description:\n \"Column: key[=Label]:type[:opt1,opt2] (type \u2208 text|number|boolean|single-select|multi-select)\",\n });\n description = Option.String(\"--description\", { description: \"Searchable description for the list\" });\n icon = Option.String(\"--icon\", {\n description: \"Entity icon as named in the web icon picker (e.g. book-open, leaf, star)\",\n });\n\n async run(): Promise<number | void> {\n if (this.type !== \"topic\" && this.type !== \"project\") {\n throw new Error(`--type must be 'topic' or 'project' (got '${this.type}').`);\n }\n const columns = (this.column ?? []).map(parseColumn);\n const spaceId = await resolveSpaceByName(this.client(), this.space);\n\n const caller = await resolveCaller();\n const entityId = await caller.mutation(entitiesCreate, {\n spaceId,\n name: this.name,\n type: this.type,\n });\n if (columns.length > 0) {\n await caller.mutation(updateDatabaseView, {\n id: entityId,\n databaseView: { version: 1, columns, filters: [], sorts: [] },\n });\n }\n // The list opens on its table: database first (= remembered default), feed second.\n await caller.mutation(setEnabledTabs, { entityId, enabledTabs: DATABASE_LIST_TABS });\n if (this.description) {\n await caller.mutation(setDescriptionFromMarkdown, { entityId, markdown: this.description });\n }\n if (this.icon) {\n await caller.mutation(setCustomIcon, { id: entityId, icon: this.icon });\n }\n\n this.emitText(\n { data: { entityId, name: this.name, type: this.type, columns, enabledTabs: DATABASE_LIST_TABS } },\n () =>\n `Created list '${this.name}' (${entityId}) with ${columns.length} column${\n columns.length === 1 ? \"\" : \"s\"\n }; opens on its database view.`,\n );\n }\n}\n\nclass ListAdd extends ClientCommand {\n static paths = [[\"list\", \"add\"]];\n static usage = Command.Usage({\n category: \"List\",\n description: \"Add a row (activity) to a database list\",\n examples: [\n [\n \"Add a categorised idea\",\n 'ente list add \"Sarah \u2013 Ideen\" --title \"Keramik bemalen\" --attr kategorie=Aktivit\u00E4t',\n ],\n [\n \"Add a recipe row whose body is the recipe\",\n 'ente list add Rezepte --title \"Tofu-Wraps\" --attr vegan=true --content-file tofu-wraps.md',\n ],\n ],\n });\n\n list = Option.String();\n title = Option.String(\"--title\", { description: \"Row title\" });\n type = Option.String(\"--type\", \"note\", { description: \"Row activity type: note (default) or task\" });\n attr = Option.Array(\"--attr\", { description: \"Column values as key=value (coerced to the column type)\" });\n deadline = Option.String(\"--deadline\", { description: \"Deadline (only meaningful for --type task)\" });\n space = Option.String(\"--space\", { description: \"Owner space (name or ID); default: the list's space\" });\n content = Option.String(\"--content\", { description: \"Row body as markdown\" });\n contentFile = Option.String(\"--content-file\", { description: \"Read the row body from a markdown file\" });\n\n async run(): Promise<number | void> {\n if (this.type !== \"note\" && this.type !== \"task\") {\n throw new Error(`--type must be 'note' or 'task' (got '${this.type}').`);\n }\n const client = this.client();\n const entityId = await resolveEntity(client, this.list);\n const caller = await resolveCaller();\n\n // Column types for coercion; fail loud on an unknown --attr key.\n const entity = await caller.query(findById, { id: entityId });\n if (!entity) throw new Error(`List '${this.list}' not found or not accessible.`);\n const columns = entity.databaseView?.columns ?? [];\n const columnByKey = new Map(columns.map((c) => [c.key, c]));\n\n const rawAttrs = parseAttrs(this.attr);\n const coerced: Array<{ key: string; value: DbValue }> = [];\n for (const [key, raw] of Object.entries(rawAttrs)) {\n const col = columnByKey.get(key);\n if (!col)\n throw new Error(\n `'${key}' is not a column of list '${entity.name}'. Columns: ${\n columns.map((c) => c.key).join(\", \") || \"(none)\"\n }. Add it with: ente list column add \"${entity.name}\" ${key}:text`,\n );\n coerced.push({ key, value: coerceValue(col.type, raw) });\n }\n\n const ownerSpaceId = await this.resolveOwnerSpace(entityId);\n const deadline =\n this.type === \"task\" && this.deadline ? parseDeadline(this.deadline) : undefined;\n const contentMarkdown = readContentOption(this.content, this.contentFile);\n\n const activityId = await caller.mutation(activitiesCreate, {\n entityId,\n ownerSpaceId,\n type: this.type,\n title: this.title,\n ...(deadline !== undefined ? { deadline } : {}),\n ...(contentMarkdown !== undefined ? { contentMarkdown } : {}),\n });\n for (const { key, value } of coerced) {\n await caller.mutation(setAttributeValue, { activityId, key, value });\n }\n\n this.emitText(\n { data: { activityId, entityId, title: this.title ?? null, attributes: Object.fromEntries(coerced.map((c) => [c.key, c.value])) } },\n () => `Added row '${this.title ?? \"(untitled)\"}' (${activityId}) to '${entity.name}'.`,\n );\n }\n\n /** Owner space for the row: explicit --space, else the list's sole space. */\n private async resolveOwnerSpace(entityId: string): Promise<string> {\n if (this.space) return resolveSpaceByName(this.client(), this.space);\n const caller = await resolveCaller();\n const spaces = await caller.query(listSpacesForEntity, { entityId });\n if (spaces.length === 0)\n throw new Error(\"The list is in no accessible space; pass --space explicitly.\");\n if (spaces.length > 1)\n throw new Error(\n `The list spans multiple spaces (${spaces\n .map((s) => s.name)\n .join(\", \")}); pass --space to choose one.`,\n );\n return spaces[0]!._id;\n }\n}\n\n/** The list entity plus its stored view with every part present, so a rewrite keeps filters and sorts. */\nasync function loadListView(\n entityId: string,\n listNameOrId: string,\n): Promise<{ entityId: string; entity: EntityDoc; view: DatabaseView }> {\n const caller = await resolveCaller();\n const entity = await caller.query(findById, { id: entityId });\n if (!entity) throw new Error(`List '${listNameOrId}' not found or not accessible.`);\n const stored = entity.databaseView;\n return {\n entityId,\n entity,\n view: {\n version: 1,\n columns: stored?.columns ?? [],\n filters: stored?.filters ?? [],\n sorts: stored?.sorts ?? [],\n },\n };\n}\n\nclass ListColumnAdd extends ClientCommand {\n static paths = [[\"list\", \"column\", \"add\"]];\n static usage = Command.Usage({\n category: \"List\",\n description: \"Add columns to an existing database list (filters and sorts are kept)\",\n examples: [[\"Add a labelled number column\", 'ente list column add Rezepte \"zeit_min=Zeit (min):number\"']],\n });\n\n list = Option.String();\n columns = Option.Rest({ required: 1 });\n\n async run(): Promise<number | void> {\n const { entityId, entity, view } = await loadListView(await resolveEntity(this.client(), this.list), this.list);\n const added = this.columns.map(parseColumn);\n const taken = new Set(view.columns.map((c) => c.key));\n for (const col of added) {\n if (taken.has(col.key)) throw new Error(`'${col.key}' is already a column of '${entity.name}'.`);\n taken.add(col.key);\n }\n const columns = [...view.columns, ...added];\n const caller = await resolveCaller();\n await caller.mutation(updateDatabaseView, { id: entityId, databaseView: { ...view, columns } });\n this.emitText(\n { data: { entityId, added, columns } },\n () => `Added ${added.length} column${added.length === 1 ? \"\" : \"s\"} to '${entity.name}': ${added\n .map((c) => c.key)\n .join(\", \")}.`,\n );\n }\n}\n\nclass ListColumnRemove extends ClientCommand {\n static paths = [[\"list\", \"column\", \"remove\"]];\n static usage = Command.Usage({\n category: \"List\",\n description: \"Remove columns from a database list; their values are erased from every row\",\n examples: [[\"Drop two columns\", \"ente list column remove Rezepte quelle kueche\"]],\n });\n\n list = Option.String();\n keys = Option.Rest({ required: 1 });\n\n async run(): Promise<number | void> {\n const { entityId, entity, view } = await loadListView(await resolveEntity(this.client(), this.list), this.list);\n const present = new Set(view.columns.map((c) => c.key));\n const missing = this.keys.filter((key) => !present.has(key));\n if (missing.length > 0) {\n throw new Error(\n `Not a column of '${entity.name}': ${missing.join(\", \")}. Columns: ${\n [...present].join(\", \") || \"(none)\"\n }.`,\n );\n }\n // Same mutation as the web column menu: it drops the column from the view\n // and erases that attribute from the linked rows (large lists continue in\n // scheduled batches). One call per key, each on the view as it then is.\n const caller = await resolveCaller();\n let current = view;\n for (const key of this.keys) {\n await caller.mutation(removeDatabaseColumn, { id: entityId, key, databaseView: current });\n current = { ...current, columns: current.columns.filter((c) => c.key !== key) };\n }\n this.emitText(\n { data: { entityId, removed: this.keys, columns: current.columns } },\n () => `Removed ${this.keys.length} column${this.keys.length === 1 ? \"\" : \"s\"} from '${\n entity.name\n }': ${this.keys.join(\", \")}.`,\n );\n }\n}\n\nclass ListShow extends ClientCommand {\n static paths = [[\"list\", \"show\"]];\n static usage = Command.Usage({\n category: \"List\",\n description: \"Show the rows of a database list\",\n });\n\n list = Option.String();\n limit = Option.String(\"--limit\", { description: \"Max rows (default 100)\" });\n\n async run(): Promise<number | void> {\n const entityId = await resolveEntity(this.client(), this.list);\n const caller = await resolveCaller();\n const numItems = this.limit ? Number(this.limit) : 100;\n const res = await caller.query(listRows, {\n entityId,\n paginationOpts: { numItems, cursor: null },\n });\n\n this.emitText({ data: { rows: res.page, isDone: res.isDone } }, () => {\n if (res.page.length === 0) return \"(no rows)\";\n return res.page\n .map((row) => {\n const attrs = row.attributes ?? {};\n const attrStr = Object.entries(attrs)\n .filter(([, v]) => v !== null && v !== undefined && !(Array.isArray(v) && v.length === 0))\n .map(([k, v]) => `${k}=${Array.isArray(v) ? v.join(\",\") : String(v)}`)\n .join(\" \");\n return `- ${row.title || \"(untitled)\"}${attrStr ? ` [${attrStr}]` : \"\"}`;\n })\n .join(\"\\n\");\n });\n }\n}\n\nexport const LIST_COMMANDS = [ListCreate, ListAdd, ListColumnAdd, ListColumnRemove, ListShow];\n", "// `ente users \u2026` \u2014 global admin user management (admin-only). Calls the SAME\n// public `api.admin.users.*` functions the in-app admin view uses, via the JWT\n// bridge (see ../convexClient.ts) \u2014 every call lands as the real authenticated\n// user, so the backend's admin gate applies. Non-admins get a `forbidden` error.\n//\n// ente users list\n// ente users set-admin <email> [--off]\n// ente users reset-password <email> [--password <pw>]\n// ente users set-plan <email> <free|sponsored|company_managed|own_models> [--company <id>]\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { formatDatetime } from \"../datetime.ts\";\nimport type { ConvexCaller } from \"../../core/convex.ts\";\n\ninterface AdminUser {\n id: string;\n email: string;\n name: string;\n isAdmin: boolean;\n isAnonymous: boolean;\n createdAt: number;\n planKey: string;\n billingStatus: string;\n}\n\nconst MANAGED_PLANS = [\"free\", \"sponsored\", \"company_managed\", \"own_models\"] as const;\ntype ManagedPlan = typeof MANAGED_PLANS[number];\n\ntype AdminUserPage = {\n page: AdminUser[];\n isDone: boolean;\n continueCursor: string;\n};\n\nconst listUsers = makeFunctionReference<\n \"query\",\n { paginationOpts: { numItems: number; cursor: string | null } },\n AdminUserPage\n>(\n \"admin/users:listUsers\",\n);\nconst setAdmin = makeFunctionReference<\"mutation\", { userId: string; isAdmin: boolean }, null>(\n \"admin/users:setAdmin\",\n);\nconst resetPassword = makeFunctionReference<\n \"action\",\n { userId: string; newPassword?: string },\n { password: string }\n>(\"admin/users:resetPassword\");\nconst changeUserPlan = makeFunctionReference<\n \"mutation\",\n { userId: string; planKey: ManagedPlan; companyBillingAccountId?: string },\n { changed: boolean; planKey: ManagedPlan }\n>(\"admin/users:changeUserPlan\");\n\nasync function listAllUsers(caller: ConvexCaller): Promise<AdminUser[]> {\n const users: AdminUser[] = [];\n let cursor: string | null = null;\n do {\n const result: AdminUserPage = await caller.query(listUsers, {\n paginationOpts: { numItems: 100, cursor },\n });\n users.push(...result.page);\n cursor = result.isDone ? null : result.continueCursor;\n } while (cursor !== null);\n return users;\n}\n\n/** Resolve a user by (case-insensitive) email via the admin user list. */\nasync function resolveUserByEmail(caller: ConvexCaller, email: string): Promise<AdminUser> {\n const needle = email.trim().toLowerCase();\n if (!needle) throw new Error(\"email must not be empty.\");\n const users = await listAllUsers(caller);\n const match = users.find((u) => u.email.toLowerCase() === needle);\n if (!match) throw new Error(`No user with email '${email}'.`);\n return match;\n}\n\n// \u2500\u2500 users list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass UsersListCommand extends ProfileCommand {\n static paths = [[\"users\", \"list\"]];\n static usage = Command.Usage({\n category: \"Users\",\n description: \"List all users with their admin flag (admin only)\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const users = await listAllUsers(caller);\n this.print(\n { data: users },\n () =>\n users.map((u) => ({\n email: u.email || \"(none)\",\n name: u.name || \"(none)\",\n is_admin: u.isAdmin ? \"yes\" : \"no\",\n plan: `${u.planKey} (${u.billingStatus})`,\n anon: u.isAnonymous ? \"yes\" : \"\",\n created: formatDatetime(u.createdAt),\n id: u.id,\n })),\n [\"email\", \"name\", \"is_admin\", \"plan\", \"anon\", \"created\", \"id\"],\n );\n }\n}\n\n// \u2500\u2500 users set-admin \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass UsersSetAdminCommand extends ProfileCommand {\n static paths = [[\"users\", \"set-admin\"]];\n static usage = Command.Usage({\n category: \"Users\",\n description: \"Grant (or --off to revoke) global admin for a user by email (admin only)\",\n });\n\n email = Option.String({ required: true, name: \"email\" });\n off = Option.Boolean(\"--off\", { description: \"Revoke admin instead of granting it\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const user = await resolveUserByEmail(caller, this.email);\n const isAdmin = !this.off;\n await caller.mutation(setAdmin, { userId: user.id, isAdmin });\n this.emitText({ data: { id: user.id, email: user.email, isAdmin } }, () =>\n `${isAdmin ? \"Granted\" : \"Revoked\"} admin for ${user.email}.`,\n );\n }\n}\n\n// \u2500\u2500 users reset-password \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass UsersResetPasswordCommand extends ProfileCommand {\n static paths = [[\"users\", \"reset-password\"]];\n static usage = Command.Usage({\n category: \"Users\",\n description: \"Reset a user's password by email; prints the new password (admin only)\",\n });\n\n email = Option.String({ required: true, name: \"email\" });\n password = Option.String(\"--password\", {\n description: \"Set this password (default: generate a strong random one)\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const user = await resolveUserByEmail(caller, this.email);\n const res = await caller.action(resetPassword, {\n userId: user.id,\n ...(this.password !== undefined ? { newPassword: this.password } : {}),\n });\n this.emitText({ data: { id: user.id, email: user.email, password: res.password } }, () =>\n `Reset password for ${user.email}.\\nNew password: ${res.password}`,\n );\n }\n}\n\n// \u2500\u2500 users set-plan \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass UsersSetPlanCommand extends ProfileCommand {\n static paths = [[\"users\", \"set-plan\"]];\n static usage = Command.Usage({\n category: \"Users\",\n description: \"Set a user's manually managed plan by email (admin only)\",\n details: `\n Plans: free, sponsored, company_managed (needs --company), own_models.\n own_models is the hidden \u20AC0 plan: the user brings their own model\n endpoints and Ente never calls its own model providers for them.\n Users whose Pro plan is billed through Stripe cannot be changed here.\n `,\n });\n\n email = Option.String({ required: true, name: \"email\" });\n plan = Option.String({ required: true, name: \"plan\" });\n company = Option.String(\"--company\", {\n description: \"Company billing account id (required for company_managed)\",\n });\n\n async run(): Promise<number | void> {\n if (!MANAGED_PLANS.includes(this.plan as ManagedPlan)) {\n throw new Error(`Unknown plan '${this.plan}'. Use one of: ${MANAGED_PLANS.join(\", \")}.`);\n }\n const planKey = this.plan as ManagedPlan;\n if (planKey === \"company_managed\" && !this.company) {\n throw new Error(\"company_managed needs --company <billing account id>.\");\n }\n const caller = await resolveCaller();\n const user = await resolveUserByEmail(caller, this.email);\n const res = await caller.mutation(changeUserPlan, {\n userId: user.id,\n planKey,\n ...(planKey === \"company_managed\" ? { companyBillingAccountId: this.company } : {}),\n });\n this.emitText({ data: { id: user.id, email: user.email, ...res } }, () =>\n res.changed\n ? `Set plan for ${user.email} to ${res.planKey}.`\n : `${user.email} already has plan ${res.planKey}.`,\n );\n }\n}\n\nexport const USERS_COMMANDS = [\n UsersListCommand,\n UsersSetAdminCommand,\n UsersResetPasswordCommand,\n UsersSetPlanCommand,\n];\n", "// `ente models \u2026` \u2014 own-models plan: the caller's model connections (OpenAI-\n// compatible endpoints such as a LiteLLM proxy) and which model serves each\n// Ente feature. Calls the same public `api.ownModels.*` functions as Settings.\n//\n// ente models status\n// ente models connection add <name> --base-url <url> --api-key-stdin\n// ente models connection update <name> [--base-url <url>] [--api-key-stdin]\n// ente models connection remove <name>\n// ente models set <slot> <connection-name> <model-id>\n// ente models clear <slot>\n// ente models test [slot]\n// ente models web-search <on|off>\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport type { ConvexCaller } from \"../../core/convex.ts\";\n\nconst SLOTS = [\"agent\", \"ask\", \"recording\", \"transcription\", \"summary\", \"small\"] as const;\ntype Slot = typeof SLOTS[number];\n\ntype Connection = { id: string; name: string; baseUrl: string; host: string; apiKeyHint: string };\ntype SlotRow = {\n slot: Slot;\n connectionId: string;\n model: string;\n status: \"untested\" | \"ok\" | \"error\";\n lastError: string | null;\n testedAt: number | null;\n};\ntype Settings = {\n ownModels: boolean;\n webSearchEnabled: boolean;\n connections: Connection[];\n slots: SlotRow[];\n};\ntype SaveResult =\n | { success: true; connectionId: string; models: string[] }\n | { success: false; error: string };\n\nconst getSettings = makeFunctionReference<\"query\", Record<string, never>, Settings>(\"ownModels:getSettings\");\nconst saveConnection = makeFunctionReference<\n \"action\",\n { connectionId?: string; name: string; baseUrl: string; apiKey?: string },\n SaveResult\n>(\"ownModels:saveConnection\");\nconst deleteConnection = makeFunctionReference<\"mutation\", { connectionId: string }, null>(\n \"ownModels:deleteConnection\",\n);\nconst setSlot = makeFunctionReference<\"mutation\", { slot: Slot; connectionId: string; model: string }, null>(\n \"ownModels:setSlot\",\n);\nconst clearSlot = makeFunctionReference<\"mutation\", { slot: Slot }, null>(\"ownModels:clearSlot\");\nconst testSlot = makeFunctionReference<\"action\", { slot: Slot }, { ok: boolean; error: string | null }>(\n \"ownModels:testSlot\",\n);\nconst setWebSearchEnabled = makeFunctionReference<\"mutation\", { enabled: boolean }, null>(\n \"ownModels:setWebSearchEnabled\",\n);\n\nfunction parseSlot(value: string): Slot {\n if (!(SLOTS as readonly string[]).includes(value)) {\n throw new Error(`Unknown slot '${value}'. Use one of: ${SLOTS.join(\", \")}.`);\n }\n return value as Slot;\n}\n\nasync function loadSettings(caller: ConvexCaller): Promise<Settings> {\n const settings = await caller.query(getSettings, {});\n if (!settings.ownModels) {\n throw new Error(\"Own model connections are only available on the own-models plan.\");\n }\n return settings;\n}\n\nfunction connectionByName(settings: Settings, name: string): Connection {\n const match = settings.connections.find((connection) => connection.name === name);\n if (!match) {\n const known = settings.connections.map((connection) => connection.name).join(\", \") || \"none\";\n throw new Error(`No connection named '${name}'. Known: ${known}.`);\n }\n return match;\n}\n\nasync function readApiKey(stdin: NodeJS.ReadableStream): Promise<string> {\n let key = \"\";\n for await (const chunk of stdin) {\n key += chunk.toString();\n if (key.length > 4096) throw new Error(\"API key input is too long\");\n }\n key = key.trim();\n if (!key || /[\\r\\n]/u.test(key)) throw new Error(\"Provide one non-empty API key on standard input\");\n return key;\n}\n\nclass ModelsStatusCommand extends ProfileCommand {\n static paths = [[\"models\", \"status\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Show your own model connections and which model serves each feature\",\n });\n\n async run(): Promise<number | void> {\n const settings = await loadSettings(await resolveCaller());\n const connectionName = (id: string) =>\n settings.connections.find((connection) => connection.id === id)?.name ?? id;\n this.print(\n { data: settings },\n () => SLOTS.map((slot) => {\n const row = settings.slots.find((candidate) => candidate.slot === slot);\n return {\n slot,\n connection: row ? connectionName(row.connectionId) : \"\",\n model: row?.model ?? \"\",\n status: row ? row.status : \"not set\",\n error: row?.lastError ?? \"\",\n };\n }),\n [\"slot\", \"connection\", \"model\", \"status\", \"error\"],\n );\n if (!this.json) {\n this.context.stdout.write(\n `\\nConnections: ${settings.connections.map((c) => `${c.name} (${c.host}, key \u2022\u2022\u2022\u2022${c.apiKeyHint})`).join(\"; \") || \"none\"}` +\n `\\nWeb search: ${settings.webSearchEnabled ? \"on\" : \"off\"}\\n`,\n );\n }\n }\n}\n\nclass ModelsConnectionAddCommand extends ProfileCommand {\n static paths = [[\"models\", \"connection\", \"add\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Add an OpenAI-compatible endpoint; the API key is read from stdin\",\n examples: [[\"Add a LiteLLM proxy\", \"printf %s \\\"$KEY\\\" | ente models connection add LiteLLM --base-url https://llm.example.eu/v1 --api-key-stdin\"]],\n });\n\n name = Option.String({ required: true, name: \"name\" });\n baseUrl = Option.String(\"--base-url\", { required: true, description: \"Endpoint base URL, e.g. https://llm.example.eu/v1\" });\n apiKeyStdin = Option.Boolean(\"--api-key-stdin\", false, { description: \"Read the API key from standard input (required)\" });\n\n async run(): Promise<number | void> {\n if (!this.apiKeyStdin) throw new Error(\"Pass the API key on standard input with --api-key-stdin.\");\n const apiKey = await readApiKey(this.context.stdin);\n const caller = await resolveCaller();\n await loadSettings(caller);\n const result = await caller.action(saveConnection, { name: this.name, baseUrl: this.baseUrl, apiKey });\n if (!result.success) throw new Error(result.error);\n this.emitText({ data: result }, () =>\n `Saved connection ${this.name}. It offers ${result.models.length} models: ${result.models.slice(0, 20).join(\", \")}`,\n );\n }\n}\n\nclass ModelsConnectionUpdateCommand extends ProfileCommand {\n static paths = [[\"models\", \"connection\", \"update\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Change a connection's base URL and/or API key (key from stdin)\",\n });\n\n name = Option.String({ required: true, name: \"name\" });\n baseUrl = Option.String(\"--base-url\", { description: \"New base URL\" });\n apiKeyStdin = Option.Boolean(\"--api-key-stdin\", false, { description: \"Read a new API key from standard input\" });\n\n async run(): Promise<number | void> {\n const apiKey = this.apiKeyStdin ? await readApiKey(this.context.stdin) : undefined;\n const caller = await resolveCaller();\n const connection = connectionByName(await loadSettings(caller), this.name);\n const result = await caller.action(saveConnection, {\n connectionId: connection.id,\n name: connection.name,\n baseUrl: this.baseUrl ?? connection.baseUrl,\n ...(apiKey ? { apiKey } : {}),\n });\n if (!result.success) throw new Error(result.error);\n this.emitText({ data: result }, () => `Updated connection ${this.name}.`);\n }\n}\n\nclass ModelsConnectionRemoveCommand extends ProfileCommand {\n static paths = [[\"models\", \"connection\", \"remove\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Remove a connection that no longer serves any feature\",\n });\n\n name = Option.String({ required: true, name: \"name\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const connection = connectionByName(await loadSettings(caller), this.name);\n await caller.mutation(deleteConnection, { connectionId: connection.id });\n this.emitText({ data: { removed: connection.id } }, () => `Removed connection ${this.name}.`);\n }\n}\n\nclass ModelsSetCommand extends ProfileCommand {\n static paths = [[\"models\", \"set\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Choose the connection and model id that serve one feature\",\n details: `Slots: ${SLOTS.join(\", \")}. Agent, ask and recording need a model with tool calling.`,\n });\n\n slot = Option.String({ required: true, name: \"slot\" });\n connection = Option.String({ required: true, name: \"connection\" });\n model = Option.String({ required: true, name: \"model\" });\n\n async run(): Promise<number | void> {\n const slot = parseSlot(this.slot);\n const caller = await resolveCaller();\n const connection = connectionByName(await loadSettings(caller), this.connection);\n await caller.mutation(setSlot, { slot, connectionId: connection.id, model: this.model });\n this.emitText({ data: { slot, connection: connection.name, model: this.model } }, () =>\n `${slot} now uses ${this.model} on ${connection.name}. Run \\`ente models test ${slot}\\` to check it.`,\n );\n }\n}\n\nclass ModelsClearCommand extends ProfileCommand {\n static paths = [[\"models\", \"clear\"]];\n static usage = Command.Usage({ category: \"Models\", description: \"Remove the model of one feature\" });\n\n slot = Option.String({ required: true, name: \"slot\" });\n\n async run(): Promise<number | void> {\n const slot = parseSlot(this.slot);\n await (await resolveCaller()).mutation(clearSlot, { slot });\n this.emitText({ data: { slot } }, () => `Cleared ${slot}.`);\n }\n}\n\nclass ModelsTestCommand extends ProfileCommand {\n static paths = [[\"models\", \"test\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Send a real request for one slot, or every configured slot\",\n });\n\n slot = Option.String({ required: false, name: \"slot\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const settings = await loadSettings(caller);\n const slots = this.slot ? [parseSlot(this.slot)] : settings.slots.map((row) => row.slot);\n if (slots.length === 0) throw new Error(\"No slot is configured yet. Use `ente models set` first.\");\n const results: Array<{ slot: Slot; ok: boolean; error: string | null }> = [];\n for (const slot of slots) {\n results.push({ slot, ...await caller.action(testSlot, { slot }) });\n }\n this.print(\n { data: results },\n () => results.map((result) => ({ slot: result.slot, result: result.ok ? \"ok\" : \"failed\", error: result.error ?? \"\" })),\n [\"slot\", \"result\", \"error\"],\n );\n return results.every((result) => result.ok) ? 0 : 1;\n }\n}\n\nclass ModelsWebSearchCommand extends ProfileCommand {\n static paths = [[\"models\", \"web-search\"]];\n static usage = Command.Usage({\n category: \"Models\",\n description: \"Allow (on) or forbid (off) the agent to send search queries to Linkup\",\n });\n\n value = Option.String({ required: true, name: \"on|off\" });\n\n async run(): Promise<number | void> {\n if (this.value !== \"on\" && this.value !== \"off\") throw new Error(\"Use on or off.\");\n const enabled = this.value === \"on\";\n await (await resolveCaller()).mutation(setWebSearchEnabled, { enabled });\n this.emitText({ data: { webSearchEnabled: enabled } }, () => `Web search is ${this.value}.`);\n }\n}\n\nexport const MODELS_COMMANDS = [\n ModelsStatusCommand,\n ModelsConnectionAddCommand,\n ModelsConnectionUpdateCommand,\n ModelsConnectionRemoveCommand,\n ModelsSetCommand,\n ModelsClearCommand,\n ModelsTestCommand,\n ModelsWebSearchCommand,\n];\n", "// Space commands \u2014 create, list, rename, members. Like every migrated\n// command this calls the SAME public `api.spaces.*` / `api.memberships.*`\n// functions the web app uses, via the JWT bridge (see ../convexClient.ts) \u2014 no\n// per-capability REST endpoint.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport {\n membershipsListForCurrentUser,\n membershipsListForSpace,\n resolveSpaceByNameC,\n spacesFooterFromMemberships,\n} from \"../convexResolve.ts\";\nimport { jsonWithSpaces } from \"../format.ts\";\n\nconst DEFAULT_SPACE_COLOR = \"kale\";\n\ninterface SpaceDoc {\n _id: string;\n name: string;\n color: string;\n [key: string]: unknown;\n}\n\nconst spacesCreate = makeFunctionReference<\n \"mutation\",\n { name: string; color: string; memberEmails?: string[] },\n { createdSpaceId: string; createdMembershipId: string }\n>(\"spaces:create\");\nconst spacesUpdate = makeFunctionReference<\n \"mutation\",\n { spaceId: string; name?: string; color?: string; scope?: string },\n SpaceDoc\n>(\"spaces:update\");\n\nclass SpaceCreateCmd extends ProfileCommand {\n static paths = [[\"space\", \"create\"]];\n static usage = Command.Usage({ category: \"Space\", description: \"Create a new space\" });\n\n name = Option.String();\n color = Option.String(\"--color\", { description: \"Accent color (default: kale)\" });\n memberEmail = Option.Array(\"--member-email\", { description: \"Seed additional members by email\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const res = await caller.mutation(spacesCreate, {\n name: this.name,\n color: this.color ?? DEFAULT_SPACE_COLOR,\n ...(this.memberEmail?.length ? { memberEmails: this.memberEmail } : {}),\n });\n this.emitText({ data: { spaceId: res.createdSpaceId } }, () =>\n `Created space '${this.name}' (${res.createdSpaceId})`,\n );\n }\n}\n\nclass SpaceListCmd extends ProfileCommand {\n static paths = [[\"space\", \"list\"]];\n static usage = Command.Usage({ category: \"Space\", description: \"List spaces you belong to\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const rows = await caller.query(membershipsListForCurrentUser, {});\n\n const spacesOut: Array<{ _id: string; name?: string; role?: string; memberEmails: string[] }> = [];\n for (const row of rows) {\n if (!row.space) continue;\n const members = await caller.query(membershipsListForSpace, { spaceId: row.space._id });\n const memberEmails = members.map((m) => m.user?.email).filter((e): e is string => !!e);\n spacesOut.push({ _id: row.space._id, name: row.space.name, role: row.membership.role, memberEmails });\n }\n\n this.emitText({ data: spacesOut }, () =>\n spacesOut\n .map(\n (s) =>\n `${s._id} ${s.name ?? \"(unnamed)\"} [${s.role ?? \"?\"}] ${(s.memberEmails ?? []).join(\", \")}`,\n )\n .join(\"\\n\"),\n );\n }\n}\n\nclass SpaceRenameCmd extends ProfileCommand {\n static paths = [[\"space\", \"rename\"]];\n static usage = Command.Usage({ category: \"Space\", description: \"Rename a space (owner/admin only)\" });\n\n spaceNameOrId = Option.String();\n newName = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const spaceId = await resolveSpaceByNameC(caller, this.spaceNameOrId);\n const res = await caller.mutation(spacesUpdate, { spaceId, name: this.newName });\n this.emitText({ data: res }, () => `Renamed space ${spaceId} \u2192 '${this.newName}'`);\n }\n}\n\nclass SpaceMembersCmd extends ProfileCommand {\n static paths = [[\"space\", \"members\"]];\n static usage = Command.Usage({ category: \"Space\", description: \"List members of a space\" });\n\n space = Option.String(\"--space\", { description: \"Space name or ID\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const spaces = await spacesFooterFromMemberships(caller);\n const spaceId = this.space ? await resolveSpaceByNameC(caller, this.space) : Object.keys(spaces)[0];\n if (!spaceId) throw new Error(\"No space found\");\n\n const members = await caller.query(membershipsListForSpace, { spaceId });\n const data = members.map((m) => ({ userId: m.user?._id, name: m.user?.name, email: m.user?.email }));\n this.emitText(jsonWithSpaces({ data }, spaces), () =>\n data.map((m) => `${m.userId} ${m.name || \"(no name)\"} <${m.email || \"(no email)\"}>`).join(\"\\n\"),\n );\n }\n}\n\nexport const SPACE_COMMANDS = [SpaceCreateCmd, SpaceListCmd, SpaceRenameCmd, SpaceMembersCmd];\n", "// Top-level `ente search` \u2014 a thin alias over the shared entity-list routine.\n// Ports commands/search.py.\n\nimport { Command, Option } from \"clipanion\";\n\nimport { ClientCommand } from \"../command.ts\";\n\nclass SearchCmd extends ClientCommand {\n static paths = [[\"search\"]];\n static usage = Command.Usage({ category: \"Entity\", description: \"Fuzzy search entities\" });\n\n query = Option.String();\n type = Option.String(\"--type\", { description: \"Filter by entity type (person, org, project, topic)\" });\n\n async run(): Promise<number | void> {\n await this.runEntityList({ query: this.query, typeFilter: this.type });\n }\n}\n\nexport const SEARCH_COMMANDS = [SearchCmd];\n", "// Shared helpers for the two evidence-retrieval commands (`ask` + `query`).\n// They take the same flags and build the same request body; only the target\n// function and the output rendering differ. Like every migrated command this\n// calls the SAME public `api.ask.query` / `api.askAction.run` functions the\n// web app uses, via the JWT bridge (see ../convexClient.ts) \u2014 no\n// per-capability REST endpoint.\n\nimport type { ConvexCaller } from \"../../core/convex.ts\";\nimport { resolveEntityC, resolveSpaceByNameC } from \"../convexResolve.ts\";\n\nexport interface EvidenceOpts {\n question: string;\n space?: string;\n entity?: string;\n limit?: string;\n since?: string;\n until?: string;\n}\n\n/** The wire contract with convex/askContract.ts's `askInputArgs`. */\nexport interface EvidenceBody {\n question: string;\n spaceId?: string;\n entityId?: string;\n limit?: number;\n since?: number;\n until?: number;\n [key: string]: unknown;\n}\n\n/** Resolve name\u2192id flags and assemble the `ask`/`query` request body. */\nexport async function buildEvidenceBodyC(\n caller: ConvexCaller,\n opts: EvidenceOpts,\n): Promise<EvidenceBody> {\n const body: EvidenceBody = { question: opts.question };\n if (opts.space) body.spaceId = await resolveSpaceByNameC(caller, opts.space);\n if (opts.entity) body.entityId = await resolveEntityC(caller, opts.entity);\n // Validate every numeric flag up front \u2014 a bare Number(\"foo\") is NaN, which\n // JSON-serialises to null and would silently send a different request than the\n // user asked for. Fail loud instead. --limit is 1-based; the epoch-ms filters\n // are 0-based.\n if (opts.limit !== undefined) body.limit = parseIntFlag(\"--limit\", opts.limit, 1);\n if (opts.since !== undefined) body.since = parseIntFlag(\"--since\", opts.since, 0);\n if (opts.until !== undefined) body.until = parseIntFlag(\"--until\", opts.until, 0);\n return body;\n}\n\n/** Parse an integer flag, requiring `value >= min`; throws on anything else. */\nfunction parseIntFlag(flag: string, raw: string, min: number): number {\n const n = Number(raw);\n if (!Number.isInteger(n) || n < min) {\n throw new Error(`${flag} must be an integer >= ${min} (got '${raw}').`);\n }\n return n;\n}\n", "// `ente ask` \u2014 natural-language question answered from the knowledge graph with\n// AI synthesis + citations. Ports commands/ask.py. Like every migrated command\n// this calls the SAME public `api.askAction.run` action the web app uses, via\n// the JWT bridge (see ../convexClient.ts) \u2014 no per-capability REST endpoint.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { dim } from \"../format.ts\";\nimport { buildEvidenceBodyC, type EvidenceBody } from \"./evidence.ts\";\n\ninterface AskEvidenceItem {\n id: string;\n kind: string;\n title: string;\n text?: string;\n [key: string]: unknown;\n}\n\ninterface AskCitationItem {\n evidenceId: string;\n kind: string;\n title: string;\n [key: string]: unknown;\n}\n\ninterface AskActionResult {\n question: string;\n answer: string;\n citations: AskCitationItem[];\n gaps: string[];\n evidence: AskEvidenceItem[];\n warnings: string[];\n model: string | null;\n synthesisStatus: \"answered\" | \"evidence_only\" | \"failed\";\n}\n\nconst askActionRun = makeFunctionReference<\"action\", EvidenceBody, AskActionResult>(\"askAction:run\");\n\nfunction formatCitation(c: AskCitationItem): string {\n return `[${c.evidenceId ?? \"\"}] ${c.kind ?? \"\"}: ${c.title ?? \"\"}`.trim();\n}\n\nfunction formatAskResult(data: AskActionResult, includeEvidence: boolean): string {\n const lines: string[] = [data.answer ?? \"\"];\n\n const gaps = data.gaps ?? [];\n if (gaps.length) {\n lines.push(\"\", dim(\"Gaps\"), ...gaps.map((g) => `- ${g}`));\n }\n\n const citations = data.citations ?? [];\n if (citations.length) {\n lines.push(\"\", dim(\"Sources\"), ...citations.map((c) => `- ${formatCitation(c)}`));\n }\n\n const warnings = data.warnings ?? [];\n if (warnings.length) {\n lines.push(\"\", dim(\"Warnings\"), ...warnings.map((w) => `- ${w}`));\n }\n\n if (includeEvidence) {\n const evidence = data.evidence ?? [];\n if (evidence.length) {\n lines.push(\"\", dim(\"Evidence\"));\n for (const item of evidence) {\n lines.push(`- [${item.id ?? \"\"}] ${item.kind ?? \"\"}: ${item.title ?? \"\"}`);\n if (item.text) lines.push(` ${item.text}`);\n }\n }\n }\n\n return lines.join(\"\\n\").trim();\n}\n\nclass AskCmd extends ProfileCommand {\n static paths = [[\"ask\"]];\n static usage = Command.Usage({\n category: \"Ask\",\n description: \"Ask a natural-language question across entities, activities, tasks, and pins\",\n });\n\n question = Option.String();\n space = Option.String(\"--space\", { description: \"Restrict evidence to a space (name or ID)\" });\n entity = Option.String(\"--entity\", { description: \"Use an entity (name or ID) as the main graph anchor\" });\n limit = Option.String(\"--limit\", { description: \"Maximum evidence items to return\" });\n since = Option.String(\"--since\", { description: \"Only include activity evidence after this epoch ms\" });\n until = Option.String(\"--until\", { description: \"Only include activity evidence before this epoch ms\" });\n evidence = Option.Boolean(\"--evidence\", false, { description: \"Print full evidence snippets\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const body = await buildEvidenceBodyC(caller, this);\n const res = await caller.action(askActionRun, body);\n this.emitText({ data: res }, () => formatAskResult(res, this.evidence));\n }\n}\n\nexport const ASK_COMMANDS = [AskCmd];\n", "// `ente query` \u2014 deterministic evidence retrieval (the same graph search that\n// backs `ask`, but WITHOUT the AI synthesis step). Ports commands/query.py.\n// Like every migrated command this calls the SAME public `api.ask.query`\n// function the web app uses, via the JWT bridge (see ../convexClient.ts) \u2014 no\n// per-capability REST endpoint.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { dim, truncate } from \"../format.ts\";\nimport { buildEvidenceBodyC, type EvidenceBody } from \"./evidence.ts\";\n\ninterface EvidenceItem {\n id: string;\n kind: string;\n title: string;\n text?: string;\n relatedEntityNames: string[];\n spaceNames: string[];\n deadline?: number;\n [key: string]: unknown;\n}\n\ninterface QueryResultC {\n evidence: EvidenceItem[];\n warnings: string[];\n}\n\nconst askQuery = makeFunctionReference<\"query\", EvidenceBody, QueryResultC>(\"ask:query\");\n\nfunction formatEvidence(item: EvidenceItem, verbose: boolean): string[] {\n const lines = [`[${item.id ?? \"\"}] ${item.kind ?? \"\"}: ${item.title ?? \"\"}`];\n const details: string[] = [];\n const spaces = item.spaceNames ?? [];\n const related = item.relatedEntityNames ?? [];\n if (spaces.length) details.push(`spaces: ${spaces.join(\", \")}`);\n if (related.length) details.push(`related: ${related.join(\", \")}`);\n if (item.deadline) details.push(`deadline: ${item.deadline}`);\n if (details.length) lines.push(` ${dim(details.join(\" \u00B7 \"))}`);\n if (item.text) lines.push(` ${verbose ? item.text : truncate(item.text, 180)}`);\n return lines;\n}\n\nfunction formatQueryResult(data: QueryResultC, verbose: boolean): string {\n const evidence = data.evidence ?? [];\n if (evidence.length === 0) return \"No evidence found.\";\n\n const lines: string[] = [];\n for (const item of evidence) lines.push(...formatEvidence(item, verbose));\n\n const warnings = data.warnings ?? [];\n if (warnings.length) {\n lines.push(\"\", dim(\"Warnings\"), ...warnings.map((w) => `- ${w}`));\n }\n return lines.join(\"\\n\");\n}\n\nclass QueryCmd extends ProfileCommand {\n static paths = [[\"query\"]];\n static usage = Command.Usage({\n category: \"Ask\",\n description: \"Run ente's deterministic evidence retrieval without AI synthesis\",\n });\n\n question = Option.String();\n space = Option.String(\"--space\", { description: \"Restrict evidence to a space (name or ID)\" });\n entity = Option.String(\"--entity\", { description: \"Use an entity (name or ID) as the main graph anchor\" });\n limit = Option.String(\"--limit\", { description: \"Maximum evidence items to return\" });\n since = Option.String(\"--since\", { description: \"Only include activity evidence after this epoch ms\" });\n until = Option.String(\"--until\", { description: \"Only include activity evidence before this epoch ms\" });\n verbose = Option.Boolean(\"--verbose,-v\", false, { description: \"Print full evidence snippets\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const body = await buildEvidenceBodyC(caller, this);\n const res = await caller.query(askQuery, body);\n this.emitText({ data: res }, () => formatQueryResult(res, this.verbose));\n }\n}\n\nexport const QUERY_COMMANDS = [QueryCmd];\n", "// Recording (voice) pipeline settings \u2014 view + edit the structuring agent prompt\n// and Whisper dictionary that drive how recordings become structured knowledge.\n//\n// These call the SAME public `api.users.*` functions the web Settings page uses\n// (VoicePipelineSectionContent). No per-capability REST endpoint: the CLI authenticates\n// via the JWT bridge (see ../convexClient.ts + ../../core/convex.ts) and acts as\n// the real user, so the prompt it sets is exactly the one the pipeline runs.\n\nimport { spawnSync } from \"node:child_process\";\nimport { mkdtempSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport path from \"node:path\";\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\n\ninterface VoicePipelineSettings {\n agentPrompt: string | null;\n agentDictionary: string | null;\n}\n\n// Typed function references. Args carry the optional settings-owner delegation\n// arg (omitted here \u2192 resolves to the caller). The CLI declares the arg/return\n// shapes itself (it stays a standalone package \u2014 it does not import the backend's\n// generated `api`); the wire contract is these four public functions in\n// convex/users.ts.\nconst getVoicePipelineSettings = makeFunctionReference<\n \"query\",\n { settingsOwnerUserId?: string },\n VoicePipelineSettings | null\n>(\"users:getVoicePipelineSettings\");\n\nconst updateAgentPrompt = makeFunctionReference<\n \"mutation\",\n { value: string; settingsOwnerUserId?: string },\n null\n>(\"users:updateAgentPrompt\");\n\nconst updateAgentDictionary = makeFunctionReference<\n \"mutation\",\n { value: string; settingsOwnerUserId?: string },\n null\n>(\"users:updateAgentDictionary\");\n\n/**\n * Resolve the new value for a prompt/dictionary from the available sources, in\n * priority order: --edit ($EDITOR pre-filled with `current`) > --file (path or\n * `-` for stdin) > positional. Exactly one source must be given.\n */\nasync function resolveValue(\n cmd: { value?: string; file?: string; edit?: boolean },\n label: string,\n current: string,\n): Promise<string> {\n const sources = [cmd.edit ? \"--edit\" : null, cmd.file ? \"--file\" : null, cmd.value ? \"<value>\" : null].filter(\n Boolean,\n );\n if (sources.length > 1) {\n throw new Error(`Provide only one of: <value>, --file, --edit (got ${sources.join(\", \")}).`);\n }\n\n if (cmd.edit) return editInEditor(current, label);\n if (cmd.file) {\n if (cmd.file === \"-\") return await readStdin();\n return readFileSync(cmd.file, \"utf8\");\n }\n if (cmd.value !== undefined) return cmd.value;\n throw new Error(`No ${label} given. Pass a value, --file <path> (or --file -), or --edit.`);\n}\n\nfunction editInEditor(initial: string, label: string): string {\n const editor = process.env.EDITOR || process.env.VISUAL || \"nano\";\n const dir = mkdtempSync(path.join(tmpdir(), \"ente-\"));\n const file = path.join(dir, `${label}.md`);\n writeFileSync(file, initial, \"utf8\");\n const res = spawnSync(editor, [file], { stdio: \"inherit\" });\n if (res.status !== 0) {\n throw new Error(`Editor '${editor}' exited with a non-zero status; ${label} unchanged.`);\n }\n return readFileSync(file, \"utf8\");\n}\n\nfunction readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n let data = \"\";\n process.stdin.setEncoding(\"utf8\");\n process.stdin.on(\"data\", (chunk) => (data += chunk));\n process.stdin.on(\"end\", () => resolve(data));\n process.stdin.on(\"error\", reject);\n });\n}\n\nclass RecordingPipelineShowCmd extends ProfileCommand {\n static paths = [[\"recording-pipeline\", \"show\"]];\n static usage = Command.Usage({\n category: \"Recording pipeline\",\n description: \"Show the recording agent prompt and dictionary\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const settings = await caller.query(getVoicePipelineSettings, {});\n this.emitText(\n { data: settings ?? { agentPrompt: null, agentDictionary: null } },\n () => {\n const prompt = settings?.agentPrompt;\n const dict = settings?.agentDictionary;\n return [\n \"\u2500\u2500 Agent prompt \u2500\u2500\",\n prompt && prompt.length ? prompt : \"(empty \u2014 pipeline regenerates the starter prompt on next run)\",\n \"\",\n \"\u2500\u2500 Dictionary \u2500\u2500\",\n dict && dict.length ? dict : \"(empty)\",\n ].join(\"\\n\");\n },\n );\n }\n}\n\nclass RecordingPipelineSetPromptCmd extends ProfileCommand {\n static paths = [[\"recording-pipeline\", \"set-prompt\"]];\n static usage = Command.Usage({\n category: \"Recording pipeline\",\n description: \"Replace the recording agent system prompt (value | --file | --edit)\",\n });\n\n value = Option.String({ required: false });\n file = Option.String(\"--file\", { description: \"Read prompt from a file, or '-' for stdin\" });\n edit = Option.Boolean(\"--edit\", false, { description: \"Edit the current prompt in $EDITOR\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n let current = \"\";\n if (this.edit) {\n const settings = await caller.query(getVoicePipelineSettings, {});\n current = settings?.agentPrompt ?? \"\";\n }\n const value = await resolveValue(this, \"prompt\", current);\n await caller.mutation(updateAgentPrompt, { value });\n this.emitText({ data: { ok: true, bytes: value.length } }, () =>\n `Updated recording agent prompt (${value.length} chars).`,\n );\n }\n}\n\nclass RecordingPipelineResetPromptCmd extends ProfileCommand {\n static paths = [[\"recording-pipeline\", \"reset-prompt\"]];\n static usage = Command.Usage({\n category: \"Recording pipeline\",\n description: \"Clear the prompt so the pipeline regenerates the starter on next run\",\n });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n await caller.mutation(updateAgentPrompt, { value: \"\" });\n this.emitText({ data: { ok: true } }, () =>\n \"Cleared recording agent prompt \u2014 the starter prompt will be regenerated on the next recording.\",\n );\n }\n}\n\nclass RecordingPipelineSetDictionaryCmd extends ProfileCommand {\n static paths = [[\"recording-pipeline\", \"set-dictionary\"]];\n static usage = Command.Usage({\n category: \"Recording pipeline\",\n description: \"Replace the transcription dictionary (value | --file | --edit)\",\n });\n\n value = Option.String({ required: false });\n file = Option.String(\"--file\", { description: \"Read dictionary from a file, or '-' for stdin\" });\n edit = Option.Boolean(\"--edit\", false, { description: \"Edit the current dictionary in $EDITOR\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n let current = \"\";\n if (this.edit) {\n const settings = await caller.query(getVoicePipelineSettings, {});\n current = settings?.agentDictionary ?? \"\";\n }\n const value = await resolveValue(this, \"dictionary\", current);\n await caller.mutation(updateAgentDictionary, { value });\n this.emitText({ data: { ok: true, bytes: value.length } }, () =>\n `Updated transcription dictionary (${value.length} chars).`,\n );\n }\n}\n\nexport const RECORDING_PIPELINE_COMMANDS = [\n RecordingPipelineShowCmd,\n RecordingPipelineSetPromptCmd,\n RecordingPipelineResetPromptCmd,\n RecordingPipelineSetDictionaryCmd,\n];\n", "// `ente recording \u2026` \u2014 inspect and reprocess recordings (admin-only). Calls the\n// public `api.admin.recordings.*` functions via the JWT bridge (see\n// ../convexClient.ts), so every call lands as the real authenticated user and\n// the backend's admin gate applies. Non-admins get a `forbidden` error.\n//\n// This exists to debug pipeline failures reported by other users: the ordinary\n// `recordings.*` API is creator-scoped, so an operator cannot otherwise see or\n// re-run somebody else's stuck recording.\n//\n// ente recording list [--user <email|id>] [--status error] [--limit 20]\n// ente recording show <recordingId>\n// ente recording inspect <recordingId>\n// ente recording rerun <recordingId> [--wait]\n//\n// `rerun` never touches the stored audio \u2014 it only resets pipeline state.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { formatDatetime } from \"../datetime.ts\";\nimport type { ConvexCaller } from \"../../core/convex.ts\";\n\ntype ProcessingStatus =\n | \"pending\"\n | \"transcribing\"\n | \"structuring\"\n | \"reflecting\"\n | \"done\"\n | \"error\";\n\ninterface RecordingSummary {\n id: string;\n createdBy: string;\n createdByEmail: string;\n createdByName: string;\n createdAt: number;\n title: string | null;\n source: string | null;\n mimeType: string;\n sizeBytes: number | null;\n durationMs: number;\n processingStatus: ProcessingStatus | null;\n processingError: string | null;\n transcriptChars: number;\n activityCount: number;\n hasAudio: boolean;\n}\n\ninterface TranscriptSegmentProgress {\n generation: number;\n total: number;\n done: number;\n running: number;\n pending: number;\n oldestClaimAt: number | null;\n maxAttempts: number;\n}\n\ninterface RecordingDetails extends RecordingSummary {\n storageId: string | null;\n storageUrl: string | null;\n threadId: string | null;\n rerunGeneration: number | null;\n transcript: string | null;\n /** Present only while a long recording is transcribed segment by segment. */\n transcriptSegments: TranscriptSegmentProgress | null;\n}\n\nconst listRecordings = makeFunctionReference<\n \"query\",\n { user?: string; status?: ProcessingStatus; limit?: number },\n { recordings: RecordingSummary[]; scanned: number; truncated: boolean }\n>(\"admin/recordings:list\");\nconst getRecording = makeFunctionReference<\n \"query\",\n { recordingId: string },\n RecordingDetails\n>(\"admin/recordings:get\");\nconst getRecordingAudioUrl = makeFunctionReference<\n \"action\",\n { recordingId: string },\n string | null\n>(\"admin/recordingStorage:getAudioUrl\");\nconst rerunRecording = makeFunctionReference<\"mutation\", { recordingId: string }, null>(\n \"admin/recordings:rerun\",\n);\nconst unreferencedAudioFiles = makeFunctionReference<\n \"query\",\n { limit?: number; minSizeBytes?: number },\n {\n files: Array<{\n storageId: string;\n createdAt: number;\n contentType: string | null;\n sizeBytes: number;\n }>;\n scannedFiles: number;\n referencedByRecordings: number;\n truncated: boolean;\n }\n>(\"admin/recordings:unreferencedAudioFiles\");\n\nconst TERMINAL_STATUSES = new Set<ProcessingStatus>([\"done\", \"error\"]);\n\nfunction formatDuration(ms: number): string {\n const totalSeconds = Math.round(ms / 1_000);\n const minutes = Math.floor(totalSeconds / 60);\n const seconds = totalSeconds % 60;\n return `${minutes}:${String(seconds).padStart(2, \"0\")}`;\n}\n\nfunction formatMiB(bytes: number | null): string {\n return bytes === null ? \"\" : `${(bytes / (1024 * 1024)).toFixed(1)}`;\n}\n\nfunction summaryRow(recording: RecordingSummary) {\n return {\n id: recording.id,\n created: formatDatetime(recording.createdAt),\n user: recording.createdByEmail || recording.createdBy,\n title: recording.title ?? \"\",\n source: recording.source ?? \"\",\n duration: formatDuration(recording.durationMs),\n mib: formatMiB(recording.sizeBytes),\n status: recording.processingStatus ?? \"\",\n error: (recording.processingError ?? \"\").slice(0, 60),\n };\n}\n\nconst SUMMARY_HEADERS = [\n \"id\",\n \"created\",\n \"user\",\n \"title\",\n \"source\",\n \"duration\",\n \"mib\",\n \"status\",\n \"error\",\n] as const;\n\n// \u2500\u2500 recording list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass RecordingListCommand extends ProfileCommand {\n static paths = [[\"recording\", \"list\"]];\n static usage = Command.Usage({\n category: \"Recordings\",\n description: \"List recordings with their pipeline status (admin only)\",\n details:\n \"Without --user this lists the newest recordings across the deployment. \" +\n \"--status filters by pipeline stage; use `--status error` to sweep for stuck recordings.\",\n });\n\n user = Option.String(\"--user\", {\n description: \"Only this owner's recordings (email or user id)\",\n });\n status = Option.String(\"--status\", {\n description: \"Filter by pipeline status (pending|transcribing|structuring|reflecting|done|error)\",\n });\n limit = Option.String(\"--limit\", { description: \"Maximum rows to return (default 20)\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const result = await caller.query(listRecordings, {\n ...(this.user !== undefined ? { user: this.user } : {}),\n ...(this.status !== undefined ? { status: this.status as ProcessingStatus } : {}),\n ...(this.limit !== undefined ? { limit: Number(this.limit) } : {}),\n });\n\n this.print(result.recordings, (rows) => rows.map(summaryRow), SUMMARY_HEADERS);\n // Status filtering has no index, so say plainly when the sweep was capped\n // rather than letting an empty tail read as \"nothing else is broken\".\n if (!this.json && result.truncated) {\n this.err(\n `Note: scanned the newest ${result.scanned} recordings only; older ones were not checked.`,\n );\n }\n }\n}\n\n// \u2500\u2500 recording show \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass RecordingShowCommand extends ProfileCommand {\n static paths = [[\"recording\", \"show\"]];\n static usage = Command.Usage({\n category: \"Recordings\",\n description: \"Show one recording's full pipeline state (admin only)\",\n });\n\n recordingId = Option.String({ required: true, name: \"recordingId\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const recording = await caller.query(getRecording, { recordingId: this.recordingId });\n this.emitText(recording, () => {\n const lines = [\n `id: ${recording.id}`,\n `owner: ${recording.createdByEmail || recording.createdBy}`,\n `created: ${formatDatetime(recording.createdAt)}`,\n `title: ${recording.title ?? \"(none)\"}`,\n `source: ${recording.source ?? \"(unknown)\"}`,\n `duration: ${formatDuration(recording.durationMs)}`,\n `mime: ${recording.mimeType}`,\n `size: ${recording.sizeBytes === null ? \"(unknown)\" : `${formatMiB(recording.sizeBytes)} MiB`}`,\n `audio: ${recording.hasAudio ? `stored (${recording.storageId ?? \"object storage\"})` : \"MISSING\"}`,\n `status: ${recording.processingStatus ?? \"(none)\"}`,\n `transcript: ${recording.transcriptChars} chars`,\n `activities: ${recording.activityCount}`,\n `re-runs: ${recording.rerunGeneration ?? 0}`,\n ];\n const segments = recording.transcriptSegments;\n if (segments) {\n lines.push(\n `segments: ${segments.done}/${segments.total} done, ` +\n `${segments.running} running, ${segments.pending} pending ` +\n `(gen ${segments.generation}, max ${segments.maxAttempts} attempts)`,\n );\n if (segments.oldestClaimAt !== null) {\n lines.push(`claimed: ${formatDatetime(segments.oldestClaimAt)} (oldest)`);\n }\n }\n if (recording.processingError) lines.push(`error: ${recording.processingError}`);\n return lines.join(\"\\n\");\n });\n }\n}\n\n// \u2500\u2500 recording inspect \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\ninterface Mp4BoxNode {\n type: string;\n size: number;\n start: number;\n}\n\n/** Walk top-level MP4/ISO-BMFF boxes. Returns [] for non-MP4 containers. */\nfunction readAscii(bytes: Uint8Array, offset: number, length: number): string {\n let value = \"\";\n for (let index = 0; index < length; index += 1) {\n value += String.fromCharCode(bytes[offset + index] ?? 0);\n }\n return value;\n}\n\nfunction readTopLevelBoxes(bytes: Uint8Array): Mp4BoxNode[] {\n const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n const boxes: Mp4BoxNode[] = [];\n let offset = 0;\n while (offset + 8 <= bytes.byteLength) {\n const size = view.getUint32(offset);\n const type = readAscii(bytes, offset + 4, 4);\n if (size < 8 || offset + size > bytes.byteLength || !/^[\\x20-\\x7e]{4}$/.test(type)) break;\n boxes.push({ type, size, start: offset });\n offset += size;\n }\n return boxes;\n}\n\nfunction describeContainer(bytes: Uint8Array): string {\n if (bytes.byteLength < 8) return \"unknown\";\n if (readAscii(bytes, 0, 4) === \"OggS\") return \"ogg\";\n if (bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3) return \"webm\";\n if (readAscii(bytes, 0, 3) === \"ID3\" || (bytes[0] === 0xff && ((bytes[1] ?? 0) & 0xe0) === 0xe0)) {\n return \"mp3\";\n }\n if (readAscii(bytes, 4, 4) === \"ftyp\") return \"mp4\";\n return \"unknown\";\n}\n\nclass RecordingInspectCommand extends ProfileCommand {\n static paths = [[\"recording\", \"inspect\"]];\n static usage = Command.Usage({\n category: \"Recordings\",\n description: \"Inspect a recording's audio container structure (admin only)\",\n details:\n \"Downloads the stored audio and prints its container layout. For MP4/M4A this \" +\n \"reports the ftyp brands and whether the file is fragmented (moof boxes), which \" +\n \"is what distinguishes iOS Safari recordings from progressive M4A.\",\n });\n\n recordingId = Option.String({ required: true, name: \"recordingId\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const recording = await caller.query(getRecording, { recordingId: this.recordingId });\n const storageUrl = recording.storageUrl ?? await caller.action(\n getRecordingAudioUrl,\n { recordingId: this.recordingId },\n );\n if (!storageUrl) {\n throw new Error(`Recording ${recording.id} has no stored audio.`);\n }\n\n const response = await fetch(storageUrl);\n if (!response.ok) {\n throw new Error(`Failed to download audio: ${response.status} ${response.statusText}`);\n }\n const bytes = new Uint8Array(await response.arrayBuffer());\n\n const container = describeContainer(bytes);\n const boxes = container === \"mp4\" ? readTopLevelBoxes(bytes) : [];\n const counts: Record<string, number> = {};\n for (const box of boxes) counts[box.type] = (counts[box.type] ?? 0) + 1;\n const ftyp = boxes[0]?.type === \"ftyp\" ? boxes[0] : undefined;\n const brands = ftyp\n ? readAscii(bytes, 8, Math.min(ftyp.size, 40) - 8)\n .replace(/[^\\x20-\\x7e]/g, \" \")\n .replace(/\\s+/g, \" \")\n .trim()\n : null;\n const fragmented = (counts.moof ?? 0) > 0;\n\n const data = {\n id: recording.id,\n mimeType: recording.mimeType,\n declaredSizeBytes: recording.sizeBytes,\n downloadedBytes: bytes.byteLength,\n container,\n brands,\n fragmented,\n topLevelBoxCounts: counts,\n };\n\n this.emitText(data, () => {\n const lines = [\n `id: ${recording.id}`,\n `mime: ${recording.mimeType}`,\n `downloaded: ${formatMiB(bytes.byteLength)} MiB`,\n `container: ${container}`,\n ];\n if (brands) lines.push(`brands: ${brands}`);\n if (container === \"mp4\") {\n lines.push(`fragmented: ${fragmented ? `yes (${counts.moof} moof boxes)` : \"no\"}`);\n lines.push(\n `boxes: ${\n Object.entries(counts)\n .map(([type, count]) => `${type}\u00D7${count}`)\n .join(\", \")\n }`,\n );\n }\n return lines.join(\"\\n\");\n });\n }\n}\n\n// \u2500\u2500 recording rerun \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nasync function waitForTerminalStatus(\n caller: ConvexCaller,\n recordingId: string,\n options: { timeoutMs: number; pollMs: number; onStage: (status: string) => void },\n): Promise<RecordingDetails> {\n const deadline = Date.now() + options.timeoutMs;\n let lastStatus: string | undefined;\n for (;;) {\n const recording = await caller.query(getRecording, { recordingId });\n const status = recording.processingStatus ?? \"(none)\";\n if (status !== lastStatus) {\n lastStatus = status;\n options.onStage(status);\n }\n if (recording.processingStatus && TERMINAL_STATUSES.has(recording.processingStatus)) {\n return recording;\n }\n if (Date.now() >= deadline) {\n throw new Error(\n `Timed out after ${Math.round(options.timeoutMs / 1000)}s waiting for ${recordingId} ` +\n `(still ${status}).`,\n );\n }\n await new Promise((resolve) => setTimeout(resolve, options.pollMs));\n }\n}\n\nclass RecordingRerunCommand extends ProfileCommand {\n static paths = [[\"recording\", \"rerun\"]];\n static usage = Command.Usage({\n category: \"Recordings\",\n description: \"Re-run the processing pipeline for a recording (admin only)\",\n details:\n \"Resets pipeline state and reprocesses the recording, exactly like the in-app \" +\n \"\\\"Re-run pipeline\\\" button. The stored audio is never modified or deleted. \" +\n \"With --wait, polls until the recording reaches done or error and exits non-zero on error.\",\n });\n\n recordingId = Option.String({ required: true, name: \"recordingId\" });\n wait = Option.Boolean(\"--wait\", false, {\n description: \"Poll until the pipeline finishes\",\n });\n timeout = Option.String(\"--timeout\", {\n description: \"Seconds to wait with --wait (default 900)\",\n });\n poll = Option.String(\"--poll\", { description: \"Seconds between polls (default 5)\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const before = await caller.query(getRecording, { recordingId: this.recordingId });\n await caller.mutation(rerunRecording, { recordingId: this.recordingId });\n\n if (!this.wait) {\n this.emitText({ id: before.id, rerunStarted: true }, () =>\n `Re-run started for ${before.id}. Poll with: ente recording show ${before.id}`,\n );\n return;\n }\n\n const after = await waitForTerminalStatus(caller, this.recordingId, {\n timeoutMs: Number(this.timeout ?? 900) * 1_000,\n pollMs: Number(this.poll ?? 5) * 1_000,\n onStage: (status) => {\n if (!this.json) this.err(`\u2026 ${status}`);\n },\n });\n\n const audioPreserved = after.storageId === before.storageId;\n const data = {\n id: after.id,\n processingStatus: after.processingStatus,\n processingError: after.processingError,\n transcriptChars: after.transcriptChars,\n activityCount: after.activityCount,\n audioPreserved,\n };\n\n if (after.processingStatus === \"error\") {\n this.emitText(data, () => `Pipeline failed for ${after.id}: ${after.processingError}`);\n return 1;\n }\n this.emitText(data, () =>\n [\n `Pipeline finished for ${after.id}.`,\n `transcript: ${after.transcriptChars} chars`,\n `activities: ${after.activityCount}`,\n `audio: ${audioPreserved ? \"unchanged\" : \"CHANGED\"}`,\n ].join(\"\\n\"),\n );\n }\n}\n\n// \u2500\u2500 recording orphans \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass RecordingOrphansCommand extends ProfileCommand {\n static paths = [[\"recording\", \"orphans\"]];\n static usage = Command.Usage({\n category: \"Recordings\",\n description: \"Find uploaded audio that no recording row points at (admin only)\",\n details:\n \"The recorder uploads the audio blob first and creates the recording row second. \" +\n \"If the page dies in between, the audio survives in storage but no recording exists. \" +\n \"This lists those blobs newest first so they can be recovered.\",\n });\n\n limit = Option.String(\"--limit\", { description: \"Storage files to scan (default 2000)\" });\n minSize = Option.String(\"--min-mib\", { description: \"Ignore blobs smaller than this many MiB\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const result = await caller.query(unreferencedAudioFiles, {\n ...(this.limit !== undefined ? { limit: Number(this.limit) } : {}),\n ...(this.minSize !== undefined\n ? { minSizeBytes: Math.round(Number(this.minSize) * 1024 * 1024) }\n : {}),\n });\n\n this.print(\n result.files,\n (rows) =>\n rows.map((file) => ({\n storageId: file.storageId,\n created: formatDatetime(file.createdAt),\n type: file.contentType ?? \"\",\n mib: formatMiB(file.sizeBytes),\n })),\n [\"storageId\", \"created\", \"type\", \"mib\"],\n );\n if (!this.json) {\n this.err(\n `Scanned ${result.scannedFiles} storage files against ` +\n `${result.referencedByRecordings} recording references` +\n (result.truncated ? \" (scan hit its limit; raise --limit to go further back).\" : \".\"),\n );\n }\n }\n}\n\nexport const RECORDINGS_COMMANDS = [\n RecordingListCommand,\n RecordingShowCommand,\n RecordingInspectCommand,\n RecordingRerunCommand,\n RecordingOrphansCommand,\n];\n", "// Agent thread inspection \u2014 read your agent conversation threads to analyze and\n// debug where the agent struggled (failed tool calls, error threads) and which\n// requests ente could not handle well.\n//\n// Calls the SAME public `api.agents.*` functions the web app uses, via the JWT\n// bridge (see ../convexClient.ts) \u2014 the CLI acts as the real user, so it only\n// ever sees that user's own threads. No per-capability REST endpoint.\n\nimport { readFileSync } from \"node:fs\";\nimport { randomUUID } from \"node:crypto\";\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ClientCommand } from \"../command.ts\";\nimport type { EnteClient } from \"../client.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport type {\n AgentConfiguration,\n AgentScheduleInput,\n OperatorAgentMessage,\n OperatorAgentThread,\n} from \"../types.ts\";\n\ntype ThreadStatus = \"idle\" | \"running\" | \"error\";\ntype ThreadSource = \"recording\" | \"manual\" | \"automation\";\n\ninterface AgentSummary {\n _id: string;\n name: string;\n spaceName: string;\n isDefault: boolean;\n [key: string]: unknown;\n}\n\ninterface AgentThread {\n _id: string;\n agentId: string;\n title?: string;\n source: ThreadSource;\n recordingId?: string;\n status: ThreadStatus;\n execution?: \"hosted\" | \"external\";\n attention?: \"user\" | \"agent\" | \"none\";\n attentionVersion?: number;\n errorMessage?: string;\n lastActivityAt: number;\n archivedAt?: number;\n messageCount: number;\n createdAt: number;\n [key: string]: unknown;\n}\n\ninterface AgentToolCall {\n id: string;\n name: string;\n input: unknown;\n}\n\ninterface AgentToolResult {\n toolCallId: string;\n name: string;\n result: unknown;\n isError?: boolean;\n}\n\ninterface AgentMessage {\n _id: string;\n order: number;\n runId?: string;\n phase: string;\n role: \"user\" | \"assistant\" | \"tool\";\n content?: string;\n toolCalls?: AgentToolCall[];\n toolResults?: AgentToolResult[];\n model?: string;\n usage?: { inputTokens: number; outputTokens: number };\n createdAt: number;\n [key: string]: unknown;\n}\n\nconst agentsListMine = makeFunctionReference<\"query\", Record<string, never>, AgentSummary[]>(\n \"agents:listMyAgents\",\n);\nconst agentsListRecentThreads = makeFunctionReference<\n \"query\",\n { status?: ThreadStatus; includeArchived?: boolean; limit?: number },\n AgentThread[]\n>(\"agents:listRecentThreads\");\nconst agentsGetThreadWithMessages = makeFunctionReference<\n \"query\",\n { threadId: string },\n { thread: AgentThread; messages: AgentMessage[] } | null\n>(\"agents:getThreadWithMessages\");\nconst agentsSendUserMessage = makeFunctionReference<\n \"mutation\",\n { threadId: string; content: string },\n null\n>(\"agents:sendUserMessage\");\nconst agentsCreateManualThread = makeFunctionReference<\n \"mutation\",\n { content: string; agentId?: string; spaceIdHint?: string; entityIdHint?: string },\n string\n>(\"agents:createManualThread\");\n\nfunction fmtTime(ms: number): string {\n return new Date(ms).toISOString().replace(\"T\", \" \").slice(0, 16);\n}\n\nfunction summarizeValue(value: unknown, maxLen = 200): string {\n let text: string;\n try {\n text = typeof value === \"string\" ? value : JSON.stringify(value);\n } catch {\n text = String(value);\n }\n if (text === undefined) text = \"\";\n return text.length > maxLen ? `${text.slice(0, maxLen - 1)}\u2026` : text;\n}\n\nfunction isErrorResult(result: AgentToolResult): boolean {\n if (result.isError) return true;\n return !!(result.result && typeof result.result === \"object\" && \"error\" in (result.result as object));\n}\n\nfunction normalizeOperatorThread(\n thread: OperatorAgentThread,\n agentId = \"\",\n): AgentThread {\n return {\n ...thread,\n _id: thread.threadId,\n agentId,\n };\n}\n\nfunction normalizeOperatorMessage(message: OperatorAgentMessage): AgentMessage {\n return {\n ...message,\n _id: message.messageId,\n toolCalls: message.toolCalls,\n toolResults: message.toolResults,\n };\n}\n\nasync function fetchOperatorThread(\n client: EnteClient,\n threadId: string,\n agentId = \"\",\n): Promise<{ thread: AgentThread; messages: AgentMessage[] } | null> {\n let cursor: string | undefined;\n let thread: AgentThread | undefined;\n const messages: AgentMessage[] = [];\n do {\n const response = await client.getAgentThread(threadId, cursor, 50);\n thread = normalizeOperatorThread(response.data.thread, agentId);\n messages.push(...response.data.messages.map(normalizeOperatorMessage));\n cursor = response.data.continueCursor;\n } while (cursor);\n return thread ? { thread, messages } : null;\n}\n\nfunction renderAgentConfiguration(agent: AgentConfiguration): string {\n const lines = [\n `${agent.name} ${agent.agentId}`,\n `Space: ${agent.spaceId}`,\n `Mailbox: ${agent.mailbox?.status === \"active\" ? agent.mailbox.address : \"not active\"}`,\n \"\",\n \"Ente prompt configuration:\",\n agent.prompt || \"(empty)\",\n \"\",\n `Ente scheduled runs: ${agent.schedules.length}`,\n ];\n for (const schedule of agent.schedules) {\n const time = schedule.timeMinutes === undefined\n ? schedule.scheduleType\n : `${String(Math.floor(schedule.timeMinutes / 60)).padStart(2, \"0\")}:${String(schedule.timeMinutes % 60).padStart(2, \"0\")} ${schedule.timezone ?? \"\"}`.trim();\n lines.push(\n ` ${schedule.enabled ? \"enabled\" : \"disabled\"} ${time} ${schedule.prompt} ${schedule.automationId}`,\n );\n }\n return lines.join(\"\\n\");\n}\n\nclass AgentList extends ClientCommand {\n static paths = [[\"agent\", \"list\"]];\n static usage = Command.Usage({ category: \"Agent\", description: \"List your agents\" });\n\n async run(): Promise<number | void> {\n const context = await this.client().getAuthContext();\n if (context.data.kind === \"agent_operator\") {\n const { data: agent } = await this.client().getAgentConfiguration();\n this.emitText({ data: [agent] }, () =>\n `\u2605 ${agent.name} (bound operator agent) ${agent.agentId}`);\n return;\n }\n const caller = await resolveCaller();\n const agents = await caller.query(agentsListMine, {});\n this.emitText({ data: agents }, () => {\n if (agents.length === 0) return \"No agents.\";\n return agents\n .map((a) => `${a.isDefault ? \"\u2605\" : \" \"} ${a.name} (${a.spaceName}) ${a._id}`)\n .join(\"\\n\");\n });\n }\n}\n\nclass AgentThreads extends ClientCommand {\n static paths = [[\"agent\", \"threads\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"List your agent threads (newest first); filter by --status/--agent\",\n });\n\n status = Option.String(\"--status\", { description: \"Filter by status: idle | running | error\" });\n agent = Option.String(\"--agent\", { description: \"Filter by agent id\" });\n includeArchived = Option.Boolean(\"--include-archived\", false, { description: \"Include archived threads\" });\n limit = Option.String(\"--limit\", { description: \"Max threads to return (default 200)\" });\n attention = Option.String(\"--attention\", { description: \"Filter by attention: user | agent | none\" });\n\n async run(): Promise<number | void> {\n const status = this.status as ThreadStatus | undefined;\n if (status && ![\"idle\", \"running\", \"error\"].includes(status)) {\n throw new Error(`--status must be one of: idle, running, error (got \"${status}\").`);\n }\n const requestedLimit = this.limit ? Number(this.limit) : undefined;\n if (this.attention && ![\"user\", \"agent\", \"none\"].includes(this.attention)) {\n throw new Error(`--attention must be one of: user, agent, none (got \"${this.attention}\").`);\n }\n const context = await this.client().getAuthContext();\n let threads: AgentThread[];\n if (context.data.kind === \"agent_operator\") {\n if (this.agent && this.agent !== context.data.agentId) {\n throw new Error(\n `This operator key is bound to agent ${context.data.agentId}; --agent cannot select another agent.`,\n );\n }\n const cap = requestedLimit ?? 200;\n const operatorThreads: OperatorAgentThread[] = [];\n let cursor: string | undefined;\n do {\n const response = await this.client().listAgentThreads({\n includeArchived: this.includeArchived ? \"true\" : undefined,\n limit: String(Math.min(cap - operatorThreads.length, 50)),\n cursor,\n attention: this.attention,\n });\n operatorThreads.push(...response.data);\n cursor = response.continueCursor;\n } while (cursor && operatorThreads.length < cap);\n threads = operatorThreads.map((thread) =>\n normalizeOperatorThread(thread, context.data.agentId));\n if (status) threads = threads.filter((thread) => thread.status === status);\n } else {\n const caller = await resolveCaller();\n threads = await caller.query(agentsListRecentThreads, {\n status,\n includeArchived: this.includeArchived,\n limit: requestedLimit,\n });\n if (this.agent) threads = threads.filter((t) => t.agentId === this.agent);\n if (this.attention) threads = threads.filter((t) => t.attention === this.attention);\n }\n\n this.emitText({ data: threads }, () => {\n if (threads.length === 0) return \"No matching threads.\";\n return threads\n .map((t) => {\n const flag = t.status === \"error\" ? \"\u2717\" : t.status === \"running\" ? \"\u2026\" : \" \";\n const title = t.title ?? \"(untitled)\";\n const err = t.status === \"error\" && t.errorMessage ? `\\n error: ${t.errorMessage}` : \"\";\n const attention = t.attention ? ` attention:${t.attention}` : \"\";\n return `${flag} ${fmtTime(t.lastActivityAt)} [${t.source}] ${t.messageCount} msgs${attention} ${title} ${t._id}${err}`;\n })\n .join(\"\\n\");\n });\n }\n}\n\nfunction renderMessage(m: AgentMessage, onlyErrors: boolean): string[] {\n const lines: string[] = [];\n const header = `\u2500\u2500 ${m.role}${m.phase !== \"chat\" ? ` (${m.phase})` : \"\"}${m.model ? ` ${m.model}` : \"\"}`;\n if (!onlyErrors) {\n lines.push(header);\n if (m.content && m.content.trim()) lines.push(summarizeValue(m.content, 1000));\n for (const call of m.toolCalls ?? []) {\n lines.push(` \u2192 tool ${call.name}(${summarizeValue(call.input, 300)})`);\n }\n }\n for (const res of m.toolResults ?? []) {\n const failed = isErrorResult(res);\n if (onlyErrors && !failed) continue;\n const marker = failed ? \"\u2717\" : \"\u2713\";\n lines.push(` ${marker} ${res.name}: ${summarizeValue(res.result, 400)}`);\n }\n return lines;\n}\n\nclass AgentShow extends ClientCommand {\n static paths = [[\"agent\", \"show\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Show a thread's full turn-by-turn transcript; --errors for failures only\",\n });\n\n threadId = Option.String();\n errorsOnly = Option.Boolean(\"--errors\", false, { description: \"Only show failed tool calls + error status\" });\n\n async run(): Promise<number | void> {\n const context = await this.client().getAuthContext();\n const data = context.data.kind === \"agent_operator\"\n ? await fetchOperatorThread(this.client(), this.threadId, context.data.agentId)\n : await resolveCaller().then((caller) =>\n caller.query(agentsGetThreadWithMessages, { threadId: this.threadId }));\n if (!data) throw new Error(`Thread not found or not accessible: ${this.threadId}`);\n\n this.emitText({ data }, () => {\n const { thread, messages } = data;\n const head = [\n `Thread ${thread._id} [${thread.source}] status: ${thread.status}`,\n thread.title ? `Title: ${thread.title}` : null,\n thread.status === \"error\" && thread.errorMessage ? `Error: ${thread.errorMessage}` : null,\n \"\",\n ].filter((l) => l !== null) as string[];\n\n const body = messages.flatMap((m) => renderMessage(m, this.errorsOnly));\n if (this.errorsOnly && body.length === 0) {\n return [...head, \"No tool errors in this thread.\"].join(\"\\n\");\n }\n return [...head, ...body].join(\"\\n\");\n });\n }\n}\n\nclass AgentAnalyze extends ClientCommand {\n static paths = [[\"agent\", \"analyze\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Aggregate tool failures + error threads across recent threads\",\n });\n\n limit = Option.String(\"--limit\", { description: \"Max threads to scan (default 30)\" });\n\n async run(): Promise<number | void> {\n const cap = this.limit ? Number(this.limit) : 30;\n const context = await this.client().getAuthContext();\n const caller = context.data.kind === \"agent_operator\" ? null : await resolveCaller();\n const threads = context.data.kind === \"agent_operator\"\n ? (await this.client().listAgentThreads({\n includeArchived: \"true\",\n limit: String(Math.min(cap, 50)),\n })).data.map((thread) => normalizeOperatorThread(thread, context.data.agentId))\n : await caller!.query(agentsListRecentThreads, { includeArchived: true, limit: cap });\n\n const errorThreads: Array<{ id: string; message?: string }> = [];\n const toolErrorCounts = new Map<string, number>();\n const errorSamples: string[] = [];\n\n for (const thread of threads) {\n if (thread.status === \"error\") errorThreads.push({ id: thread._id, message: thread.errorMessage });\n const data = context.data.kind === \"agent_operator\"\n ? await fetchOperatorThread(this.client(), thread._id, context.data.agentId)\n : await caller!.query(agentsGetThreadWithMessages, { threadId: thread._id });\n if (!data) continue;\n for (const m of data.messages) {\n for (const res of m.toolResults ?? []) {\n if (!isErrorResult(res)) continue;\n toolErrorCounts.set(res.name, (toolErrorCounts.get(res.name) ?? 0) + 1);\n if (errorSamples.length < 20) errorSamples.push(`${res.name}: ${summarizeValue(res.result, 200)}`);\n }\n }\n }\n\n const rankedToolErrors = [...toolErrorCounts.entries()].sort((a, b) => b[1] - a[1]);\n const data = {\n threadsScanned: threads.length,\n errorThreads,\n toolErrorsByTool: Object.fromEntries(rankedToolErrors),\n errorSamples,\n };\n\n this.emitText({ data }, () => {\n const lines: string[] = [`Scanned ${threads.length} thread(s).`, \"\"];\n lines.push(`Error threads: ${errorThreads.length}`);\n for (const t of errorThreads) lines.push(` \u2717 ${t.id}${t.message ? ` \u2014 ${t.message}` : \"\"}`);\n lines.push(\"\");\n lines.push(`Failed tool calls by tool: ${rankedToolErrors.length === 0 ? \"(none)\" : \"\"}`);\n for (const [name, count] of rankedToolErrors) lines.push(` ${count}\u00D7 ${name}`);\n if (errorSamples.length) {\n lines.push(\"\", \"Sample failures:\");\n for (const s of errorSamples) lines.push(` - ${s}`);\n }\n return lines.join(\"\\n\");\n });\n }\n}\n\nconst REPLY_POLL_INTERVAL_MS = 2_000;\nconst DEFAULT_REPLY_TIMEOUT_S = 180;\n\ntype Caller = Awaited<ReturnType<typeof resolveCaller>>;\ninterface ThreadWithMessages {\n thread: AgentThread;\n messages: AgentMessage[];\n}\n\nasync function fetchThread(caller: Caller, threadId: string): Promise<ThreadWithMessages> {\n const data = await caller.query(agentsGetThreadWithMessages, { threadId });\n if (!data) throw new Error(`Thread not found or not accessible: ${threadId}`);\n return data;\n}\n\nconst sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Wait for the run our message started.\n *\n * `sendUserMessage` sets the thread back to idle and only *schedules* the\n * runner, so \"not running\" alone does not mean the agent answered \u2014 we also\n * require a non-user message beyond our own. An error status is terminal on its\n * own, otherwise a failed run would be indistinguishable from a slow one until\n * the timeout.\n */\nasync function awaitReply(\n caller: Caller,\n threadId: string,\n fromOrder: number,\n timeoutMs: number,\n): Promise<{ data: ThreadWithMessages; timedOut: boolean }> {\n const deadline = Date.now() + timeoutMs;\n for (;;) {\n const data = await fetchThread(caller, threadId);\n const replied = data.messages.some((m) => m.order >= fromOrder && m.role !== \"user\");\n if (data.thread.status === \"error\") return { data, timedOut: false };\n if (data.thread.status !== \"running\" && replied) return { data, timedOut: false };\n if (Date.now() >= deadline) return { data, timedOut: true };\n await sleep(REPLY_POLL_INTERVAL_MS);\n }\n}\n\nfunction renderReply(data: ThreadWithMessages, fromOrder: number, timedOut: boolean): string {\n const lines = data.messages\n .filter((m) => m.order >= fromOrder)\n .flatMap((m) => renderMessage(m, false));\n const head = `Thread ${data.thread._id} status: ${data.thread.status}`;\n const error = data.thread.status === \"error\" && data.thread.errorMessage\n ? `Error: ${data.thread.errorMessage}`\n : null;\n const tail = timedOut\n ? \"\\n(timed out waiting for the agent \u2014 re-run `ente agent show` for the final state)\"\n : \"\";\n return [head, error, \"\", ...lines].filter((l) => l !== null).join(\"\\n\") + tail;\n}\n\n/**\n * Shared tail of the two commands that hand a message to the agent: both take\n * the same wait options and, once the turn is over, print the messages the run\n * produced. `fromOrder` is the first order *after* the caller's own message, so\n * the echo of what we just sent stays out of the output.\n */\nabstract class ThreadMessageCommand extends ClientCommand {\n wait = Option.Boolean(\"--wait\", false, { description: \"Wait for the agent's reply and print it\" });\n timeout = Option.String(\"--timeout\", { description: `Seconds to wait with --wait (default ${DEFAULT_REPLY_TIMEOUT_S})` });\n\n protected async emitReply(\n caller: Caller,\n threadId: string,\n fromOrder: number,\n ): Promise<number | void> {\n const timeoutMs = (this.timeout ? Number(this.timeout) : DEFAULT_REPLY_TIMEOUT_S) * 1_000;\n const { data, timedOut } = await awaitReply(caller, threadId, fromOrder, timeoutMs);\n const messages = data.messages.filter((m) => m.order >= fromOrder);\n this.emitText(\n { data: { thread: data.thread, messages, timedOut } },\n () => renderReply(data, fromOrder, timedOut),\n );\n if (data.thread.status === \"error\") return 1;\n }\n}\n\nclass AgentSend extends ThreadMessageCommand {\n static paths = [[\"agent\", \"send\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Send a message into an existing agent thread; --wait prints the reply\",\n });\n\n threadId = Option.String();\n message = Option.String();\n request = Option.String(\"--request\", \"none\", { description: \"What the user must do next: none | ack | text\" });\n requestPrompt = Option.String(\"--request-prompt\", { description: \"Short prompt shown with the request (at most 1000 characters)\" });\n htmlFile = Option.String(\"--html-file\", { description: \"Optional HTML presentation; the message remains the text fallback\" });\n idempotencyKey = Option.String(\"--idempotency-key\", { description: \"Stable retry key (generated when omitted)\" });\n\n async run(): Promise<number | void> {\n const context = await this.client().getAuthContext();\n if (context.data.kind === \"agent_operator\") {\n if (!context.data.scopes.includes(\"agent:communicate\"))\n throw new Error(\"This operator key does not have the agent:communicate scope. Create a new write-capable agent key.\");\n if (![\"none\", \"ack\", \"text\"].includes(this.request))\n throw new Error(\"--request must be one of: none, ack, text.\");\n const before = await fetchOperatorThread(this.client(), this.threadId, context.data.agentId);\n if (!before) throw new Error(`Thread not found or not accessible: ${this.threadId}`);\n let claimId: string | undefined;\n if (before.thread.attention === \"agent\") {\n const claimed = await this.client().claimAgentThread(\n this.threadId,\n before.thread.attentionVersion ?? 0,\n );\n if (!claimed.data)\n throw new Error(\"Thread was already claimed or no longer awaits this agent. Fetch it again before replying.\");\n claimId = claimed.data.claimId;\n }\n const response = await this.client().replyAgentThread({\n threadId: this.threadId,\n claimId,\n text: this.message,\n ...(this.htmlFile ? { html: readFileSync(this.htmlFile, \"utf8\") } : {}),\n ...(this.request === \"none\" ? {} : { requestKind: this.request as \"ack\" | \"text\" }),\n ...(this.requestPrompt ? { requestPrompt: this.requestPrompt } : {}),\n idempotencyKey: this.idempotencyKey ?? randomUUID(),\n });\n this.emitText(response, () => `Sent external-agent response in thread ${this.threadId}.`);\n return;\n }\n const caller = await resolveCaller();\n const before = await fetchThread(caller, this.threadId);\n if (before.thread.status === \"running\")\n throw new Error(`Thread ${this.threadId} is still running \u2014 wait for the current turn to finish.`);\n const fromOrder = before.thread.messageCount + 1;\n\n await caller.mutation(agentsSendUserMessage, {\n threadId: this.threadId,\n content: this.message,\n });\n\n if (!this.wait) {\n this.emitText({ data: { threadId: this.threadId, sent: true } }, () =>\n `Sent. Follow with: ente agent show ${this.threadId}`);\n return;\n }\n return await this.emitReply(caller, this.threadId, fromOrder);\n }\n}\n\nclass AgentNew extends ThreadMessageCommand {\n static paths = [[\"agent\", \"new\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Start a new agent thread with a first message; --wait prints the reply\",\n });\n\n message = Option.String();\n agent = Option.String(\"--agent\", { description: \"Agent id (defaults to your default agent)\" });\n space = Option.String(\"--space\", { description: \"Space id hint for the thread\" });\n title = Option.String(\"--title\", { description: \"Thread title for external-agent conversations (at most 200 characters)\" });\n request = Option.String(\"--request\", \"none\", { description: \"What the user must do: none | ack | text (default none)\" });\n requestPrompt = Option.String(\"--request-prompt\", { description: \"Short prompt shown with the request (at most 1000 characters)\" });\n htmlFile = Option.String(\"--html-file\", { description: \"Optional HTML presentation; the message remains the text fallback\" });\n idempotencyKey = Option.String(\"--idempotency-key\", { description: \"Stable retry key (generated when omitted)\" });\n\n async run(): Promise<number | void> {\n const context = await this.client().getAuthContext();\n if (context.data.kind === \"agent_operator\") {\n if (!context.data.scopes.includes(\"agent:communicate\"))\n throw new Error(\"This operator key does not have the agent:communicate scope. Create a new write-capable agent key.\");\n if (![\"none\", \"ack\", \"text\"].includes(this.request))\n throw new Error(\"--request must be one of: none, ack, text.\");\n const response = await this.client().createAgentThread({\n title: this.title,\n text: this.message,\n ...(this.htmlFile ? { html: readFileSync(this.htmlFile, \"utf8\") } : {}),\n ...(this.request === \"none\" ? {} : { requestKind: this.request as \"ack\" | \"text\" }),\n ...(this.requestPrompt ? { requestPrompt: this.requestPrompt } : {}),\n idempotencyKey: this.idempotencyKey ?? randomUUID(),\n });\n this.emitText(response, () => `Thread ${response.data.thread.threadId}`);\n return;\n }\n const caller = await resolveCaller();\n const threadId = await caller.mutation(agentsCreateManualThread, {\n content: this.message,\n agentId: this.agent,\n spaceIdHint: this.space,\n });\n\n if (!this.wait) {\n this.emitText({ data: { threadId } }, () => `Thread ${threadId}\\nFollow with: ente agent show ${threadId}`);\n return;\n }\n // The thread opens with the caller's message at order 0.\n return await this.emitReply(caller, threadId, 1);\n }\n}\n\nclass AgentConfigShow extends ClientCommand {\n static paths = [[\"agent\", \"config\", \"show\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Show the bound agent's Ente configuration, mailbox, and scheduled runs\",\n });\n\n async run(): Promise<number | void> {\n const { data } = await this.client().getAgentConfiguration();\n this.emitText({ data }, () => renderAgentConfiguration(data));\n }\n}\n\nclass AgentConfigSetPrompt extends ClientCommand {\n static paths = [[\"agent\", \"config\", \"set-prompt\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Replace the bound agent's Ente prompt configuration\",\n });\n\n prompt = Option.String(\"--text\", { description: \"New prompt text\" });\n file = Option.String(\"--file\", { description: \"Read the new prompt from a UTF-8 file\" });\n\n async run(): Promise<number | void> {\n if (!!this.prompt === !!this.file) {\n throw new Error(\"Provide exactly one of --text or --file.\");\n }\n const prompt = this.file ? readFileSync(this.file, \"utf8\") : this.prompt!;\n const { data } = await this.client().updateAgentPrompt(prompt);\n this.emitText({ data }, () => `Updated Ente prompt configuration for ${data.name}.`);\n }\n}\n\nclass AgentSchedulesConfigure extends ClientCommand {\n static paths = [[\"agent\", \"schedules\", \"configure\"]];\n static usage = Command.Usage({\n category: \"Agent\",\n description: \"Replace the bound agent's Ente scheduled-run configuration from JSON\",\n });\n\n file = Option.String(\"--file\", { required: true, description: \"JSON file containing an array of schedules\" });\n\n async run(): Promise<number | void> {\n const parsed = JSON.parse(readFileSync(this.file, \"utf8\")) as unknown;\n if (!Array.isArray(parsed)) {\n throw new Error(\"The schedules file must contain a JSON array.\");\n }\n const { data } = await this.client().configureAgentSchedules(\n parsed as AgentScheduleInput[],\n );\n this.emitText({ data }, () =>\n `Saved ${data.schedules.length} Ente scheduled run(s) for ${data.name}.`);\n }\n}\n\nexport const AGENT_COMMANDS = [\n AgentList,\n AgentThreads,\n AgentShow,\n AgentSend,\n AgentNew,\n AgentAnalyze,\n AgentConfigShow,\n AgentConfigSetPrompt,\n AgentSchedulesConfigure,\n];\n", "// Meeting agenda commands over the external REST surface shared with other\n// agentic clients.\n\nimport { readFileSync } from \"node:fs\";\n\nimport { Command, Option } from \"clipanion\";\n\nimport { ProfileCommand, ClientCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { spacesFooterFromMemberships, withFooter } from \"../convexResolve.ts\";\nimport { jsonWithSpaces } from \"../format.ts\";\nimport {\n addHtmlBlock,\n formatHtmlBlockList,\n getHtmlBlock,\n listHtmlBlocks,\n readHtmlSource,\n updateHtmlBlock,\n} from \"../htmlBlocks.ts\";\n\nclass AgendaPointCreate extends ClientCommand {\n static paths = [[\"agenda\", \"create-point\"]];\n static usage = Command.Usage({\n category: \"Meeting agenda\",\n description: \"Create a titled agenda point with optional markdown content\",\n });\n\n meeting = Option.String(\"--meeting\", {\n required: true,\n description: \"Meeting activity ID\",\n });\n title = Option.String(\"--title\", {\n required: true,\n description: \"Agenda point title\",\n });\n content = Option.String(\"--content\", {\n description: \"Agenda point markdown content\",\n });\n contentFile = Option.String(\"--content-file\", {\n description: \"Read agenda point markdown from a file\",\n });\n parent = Option.String(\"--parent\", {\n description: \"Optional parent agenda point ID\",\n });\n after = Option.String(\"--after\", {\n description: \"Optional sibling agenda point ID after which to insert\",\n });\n\n async run(): Promise<number | void> {\n if (this.content !== undefined && this.contentFile !== undefined)\n throw new Error(\"Use either --content or --content-file, not both.\");\n\n const contentMarkdown = this.content !== undefined\n ? this.content\n : this.contentFile !== undefined\n ? readFileSync(this.contentFile, \"utf8\")\n : undefined;\n const result = await this.client().createAgendaPoint({\n meetingActivityId: this.meeting,\n title: this.title,\n contentMarkdown,\n parentPointId: this.parent,\n afterPointId: this.after,\n });\n const { agendaPointId } = result.data;\n this.emitText({ data: { agendaPointId } }, () =>\n `Created agenda point \"${this.title}\" (${agendaPointId}).`);\n }\n}\n\nconst agendaPointDocumentId = (pointId: string) => `agenda-point:${pointId}`;\n\nclass AgendaHtmlList extends ProfileCommand {\n static paths = [[\"agenda\", \"html\", \"list\"]];\n static usage = Command.Usage({ category: \"Meeting agenda\", description: \"List interactive HTML blocks in an agenda point\" });\n\n pointId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await listHtmlBlocks(caller, agendaPointDocumentId(this.pointId));\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(formatHtmlBlockList(data), spaces));\n }\n}\n\nclass AgendaHtmlGet extends ProfileCommand {\n static paths = [[\"agenda\", \"html\", \"get\"]];\n static usage = Command.Usage({ category: \"Meeting agenda\", description: \"Read one agenda-point HTML block including source\" });\n\n pointId = Option.String();\n blockId = Option.String();\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const data = await getHtmlBlock(caller, agendaPointDocumentId(this.pointId), this.blockId);\n if (!data) throw new Error(`HTML block not found: ${this.blockId}`);\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(data.source, spaces));\n }\n}\n\nclass AgendaHtmlAdd extends ProfileCommand {\n static paths = [[\"agenda\", \"html\", \"add\"]];\n static usage = Command.Usage({ category: \"Meeting agenda\", description: \"Append an interactive HTML block to an agenda point\" });\n\n pointId = Option.String();\n htmlFile = Option.String({ required: false, name: \"htmlFile\" });\n htmlFileFlag = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - or omit for stdin\" });\n title = Option.String(\"--title\", { required: true, description: \"Block title\" });\n height = Option.String(\"--height\", \"480\", { description: \"Block height in pixels\" });\n\n async run(): Promise<number | void> {\n if (this.htmlFile !== undefined && this.htmlFileFlag !== undefined)\n throw new Error(\"Pass a positional HTML file or --html-file, not both.\");\n const caller = await resolveCaller();\n const data = await addHtmlBlock(caller, {\n documentId: agendaPointDocumentId(this.pointId),\n title: this.title,\n source: readHtmlSource(this.htmlFileFlag ?? this.htmlFile ?? \"-\"),\n height: Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Added interactive HTML '${data.title}' (${data.artifactId})`,\n spaces,\n ));\n }\n}\n\nclass AgendaHtmlUpdate extends ProfileCommand {\n static paths = [[\"agenda\", \"html\", \"update\"]];\n static usage = Command.Usage({ category: \"Meeting agenda\", description: \"Surgically update one agenda-point HTML block\" });\n\n pointId = Option.String();\n blockId = Option.String();\n htmlFile = Option.String(\"--html-file\", { description: \"Read HTML from a file; use - for stdin\" });\n html = Option.String(\"--html\", { description: \"Inline complete HTML source\" });\n title = Option.String(\"--title\", { description: \"Replacement title\" });\n height = Option.String(\"--height\", { description: \"Replacement height in pixels\" });\n\n async run(): Promise<number | void> {\n if ((this.htmlFile === undefined) === (this.html === undefined))\n throw new Error(\"Use exactly one of --html or --html-file.\");\n const caller = await resolveCaller();\n const data = await updateHtmlBlock(caller, {\n documentId: agendaPointDocumentId(this.pointId),\n blockId: this.blockId,\n source: this.html ?? readHtmlSource(this.htmlFile!),\n title: this.title,\n height: this.height === undefined ? undefined : Number(this.height),\n });\n const spaces = await spacesFooterFromMemberships(caller);\n this.emitText(jsonWithSpaces({ data }, spaces), () => withFooter(\n `Updated interactive HTML '${data.title}' to v${data.version}`,\n spaces,\n ));\n }\n}\n\nexport const AGENDA_COMMANDS = [\n AgendaPointCreate,\n AgendaHtmlList,\n AgendaHtmlGet,\n AgendaHtmlAdd,\n AgendaHtmlUpdate,\n];\n", "// `ente feedback \u2026` \u2014 file and triage feedback on the in-app board (the board\n// that replaced the old GitHub-issue pipe). Like every migrated command this\n// calls the SAME public `api.feedback.*` functions the web board uses, via the\n// JWT bridge (see ../convexClient.ts) \u2014 no per-capability REST endpoint. Access:\n// a user manages their own feedback; `--all` (admin-only, mirrors the board's\n// Mine/All toggle) lists every user's \u2014 the backend silently scopes non-admins\n// back to their own.\n\nimport { Command, Option } from \"clipanion\";\nimport { makeFunctionReference } from \"convex/server\";\n\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { formatDatetime } from \"../datetime.ts\";\nimport type { ConvexCaller } from \"../../core/convex.ts\";\n\n// Must match convex/schema/feedback_items.table.ts.\nconst CATEGORIES = [\"missing\", \"confusing\", \"wrong_data\", \"workflow\", \"bug\", \"other\"] as const;\nconst STATUSES = [\"offen\", \"todo\", \"bearbeitung\", \"klaerung\", \"abgeschlossen\", \"spaeter\"] as const;\ntype FeedbackCategory = (typeof CATEGORIES)[number];\ntype FeedbackStatus = (typeof STATUSES)[number];\n\ninterface FeedbackTagView {\n id: string;\n name: string;\n color: string;\n}\n\ninterface FeedbackItemView {\n id: string;\n category: FeedbackCategory;\n summary: string;\n situation?: string;\n goal?: string;\n needToSee?: string;\n needToDo?: string;\n reason?: string;\n currentWorkaround?: string;\n status: FeedbackStatus;\n boardRank: number;\n screenshotUrl: string | null;\n attachments: Array<{ id: string; fileName: string; contentType: string; sizeBytes: number }>;\n createdAt: number;\n submittedBy: { id: string; name: string; email: string };\n tags: FeedbackTagView[];\n}\n\ninterface FeedbackCommentView {\n id: string;\n body: string;\n authorName: string;\n createdAt: number;\n}\n\ninterface PaginationResult<T> {\n page: T[];\n isDone: boolean;\n continueCursor: string;\n}\n\ntype PaginationOpts = { numItems: number; cursor: string | null };\n\n// Typed function references (the CLI is standalone \u2014 it does not import the\n// backend's generated `api`; the wire contract is these public functions in\n// convex/feedback.ts). The `context` object mirrors the browser's submit-time\n// context; the CLI has no browser, so it sends a `/cli` marker.\ntype CreateArgs = {\n category: FeedbackCategory;\n summary: string;\n situation?: string;\n goal?: string;\n needToSee?: string;\n needToDo?: string;\n reason?: string;\n currentWorkaround?: string;\n context: {\n pathname: string;\n search: string;\n hash: string;\n pageTitle: string;\n viewport: { width: number; height: number; devicePixelRatio: number };\n locale: string;\n timezone: string;\n };\n};\n\nconst createFeedback = makeFunctionReference<\"mutation\", CreateArgs, { feedbackId: string }>(\n \"feedback:create\",\n);\nconst getFeedback = makeFunctionReference<\"query\", { id: string }, FeedbackItemView | null>(\n \"feedback:get\",\n);\ntype FeedbackScope = \"mine\" | \"all\";\nconst listColumn = makeFunctionReference<\n \"query\",\n { status: FeedbackStatus; paginationOpts: PaginationOpts; text?: string; scope?: FeedbackScope },\n PaginationResult<FeedbackItemView>\n>(\"feedback:listColumn\");\nconst updateStatus = makeFunctionReference<\"mutation\", { id: string; status: FeedbackStatus }, null>(\n \"feedback:updateStatus\",\n);\nconst listComments = makeFunctionReference<\"query\", { id: string }, FeedbackCommentView[]>(\n \"feedback:listComments\",\n);\nconst addComment = makeFunctionReference<\"mutation\", { id: string; body: string }, FeedbackCommentView>(\n \"feedback:addComment\",\n);\n\nconst CLI_CONTEXT: CreateArgs[\"context\"] = {\n pathname: \"/cli\",\n search: \"\",\n hash: \"\",\n pageTitle: \"ente-cli feedback send\",\n viewport: { width: 0, height: 0, devicePixelRatio: 1 },\n locale: \"de\",\n timezone: \"Europe/Berlin\",\n};\n\nconst PAGE_SIZE = 50;\nconst MAX_PAGES = 50;\n\n/** Paginate one board column, up to `limit` items (server-side `text` filter). */\nasync function collectColumn(\n caller: ConvexCaller,\n status: FeedbackStatus,\n text: string | undefined,\n limit: number,\n scope: FeedbackScope,\n): Promise<FeedbackItemView[]> {\n const items: FeedbackItemView[] = [];\n let cursor: string | null = null;\n for (let page = 0; page < MAX_PAGES; page += 1) {\n const res: PaginationResult<FeedbackItemView> = await caller.query(listColumn, {\n status,\n paginationOpts: { numItems: Math.min(PAGE_SIZE, limit - items.length), cursor },\n ...(text ? { text } : {}),\n scope,\n });\n items.push(...res.page);\n if (res.isDone || items.length >= limit) break;\n cursor = res.continueCursor;\n }\n return items.slice(0, limit);\n}\n\nfunction parseCategory(value: string): FeedbackCategory {\n if ((CATEGORIES as readonly string[]).includes(value)) return value as FeedbackCategory;\n throw new Error(`Invalid category '${value}'. Use one of: ${CATEGORIES.join(\" | \")}.`);\n}\n\nfunction parseStatus(value: string): FeedbackStatus {\n if ((STATUSES as readonly string[]).includes(value)) return value as FeedbackStatus;\n throw new Error(`Invalid status '${value}'. Use one of: ${STATUSES.join(\" | \")}.`);\n}\n\nfunction submitter(item: FeedbackItemView): string {\n return item.submittedBy.name || item.submittedBy.email || \"(unknown)\";\n}\n\n// \u2500\u2500 feedback send \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass FeedbackSendCommand extends ProfileCommand {\n static paths = [[\"feedback\", \"send\"]];\n static usage = Command.Usage({\n category: \"Feedback\",\n description: \"File feedback on the in-app board (category + summary + optional detail fields)\",\n });\n\n summary = Option.String({ required: true, name: \"summary\" });\n category = Option.String(\"--category\", { description: `Category: ${CATEGORIES.join(\"|\")} (default other)` });\n situation = Option.String(\"--situation\", { description: \"What happened / where you were\" });\n goal = Option.String(\"--goal\", { description: \"What you were trying to do\" });\n needToSee = Option.String(\"--need-to-see\", { description: \"What you expected to see\" });\n needToDo = Option.String(\"--need-to-do\", { description: \"What you needed to do\" });\n reason = Option.String(\"--reason\", { description: \"Why it matters\" });\n workaround = Option.String(\"--workaround\", { description: \"Current workaround, if any\" });\n\n async run(): Promise<number | void> {\n const summary = this.summary.trim();\n if (summary.length === 0) throw new Error(\"feedback send: summary must not be empty.\");\n const category = parseCategory(this.category ?? \"other\");\n\n const caller = await resolveCaller();\n const res = await caller.mutation(createFeedback, {\n category,\n summary,\n ...(this.situation !== undefined ? { situation: this.situation } : {}),\n ...(this.goal !== undefined ? { goal: this.goal } : {}),\n ...(this.needToSee !== undefined ? { needToSee: this.needToSee } : {}),\n ...(this.needToDo !== undefined ? { needToDo: this.needToDo } : {}),\n ...(this.reason !== undefined ? { reason: this.reason } : {}),\n ...(this.workaround !== undefined ? { currentWorkaround: this.workaround } : {}),\n context: CLI_CONTEXT,\n });\n this.emitText({ data: { feedbackId: res.feedbackId, category, summary } }, () =>\n `Filed feedback ${res.feedbackId} [${category}] \"${summary}\".`,\n );\n }\n}\n\n// \u2500\u2500 feedback list \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass FeedbackListCommand extends ProfileCommand {\n static paths = [[\"feedback\", \"list\"]];\n static usage = Command.Usage({\n category: \"Feedback\",\n description: \"List feedback board items (all columns, or one via --status)\",\n });\n\n status = Option.String(\"--status\", { description: `Only this column: ${STATUSES.join(\"|\")}` });\n text = Option.String(\"--text\", { description: \"Filter: summary/detail contains this text\" });\n limit = Option.String(\"--limit\", { description: \"Max rows (default 50)\" });\n all = Option.Boolean(\"--all\", { description: \"Admin only: list every user's feedback (default: only yours)\" });\n\n async run(): Promise<number | void> {\n const limit = this.limit === undefined ? 50 : Number.parseInt(this.limit, 10);\n if (Number.isNaN(limit) || limit <= 0) {\n throw new Error(`feedback list: --limit must be a positive integer, got \"${this.limit}\".`);\n }\n const statuses: FeedbackStatus[] = this.status ? [parseStatus(this.status)] : [...STATUSES];\n const scope: FeedbackScope = this.all ? \"all\" : \"mine\";\n\n const caller = await resolveCaller();\n const collected: FeedbackItemView[] = [];\n for (const status of statuses) {\n if (collected.length >= limit) break;\n collected.push(...(await collectColumn(caller, status, this.text, limit - collected.length, scope)));\n }\n // Newest first across columns so the CLI list reads chronologically.\n collected.sort((a, b) => b.createdAt - a.createdAt);\n const items = collected.slice(0, limit);\n\n this.print(\n { data: items },\n () =>\n items.map((it) => ({\n id: it.id,\n status: it.status,\n category: it.category,\n summary: it.summary.length > 60 ? `${it.summary.slice(0, 57)}\u2026` : it.summary,\n by: submitter(it),\n created: formatDatetime(it.createdAt),\n })),\n [\"id\", \"status\", \"category\", \"summary\", \"by\", \"created\"],\n );\n }\n}\n\n// \u2500\u2500 feedback view \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass FeedbackViewCommand extends ProfileCommand {\n static paths = [[\"feedback\", \"view\"]];\n static usage = Command.Usage({\n category: \"Feedback\",\n description: \"Show one feedback item in full, with its comment thread\",\n });\n\n feedbackId = Option.String({ required: true, name: \"feedbackId\" });\n\n async run(): Promise<number | void> {\n const caller = await resolveCaller();\n const item = await caller.query(getFeedback, { id: this.feedbackId });\n if (item === null) throw new Error(`No feedback item with id ${this.feedbackId}.`);\n const comments = await caller.query(listComments, { id: this.feedbackId });\n\n this.emitText({ data: { item, comments } }, () => {\n const lines: string[] = [\n `${item.id} [${item.category}] ${item.status}`,\n item.summary,\n \"\",\n `Submitted by: ${submitter(item)} ${formatDatetime(item.createdAt)}`,\n ];\n if (item.tags.length) lines.push(`Tags: ${item.tags.map((t) => t.name).join(\", \")}`);\n const detail: Array<[string, string | undefined]> = [\n [\"Situation\", item.situation],\n [\"Goal\", item.goal],\n [\"Need to see\", item.needToSee],\n [\"Need to do\", item.needToDo],\n [\"Reason\", item.reason],\n [\"Workaround\", item.currentWorkaround],\n ];\n for (const [label, value] of detail) {\n if (value && value.trim().length) lines.push(\"\", `\u2500\u2500 ${label} \u2500\u2500`, value);\n }\n if (item.screenshotUrl) lines.push(\"\", `Screenshot: ${item.screenshotUrl}`);\n if (item.attachments.length) {\n lines.push(\"\", `\u2500\u2500 Attachments (${item.attachments.length}) \u2500\u2500`);\n for (const a of item.attachments) lines.push(` ${a.fileName} (${a.contentType}, ${a.sizeBytes} B)`);\n }\n lines.push(\"\", `\u2500\u2500 Comments (${comments.length}) \u2500\u2500`);\n if (comments.length === 0) {\n lines.push(\"(none)\");\n } else {\n for (const c of comments) {\n lines.push(`[${formatDatetime(c.createdAt)}] ${c.authorName || \"(unknown)\"}: ${c.body}`);\n }\n }\n return lines.join(\"\\n\");\n });\n }\n}\n\n// \u2500\u2500 feedback comment \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass FeedbackCommentCommand extends ProfileCommand {\n static paths = [[\"feedback\", \"comment\"]];\n static usage = Command.Usage({\n category: \"Feedback\",\n description: \"Add a comment to a feedback item's thread\",\n });\n\n feedbackId = Option.String({ required: true, name: \"feedbackId\" });\n body = Option.String({ required: true, name: \"body\" });\n\n async run(): Promise<number | void> {\n if (this.body.trim().length === 0) throw new Error(\"feedback comment: body must not be empty.\");\n const caller = await resolveCaller();\n const comment = await caller.mutation(addComment, { id: this.feedbackId, body: this.body });\n this.emitText({ data: comment }, () =>\n `Added comment ${comment.id} by ${comment.authorName || \"(unknown)\"}.`,\n );\n }\n}\n\n// \u2500\u2500 feedback status \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass FeedbackStatusCommand extends ProfileCommand {\n static paths = [[\"feedback\", \"status\"]];\n static usage = Command.Usage({\n category: \"Feedback\",\n description: `Move a feedback item to a board column (${STATUSES.join(\"|\")})`,\n });\n\n feedbackId = Option.String({ required: true, name: \"feedbackId\" });\n status = Option.String({ required: true, name: \"status\" });\n\n async run(): Promise<number | void> {\n const status = parseStatus(this.status);\n const caller = await resolveCaller();\n await caller.mutation(updateStatus, { id: this.feedbackId, status });\n this.emitText({ data: { feedbackId: this.feedbackId, status } }, () =>\n `Moved feedback ${this.feedbackId} to '${status}'.`,\n );\n }\n}\n\nexport const FEEDBACK_COMMANDS = [\n FeedbackSendCommand,\n FeedbackListCommand,\n FeedbackViewCommand,\n FeedbackCommentCommand,\n FeedbackStatusCommand,\n];\n", "// Guide / topics command \u2014 the built-in help system. Offline (no API client).\n// Ports commands/guide.py, plus a new \"limits\" topic documenting the backend\n// boundaries the CLI surfaces (rename, pin scoping, cross-space linking, merge).\n\nimport { Command, Option } from \"clipanion\";\n\nimport { BaseCommand } from \"../command.ts\";\n\ninterface Topic {\n title: string;\n content: string;\n}\n\nconst TOPICS: Record<string, Topic> = {\n overview: {\n title: \"ente CLI \u2014 Quick Reference\",\n content: `ente is a shared knowledge graph for people, orgs, projects, topics, and their activities.\n\nCore concepts:\n \u2022 Entities (nouns): person, org, project, topic\n \u2022 Activities (verbs): note, conversation, meeting, call, message, task\n \u2022 Pins: direct child-to-parent relationships (\"Sarah works at Acme\")\n \u2022 Aliases: searchable alternative names on entities\n\nLink each activity to the most specific independently central entities. Child\nrelationships make activities visible on direct parents, so do not link\nancestors redundantly.\n\nCommands:\n ente search <query> Fuzzy search entities\n ente ask <question> Natural-language answer (AI synthesis + citations)\n ente query <question> Deterministic evidence retrieval (no synthesis)\n ente entity create|get|update|rename|archive|restore|pin|unpin\n ente entity list [--archived]\n ente pins list <entity> List pins for an entity\n ente task list|get|create|update|done|assign|unassign|set-assignees|clear-assignees\n ente space members\n ente recording-pipeline show|set-prompt|reset-prompt|set-dictionary\n ente feedback send|list|view|comment|status File + triage in-app feedback\n ente notification send Email your own Ente account (text, HTML, and images)\n ente activity create|list|get|update|delete|restore\n ente activity content read|edit\n ente agenda create-point|link-task\n ente activity message add <activityId> --content \"...\"\n ente activity attachment upload <activityId> <file>\n ente activity list [--archived]\n ente guide [topic] This help\n\nRun \\`ente <command> --help\\` for detailed usage on any command.\nRun \\`ente guide <topic>\\` for deep dives: entities, tasks, activities, search, patterns, limits`,\n },\n entities: {\n title: \"Entities \u2014 People, Orgs, Projects, Topics\",\n content: `Types: person | org | project | topic\n\nCreating entities:\n ente entity create \"Jane Doe\" --type person --pin \"Acme Corp\" --alias \"JD\"\n # Add --share-parents when the parent is not already in the new entity's space.\n\n \u26A0 ALWAYS search before creating:\n ente search \"Jane Doe\"\n Duplicates are hard to clean up. Even if you think an entity doesn't exist, search first.\n\nRenaming:\n ente entity rename \"Lorey Georg\" \"Georg Lorey\" # changes the display name\n # or: ente entity update \"<id>\" --name \"Georg Lorey\"\n\nAliases:\n Searchable alternative names. Add them when entities have common abbreviations:\n ente entity update \"Helmholtz-Zentrum\" --alias-add \"HZI\"\n\n Proactively add aliases when you notice a nickname/abbreviation. Prevents duplicates.\n\nPins (relationships):\n ente entity pin \"Jane Doe\" \"Acme Corp\" --role \"student\"\n # optional role; displays as Acme Corp \u00B7 student\n\n Add --share-parents to confirm sharing a missing parent and its ancestors into\n every space of the child. Without that flag, the command reports the required grants.\n\n Pins are structural, not generic related-to links. When a durable direct\n parent is known, pin the child to that parent (for example person -> org or\n development area -> project). Do not pin every merely relevant project.\n\nAttributes:\n Free key-value pairs (email, phone, role, \u2026):\n ente entity update \"Jane\" --attr email=jane@acme.com --attr role=CEO\n Attributes are merged on update \u2014 existing keys are preserved.\n\nArchiving (trash):\n ente entity archive \"Old Project\" # move to trash (soft delete)\n ente entity list --archived # list trashed entities\n ente entity restore <entity-id> [--share-parents] # restore from trash`,\n },\n tasks: {\n title: \"Tasks \u2014 Deadlines, Assignments\",\n content: `Tasks are activities with type \"task\". They have deadline, completed, assigneeIds.\n\nCreating tasks:\n ente task create \"Reply to Ashley\" --entity \"Ashley\" --space \"Personal\" --deadline \"tomorrow\" --assignee ashley@example.com\n ente task create \"Fix bug\" --entity \"TiVA\" --space \"TiVA\" --deadline \"+3 days\" --attr github-issue=https://...\n\n Every task needs a deadline. If not specified, defaults to tomorrow 22:00 Berlin.\n\nDeadlines (human-friendly):\n \"tomorrow\" \u2192 tomorrow 22:00 Berlin\n \"tomorrow 14:00\" \u2192 tomorrow 14:00 Berlin\n \"today\" \u2192 today 22:00 Berlin\n \"+3 days\" / \"+1 week\" \u2192 relative, 22:00 Berlin\n \"2026-03-15\" \u2192 that date 22:00 Berlin\n \"2026-03-15 14:00\" \u2192 that date+time Berlin\n\nShortIds:\n Tasks get a #N number. Use it everywhere:\n ente task get 5 ; ente task done 5 ; ente task update 5 --content \"new proposal\"\n\nAssignees:\n ente space members --space \"TiVA\" # find member user IDs/emails\n ente task assign 5 <userId-or-email> # add assignee (must be space member)\n ente task unassign 5 <userId-or-email>\n ente task set-assignees 5 --assignee <userId-or-email>\n ente task clear-assignees 5\n\nCompleting:\n ente task done 5 # marks completed, frees shortId`,\n },\n activities: {\n title: \"Activities \u2014 Notes, Conversations, Meetings, Calls, Messages\",\n content: `Activity types: note | conversation | meeting | call | message | task\n\nCreating activities:\n ente activity create --type conversation --title \"Call with Erik\" \\\\\n --entity \"Erik Stahl\" --entity \"Preclinics\" --space \"Preclinics\" \\\\\n --content \"Discussed QM system. Follow up on export feature.\"\n\nMeeting agendas:\n ente activity create --type meeting --title \"QM system review\" ...\n ente agenda create-point --meeting <meeting-id> --title \"Rollout\" --content=\"- Decision ...\"\n ente agenda link-task --point <point-id> --task \"#12\"\n\n Prefer agenda points for structured meeting content when they add useful\n topic structure. Link meeting-derived tasks to the point they came from.\n\nGolden rule:\n Link the most specific independently central entities. For a meeting with a\n known person, link the person; their parent organization is already implied.\n Add the organization or project only when it is independently the subject.\n\nListing:\n ente activity list --entity \"Erik\" --hours 168 # last 7 days\n ente activity list --limit 20 # most recent\n\nChronological updates:\n ente activity message add <activity-id> --content \"Requirements changed: export must include archived rows.\"\n\nFocused edits to long bodies:\n 1. ente activity content read <activity-id> --json\n 2. Write a small JSON operation array using returned targets.\n 3. ente activity content edit <activity-id> --expected-version <contentVersion> --operations-file edits.json --json\n If the version conflicts, reread before editing. Use activity update --content-file only for deliberate whole-body replacement.\n\nTitle rules:\n \u2022 Never put a date in the title \u2014 activities have timestamps\n \u2022 Keep titles concise and descriptive\n\nArchiving (trash):\n ente activity delete <activity-id> # move to trash (soft delete)\n ente activity list --archived # list trashed activities\n ente activity restore <activity-id> # restore from trash`,\n },\n search: {\n title: \"Search \u2014 Fuzzy, Multi-Strategy\",\n content: `Search is fuzzy and multi-strategy. A single query searches across:\n\n 1. Name (exact > prefix > Levenshtein fuzzy)\n 2. Aliases (same fuzzy matching, slightly lower rank than name)\n 3. Attributes (email, phone \u2014 use local part only, not full address)\n 4. Description text\n\nUsage:\n ente search \"Ashley\" # fuzzy name search\n ente search \"Ashley\" --type person # filter by type\n ente search \"HZI\" # finds via alias\n\nTips:\n \u2022 Typos work: \"Scharkowsky\" finds \"Scharkowski\"\n \u2022 For email search, use local part only (e.g. \"lernst\" not \"lernst@\u2026\")\n \u2022 Use --json for full API response with all entity details`,\n },\n patterns: {\n title: \"Common Patterns\",\n content: `Log a meeting:\n 1. ente search \"person name\" # find entity, check pins\n 2. ente activity create --type meeting --title \"...\" \\\\\n --entity \"person\" --entity \"their org\" --space \"...\"\n 3. ente agenda create-point --meeting <meeting-id> --title \"...\" --content=\"...\"\n 4. If follow-ups: create each task, then:\n ente agenda link-task --point <point-id> --task <task-id|#N>\n\nPrepare for a meeting:\n 1. ente entity get \"person name\" # see recent activities + pins\n 2. ente task list --entity \"person\" # open tasks related to them\n\nBrain dump \u2192 tasks:\n 1. For each actionable item:\n ente task create \"title\" --entity \"...\" --space \"...\" --deadline \"...\" --content \"Context: ...\"\n\nFind-or-create entity:\n 1. ente search \"name\"\n 2. If not found: ente entity create \"name\" --type person --pin \"org\" --alias \"nick\"`,\n },\n limits: {\n title: \"Limits & Boundaries \u2014 what the API does and doesn't allow\",\n content: `Some operations are bounded by the backend, not the CLI. What's possible:\n\nRename \u2014 SUPPORTED:\n ente entity rename \"<old>\" \"<new>\" (or: entity update <id> --name \"<new>\")\n\nRelationships are spaceless:\n A parent relationship is visible when your key can access both entities,\n even through different spaces. Every active parent and ancestor must also belong to\n every space of its active children. Use --share-parents to confirm the required grants\n when pinning a child or adding it to a space. A parent cannot leave a space\n while an active child remains there. An entity also cannot leave a space while\n it owns activities there. Use --remove-from-activities to remove those links in\n one operation when every affected activity has another owner.\n\nCross-space activity linking \u2014 BOUNDED:\n An activity can only link entities that are already in its target space.\n A failed write returns the exact grant set and fingerprint. Retry with\n \\`--auto-link --entity-space-grant-fingerprint <token>\\` only after confirming\n those grants. A changed hierarchy requires a new confirmation.\n\nMerging duplicates \u2014 UI ONLY:\n The external API has no merge endpoint. To merge two entities, do it in the web\n UI. \\`entity rename\\` lets you fix the surviving entity's display name afterward.\n\nAdding an entity to a shared space \u2014 UI ONLY:\n There is no API to add an existing entity to a shared space (only personal-space\n confirmed auto-link, and remove-from-space). Do it in the web UI.`,\n },\n};\n\nconst TOPIC_NAMES = Object.keys(TOPICS);\n\nclass GuideCmd extends BaseCommand {\n static paths = [[\"guide\"]];\n static usage = Command.Usage({ category: \"Help\", description: \"Show usage guide\" });\n\n topic = Option.String({ required: false });\n\n async run(): Promise<number | void> {\n if (!this.topic) {\n const overview = TOPICS.overview!;\n this.out(`\\n ${overview.title}\\n`);\n this.out(overview.content);\n this.out(\n \"\\nTopics:\\n\" +\n TOPIC_NAMES.filter((t) => t !== \"overview\")\n .map((t) => ` ${t.padEnd(12)} ${TOPICS[t]!.title}`)\n .join(\"\\n\"),\n );\n return;\n }\n\n const entry = TOPICS[this.topic.toLowerCase()];\n if (!entry) {\n this.err(`Unknown topic: '${this.topic}'. Available: ${TOPIC_NAMES.join(\", \")}`);\n return 1;\n }\n this.out(`\\n ${entry.title}\\n`);\n this.out(entry.content);\n }\n}\n\nexport const GUIDE_COMMANDS = [GuideCmd];\n", "import { makeFunctionReference } from \"convex/server\";\nimport type { ConvexCaller } from \"../core/convex.ts\";\n\nexport interface CanvasBoardSummary {\n boardId: string;\n entityId: string;\n spaceId: string;\n title: string;\n updatedAt: number;\n reviewPath: string;\n}\n\nexport interface CanvasHtmlPanelSummary {\n boardId: string;\n entityId: string;\n elementId: string;\n title: string;\n sourceHash: string;\n sourceBytes: number;\n x: number;\n y: number;\n width: number;\n height: number;\n version: number;\n reviewPath: string;\n}\n\nexport interface CanvasHtmlPanel extends CanvasHtmlPanelSummary { html: string }\n\nconst listBoardsRef = makeFunctionReference<\"query\", { entityId: string }, CanvasBoardSummary[]>(\n \"excalidrawBoardHtmlTools:listBoards\",\n);\nconst listPanelsRef = makeFunctionReference<\"query\", { boardId: string }, CanvasHtmlPanelSummary[]>(\n \"excalidrawBoardHtmlTools:listPanels\",\n);\nconst getPanelRef = makeFunctionReference<\"query\", { boardId: string; elementId: string }, CanvasHtmlPanel | null>(\n \"excalidrawBoardHtmlTools:getPanel\",\n);\nconst createPanelRef = makeFunctionReference<\"mutation\", {\n boardId: string; title: string; html: string; width?: number; height?: number;\n placement?: \"below_content\" | \"empty_region\" | \"manual\";\n direction?: \"right\" | \"down\" | \"left\" | \"up\";\n x?: number; y?: number; operationId?: string;\n}, CanvasHtmlPanel & { replayed: boolean }>(\"excalidrawBoardHtmlTools:createPanel\");\nconst updatePanelRef = makeFunctionReference<\"mutation\", {\n boardId: string; elementId: string; expectedVersion: number; expectedSourceHash: string;\n title: string; html: string; x?: number; y?: number; width?: number; height?: number;\n}, CanvasHtmlPanel | null>(\"excalidrawBoardHtmlTools:updatePanel\");\nconst deletePanelRef = makeFunctionReference<\"mutation\", {\n boardId: string; elementId: string; expectedVersion: number; expectedSourceHash: string;\n}, { deleted: true; boardId: string; entityId: string; elementId: string }>(\"excalidrawBoardHtmlTools:deletePanel\");\n\nexport const listCanvasBoards = (caller: ConvexCaller, entityId: string) =>\n caller.query(listBoardsRef, { entityId });\nexport const listCanvasHtmlPanels = (caller: ConvexCaller, boardId: string) =>\n caller.query(listPanelsRef, { boardId });\nexport const getCanvasHtmlPanel = (caller: ConvexCaller, boardId: string, elementId: string) =>\n caller.query(getPanelRef, { boardId, elementId });\nexport const createCanvasHtmlPanel = (caller: ConvexCaller, args: {\n boardId: string; title: string; html: string; width?: number; height?: number;\n placement?: \"below_content\" | \"empty_region\" | \"manual\";\n direction?: \"right\" | \"down\" | \"left\" | \"up\";\n x?: number; y?: number; operationId?: string;\n}) =>\n caller.mutation(createPanelRef, args);\n\nexport async function updateCanvasHtmlPanel(\n caller: ConvexCaller,\n args: { boardId: string; elementId: string; title?: string; html: string; x?: number; y?: number; width?: number; height?: number },\n) {\n const current = await getCanvasHtmlPanel(caller, args.boardId, args.elementId);\n if (!current) throw new Error(`Canvas HTML panel not found: ${args.elementId}`);\n return caller.mutation(updatePanelRef, {\n ...args,\n title: args.title ?? current.title,\n expectedVersion: current.version,\n expectedSourceHash: current.sourceHash,\n });\n}\n\nexport async function deleteCanvasHtmlPanel(caller: ConvexCaller, boardId: string, elementId: string) {\n const current = await getCanvasHtmlPanel(caller, boardId, elementId);\n if (!current) throw new Error(`Canvas HTML panel not found: ${elementId}`);\n return caller.mutation(deletePanelRef, {\n boardId,\n elementId,\n expectedVersion: current.version,\n expectedSourceHash: current.sourceHash,\n });\n}\n", "import { Command, Option } from \"clipanion\";\nimport { ProfileCommand } from \"../command.ts\";\nimport { resolveCaller } from \"../convexClient.ts\";\nimport { readHtmlSource } from \"../htmlBlocks.ts\";\nimport {\n createCanvasHtmlPanel,\n deleteCanvasHtmlPanel,\n getCanvasHtmlPanel,\n listCanvasBoards,\n listCanvasHtmlPanels,\n updateCanvasHtmlPanel,\n} from \"../canvasHtml.ts\";\n\nfunction numberFlag(value: string | undefined, name: string) {\n if (value === undefined) return undefined;\n const parsed = Number(value);\n if (!Number.isFinite(parsed)) throw new Error(`${name} must be a finite number`);\n return parsed;\n}\n\nclass CanvasBoardsCmd extends ProfileCommand {\n static paths = [[\"canvas\", \"boards\"]];\n static usage = Command.Usage({ category: \"Canvas\", description: \"List an entity's accessible Excalidraw boards\" });\n entityId = Option.String({ required: true });\n async run() {\n const data = await listCanvasBoards(await resolveCaller(), this.entityId);\n this.emitText({ data }, () => data.length\n ? data.map((board) => `${board.boardId} ${board.title} ${board.reviewPath}`).join(\"\\n\")\n : \"No Canvas boards.\");\n }\n}\n\nclass CanvasHtmlListCmd extends ProfileCommand {\n static paths = [[\"canvas\", \"html\", \"list\"]];\n static usage = Command.Usage({ category: \"Canvas\", description: \"List interactive HTML panels on a Canvas board\" });\n boardId = Option.String({ required: true });\n async run() {\n const data = await listCanvasHtmlPanels(await resolveCaller(), this.boardId);\n this.emitText({ data }, () => data.length\n ? data.map((panel) => `${panel.elementId} v${panel.version} ${panel.title} ${panel.width}\u00D7${panel.height}`).join(\"\\n\")\n : \"No Canvas HTML panels.\");\n }\n}\n\nclass CanvasHtmlGetCmd extends ProfileCommand {\n static paths = [[\"canvas\", \"html\", \"get\"]];\n static usage = Command.Usage({ category: \"Canvas\", description: \"Read one Canvas HTML panel, including its source\" });\n boardId = Option.String({ required: true });\n elementId = Option.String({ required: true });\n async run() {\n const data = await getCanvasHtmlPanel(await resolveCaller(), this.boardId, this.elementId);\n if (!data) throw new Error(`Canvas HTML panel not found: ${this.elementId}`);\n this.emitText({ data }, () => data.html);\n }\n}\n\nclass CanvasHtmlCreateCmd extends ProfileCommand {\n static paths = [[\"canvas\", \"html\", \"create\"]];\n static usage = Command.Usage({ category: \"Canvas\", description: \"Insert a self-contained HTML panel on a Canvas board\" });\n boardId = Option.String({ required: true });\n title = Option.String(\"--title\", { required: true, description: \"Panel title\" });\n file = Option.String(\"--file\", { required: true, description: \"HTML file path, or '-' for stdin\" });\n placement = Option.String(\"--placement\", \"below_content\", { description: \"below_content, empty_region, or manual\" });\n direction = Option.String(\"--direction\", \"right\", { description: \"Direction for empty_region: right, down, left, or up\" });\n x = Option.String(\"--x\");\n y = Option.String(\"--y\");\n width = Option.String(\"--width\");\n height = Option.String(\"--height\");\n operationId = Option.String(\"--operation-id\", { description: \"Stable retry key for idempotent creation\" });\n async run() {\n if (![\"below_content\", \"empty_region\", \"manual\"].includes(this.placement)) throw new Error(\"Invalid --placement\");\n if (![\"right\", \"down\", \"left\", \"up\"].includes(this.direction)) throw new Error(\"Invalid --direction\");\n const data = await createCanvasHtmlPanel(await resolveCaller(), {\n boardId: this.boardId,\n title: this.title,\n html: readHtmlSource(this.file),\n placement: this.placement as \"below_content\" | \"empty_region\" | \"manual\",\n direction: this.direction as \"right\" | \"down\" | \"left\" | \"up\",\n x: numberFlag(this.x, \"--x\"),\n y: numberFlag(this.y, \"--y\"),\n width: numberFlag(this.width, \"--width\"),\n height: numberFlag(this.height, \"--height\"),\n operationId: this.operationId,\n });\n this.emitText({ data }, () => `${data.replayed ? \"Reused\" : \"Created\"} ${data.elementId}\\n${data.reviewPath}`);\n }\n}\n\nclass CanvasHtmlUpdateCmd extends ProfileCommand {\n static paths = [[\"canvas\", \"html\", \"update\"]];\n static usage = Command.Usage({ category: \"Canvas\", description: \"Replace a Canvas HTML panel after a fresh version read\" });\n boardId = Option.String({ required: true });\n elementId = Option.String({ required: true });\n file = Option.String(\"--file\", { required: true, description: \"HTML file path, or '-' for stdin\" });\n title = Option.String(\"--title\");\n x = Option.String(\"--x\");\n y = Option.String(\"--y\");\n width = Option.String(\"--width\");\n height = Option.String(\"--height\");\n async run() {\n const data = await updateCanvasHtmlPanel(await resolveCaller(), {\n boardId: this.boardId,\n elementId: this.elementId,\n html: readHtmlSource(this.file),\n title: this.title,\n x: numberFlag(this.x, \"--x\"), y: numberFlag(this.y, \"--y\"),\n width: numberFlag(this.width, \"--width\"), height: numberFlag(this.height, \"--height\"),\n });\n this.emitText({ data }, () => `Updated ${this.elementId}`);\n }\n}\n\nclass CanvasHtmlDeleteCmd extends ProfileCommand {\n static paths = [[\"canvas\", \"html\", \"delete\"]];\n static usage = Command.Usage({ category: \"Canvas\", description: \"Delete one Canvas HTML panel after a fresh version read\" });\n boardId = Option.String({ required: true });\n elementId = Option.String({ required: true });\n async run() {\n const data = await deleteCanvasHtmlPanel(await resolveCaller(), this.boardId, this.elementId);\n this.emitText({ data }, () => `Deleted ${this.elementId}`);\n }\n}\n\nexport const CANVAS_COMMANDS = [\n CanvasBoardsCmd,\n CanvasHtmlListCmd,\n CanvasHtmlGetCmd,\n CanvasHtmlCreateCmd,\n CanvasHtmlUpdateCmd,\n CanvasHtmlDeleteCmd,\n];\n", "import { readFileSync } from \"node:fs\";\nimport { Command, Option } from \"clipanion\";\nimport { ClientCommand } from \"../command.ts\";\nimport { parseInlineImageSpecs, readOutgoingEmailAttachment } from \"../fileAttachments.ts\";\nimport { NOTIFICATION_EMAIL_CLI_SURFACE } from \"../notificationEmailContract.ts\";\nimport type { NotificationEmailAttachmentInput } from \"../types.ts\";\n\nconst CLI_FIELDS = NOTIFICATION_EMAIL_CLI_SURFACE.inputProperties;\nconst CLI_LIMITS = NOTIFICATION_EMAIL_CLI_SURFACE.limits;\n\nfunction readBody(\n inline: string | undefined,\n file: string | undefined,\n label: \"text\" | \"html\",\n): string | undefined {\n if (inline !== undefined && file !== undefined)\n throw new Error(`notification send: use either --${label} or --${label}-file, not both.`);\n const value = file !== undefined ? readFileSync(file, \"utf8\") : inline;\n if (value !== undefined && !value.trim())\n throw new Error(`notification send: ${label} body must not be empty.`);\n return value;\n}\n\nexport function readNotificationEmailAttachments(\n imagePaths: readonly string[] = [],\n inlineImageSpecs: readonly string[] = [],\n attachmentPaths: readonly string[] = [],\n): NotificationEmailAttachmentInput[] | undefined {\n const count = imagePaths.length + inlineImageSpecs.length + attachmentPaths.length;\n if (count === 0) return undefined;\n if (count > CLI_LIMITS.maxAttachments) {\n throw new Error(\n `notification send: at most ${CLI_LIMITS.maxAttachments} files may be attached.`,\n );\n }\n\n const inlineImages = parseInlineImageSpecs(inlineImageSpecs, {\n maxContentIdLength: CLI_LIMITS.maxContentIdLength,\n commandLabel: \"notification send\",\n });\n\n return [\n ...imagePaths.map((path) => readOutgoingEmailAttachment(path, {\n maxBytes: CLI_LIMITS.maxAttachmentBytes,\n maxFilenameLength: CLI_LIMITS.maxFilenameLength,\n requireImage: true,\n commandLabel: \"notification send\",\n })),\n ...inlineImages.map(({ contentId, path }) => readOutgoingEmailAttachment(path, {\n maxBytes: CLI_LIMITS.maxAttachmentBytes,\n maxFilenameLength: CLI_LIMITS.maxFilenameLength,\n contentId,\n requireImage: true,\n commandLabel: \"notification send\",\n })),\n ...attachmentPaths.map((path) => readOutgoingEmailAttachment(path, {\n maxBytes: CLI_LIMITS.maxAttachmentBytes,\n maxFilenameLength: CLI_LIMITS.maxFilenameLength,\n commandLabel: \"notification send\",\n })),\n ];\n}\n\nclass NotificationSendCommand extends ClientCommand {\n static paths = [[\"notification\", \"send\"]];\n static usage = Command.Usage({\n category: \"Notifications\",\n description: \"Send an email from Ente to your own account email\",\n examples: [[\n \"Send a rich notification\",\n \"ente notification send --subject \\\"Weekly brief\\\" --text \\\"Your brief is ready.\\\" --html-file ./brief.html\",\n ], [\n \"Embed a screenshot in HTML\",\n \"ente notification send --subject \\\"Runway\\\" --text \\\"Runway report attached.\\\" --html-file ./report.html --inline-image runway=./runway.png\",\n ]],\n });\n\n subject = Option.String(CLI_FIELDS.subject.flags[0], {\n required: true,\n description: \"Email subject\",\n });\n text = Option.String(CLI_FIELDS.text.flags[0], {\n description: \"Plain-text body and fallback\",\n });\n textFile = Option.String(CLI_FIELDS.text.flags[1], {\n description: \"Read the plain-text body from a UTF-8 file\",\n });\n html = Option.String(CLI_FIELDS.html.flags[0], {\n description: \"Optional inline HTML body\",\n });\n htmlFile = Option.String(CLI_FIELDS.html.flags[1], {\n description: \"Read the optional HTML body from a UTF-8 file\",\n });\n image = Option.Array(CLI_FIELDS.attachments.flags[0], {\n description: \"Attach an image file (repeatable; PNG, JPEG, GIF, or WebP)\",\n });\n inlineImage = Option.Array(CLI_FIELDS.attachments.flags[1], {\n description: \"Embed an image as CONTENT_ID=PATH; reference it as cid:CONTENT_ID in HTML\",\n });\n attachment = Option.Array(CLI_FIELDS.attachments.flags[2], {\n description: \"Attach any bounded file (repeatable)\",\n });\n\n async run(): Promise<number | void> {\n const text = readBody(this.text, this.textFile, \"text\");\n if (text === undefined)\n throw new Error(\"notification send: --text or --text-file is required.\");\n const html = readBody(this.html, this.htmlFile, \"html\");\n const attachments = readNotificationEmailAttachments(\n this.image,\n this.inlineImage,\n this.attachment,\n );\n const response = await this.client().sendNotificationEmail({\n subject: this.subject,\n text,\n ...(html !== undefined ? { html } : {}),\n ...(attachments ? { attachments } : {}),\n });\n this.emitText(response, () =>\n `Sent notification email to your account email from ${response.data.from}.`,\n );\n }\n}\n\nexport const NOTIFICATION_COMMANDS = [NotificationSendCommand];\n", "/**\n * Machine-readable map from notification-email input fields to their CLI flags.\n * The cross-surface contract test compares these keys with the backend tool\n * schema so a backend capability cannot ship without a corresponding CLI path.\n */\nexport const NOTIFICATION_EMAIL_CLI_SURFACE = {\n inputProperties: {\n subject: { flags: [\"--subject\"] },\n text: { flags: [\"--text\", \"--text-file\"] },\n html: { flags: [\"--html\", \"--html-file\"] },\n attachments: { flags: [\"--image\", \"--inline-image\", \"--attachment\"] },\n },\n attachmentProperties: {\n filename: { source: \"file basename\" },\n mimeType: { source: \"detected image signature or file extension\" },\n data: { source: \"base64-encoded file\" },\n contentId: { source: \"--inline-image CONTENT_ID=PATH\" },\n },\n limits: {\n maxAttachments: 4,\n maxAttachmentBytes: 750_000,\n maxBase64Length: 1_000_000,\n maxFilenameLength: 200,\n maxMimeTypeLength: 255,\n maxContentIdLength: 128,\n },\n imageMimeTypes: [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"],\n} as const;\n", "import { randomUUID } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport { Command, Option } from \"clipanion\";\nimport { ClientCommand } from \"../command.ts\";\nimport { AGENT_MAIL_CLI_SURFACE } from \"../agentMailContract.ts\";\nimport { parseInlineImageSpecs, readOutgoingEmailAttachment } from \"../fileAttachments.ts\";\nimport { agentMailInlineReferenceError } from \"../inlineImages.ts\";\nimport type {\n AgentMailMessage,\n AgentMailOperationResponse,\n AgentMailThreadSummary,\n AgentMailThreadState,\n NotificationEmailAttachmentInput,\n} from \"../types.ts\";\n\nexport function renderAgentMailOperation(\n noun: \"message\" | \"reply\",\n response: AgentMailOperationResponse,\n): string {\n return `${response.data.deliveryStatus} ${noun} ${response.data.messageId} in thread ${response.data.threadId}.`;\n}\n\nfunction readBody(\n inline: string | undefined,\n file: string | undefined,\n label: \"text\" | \"html\",\n): string | undefined {\n if (inline !== undefined && file !== undefined) {\n throw new Error(`agent mail: use either --${label} or --${label}-file, not both.`);\n }\n const value = file === undefined ? inline : readFileSync(file, \"utf8\");\n if (value !== undefined && !value.trim()) {\n throw new Error(`agent mail: ${label} body must not be empty.`);\n }\n return value;\n}\n\nexport function normalizeAgentMailIdempotencyKey(value: string | undefined): string {\n const key = value?.trim() || `cli-${randomUUID()}`;\n if (key.length < 8 || key.length > 200 || /[\\r\\n]/u.test(key)) {\n throw new Error(\"agent mail: --idempotency-key must be 8 to 200 characters.\");\n }\n return key;\n}\n\nexport interface AgentMailBodyOptions {\n text?: string;\n textFile?: string;\n html?: string;\n htmlFile?: string;\n attachment?: readonly string[];\n inlineImage?: readonly string[];\n}\n\nexport function readAgentMailBodies(\n options: AgentMailBodyOptions,\n): { text: string; html?: string; attachments?: NotificationEmailAttachmentInput[] } {\n const text = readBody(options.text, options.textFile, \"text\");\n if (text === undefined) {\n throw new Error(\"agent mail: --text or --text-file is required.\");\n }\n const html = readBody(options.html, options.htmlFile, \"html\");\n const paths = options.attachment ?? [];\n const inlineImages = parseInlineImageSpecs(options.inlineImage ?? [], {\n maxContentIdLength: AGENT_MAIL_CLI_SURFACE.limits.maxContentIdLength,\n commandLabel: \"agent mail\",\n });\n if (paths.length + inlineImages.length > AGENT_MAIL_CLI_SURFACE.limits.maxAttachments) {\n throw new Error(\n `agent mail: at most ${AGENT_MAIL_CLI_SURFACE.limits.maxAttachments} files (ordinary attachments and inline images combined) may be attached.`,\n );\n }\n const attachments = [\n ...inlineImages.map(({ path, contentId }) => readOutgoingEmailAttachment(path, {\n maxBytes: AGENT_MAIL_CLI_SURFACE.limits.maxAttachmentBytes,\n maxFilenameLength: AGENT_MAIL_CLI_SURFACE.limits.maxFilenameLength,\n contentId,\n requireImage: true,\n commandLabel: \"agent mail\",\n })),\n ...paths.map((path) => readOutgoingEmailAttachment(path, {\n maxBytes: AGENT_MAIL_CLI_SURFACE.limits.maxAttachmentBytes,\n maxFilenameLength: AGENT_MAIL_CLI_SURFACE.limits.maxFilenameLength,\n commandLabel: \"agent mail\",\n })),\n ];\n const referenceError = agentMailInlineReferenceError(html, attachments);\n if (referenceError) throw new Error(`agent mail: ${referenceError}`);\n return {\n text,\n ...(html === undefined ? {} : { html }),\n ...(attachments.length ? { attachments } : {}),\n };\n}\n\nexport interface AgentMailMarkOptions {\n threadId: string;\n version: string;\n handled: boolean;\n open: boolean;\n needsReply: boolean;\n read: boolean;\n unread: boolean;\n}\n\nexport function parseAgentMailMark(options: AgentMailMarkOptions): {\n threadId: string;\n stateVersion: number;\n state?: AgentMailThreadState;\n hasUnread?: boolean;\n} {\n const selected = [\n options.handled,\n options.open,\n options.needsReply,\n options.read,\n options.unread,\n ].filter(Boolean).length;\n if (selected !== 1) {\n throw new Error(\"agent mail mark: choose exactly one state flag.\");\n }\n const state: AgentMailThreadState | undefined = options.handled\n ? \"handled\"\n : options.open\n ? \"open\"\n : options.needsReply\n ? \"needsReply\"\n : undefined;\n const stateVersion = Number(options.version);\n if (!Number.isSafeInteger(stateVersion) || stateVersion < 0) {\n throw new Error(\"agent mail mark: --state-version must be a non-negative integer.\");\n }\n return {\n threadId: options.threadId,\n stateVersion,\n ...(state ? { state } : { hasUnread: options.unread }),\n };\n}\n\nfunction fmtTime(value: number | null): string {\n return value === null ? \"unknown\" : new Date(value).toISOString();\n}\n\nfunction renderThread(thread: AgentMailThreadSummary): string {\n const unread = thread.hasUnread ? ` unread:${thread.unreadCount}` : \"\";\n return `${fmtTime(thread.latestAt)} [${thread.state}]${unread} ${thread.subject} ${thread.threadId}`;\n}\n\nfunction renderMessage(message: AgentMailMessage): string {\n const direction = message.direction === \"inbound\" ? \"\u2190\" : \"\u2192\";\n const date = message.receivedAt ?? message.sentAt;\n const body = message.text ? `\\n${message.text}` : \"\";\n return `${direction} ${fmtTime(date)} ${message.from ?? \"unknown\"} [${message.deliveryStatus}] ${message.messageId}${body}`;\n}\n\nclass AgentMailAddress extends ClientCommand {\n static paths = [[\"agent\", \"mail\", \"address\"]];\n static usage = Command.Usage({\n category: \"Agent mail\",\n description: \"Show the inbox address bound to this agent key\",\n });\n\n async run(): Promise<void> {\n const response = await this.client().getAgentMailbox();\n this.emitText(response, () => response.data.address);\n }\n}\n\nclass AgentMailThreads extends ClientCommand {\n static paths = [[\"agent\", \"mail\", \"threads\"]];\n static usage = Command.Usage({\n category: \"Agent mail\",\n description: \"List mail threads for the agent bound to this key\",\n });\n\n unread = Option.Boolean(\"--unread\", false);\n needsReply = Option.Boolean(\"--needs-reply\", false);\n limit = Option.String(\"--limit\", { description: \"Number of threads (1-50)\" });\n cursor = Option.String(\"--cursor\", { description: \"Opaque pagination cursor\" });\n\n async run(): Promise<void> {\n const limit = this.limit === undefined ? 20 : Number(this.limit);\n if (!Number.isInteger(limit) || limit < 1 || limit > 50) {\n throw new Error(\"agent mail threads: --limit must be an integer from 1 to 50.\");\n }\n const response = await this.client().listAgentMailThreads({\n limit: String(limit),\n cursor: this.cursor,\n hasUnread: this.unread ? \"true\" : undefined,\n state: this.needsReply ? \"needsReply\" : undefined,\n });\n this.emitText(response, () => {\n if (response.data.length === 0) return \"No mail threads.\";\n const lines = response.data.map(renderThread);\n if (response.continueCursor) lines.push(`next cursor: ${response.continueCursor}`);\n return lines.join(\"\\n\");\n });\n }\n}\n\nclass AgentMailShow extends ClientCommand {\n static paths = [[\"agent\", \"mail\", \"show\"]];\n static usage = Command.Usage({ category: \"Agent mail\", description: \"Read one mail thread\" });\n\n threadId = Option.String();\n cursor = Option.String(\"--cursor\", { description: \"Opaque message cursor\" });\n\n async run(): Promise<void> {\n const response = await this.client().getAgentMailThread(this.threadId, this.cursor);\n this.emitText(response, () => [\n renderThread(response.data.thread),\n ...response.data.messages.map(renderMessage),\n ...(response.data.continueCursor\n ? [`next cursor: ${response.data.continueCursor}`]\n : []),\n ].join(\"\\n\\n\"));\n }\n}\n\nabstract class AgentMailBodyCommand extends ClientCommand {\n text = Option.String(\"--text\", { description: \"Required plain-text body and complete fallback\" });\n textFile = Option.String(\"--text-file\", { description: \"Read plain text from a UTF-8 file\" });\n html = Option.String(\"--html\", { description: \"Inline HTML body\" });\n htmlFile = Option.String(\"--html-file\", { description: \"Read HTML from a UTF-8 file\" });\n attachment = Option.Array(\"--attachment\", {\n description: \"Attach any bounded file (repeatable; maximum 4 including inline images)\",\n });\n inlineImage = Option.Array(\"--inline-image\", {\n description: \"Embed PNG, JPEG, GIF, or WebP as CONTENT_ID=PATH; reference cid:CONTENT_ID in HTML (750000 bytes per file; maximum 4 files combined)\",\n });\n key = Option.String(\"--idempotency-key\", {\n description: \"Reuse this key only when retrying the same operation\",\n });\n\n protected bodies(): {\n text: string;\n html?: string;\n attachments?: NotificationEmailAttachmentInput[];\n } {\n return readAgentMailBodies({\n text: this.text,\n textFile: this.textFile,\n html: this.html,\n htmlFile: this.htmlFile,\n attachment: this.attachment,\n inlineImage: this.inlineImage,\n });\n }\n}\n\nclass AgentMailSend extends AgentMailBodyCommand {\n static paths = [[\"agent\", \"mail\", \"send\"]];\n static usage = Command.Usage({\n category: \"Agent mail\",\n description: \"Send mail from the agent address\",\n examples: [[\n \"Send a report with a CID chart and complete plain-text fallback\",\n 'ente agent mail send --to owner@example.net --subject \"Readiness\" --text-file ./report.txt --html-file ./report.html --inline-image readiness=./readiness.png --idempotency-key readiness-report-v1',\n ]],\n });\n\n to = Option.String(\"--to\", { required: true });\n subject = Option.String(\"--subject\", { required: true });\n\n async run(): Promise<void> {\n const response = await this.client().sendAgentMail({\n to: this.to,\n subject: this.subject,\n ...this.bodies(),\n }, normalizeAgentMailIdempotencyKey(this.key));\n this.emitText(response, () => renderAgentMailOperation(\"message\", response));\n }\n}\n\nclass AgentMailReply extends AgentMailBodyCommand {\n static paths = [[\"agent\", \"mail\", \"reply\"]];\n static usage = Command.Usage({\n category: \"Agent mail\",\n description: \"Reply to a specific message in a mail thread\",\n examples: [[\n \"Reply with a CID chart referenced as cid:readiness in report.html\",\n \"ente agent mail reply <thread-id> --message <message-id> --text-file ./report.txt --html-file ./report.html --inline-image readiness=./readiness.png --idempotency-key readiness-reply-v1\",\n ]],\n });\n\n threadId = Option.String();\n messageId = Option.String(\"--message\", { required: true });\n\n async run(): Promise<void> {\n const response = await this.client().replyAgentMail({\n threadId: this.threadId,\n replyToMessageId: this.messageId,\n ...this.bodies(),\n }, normalizeAgentMailIdempotencyKey(this.key));\n this.emitText(response, () => renderAgentMailOperation(\"reply\", response));\n }\n}\n\nclass AgentMailMark extends ClientCommand {\n static paths = [[\"agent\", \"mail\", \"mark\"]];\n static usage = Command.Usage({\n category: \"Agent mail\",\n description: \"Update workflow or unread state with optimistic concurrency\",\n });\n\n threadId = Option.String();\n version = Option.String(\"--state-version\", { required: true });\n handled = Option.Boolean(\"--handled\", false);\n open = Option.Boolean(\"--open\", false);\n needsReply = Option.Boolean(\"--needs-reply\", false);\n read = Option.Boolean(\"--read\", false);\n unread = Option.Boolean(\"--unread\", false);\n\n async run(): Promise<void> {\n const response = await this.client().markAgentMailThread(parseAgentMailMark({\n threadId: this.threadId,\n version: this.version,\n handled: this.handled,\n open: this.open,\n needsReply: this.needsReply,\n read: this.read,\n unread: this.unread,\n }));\n this.emitText(response, () => `Updated thread ${response.data.threadId}; state version ${response.data.stateVersion}.`);\n }\n}\n\nexport const AGENT_MAIL_COMMANDS = [\n AgentMailAddress,\n AgentMailThreads,\n AgentMailShow,\n AgentMailSend,\n AgentMailReply,\n AgentMailMark,\n];\n", "/** CLI flags and limits mirrored by the agent-mail cross-surface parity test. */\nexport const AGENT_MAIL_CLI_SURFACE = {\n sendInputProperties: {\n to: { flags: [\"--to\"] },\n subject: { flags: [\"--subject\"] },\n text: { flags: [\"--text\", \"--text-file\"] },\n html: { flags: [\"--html\", \"--html-file\"] },\n attachments: { flags: [\"--attachment\", \"--inline-image\"] },\n idempotency_key: { flags: [\"--idempotency-key\"] },\n },\n replyInputProperties: {\n threadId: { source: \"positional argument\" },\n replyToMessageId: { flags: [\"--message\"] },\n text: { flags: [\"--text\", \"--text-file\"] },\n html: { flags: [\"--html\", \"--html-file\"] },\n attachments: { flags: [\"--attachment\", \"--inline-image\"] },\n idempotency_key: { flags: [\"--idempotency-key\"] },\n },\n attachmentProperties: {\n filename: { source: \"file basename\" },\n mimeType: { source: \"detected image signature or file extension\" },\n data: { source: \"base64-encoded file\" },\n contentId: { source: \"--inline-image CONTENT_ID=PATH\" },\n },\n imageMimeTypes: [\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\"],\n limits: {\n maxAttachments: 4,\n maxAttachmentBytes: 750_000,\n maxFilenameLength: 200,\n maxBase64Length: 1_000_000,\n maxMimeTypeLength: 255,\n maxContentIdLength: 128,\n },\n} as const;\n", "/** Keep this standalone CLI check in parity with the server's CID check. */\nexport function agentMailInlineReferenceError(\n html: string | undefined,\n attachments: readonly { contentId?: string }[],\n): string | undefined {\n const contentIds = new Set(attachments.flatMap((file) => file.contentId ? [file.contentId] : []));\n // Read URL attributes from tags, not CID examples in prose or comments.\n // Keep the body unchanged and require literal, case-sensitive Content-IDs.\n const source = (html ?? \"\").replace(/<!--[\\s\\S]*?-->/gu, \"\");\n const tags = source.match(/<[a-z](?:[^\"'<>]|\"[^\"]*\"|'[^']*')*>/giu) ?? [];\n const urls: string[] = [];\n const styles: string[] = [];\n for (const tag of tags) {\n // Consume each quoted value as a whole so alt/data attributes cannot\n // masquerade as a src attribute or make an unused image look referenced.\n for (const match of tag.matchAll(/\\s+([a-z_:][a-z\\d_:.-]*)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"'=<>`]+))/giu)) {\n const name = match[1]!.toLowerCase();\n const value = match[2] ?? match[3] ?? match[4]!;\n if ([\"src\", \"href\", \"background\", \"poster\"].includes(name)) urls.push(value);\n if (name === \"srcset\") urls.push(...value.split(/[,\\s]+/u));\n if (name === \"style\") styles.push(value);\n }\n }\n styles.push(...Array.from(source.matchAll(/<style\\b[^>]*>([\\s\\S]*?)<\\/style\\s*>/giu),\n (match) => match[1]!));\n for (const style of styles) {\n urls.push(...Array.from(style.matchAll(/url\\(\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s\"')]+))\\s*\\)/giu),\n (match) => match[1] ?? match[2] ?? match[3]!));\n }\n const references = new Set(urls.filter((url) => /^cid:/iu.test(url.trim()))\n .map((url) => url.trim().slice(4)));\n for (const reference of references) {\n if (!contentIds.has(reference)) return `HTML cid:${reference} has no matching inline image.`;\n }\n for (const contentId of contentIds) {\n if (!references.has(contentId)) return `Inline image '${contentId}' must be referenced as cid:${contentId} in HTML.`;\n }\n return undefined;\n}\n", "// ente CLI \u2014 one in-repo TypeScript tool for the ente knowledge graph (people,\n// orgs, projects, topics + their activities) against any deployment. Auth: a\n// static `ente_\u2026` API key (Bearer). Mirrors the plexus-cli architecture:\n// brand-neutral core/ + branded ente/, clipanion commands, esbuild bundle.\n//\n// Installed: ente <command> [...flags]\n// In-repo: node --import tsx cli.ts <command> [...flags] (pnpm dev <cmd>)\n\nimport { Builtins, Cli } from \"clipanion\";\n\nimport { configDir } from \"./core/config.ts\";\nimport { checkForUpdate } from \"./core/update.ts\";\nimport { ENTE_BRANDING } from \"./ente/branding.ts\";\nimport { ensureSkillInstalled } from \"./ente/skill.ts\";\nimport { AUTH_COMMANDS } from \"./ente/commands/auth.ts\";\nimport { ENTITY_COMMANDS } from \"./ente/commands/entity.ts\";\nimport { ACTIVITY_COMMANDS } from \"./ente/commands/activity.ts\";\nimport { TASK_COMMANDS } from \"./ente/commands/task.ts\";\nimport { LIST_COMMANDS } from \"./ente/commands/list.ts\";\nimport { USERS_COMMANDS } from \"./ente/commands/users.ts\";\nimport { MODELS_COMMANDS } from \"./ente/commands/models.ts\";\nimport { SPACE_COMMANDS } from \"./ente/commands/space.ts\";\nimport { PINS_COMMANDS } from \"./ente/commands/pins.ts\";\nimport { SEARCH_COMMANDS } from \"./ente/commands/search.ts\";\nimport { ASK_COMMANDS } from \"./ente/commands/ask.ts\";\nimport { QUERY_COMMANDS } from \"./ente/commands/query.ts\";\nimport { RECORDING_PIPELINE_COMMANDS } from \"./ente/commands/recordingPipeline.ts\";\nimport { RECORDINGS_COMMANDS } from \"./ente/commands/recordings.ts\";\nimport { AGENT_COMMANDS } from \"./ente/commands/agent.ts\";\nimport { AGENDA_COMMANDS } from \"./ente/commands/agenda.ts\";\nimport { FEEDBACK_COMMANDS } from \"./ente/commands/feedback.ts\";\nimport { GUIDE_COMMANDS } from \"./ente/commands/guide.ts\";\nimport { CANVAS_COMMANDS } from \"./ente/commands/canvas.ts\";\nimport { NOTIFICATION_COMMANDS } from \"./ente/commands/notification.ts\";\nimport { AGENT_MAIL_COMMANDS } from \"./ente/commands/agentMail.ts\";\n\nconst cli = new Cli({\n binaryLabel: \"Ente knowledge-graph / relationship-manager CLI (ente.fast)\",\n binaryName: \"ente\",\n binaryVersion: ENTE_BRANDING.version,\n});\n\ncli.register(Builtins.HelpCommand);\ncli.register(Builtins.VersionCommand);\n\nfor (const Cmd of [\n ...AUTH_COMMANDS,\n ...ENTITY_COMMANDS,\n ...ACTIVITY_COMMANDS,\n ...TASK_COMMANDS,\n ...LIST_COMMANDS,\n ...USERS_COMMANDS,\n ...MODELS_COMMANDS,\n ...SPACE_COMMANDS,\n ...PINS_COMMANDS,\n ...SEARCH_COMMANDS,\n ...ASK_COMMANDS,\n ...QUERY_COMMANDS,\n ...RECORDING_PIPELINE_COMMANDS,\n ...RECORDINGS_COMMANDS,\n ...AGENT_COMMANDS,\n ...AGENDA_COMMANDS,\n ...FEEDBACK_COMMANDS,\n ...GUIDE_COMMANDS,\n ...CANVAS_COMMANDS,\n ...NOTIFICATION_COMMANDS,\n ...AGENT_MAIL_COMMANDS,\n]) {\n cli.register(Cmd);\n}\n\nconst SKIP_UPDATE = new Set([\"auth\", \"--help\", \"-h\", \"--version\", \"-V\"]);\n\nasync function main(): Promise<void> {\n // Best-effort skill install + 24h-cached update check (both swallow errors).\n ensureSkillInstalled();\n const argv = process.argv.slice(2);\n if (!SKIP_UPDATE.has(argv[0] ?? \"\")) {\n await checkForUpdate({\n packageName: ENTE_BRANDING.packageName,\n registryUrl: ENTE_BRANDING.registryUrl,\n currentVersion: ENTE_BRANDING.version,\n cacheDir: configDir(ENTE_BRANDING),\n upgradeCommand: ENTE_BRANDING.upgradeCommand,\n });\n }\n await cli.runExit(argv);\n}\n\nvoid main();\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAEA,WAAO,eAAe,SAAS,cAAc,EAAE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AI,CAAC,QAAQ,UAAU,MAAM,aAAa,IAAI,CAAC;AAEvE,eAAe,OAAsB;AAEnC,uBAAqB;AACrB,QAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,MAAI,CAAC,YAAY,IAAI,KAAK,CAAC,KAAK,EAAE,GAAG;AACnC,UAAM,eAAe;AAAA,MACnB,aAAa,cAAc;AAAA,MAC3B,aAAa,cAAc;AAAA,MAC3B,gBAAgB,cAAc;AAAA,MAC9B,UAAU,UAAU,aAAa;AAAA,MACjC,gBAAgB,cAAc;AAAA,IAChC,CAAC;AAAA,EACH;AACA,QAAM,IAAI,QAAQ,IAAI;AACxB;AAEA,KAAK,KAAK;",
|
|
6
|
+
"names": ["value", "_a", "_b", "plural", "v", "fn", "valid", "errorMessage", "spec", "SpecialToken", "NodeType", "path", "v", "context", "process", "to", "path", "_a", "errorMessage", "machine", "cli", "_a", "path", "process", "_b", "command", "colored", "input", "commandClass", "description", "HelpCommand", "HelpCommand", "Proxy", "_a", "Proxy", "_a", "Array", "Boolean", "Proxy", "String", "Array", "Boolean", "_a", "_a", "String", "t", "v", "normalized", "normalized", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "path", "existsSync", "mkdirSync", "readFileSync", "writeFileSync", "os", "path", "existsSync", "mkdirSync", "readFileSync", "rmSync", "writeFileSync", "path", "code", "code", "code", "path", "v", "v", "v", "attrDict", "v", "createHash", "arr", "value", "v", "v", "v", "__publicField", "__publicField", "path", "__publicField", "__commonJS", "__require", "path", "os", "vars", "debug", "dir", "readdirSync", "arr", "platform", "arch", "extension", "runtime", "abi", "require_node_gyp_build", "mask", "PerMessageDeflate", "data", "code", "Receiver", "Sender", "parse", "v", "randomBytes", "createHash", "URL", "WebSocket", "key", "createWebSocketStream", "err", "protocol", "subprotocol", "WebSocketServer", "version", "__toESM", "__publicField", "debug", "createHash", "createHash", "existsSync", "readFileSync", "rmSync", "writeFileSync", "readFileSync", "createHash", "existsSync", "rmSync", "writeFileSync", "__publicField", "ID_RE", "looksLikeConvexId", "normalized", "readFileSync", "readFileSync", "readFileSync", "basename", "readFileSync", "readFileSync", "path", "code", "readFileSync", "basename", "activitiesGetByIdRich", "activitiesCreate", "activitiesUpdateCreatedAt", "activitiesUpdateTitle", "activitiesSetContentFromMarkdown", "v", "entitiesCreate", "activitiesCreate", "v", "readFileSync", "writeFileSync", "path", "readFileSync", "path", "writeFileSync", "readFileSync", "data", "before", "readFileSync", "readFileSync", "readFileSync", "MAX_PAGES", "readFileSync", "readFileSync", "path", "randomUUID", "readFileSync", "readBody", "readFileSync", "randomUUID", "path", "fmtTime", "renderMessage"]
|
|
7
|
+
}
|