@blotout/qinto-cli 0.1.0
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 +373 -0
- package/bin/qinto.js +2 -0
- package/dist/index.js +11434 -0
- package/dist/index.js.map +1 -0
- package/dist/worker-artifact/README.md +3 -0
- package/dist/worker-artifact/app-runtime/index.js +16432 -0
- package/dist/worker-artifact/apps-ui/index.js +53 -0
- package/dist/worker-artifact/main/9301296b51353552dafe33a97c95e9755e6108db-q.js.txt +1 -0
- package/dist/worker-artifact/main/index.js +26566 -0
- package/dist/worker-artifact/version.json +75 -0
- package/dist/worker-artifact/wfp/index.js +2705 -0
- package/package.json +57 -0
- package/templates/app/full/qinto.app.jsonc +124 -0
- package/templates/app/full/src/browser.ts +15 -0
- package/templates/app/full/src/server.ts +133 -0
- package/templates/app/full/ui/src/pages/index.astro +55 -0
- package/templates/app/minimal/qinto.app.jsonc +20 -0
- package/templates/app/minimal/src/server.ts +9 -0
- package/templates/project/gitignore +3 -0
- package/templates/project/package.json +12 -0
- package/templates/project/tsconfig.json +12 -0
- package/templates/ui/astro.config.mjs +6 -0
- package/templates/ui/package.json +12 -0
- package/templates/ui/src/pages/index.astro +51 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["readline","process","isPlainObject","NO_TRUNCATION","fastStringTruncatedWidth","ESC","stringWidth","exec","readline","#isTTY","#destSrc","#proxy","process","#process","#sigListeners","#emitter","#hupSig","#originalProcessReallyExit","#originalProcessEmit","#loaded","#processEmit","#processReallyExit","MuteStream","onSignalExit","_a","F","initializer","util.jsonStringifyReplacer","core.$ZodAsyncError","util.finalizeIssue","core.config","errors.$ZodError","safeParse","errors.$ZodRealError","safeParseAsync","duration","_emoji","date","time","datetime","string","number","boolean","util.floatSafeRemainder","util.NUMBER_FORMAT_RANGES","regexes.integer","util.nullish","util.getLengthableOrigin","regexes.lowercase","regexes.uppercase","util.escapeRegex","content","util.aborted","util.explicitlyAborted","core.$ZodAsyncError","safeParse","safeParseAsync","regexes.string","regexes.guid","regexes.uuid","regexes.email","regexes.emoji","regexes.nanoid","regexes.cuid","regexes.cuid2","regexes.ulid","regexes.xid","regexes.ksuid","regexes.datetime","regexes.date","regexes.time","regexes.duration","regexes.ipv4","regexes.ipv6","regexes.cidrv4","regexes.cidrv6","regexes.base64","regexes.base64url","regexes.e164","regexes.number","regexes.boolean","util.prefixIssues","util.optionalKeys","util.cached","isObject","util.isObject","util.esc","allowsEval","util.allowsEval","util.finalizeIssue","core.config","util.cleanRegex","util.isPlainObject","util.getEnumValues","util.escapeRegex","core.$ZodEncodeError","util.issue","util.normalizeParams","checks.$ZodCheckLessThan","checks.$ZodCheckGreaterThan","checks.$ZodCheckMultipleOf","checks.$ZodCheckMaxLength","checks.$ZodCheckMinLength","checks.$ZodCheckLengthEquals","checks.$ZodCheckRegex","checks.$ZodCheckLowerCase","checks.$ZodCheckUpperCase","checks.$ZodCheckIncludes","checks.$ZodCheckStartsWith","checks.$ZodCheckEndsWith","checks.$ZodCheckOverwrite","util.slugify","issue","util.issue","checks.$ZodCheck","process","process","core._isoDateTime","core._isoDate","core._isoTime","core._isoDuration","core.formatError","core.flattenError","util.jsonStringifyReplacer","parse","parse.parse","parse.safeParse","parse.parseAsync","parse.safeParseAsync","parse.encode","parse.decode","parse.encodeAsync","parse.decodeAsync","parse.safeEncode","parse.safeDecode","parse.safeEncodeAsync","parse.safeDecodeAsync","util.mergeDefs","core.clone","checks.overwrite","processors.stringProcessor","checks.regex","checks.includes","checks.startsWith","checks.endsWith","checks.minLength","checks.maxLength","checks.length","checks.lowercase","checks.uppercase","checks.trim","checks.normalize","checks.toLowerCase","checks.toUpperCase","checks.slugify","core._email","core._url","core._jwt","core._emoji","core._guid","core._uuid","core._uuidv4","core._uuidv6","core._uuidv7","core._nanoid","core._cuid","core._cuid2","core._ulid","core._base64","core._base64url","core._xid","core._ksuid","core._ipv4","core._ipv6","core._cidrv4","core._cidrv6","core._e164","iso.datetime","iso.date","iso.time","iso.duration","core._string","processors.numberProcessor","checks.gt","checks.gte","checks.lt","checks.lte","checks.multipleOf","core._number","core._int","processors.booleanProcessor","core._boolean","processors.unknownProcessor","core._unknown","processors.neverProcessor","core._never","processors.arrayProcessor","core._array","processors.objectProcessor","util.extend","util.safeExtend","util.merge","util.pick","util.omit","util.partial","util.required","util.normalizeParams","processors.unionProcessor","processors.intersectionProcessor","processors.recordProcessor","processors.enumProcessor","processors.literalProcessor","processors.transformProcessor","core.$ZodEncodeError","issue","util.issue","processors.optionalProcessor","processors.nullableProcessor","processors.defaultProcessor","util.shallowClone","processors.prefaultProcessor","processors.nonoptionalProcessor","processors.catchProcessor","processors.pipeProcessor","processors.readonlyProcessor","processors.customProcessor","core._refine","core._superRefine"],"sources":["../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/key.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/errors.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/hook-engine.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/use-state.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/use-effect.js","../../../node_modules/.pnpm/@inquirer+figures@2.0.7/node_modules/@inquirer/figures/dist/index.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/theme.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/make-theme.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/use-prefix.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/use-memo.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/use-ref.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/use-keypress.js","../__vite-browser-external","../../../node_modules/.pnpm/cli-width@4.1.0/node_modules/cli-width/index.js","../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/utils.js","../../../node_modules/.pnpm/fast-string-truncated-width@3.0.3/node_modules/fast-string-truncated-width/dist/index.js","../../../node_modules/.pnpm/fast-string-width@3.0.2/node_modules/fast-string-width/dist/index.js","../../../node_modules/.pnpm/fast-wrap-ansi@0.2.2/node_modules/fast-wrap-ansi/lib/main.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/utils.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/pagination/use-pagination.js","../../../node_modules/.pnpm/mute-stream@3.0.0/node_modules/mute-stream/lib/index.js","../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/signals.js","../../../node_modules/.pnpm/signal-exit@4.1.0/node_modules/signal-exit/dist/mjs/index.js","../../../node_modules/.pnpm/@inquirer+ansi@2.0.7/node_modules/@inquirer/ansi/dist/index.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/screen-manager.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/promise-polyfill.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/create-prompt.js","../../../node_modules/.pnpm/@inquirer+core@11.2.1_@types+node@25.6.0/node_modules/@inquirer/core/dist/lib/Separator.js","../../../node_modules/.pnpm/@inquirer+confirm@6.1.1_@types+node@25.6.0/node_modules/@inquirer/confirm/dist/index.js","../../../node_modules/.pnpm/@inquirer+input@5.1.2_@types+node@25.6.0/node_modules/@inquirer/input/dist/index.js","../../../node_modules/.pnpm/@inquirer+password@5.1.1_@types+node@25.6.0/node_modules/@inquirer/password/dist/index.js","../../../node_modules/.pnpm/@inquirer+select@5.2.1_@types+node@25.6.0/node_modules/@inquirer/select/dist/index.js","../package.json","../src/lib/errors.ts","../src/manifest.ts","../../../libs/app-build/src/errors.ts","../../../libs/app-build/src/bundles.ts","../../../libs/app-build/src/files.ts","../../../libs/app-build/src/hooks.ts","../../../libs/app-build/src/ui.ts","../src/commands/app/common/scaffold.ts","../src/commands/app/common/install.ts","../../../libs/app-manifest/src/cron.ts","../../../libs/app-manifest/src/digest.ts","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/core.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/util.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/errors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/parse.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/regexes.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/checks.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/doc.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/versions.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/schemas.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/registries.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/api.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/to-json-schema.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/core/json-schema-processors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/iso.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/errors.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/parse.js","../../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/schemas.js","../../../libs/app-manifest/src/schema.ts","../src/commands/app/common/manifest-file.ts","../src/commands/app/add-ui.ts","../src/lib/json-file.ts","../src/lib/config.ts","../src/command-spec.ts","../src/lib/machine-mode.ts","../src/lib/credentials.ts","../../../libs/oauth-grammar/src/scopes.ts","../src/lib/request.ts","../src/lib/oauth.ts","../src/lib/api.ts","../src/lib/organizations.ts","../src/commands/app/common/register-app.ts","../src/commands/app/common/slug.ts","../src/commands/app/create.ts","../../app/dev/src/compose/deployable.ts","../../app/dev/src/paths.ts","../../../libs/app-envelope/src/envelope.ts","../../../libs/app-envelope/src/control.ts","../../../libs/app-envelope/src/endpoint.ts","../../../libs/app-envelope/src/ui.ts","../../../libs/app-ui-token/src/base64url.ts","../../../libs/app-ui-token/src/env.ts","../../../libs/app-ui-token/src/jwt.ts","../../../libs/app-ui-token/src/token.ts","../../../libs/app-ui-token/src/write-ticket.ts","../../app/dev/src/artifacts.ts","../../../libs/app-deploy/src/control.ts","../../../libs/app-deploy/src/entry.ts","../../../libs/app-deploy/src/errors.ts","../../../libs/app-deploy/src/keys.ts","../../../libs/app-deploy/src/registry.ts","../../../libs/app-deploy/src/variables.ts","../../app/dev/src/compose/resources.ts","../../app/dev/src/compose/app-worker.ts","../../../libs/worker-access-token/src/endpoints.ts","../../../libs/worker-access-token/src/scopes.ts","../../../libs/worker-access-token/src/env.ts","../../../libs/worker-access-token/src/hash.ts","../../app/dev/src/read-if-present.ts","../../app/dev/src/keys.ts","../../app/dev/src/compose/site-worker.ts","../../../libs/tail-trace/src/wire.ts","../../../libs/tail-trace/src/app-spans.ts","../../../libs/tail-trace/src/budget.ts","../../../libs/tail-trace/src/scope.ts","../../app/dev/src/logs.ts","../../app/dev/src/server/app-ui.ts","../../app/dev/src/state.ts","../../../libs/cloudflare/src/deployment/common/sql-scan.ts","../../../libs/cloudflare/src/deployment/common/migration-sql.ts","../../app/dev/src/migrations.ts","../../app/dev/src/supervisor.ts","../../app/dev/src/stack.ts","../../app/dev/src/server/app-ui-write.ts","../../app/dev/src/server/console-actions.ts","../../app/dev/src/server/console-icons.ts","../../app/dev/src/server/console-style.ts","../../app/dev/src/server/console-theme.ts","../../app/dev/src/server/console-shell.ts","../../app/dev/src/server/console-install-card.ts","../../app/dev/src/server/console-logs.ts","../../app/dev/src/server/console-nav.ts","../../app/dev/src/server/console-pages.ts","../../app/dev/src/server/console-app-page.ts","../../app/dev/src/server/console-developer-app.ts","../../app/dev/src/server/console-settings-page.ts","../../app/dev/src/server/console-ui-panel.ts","../../app/dev/src/server/console.ts","../../app/dev/src/server/demo-page.ts","../../app/dev/src/server/demo.ts","../../app/dev/src/watch.ts","../src/commands/app/dev/artifact-root.ts","../src/commands/app/dev.ts","../src/lib/table.ts","../src/commands/app/list.ts","../src/lib/apps.ts","../src/lib/domain-api.ts","../src/lib/teams.ts","../src/commands/app/common/site-target.ts","../src/commands/app/publish/artifacts.ts","../src/commands/app/publish/install.ts","../src/commands/app/publish/state.ts","../src/commands/app/publish.ts","../src/commands/app/register.ts","../src/commands/app/common/app-variables.ts","../src/commands/app/secret-list.ts","../src/commands/app/secret-set.ts","../src/commands/app/status.ts","../src/commands/app/var-list.ts","../src/commands/app/var-set.ts","../src/commands/app/version-cancel.ts","../src/commands/app/versions.ts","../src/commands/describe.ts","../src/commands/domain/dns.ts","../src/generated/api-values.ts","../src/commands/domain/common/canonical.ts","../src/commands/domain/common/resume.ts","../src/commands/domain/common/types.ts","../src/commands/domain/onboarding/complete.ts","../src/commands/domain/common/emails.ts","../src/commands/domain/onboarding/dns.ts","../src/commands/domain/onboarding/result.ts","../src/commands/domain/onboarding/settings.ts","../src/commands/domain/onboarding/host.ts","../src/commands/domain/onboarding/site.ts","../src/commands/domain/onboarding/team.ts","../src/commands/domain/onboard.ts","../src/commands/env.ts","../src/lib/callback-server.ts","../src/lib/pkce.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/team/active.ts","../src/commands/team/list.ts","../src/commands/whoami.ts","../src/registry.ts","../src/program.ts","../src/index.ts"],"sourcesContent":["const keybindings = ['emacs', 'vim'];\nconst keybindingLookup = new Set(keybindings);\nfunction isKeybinding(value) {\n return keybindingLookup.has(value);\n}\nexport function getDefaultKeybindings() {\n const env = process.env['INQUIRER_KEYBINDINGS'];\n if (!env)\n return [];\n return Array.from(new Set(env\n .toLowerCase()\n .split(/[\\s,]+/)\n .filter(isKeybinding)));\n}\nexport const isUpKey = (key, keybindings = []) => \n// The up key\nkey.name === 'up' ||\n // Vim keybinding: hjkl keys map to left/down/up/right\n (keybindings.includes('vim') && key.name === 'k') ||\n // Emacs keybinding: Ctrl+P means \"previous\" in Emacs navigation conventions\n (keybindings.includes('emacs') && key.ctrl && key.name === 'p');\nexport const isDownKey = (key, keybindings = []) => \n// The down key\nkey.name === 'down' ||\n // Vim keybinding: hjkl keys map to left/down/up/right\n (keybindings.includes('vim') && key.name === 'j') ||\n // Emacs keybinding: Ctrl+N means \"next\" in Emacs navigation conventions\n (keybindings.includes('emacs') && key.ctrl && key.name === 'n');\nexport const isSpaceKey = (key) => key.name === 'space';\nexport const isBackspaceKey = (key) => key.name === 'backspace';\nexport const isTabKey = (key) => key.name === 'tab';\nexport const isNumberKey = (key) => '1234567890'.includes(key.name);\nexport const isEnterKey = (key) => key.name === 'enter' || key.name === 'return';\nexport const isShiftKey = (key) => key.shift;\n","export class AbortPromptError extends Error {\n name = 'AbortPromptError';\n message = 'Prompt was aborted';\n constructor(options) {\n super();\n this.cause = options?.cause;\n }\n}\nexport class CancelPromptError extends Error {\n name = 'CancelPromptError';\n message = 'Prompt was canceled';\n}\nexport class ExitPromptError extends Error {\n name = 'ExitPromptError';\n}\nexport class HookError extends Error {\n name = 'HookError';\n}\nexport class ValidationError extends Error {\n name = 'ValidationError';\n}\n","/* eslint @typescript-eslint/no-explicit-any: [\"off\"] */\nimport { AsyncLocalStorage, AsyncResource } from 'node:async_hooks';\nimport { HookError, ValidationError } from \"./errors.js\";\nconst hookStorage = new AsyncLocalStorage();\nfunction createStore(rl) {\n const store = {\n rl,\n hooks: [],\n hooksCleanup: [],\n hooksEffect: [],\n index: 0,\n handleChange() { },\n };\n return store;\n}\n// Run callback in with the hook engine setup.\nexport function withHooks(rl, cb) {\n const store = createStore(rl);\n return hookStorage.run(store, () => {\n function cycle(render) {\n store.handleChange = () => {\n store.index = 0;\n render();\n };\n store.handleChange();\n }\n return cb(cycle);\n });\n}\n// Safe getStore utility that'll return the store or throw if undefined.\nfunction getStore() {\n const store = hookStorage.getStore();\n if (!store) {\n throw new HookError('[Inquirer] Hook functions can only be called from within a prompt');\n }\n return store;\n}\nexport function readline() {\n return getStore().rl;\n}\n// Merge state updates happening within the callback function to avoid multiple renders.\nexport function withUpdates(fn) {\n const wrapped = (...args) => {\n const store = getStore();\n let shouldUpdate = false;\n const oldHandleChange = store.handleChange;\n store.handleChange = () => {\n shouldUpdate = true;\n };\n const returnValue = fn(...args);\n if (shouldUpdate) {\n oldHandleChange();\n }\n store.handleChange = oldHandleChange;\n return returnValue;\n };\n return AsyncResource.bind(wrapped);\n}\nexport function withPointer(cb) {\n const store = getStore();\n const { index } = store;\n const pointer = {\n get() {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return store.hooks[index];\n },\n set(value) {\n store.hooks[index] = value;\n },\n initialized: index in store.hooks,\n };\n const returnValue = cb(pointer);\n store.index++;\n return returnValue;\n}\nexport function handleChange() {\n getStore().handleChange();\n}\nexport const effectScheduler = {\n queue(cb) {\n const store = getStore();\n const { index } = store;\n store.hooksEffect.push(() => {\n store.hooksCleanup[index]?.();\n const cleanFn = cb(readline());\n if (cleanFn != null && typeof cleanFn !== 'function') {\n throw new ValidationError('useEffect return value must be a cleanup function or nothing.');\n }\n store.hooksCleanup[index] = cleanFn;\n });\n },\n run() {\n const store = getStore();\n withUpdates(() => {\n store.hooksEffect.forEach((effect) => {\n effect();\n });\n // Warning: Clean the hooks before exiting the `withUpdates` block.\n // Failure to do so means an updates would hit the same effects again.\n store.hooksEffect.length = 0;\n })();\n },\n clearAll() {\n const store = getStore();\n store.hooksCleanup.forEach((cleanFn) => {\n cleanFn?.();\n });\n store.hooksEffect.length = 0;\n store.hooksCleanup.length = 0;\n },\n};\n","import { AsyncResource } from 'node:async_hooks';\nimport { withPointer, handleChange } from \"./hook-engine.js\";\nfunction isFactory(value) {\n return typeof value === 'function';\n}\nexport function useState(defaultValue) {\n return withPointer((pointer) => {\n const setState = AsyncResource.bind(function setState(newValue) {\n // Noop if the value is still the same.\n if (pointer.get() !== newValue) {\n pointer.set(newValue);\n // Trigger re-render\n handleChange();\n }\n });\n if (pointer.initialized) {\n return [pointer.get(), setState];\n }\n const value = isFactory(defaultValue) ? defaultValue() : defaultValue;\n pointer.set(value);\n return [value, setState];\n });\n}\n","import { withPointer, effectScheduler } from \"./hook-engine.js\";\nexport function useEffect(cb, depArray) {\n withPointer((pointer) => {\n const oldDeps = pointer.get();\n const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i]));\n if (hasChanged) {\n effectScheduler.queue(cb);\n }\n pointer.set(depArray);\n });\n}\n","// process.env dot-notation access prints:\n// Property 'TERM' comes from an index signature, so it must be accessed with ['TERM'].ts(4111)\n/* eslint dot-notation: [\"off\"] */\nimport process from 'node:process';\n// Ported from is-unicode-supported\nfunction isUnicodeSupported() {\n if (!process.platform.startsWith('win')) {\n return process.env['TERM'] !== 'linux'; // Linux console (kernel)\n }\n return (Boolean(process.env['CI']) || // CI environments generally support unicode\n Boolean(process.env['WT_SESSION']) || // Windows Terminal\n Boolean(process.env['TERMINUS_SUBLIME']) || // Terminus (<0.2.27)\n process.env['ConEmuTask'] === '{cmd::Cmder}' || // ConEmu and cmder\n process.env['TERM_PROGRAM'] === 'Terminus-Sublime' ||\n process.env['TERM_PROGRAM'] === 'vscode' ||\n process.env['TERM'] === 'xterm-256color' ||\n process.env['TERM'] === 'alacritty' ||\n process.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm');\n}\n// Ported from figures\nconst common = {\n circleQuestionMark: '(?)',\n questionMarkPrefix: '(?)',\n square: '█',\n squareDarkShade: '▓',\n squareMediumShade: '▒',\n squareLightShade: '░',\n squareTop: '▀',\n squareBottom: '▄',\n squareLeft: '▌',\n squareRight: '▐',\n squareCenter: '■',\n bullet: '●',\n dot: '․',\n ellipsis: '…',\n pointerSmall: '›',\n triangleUp: '▲',\n triangleUpSmall: '▴',\n triangleDown: '▼',\n triangleDownSmall: '▾',\n triangleLeftSmall: '◂',\n triangleRightSmall: '▸',\n home: '⌂',\n heart: '♥',\n musicNote: '♪',\n musicNoteBeamed: '♫',\n arrowUp: '↑',\n arrowDown: '↓',\n arrowLeft: '←',\n arrowRight: '→',\n arrowLeftRight: '↔',\n arrowUpDown: '↕',\n almostEqual: '≈',\n notEqual: '≠',\n lessOrEqual: '≤',\n greaterOrEqual: '≥',\n identical: '≡',\n infinity: '∞',\n subscriptZero: '₀',\n subscriptOne: '₁',\n subscriptTwo: '₂',\n subscriptThree: '₃',\n subscriptFour: '₄',\n subscriptFive: '₅',\n subscriptSix: '₆',\n subscriptSeven: '₇',\n subscriptEight: '₈',\n subscriptNine: '₉',\n oneHalf: '½',\n oneThird: '⅓',\n oneQuarter: '¼',\n oneFifth: '⅕',\n oneSixth: '⅙',\n oneEighth: '⅛',\n twoThirds: '⅔',\n twoFifths: '⅖',\n threeQuarters: '¾',\n threeFifths: '⅗',\n threeEighths: '⅜',\n fourFifths: '⅘',\n fiveSixths: '⅚',\n fiveEighths: '⅝',\n sevenEighths: '⅞',\n line: '─',\n lineBold: '━',\n lineDouble: '═',\n lineDashed0: '┄',\n lineDashed1: '┅',\n lineDashed2: '┈',\n lineDashed3: '┉',\n lineDashed4: '╌',\n lineDashed5: '╍',\n lineDashed6: '╴',\n lineDashed7: '╶',\n lineDashed8: '╸',\n lineDashed9: '╺',\n lineDashed10: '╼',\n lineDashed11: '╾',\n lineDashed12: '−',\n lineDashed13: '–',\n lineDashed14: '‐',\n lineDashed15: '⁃',\n lineVertical: '│',\n lineVerticalBold: '┃',\n lineVerticalDouble: '║',\n lineVerticalDashed0: '┆',\n lineVerticalDashed1: '┇',\n lineVerticalDashed2: '┊',\n lineVerticalDashed3: '┋',\n lineVerticalDashed4: '╎',\n lineVerticalDashed5: '╏',\n lineVerticalDashed6: '╵',\n lineVerticalDashed7: '╷',\n lineVerticalDashed8: '╹',\n lineVerticalDashed9: '╻',\n lineVerticalDashed10: '╽',\n lineVerticalDashed11: '╿',\n lineDownLeft: '┐',\n lineDownLeftArc: '╮',\n lineDownBoldLeftBold: '┓',\n lineDownBoldLeft: '┒',\n lineDownLeftBold: '┑',\n lineDownDoubleLeftDouble: '╗',\n lineDownDoubleLeft: '╖',\n lineDownLeftDouble: '╕',\n lineDownRight: '┌',\n lineDownRightArc: '╭',\n lineDownBoldRightBold: '┏',\n lineDownBoldRight: '┎',\n lineDownRightBold: '┍',\n lineDownDoubleRightDouble: '╔',\n lineDownDoubleRight: '╓',\n lineDownRightDouble: '╒',\n lineUpLeft: '┘',\n lineUpLeftArc: '╯',\n lineUpBoldLeftBold: '┛',\n lineUpBoldLeft: '┚',\n lineUpLeftBold: '┙',\n lineUpDoubleLeftDouble: '╝',\n lineUpDoubleLeft: '╜',\n lineUpLeftDouble: '╛',\n lineUpRight: '└',\n lineUpRightArc: '╰',\n lineUpBoldRightBold: '┗',\n lineUpBoldRight: '┖',\n lineUpRightBold: '┕',\n lineUpDoubleRightDouble: '╚',\n lineUpDoubleRight: '╙',\n lineUpRightDouble: '╘',\n lineUpDownLeft: '┤',\n lineUpBoldDownBoldLeftBold: '┫',\n lineUpBoldDownBoldLeft: '┨',\n lineUpDownLeftBold: '┥',\n lineUpBoldDownLeftBold: '┩',\n lineUpDownBoldLeftBold: '┪',\n lineUpDownBoldLeft: '┧',\n lineUpBoldDownLeft: '┦',\n lineUpDoubleDownDoubleLeftDouble: '╣',\n lineUpDoubleDownDoubleLeft: '╢',\n lineUpDownLeftDouble: '╡',\n lineUpDownRight: '├',\n lineUpBoldDownBoldRightBold: '┣',\n lineUpBoldDownBoldRight: '┠',\n lineUpDownRightBold: '┝',\n lineUpBoldDownRightBold: '┡',\n lineUpDownBoldRightBold: '┢',\n lineUpDownBoldRight: '┟',\n lineUpBoldDownRight: '┞',\n lineUpDoubleDownDoubleRightDouble: '╠',\n lineUpDoubleDownDoubleRight: '╟',\n lineUpDownRightDouble: '╞',\n lineDownLeftRight: '┬',\n lineDownBoldLeftBoldRightBold: '┳',\n lineDownLeftBoldRightBold: '┯',\n lineDownBoldLeftRight: '┰',\n lineDownBoldLeftBoldRight: '┱',\n lineDownBoldLeftRightBold: '┲',\n lineDownLeftRightBold: '┮',\n lineDownLeftBoldRight: '┭',\n lineDownDoubleLeftDoubleRightDouble: '╦',\n lineDownDoubleLeftRight: '╥',\n lineDownLeftDoubleRightDouble: '╤',\n lineUpLeftRight: '┴',\n lineUpBoldLeftBoldRightBold: '┻',\n lineUpLeftBoldRightBold: '┷',\n lineUpBoldLeftRight: '┸',\n lineUpBoldLeftBoldRight: '┹',\n lineUpBoldLeftRightBold: '┺',\n lineUpLeftRightBold: '┶',\n lineUpLeftBoldRight: '┵',\n lineUpDoubleLeftDoubleRightDouble: '╩',\n lineUpDoubleLeftRight: '╨',\n lineUpLeftDoubleRightDouble: '╧',\n lineUpDownLeftRight: '┼',\n lineUpBoldDownBoldLeftBoldRightBold: '╋',\n lineUpDownBoldLeftBoldRightBold: '╈',\n lineUpBoldDownLeftBoldRightBold: '╇',\n lineUpBoldDownBoldLeftRightBold: '╊',\n lineUpBoldDownBoldLeftBoldRight: '╉',\n lineUpBoldDownLeftRight: '╀',\n lineUpDownBoldLeftRight: '╁',\n lineUpDownLeftBoldRight: '┽',\n lineUpDownLeftRightBold: '┾',\n lineUpBoldDownBoldLeftRight: '╂',\n lineUpDownLeftBoldRightBold: '┿',\n lineUpBoldDownLeftBoldRight: '╃',\n lineUpBoldDownLeftRightBold: '╄',\n lineUpDownBoldLeftBoldRight: '╅',\n lineUpDownBoldLeftRightBold: '╆',\n lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬',\n lineUpDoubleDownDoubleLeftRight: '╫',\n lineUpDownLeftDoubleRightDouble: '╪',\n lineCross: '╳',\n lineBackslash: '╲',\n lineSlash: '╱',\n};\nconst specialMainSymbols = {\n tick: '✔',\n info: 'ℹ',\n warning: '⚠',\n cross: '✘',\n squareSmall: '◻',\n squareSmallFilled: '◼',\n circle: '◯',\n circleFilled: '◉',\n circleDotted: '◌',\n circleDouble: '◎',\n circleCircle: 'ⓞ',\n circleCross: 'ⓧ',\n circlePipe: 'Ⓘ',\n radioOn: '◉',\n radioOff: '◯',\n checkboxOn: '☒',\n checkboxOff: '☐',\n checkboxCircleOn: 'ⓧ',\n checkboxCircleOff: 'Ⓘ',\n pointer: '❯',\n triangleUpOutline: '△',\n triangleLeft: '◀',\n triangleRight: '▶',\n lozenge: '◆',\n lozengeOutline: '◇',\n hamburger: '☰',\n smiley: '㋡',\n mustache: '෴',\n star: '★',\n play: '▶',\n nodejs: '⬢',\n oneSeventh: '⅐',\n oneNinth: '⅑',\n oneTenth: '⅒',\n};\nconst specialFallbackSymbols = {\n tick: '√',\n info: 'i',\n warning: '‼',\n cross: '×',\n squareSmall: '□',\n squareSmallFilled: '■',\n circle: '( )',\n circleFilled: '(*)',\n circleDotted: '( )',\n circleDouble: '( )',\n circleCircle: '(○)',\n circleCross: '(×)',\n circlePipe: '(│)',\n radioOn: '(*)',\n radioOff: '( )',\n checkboxOn: '[×]',\n checkboxOff: '[ ]',\n checkboxCircleOn: '(×)',\n checkboxCircleOff: '( )',\n pointer: '>',\n triangleUpOutline: '∆',\n triangleLeft: '◄',\n triangleRight: '►',\n lozenge: '♦',\n lozengeOutline: '◊',\n hamburger: '≡',\n smiley: '☺',\n mustache: '┌─┐',\n star: '✶',\n play: '►',\n nodejs: '♦',\n oneSeventh: '1/7',\n oneNinth: '1/9',\n oneTenth: '1/10',\n};\nexport const mainSymbols = {\n ...common,\n ...specialMainSymbols,\n};\nexport const fallbackSymbols = {\n ...common,\n ...specialFallbackSymbols,\n};\nconst shouldUseMain = isUnicodeSupported();\nconst figures = shouldUseMain\n ? mainSymbols\n : fallbackSymbols;\nexport default figures;\nconst replacements = Object.entries(specialMainSymbols);\n// On terminals which do not support Unicode symbols, substitute them to other symbols\nexport const replaceSymbols = (string, { useFallback = !shouldUseMain } = {}) => {\n if (useFallback) {\n for (const [key, mainSymbol] of replacements) {\n const fallbackSymbol = fallbackSymbols[key];\n if (!fallbackSymbol) {\n throw new Error(`Unable to find fallback for ${key}`);\n }\n string = string.replaceAll(mainSymbol, fallbackSymbol);\n }\n }\n return string;\n};\n","import { styleText } from 'node:util';\nimport figures from '@inquirer/figures';\nimport { getDefaultKeybindings } from \"./key.js\";\nexport const defaultTheme = {\n prefix: {\n idle: styleText('blue', '?'),\n done: styleText('green', figures.tick),\n },\n spinner: {\n interval: 80,\n frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => styleText('yellow', frame)),\n },\n keybindings: [],\n style: {\n answer: (text) => styleText('cyan', text),\n message: (text) => styleText('bold', text),\n error: (text) => styleText('red', `> ${text}`),\n defaultAnswer: (text) => styleText('dim', `(${text})`),\n help: (text) => styleText('dim', text),\n highlight: (text) => styleText('cyan', text),\n key: (text) => styleText('cyan', styleText('bold', `<${text}>`)),\n },\n};\nexport function getDefaultTheme() {\n return {\n ...defaultTheme,\n keybindings: getDefaultKeybindings(),\n };\n}\n","import { getDefaultTheme } from \"./theme.js\";\nfunction isPlainObject(value) {\n if (typeof value !== 'object' || value === null)\n return false;\n let proto = value;\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n return Object.getPrototypeOf(value) === proto;\n}\nfunction deepMerge(...objects) {\n const output = {};\n for (const obj of objects) {\n for (const [key, value] of Object.entries(obj)) {\n const prevValue = output[key];\n output[key] =\n isPlainObject(prevValue) && isPlainObject(value)\n ? deepMerge(prevValue, value)\n : value;\n }\n }\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n return output;\n}\nexport function makeTheme(...themes) {\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const themesToMerge = [\n getDefaultTheme(),\n ...themes.filter((theme) => theme != null),\n ];\n return deepMerge(...themesToMerge);\n}\n","import { useState } from \"./use-state.js\";\nimport { useEffect } from \"./use-effect.js\";\nimport { makeTheme } from \"./make-theme.js\";\nexport function usePrefix({ status = 'idle', theme, }) {\n const [showLoader, setShowLoader] = useState(false);\n const [tick, setTick] = useState(0);\n const { prefix, spinner } = makeTheme(theme);\n useEffect(() => {\n if (status === 'loading') {\n let tickInterval;\n let inc = -1;\n // Delay displaying spinner by 300ms, to avoid flickering\n const delayTimeout = setTimeout(() => {\n setShowLoader(true);\n tickInterval = setInterval(() => {\n inc = inc + 1;\n setTick(inc % spinner.frames.length);\n }, spinner.interval);\n }, 300);\n return () => {\n clearTimeout(delayTimeout);\n clearInterval(tickInterval);\n };\n }\n else {\n setShowLoader(false);\n }\n }, [status]);\n if (showLoader) {\n return spinner.frames[tick];\n }\n // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead.\n const iconName = status === 'loading' ? 'idle' : status;\n return typeof prefix === 'string' ? prefix : (prefix[iconName] ?? prefix['idle']);\n}\n","import { withPointer } from \"./hook-engine.js\";\nexport function useMemo(fn, dependencies) {\n return withPointer((pointer) => {\n const prev = pointer.get();\n if (!prev ||\n prev.dependencies.length !== dependencies.length ||\n prev.dependencies.some((dep, i) => dep !== dependencies[i])) {\n const value = fn();\n pointer.set({ value, dependencies });\n return value;\n }\n return prev.value;\n });\n}\n","import { useState } from \"./use-state.js\";\nexport function useRef(val) {\n return useState({ current: val })[0];\n}\n","import { useRef } from \"./use-ref.js\";\nimport { useEffect } from \"./use-effect.js\";\nimport { withUpdates } from \"./hook-engine.js\";\nexport function useKeypress(userHandler) {\n const signal = useRef(userHandler);\n signal.current = userHandler;\n useEffect((rl) => {\n let ignore = false;\n const handler = withUpdates((_input, event) => {\n if (ignore)\n return;\n void signal.current(event, rl);\n });\n rl.input.on('keypress', handler);\n return () => {\n ignore = true;\n rl.input.removeListener('keypress', handler);\n };\n }, []);\n}\n","module.exports = {}","'use strict';\n\nmodule.exports = cliWidth;\n\nfunction normalizeOpts(options) {\n const defaultOpts = {\n defaultWidth: 0,\n output: process.stdout,\n tty: require('tty'),\n };\n\n if (!options) {\n return defaultOpts;\n }\n\n Object.keys(defaultOpts).forEach(function (key) {\n if (!options[key]) {\n options[key] = defaultOpts[key];\n }\n });\n\n return options;\n}\n\nfunction cliWidth(options) {\n const opts = normalizeOpts(options);\n\n if (opts.output.getWindowSize) {\n return opts.output.getWindowSize()[0] || opts.defaultWidth;\n }\n\n if (opts.tty.getWindowSize) {\n return opts.tty.getWindowSize()[1] || opts.defaultWidth;\n }\n\n if (opts.output.columns) {\n return opts.output.columns;\n }\n\n if (process.env.CLI_WIDTH) {\n const width = parseInt(process.env.CLI_WIDTH, 10);\n\n if (!isNaN(width) && width !== 0) {\n return width;\n }\n }\n\n return opts.defaultWidth;\n}\n","/* MAIN */\nconst getCodePointsLength = (() => {\n const SURROGATE_PAIR_RE = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n return (input) => {\n let surrogatePairsNr = 0;\n SURROGATE_PAIR_RE.lastIndex = 0;\n while (SURROGATE_PAIR_RE.test(input)) {\n surrogatePairsNr += 1;\n }\n return input.length - surrogatePairsNr;\n };\n})();\nconst isFullWidth = (x) => {\n return x === 0x3000 || x >= 0xFF01 && x <= 0xFF60 || x >= 0xFFE0 && x <= 0xFFE6;\n};\nconst isWideNotCJKTNotEmoji = (x) => {\n return x === 0x231B || x === 0x2329 || x >= 0x2FF0 && x <= 0x2FFF || x >= 0x3001 && x <= 0x303E || x >= 0x3099 && x <= 0x30FF || x >= 0x3105 && x <= 0x312F || x >= 0x3131 && x <= 0x318E || x >= 0x3190 && x <= 0x31E3 || x >= 0x31EF && x <= 0x321E || x >= 0x3220 && x <= 0x3247 || x >= 0x3250 && x <= 0x4DBF || x >= 0xFE10 && x <= 0xFE19 || x >= 0xFE30 && x <= 0xFE52 || x >= 0xFE54 && x <= 0xFE66 || x >= 0xFE68 && x <= 0xFE6B || x >= 0x1F200 && x <= 0x1F202 || x >= 0x1F210 && x <= 0x1F23B || x >= 0x1F240 && x <= 0x1F248 || x >= 0x20000 && x <= 0x2FFFD || x >= 0x30000 && x <= 0x3FFFD;\n};\n/* EXPORT */\nexport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji };\n","/* IMPORT */\nimport { getCodePointsLength, isFullWidth, isWideNotCJKTNotEmoji } from './utils.js';\n/* HELPERS */\nconst ANSI_RE = /[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\\u001b\\]8;[^;]*;.*?(?:\\u0007|\\u001b\\u005c)/y;\nconst CONTROL_RE = /[\\x00-\\x08\\x0A-\\x1F\\x7F-\\x9F]{1,1000}/y;\nconst CJKT_WIDE_RE = /(?:(?![\\uFF61-\\uFF9F\\uFF00-\\uFFEF])[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}\\p{Script=Tangut}]){1,1000}/yu;\nconst TAB_RE = /\\t{1,1000}/y;\nconst EMOJI_RE = /[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*/yu;\nconst LATIN_RE = /(?:[\\x20-\\x7E\\xA0-\\xFF](?!\\uFE0F)){1,1000}/y;\nconst MODIFIER_RE = /\\p{M}+/gu;\nconst NO_TRUNCATION = { limit: Infinity, ellipsis: '' };\n/* MAIN */\nconst getStringTruncatedWidth = (input, truncationOptions = {}, widthOptions = {}) => {\n /* CONSTANTS */\n const LIMIT = truncationOptions.limit ?? Infinity;\n const ELLIPSIS = truncationOptions.ellipsis ?? '';\n const ELLIPSIS_WIDTH = truncationOptions?.ellipsisWidth ?? (ELLIPSIS ? getStringTruncatedWidth(ELLIPSIS, NO_TRUNCATION, widthOptions).width : 0);\n const ANSI_WIDTH = 0;\n const CONTROL_WIDTH = widthOptions.controlWidth ?? 0;\n const TAB_WIDTH = widthOptions.tabWidth ?? 8;\n const EMOJI_WIDTH = widthOptions.emojiWidth ?? 2;\n const FULL_WIDTH_WIDTH = 2;\n const REGULAR_WIDTH = widthOptions.regularWidth ?? 1;\n const WIDE_WIDTH = widthOptions.wideWidth ?? FULL_WIDTH_WIDTH;\n const PARSE_BLOCKS = [\n [LATIN_RE, REGULAR_WIDTH],\n [ANSI_RE, ANSI_WIDTH],\n [CONTROL_RE, CONTROL_WIDTH],\n [TAB_RE, TAB_WIDTH],\n [EMOJI_RE, EMOJI_WIDTH],\n [CJKT_WIDE_RE, WIDE_WIDTH],\n ];\n /* STATE */\n let indexPrev = 0;\n let index = 0;\n let length = input.length;\n let lengthExtra = 0;\n let truncationEnabled = false;\n let truncationIndex = length;\n let truncationLimit = Math.max(0, LIMIT - ELLIPSIS_WIDTH);\n let unmatchedStart = 0;\n let unmatchedEnd = 0;\n let width = 0;\n let widthExtra = 0;\n /* PARSE LOOP */\n outer: while (true) {\n /* UNMATCHED */\n if ((unmatchedEnd > unmatchedStart) || (index >= length && index > indexPrev)) {\n const unmatched = input.slice(unmatchedStart, unmatchedEnd) || input.slice(indexPrev, index);\n lengthExtra = 0;\n for (const char of unmatched.replaceAll(MODIFIER_RE, '')) {\n const codePoint = char.codePointAt(0) || 0;\n if (isFullWidth(codePoint)) {\n widthExtra = FULL_WIDTH_WIDTH;\n }\n else if (isWideNotCJKTNotEmoji(codePoint)) {\n widthExtra = WIDE_WIDTH;\n }\n else {\n widthExtra = REGULAR_WIDTH;\n }\n if ((width + widthExtra) > truncationLimit) {\n truncationIndex = Math.min(truncationIndex, Math.max(unmatchedStart, indexPrev) + lengthExtra);\n }\n if ((width + widthExtra) > LIMIT) {\n truncationEnabled = true;\n break outer;\n }\n lengthExtra += char.length;\n width += widthExtra;\n }\n unmatchedStart = unmatchedEnd = 0;\n }\n /* EXITING */\n if (index >= length) {\n break outer;\n }\n /* PARSE BLOCKS */\n for (let i = 0, l = PARSE_BLOCKS.length; i < l; i++) {\n const [BLOCK_RE, BLOCK_WIDTH] = PARSE_BLOCKS[i];\n BLOCK_RE.lastIndex = index;\n if (BLOCK_RE.test(input)) {\n lengthExtra = BLOCK_RE === CJKT_WIDE_RE ? getCodePointsLength(input.slice(index, BLOCK_RE.lastIndex)) : BLOCK_RE === EMOJI_RE ? 1 : BLOCK_RE.lastIndex - index;\n widthExtra = lengthExtra * BLOCK_WIDTH;\n if ((width + widthExtra) > truncationLimit) {\n truncationIndex = Math.min(truncationIndex, index + Math.floor((truncationLimit - width) / BLOCK_WIDTH));\n }\n if ((width + widthExtra) > LIMIT) {\n truncationEnabled = true;\n break outer;\n }\n width += widthExtra;\n unmatchedStart = indexPrev;\n unmatchedEnd = index;\n index = indexPrev = BLOCK_RE.lastIndex;\n continue outer;\n }\n }\n /* UNMATCHED INDEX */\n index += 1;\n }\n /* RETURN */\n return {\n width: truncationEnabled ? truncationLimit : width,\n index: truncationEnabled ? truncationIndex : length,\n truncated: truncationEnabled,\n ellipsed: truncationEnabled && LIMIT >= ELLIPSIS_WIDTH\n };\n};\n/* EXPORT */\nexport default getStringTruncatedWidth;\n","/* IMPORT */\nimport fastStringTruncatedWidth from 'fast-string-truncated-width';\n/* HELPERS */\nconst NO_TRUNCATION = {\n limit: Infinity,\n ellipsis: '',\n ellipsisWidth: 0,\n};\n/* MAIN */\nconst fastStringWidth = (input, options = {}) => {\n return fastStringTruncatedWidth(input, NO_TRUNCATION, options).width;\n};\n/* EXPORT */\nexport default fastStringWidth;\n","import stringWidth from 'fast-string-width';\nconst ESC = '\\x1B';\nconst CSI = '\\x9B';\nconst END_CODE = 39;\nconst ANSI_ESCAPE_BELL = '\\u0007';\nconst ANSI_CSI = '[';\nconst ANSI_OSC = ']';\nconst ANSI_SGR_TERMINATOR = 'm';\nconst ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`;\nconst GROUP_REGEX = new RegExp(`(?:\\\\${ANSI_CSI}(?<code>\\\\d+)m|\\\\${ANSI_ESCAPE_LINK}(?<uri>.*)${ANSI_ESCAPE_BELL})`, 'y');\nconst getClosingCode = (openingCode) => {\n if (openingCode >= 30 && openingCode <= 37)\n return 39;\n if (openingCode >= 90 && openingCode <= 97)\n return 39;\n if (openingCode >= 40 && openingCode <= 47)\n return 49;\n if (openingCode >= 100 && openingCode <= 107)\n return 49;\n if (openingCode === 1 || openingCode === 2)\n return 22;\n if (openingCode === 3)\n return 23;\n if (openingCode === 4)\n return 24;\n if (openingCode === 7)\n return 27;\n if (openingCode === 8)\n return 28;\n if (openingCode === 9)\n return 29;\n if (openingCode === 0)\n return 0;\n return undefined;\n};\nconst wrapAnsiCode = (code) => `${ESC}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`;\nconst wrapAnsiHyperlink = (url) => `${ESC}${ANSI_ESCAPE_LINK}${url}${ANSI_ESCAPE_BELL}`;\nconst wrapWord = (rows, word, columns) => {\n const characters = word[Symbol.iterator]();\n let isInsideEscape = false;\n let isInsideLinkEscape = false;\n let lastRow = rows.at(-1);\n let visible = lastRow === undefined ? 0 : stringWidth(lastRow);\n let currentCharacter = characters.next();\n let nextCharacter = characters.next();\n let rawCharacterIndex = 0;\n while (!currentCharacter.done) {\n const character = currentCharacter.value;\n const characterLength = stringWidth(character);\n if (visible + characterLength <= columns) {\n rows[rows.length - 1] += character;\n }\n else {\n rows.push(character);\n visible = 0;\n }\n if (character === ESC || character === CSI) {\n isInsideEscape = true;\n isInsideLinkEscape = word.startsWith(ANSI_ESCAPE_LINK, rawCharacterIndex + 1);\n }\n if (isInsideEscape) {\n if (isInsideLinkEscape) {\n if (character === ANSI_ESCAPE_BELL) {\n isInsideEscape = false;\n isInsideLinkEscape = false;\n }\n }\n else if (character === ANSI_SGR_TERMINATOR) {\n isInsideEscape = false;\n }\n }\n else {\n visible += characterLength;\n if (visible === columns && !nextCharacter.done) {\n rows.push('');\n visible = 0;\n }\n }\n currentCharacter = nextCharacter;\n nextCharacter = characters.next();\n rawCharacterIndex += character.length;\n }\n lastRow = rows.at(-1);\n if (!visible && lastRow !== undefined && lastRow.length && rows.length > 1) {\n rows[rows.length - 2] += rows.pop();\n }\n};\nconst stringVisibleTrimSpacesRight = (string) => {\n const words = string.split(' ');\n let last = words.length;\n while (last) {\n if (stringWidth(words[last - 1])) {\n break;\n }\n last--;\n }\n if (last === words.length) {\n return string;\n }\n return words.slice(0, last).join(' ') + words.slice(last).join('');\n};\nconst exec = (string, columns, options = {}) => {\n if (options.trim !== false && string.trim() === '') {\n return '';\n }\n let returnValue = '';\n let escapeCode;\n let escapeUrl;\n const words = string.split(' ');\n let rows = [''];\n let rowLength = 0;\n for (let index = 0; index < words.length; index++) {\n const word = words[index];\n if (options.trim !== false) {\n const row = rows.at(-1) ?? '';\n const trimmed = row.trimStart();\n if (row.length !== trimmed.length) {\n rows[rows.length - 1] = trimmed;\n rowLength = stringWidth(trimmed);\n }\n }\n if (index !== 0) {\n if (rowLength >= columns &&\n (options.wordWrap === false || options.trim === false)) {\n rows.push('');\n rowLength = 0;\n }\n if (rowLength || options.trim === false) {\n rows[rows.length - 1] += ' ';\n rowLength++;\n }\n }\n const wordLength = stringWidth(word);\n if (options.hard && wordLength > columns) {\n const remainingColumns = columns - rowLength;\n const breaksStartingThisLine = 1 + Math.floor((wordLength - remainingColumns - 1) / columns);\n const breaksStartingNextLine = Math.floor((wordLength - 1) / columns);\n if (breaksStartingNextLine < breaksStartingThisLine) {\n rows.push('');\n }\n wrapWord(rows, word, columns);\n rowLength = stringWidth(rows.at(-1) ?? '');\n continue;\n }\n if (rowLength + wordLength > columns && rowLength && wordLength) {\n if (options.wordWrap === false && rowLength < columns) {\n wrapWord(rows, word, columns);\n rowLength = stringWidth(rows.at(-1) ?? '');\n continue;\n }\n rows.push('');\n rowLength = 0;\n }\n if (rowLength + wordLength > columns && options.wordWrap === false) {\n wrapWord(rows, word, columns);\n rowLength = stringWidth(rows.at(-1) ?? '');\n continue;\n }\n rows[rows.length - 1] += word;\n rowLength += wordLength;\n }\n if (options.trim !== false) {\n rows = rows.map((row) => stringVisibleTrimSpacesRight(row));\n }\n const preString = rows.join('\\n');\n let inSurrogate = false;\n for (let i = 0; i < preString.length; i++) {\n const character = preString[i];\n returnValue += character;\n if (!inSurrogate) {\n inSurrogate = character >= '\\ud800' && character <= '\\udbff';\n if (inSurrogate) {\n continue;\n }\n }\n else {\n inSurrogate = false;\n }\n if (character === ESC || character === CSI) {\n GROUP_REGEX.lastIndex = i + 1;\n const groupsResult = GROUP_REGEX.exec(preString);\n const groups = groupsResult?.groups;\n if (groups?.code !== undefined) {\n const code = Number.parseFloat(groups.code);\n escapeCode = code === END_CODE ? undefined : code;\n }\n else if (groups?.uri !== undefined) {\n escapeUrl = groups.uri.length === 0 ? undefined : groups.uri;\n }\n }\n if (preString[i + 1] === '\\n') {\n if (escapeUrl) {\n returnValue += wrapAnsiHyperlink('');\n }\n const closingCode = escapeCode ? getClosingCode(escapeCode) : undefined;\n if (escapeCode && closingCode) {\n returnValue += wrapAnsiCode(closingCode);\n }\n }\n else if (character === '\\n') {\n if (escapeCode && getClosingCode(escapeCode)) {\n returnValue += wrapAnsiCode(escapeCode);\n }\n if (escapeUrl) {\n returnValue += wrapAnsiHyperlink(escapeUrl);\n }\n }\n }\n return returnValue;\n};\nconst CRLF_OR_LF = /\\r?\\n/;\nexport function wrapAnsi(string, columns, options) {\n return String(string)\n .normalize()\n .split(CRLF_OR_LF)\n .map((line) => exec(line, columns, options))\n .join('\\n');\n}\n","import cliWidth from 'cli-width';\nimport { wrapAnsi } from 'fast-wrap-ansi';\nimport { readline } from \"./hook-engine.js\";\n/**\n * Force line returns at specific width. This function is ANSI code friendly and it'll\n * ignore invisible codes during width calculation.\n * @param {string} content\n * @param {number} width\n * @return {string}\n */\nexport function breakLines(content, width) {\n return content\n .split('\\n')\n .flatMap((line) => wrapAnsi(line, width, { trim: false, wordWrap: false })\n .split('\\n')\n .map((str) => str.trimEnd()))\n .join('\\n');\n}\n/**\n * Returns the width of the active readline, or 80 as default value.\n * @returns {number}\n */\nexport function readlineWidth() {\n return cliWidth({ defaultWidth: 80, output: readline().output });\n}\n","import { useRef } from \"../use-ref.js\";\nimport { readlineWidth, breakLines } from \"../utils.js\";\nfunction usePointerPosition({ active, renderedItems, pageSize, loop, }) {\n const state = useRef({\n lastPointer: active,\n lastActive: undefined,\n });\n const { lastPointer, lastActive } = state.current;\n const middle = Math.floor(pageSize / 2);\n const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);\n const defaultPointerPosition = renderedItems\n .slice(0, active)\n .reduce((acc, item) => acc + item.length, 0);\n let pointer = defaultPointerPosition;\n if (renderedLength > pageSize) {\n if (loop) {\n /**\n * Creates the next position for the pointer considering an infinitely\n * looping list of items to be rendered on the page.\n *\n * The goal is to progressively move the cursor to the middle position as the user move down, and then keep\n * the cursor there. When the user move up, maintain the cursor position.\n */\n // By default, keep the cursor position as-is.\n pointer = lastPointer;\n if (\n // First render, skip this logic.\n lastActive != null &&\n // Only move the pointer down when the user moves down.\n lastActive < active &&\n // Check user didn't move up across page boundary.\n active - lastActive < pageSize) {\n pointer = Math.min(\n // Furthest allowed position for the pointer is the middle of the list\n middle, Math.abs(active - lastActive) === 1\n ? Math.min(\n // Move the pointer at most the height of the last active item.\n lastPointer + (renderedItems[lastActive]?.length ?? 0), \n // If the user moved by one item, move the pointer to the natural position of the active item as\n // long as it doesn't move the cursor up.\n Math.max(defaultPointerPosition, lastPointer))\n : // Otherwise, move the pointer down by the difference between the active and last active item.\n lastPointer + active - lastActive);\n }\n }\n else {\n /**\n * Creates the next position for the pointer considering a finite list of\n * items to be rendered on a page.\n *\n * The goal is to keep the pointer in the middle of the page whenever possible, until\n * we reach the bounds of the list (top or bottom). In which case, the cursor moves progressively\n * to the bottom or top of the list.\n */\n const spaceUnderActive = renderedItems\n .slice(active)\n .reduce((acc, item) => acc + item.length, 0);\n pointer =\n spaceUnderActive < pageSize - middle\n ? // If the active item is near the end of the list, progressively move the cursor towards the end.\n pageSize - spaceUnderActive\n : // Otherwise, progressively move the pointer to the middle of the list.\n Math.min(defaultPointerPosition, middle);\n }\n }\n // Save state for the next render\n state.current.lastPointer = pointer;\n state.current.lastActive = active;\n return pointer;\n}\nexport function usePagination({ items, active, renderItem, pageSize, loop = true, }) {\n const width = readlineWidth();\n const bound = (num) => ((num % items.length) + items.length) % items.length;\n const renderedItems = items.map((item, index) => {\n if (item == null)\n return [];\n return breakLines(renderItem({ item, index, isActive: index === active }), width).split('\\n');\n });\n const renderedLength = renderedItems.reduce((acc, item) => acc + item.length, 0);\n const renderItemAtIndex = (index) => renderedItems[index] ?? [];\n const pointer = usePointerPosition({ active, renderedItems, pageSize, loop });\n // Render the active item to decide the position.\n // If the active item fits under the pointer, we render it there.\n // Otherwise, we need to render it to fit at the bottom of the page; moving the pointer up.\n const activeItem = renderItemAtIndex(active).slice(0, pageSize);\n const activeItemPosition = pointer + activeItem.length <= pageSize ? pointer : pageSize - activeItem.length;\n // Create an array of lines for the page, and add the lines of the active item into the page\n const pageBuffer = Array.from({ length: pageSize });\n pageBuffer.splice(activeItemPosition, activeItem.length, ...activeItem);\n // Store to prevent rendering the same item twice\n const itemVisited = new Set([active]);\n // Fill the page under the active item\n let bufferPointer = activeItemPosition + activeItem.length;\n let itemPointer = bound(active + 1);\n while (bufferPointer < pageSize &&\n !itemVisited.has(itemPointer) &&\n (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer > active)) {\n const lines = renderItemAtIndex(itemPointer);\n const linesToAdd = lines.slice(0, pageSize - bufferPointer);\n pageBuffer.splice(bufferPointer, linesToAdd.length, ...linesToAdd);\n // Move pointers for next iteration\n itemVisited.add(itemPointer);\n bufferPointer += linesToAdd.length;\n itemPointer = bound(itemPointer + 1);\n }\n // Fill the page over the active item\n bufferPointer = activeItemPosition - 1;\n itemPointer = bound(active - 1);\n while (bufferPointer >= 0 &&\n !itemVisited.has(itemPointer) &&\n (loop && renderedLength > pageSize ? itemPointer !== active : itemPointer < active)) {\n const lines = renderItemAtIndex(itemPointer);\n const linesToAdd = lines.slice(Math.max(0, lines.length - bufferPointer - 1));\n pageBuffer.splice(bufferPointer - linesToAdd.length + 1, linesToAdd.length, ...linesToAdd);\n // Move pointers for next iteration\n itemVisited.add(itemPointer);\n bufferPointer -= linesToAdd.length;\n itemPointer = bound(itemPointer - 1);\n }\n return pageBuffer.filter((line) => typeof line === 'string').join('\\n');\n}\n","const Stream = require('stream')\n\nclass MuteStream extends Stream {\n #isTTY = null\n\n constructor (opts = {}) {\n super(opts)\n this.writable = this.readable = true\n this.muted = false\n this.on('pipe', this._onpipe)\n this.replace = opts.replace\n\n // For readline-type situations\n // This much at the start of a line being redrawn after a ctrl char\n // is seen (such as backspace) won't be redrawn as the replacement\n this._prompt = opts.prompt || null\n this._hadControl = false\n }\n\n #destSrc (key, def) {\n if (this._dest) {\n return this._dest[key]\n }\n if (this._src) {\n return this._src[key]\n }\n return def\n }\n\n #proxy (method, ...args) {\n if (typeof this._dest?.[method] === 'function') {\n this._dest[method](...args)\n }\n if (typeof this._src?.[method] === 'function') {\n this._src[method](...args)\n }\n }\n\n get isTTY () {\n if (this.#isTTY !== null) {\n return this.#isTTY\n }\n return this.#destSrc('isTTY', false)\n }\n\n // basically just get replace the getter/setter with a regular value\n set isTTY (val) {\n this.#isTTY = val\n }\n\n get rows () {\n return this.#destSrc('rows')\n }\n\n get columns () {\n return this.#destSrc('columns')\n }\n\n mute () {\n this.muted = true\n }\n\n unmute () {\n this.muted = false\n }\n\n _onpipe (src) {\n this._src = src\n }\n\n pipe (dest, options) {\n this._dest = dest\n return super.pipe(dest, options)\n }\n\n pause () {\n if (this._src) {\n return this._src.pause()\n }\n }\n\n resume () {\n if (this._src) {\n return this._src.resume()\n }\n }\n\n write (c) {\n if (this.muted) {\n if (!this.replace) {\n return true\n }\n // eslint-disable-next-line no-control-regex\n if (c.match(/^\\u001b/)) {\n if (c.indexOf(this._prompt) === 0) {\n c = c.slice(this._prompt.length)\n c = c.replace(/./g, this.replace)\n c = this._prompt + c\n }\n this._hadControl = true\n return this.emit('data', c)\n } else {\n if (this._prompt && this._hadControl &&\n c.indexOf(this._prompt) === 0) {\n this._hadControl = false\n this.emit('data', this._prompt)\n c = c.slice(this._prompt.length)\n }\n c = c.toString().replace(/./g, this.replace)\n }\n }\n this.emit('data', c)\n }\n\n end (c) {\n if (this.muted) {\n if (c && this.replace) {\n c = c.toString().replace(/./g, this.replace)\n } else {\n c = null\n }\n }\n if (c) {\n this.emit('data', c)\n }\n this.emit('end')\n }\n\n destroy (...args) {\n return this.#proxy('destroy', ...args)\n }\n\n destroySoon (...args) {\n return this.#proxy('destroySoon', ...args)\n }\n\n close (...args) {\n return this.#proxy('close', ...args)\n }\n}\n\nmodule.exports = MuteStream\n","/**\n * This is not the set of all possible signals.\n *\n * It IS, however, the set of all signals that trigger\n * an exit on either Linux or BSD systems. Linux is a\n * superset of the signal names supported on BSD, and\n * the unknown signals just fail to register, so we can\n * catch that easily enough.\n *\n * Windows signals are a different set, since there are\n * signals that terminate Windows processes, but don't\n * terminate (or don't even exist) on Posix systems.\n *\n * Don't bother with SIGKILL. It's uncatchable, which\n * means that we can't fire any callbacks anyway.\n *\n * If a user does happen to register a handler on a non-\n * fatal signal like SIGWINCH or something, and then\n * exit, it'll end up firing `process.emit('exit')`, so\n * the handler will be fired anyway.\n *\n * SIGBUS, SIGFPE, SIGSEGV and SIGILL, when not raised\n * artificially, inherently leave the process in a\n * state from which it is not safe to try and enter JS\n * listeners.\n */\nexport const signals = [];\nsignals.push('SIGHUP', 'SIGINT', 'SIGTERM');\nif (process.platform !== 'win32') {\n signals.push('SIGALRM', 'SIGABRT', 'SIGVTALRM', 'SIGXCPU', 'SIGXFSZ', 'SIGUSR2', 'SIGTRAP', 'SIGSYS', 'SIGQUIT', 'SIGIOT'\n // should detect profiler and enable/disable accordingly.\n // see #21\n // 'SIGPROF'\n );\n}\nif (process.platform === 'linux') {\n signals.push('SIGIO', 'SIGPOLL', 'SIGPWR', 'SIGSTKFLT');\n}\n//# sourceMappingURL=signals.js.map","// Note: since nyc uses this module to output coverage, any lines\n// that are in the direct sync flow of nyc's outputCoverage are\n// ignored, since we can never get coverage for them.\n// grab a reference to node's real process object right away\nimport { signals } from './signals.js';\nexport { signals };\nconst processOk = (process) => !!process &&\n typeof process === 'object' &&\n typeof process.removeListener === 'function' &&\n typeof process.emit === 'function' &&\n typeof process.reallyExit === 'function' &&\n typeof process.listeners === 'function' &&\n typeof process.kill === 'function' &&\n typeof process.pid === 'number' &&\n typeof process.on === 'function';\nconst kExitEmitter = Symbol.for('signal-exit emitter');\nconst global = globalThis;\nconst ObjectDefineProperty = Object.defineProperty.bind(Object);\n// teeny special purpose ee\nclass Emitter {\n emitted = {\n afterExit: false,\n exit: false,\n };\n listeners = {\n afterExit: [],\n exit: [],\n };\n count = 0;\n id = Math.random();\n constructor() {\n if (global[kExitEmitter]) {\n return global[kExitEmitter];\n }\n ObjectDefineProperty(global, kExitEmitter, {\n value: this,\n writable: false,\n enumerable: false,\n configurable: false,\n });\n }\n on(ev, fn) {\n this.listeners[ev].push(fn);\n }\n removeListener(ev, fn) {\n const list = this.listeners[ev];\n const i = list.indexOf(fn);\n /* c8 ignore start */\n if (i === -1) {\n return;\n }\n /* c8 ignore stop */\n if (i === 0 && list.length === 1) {\n list.length = 0;\n }\n else {\n list.splice(i, 1);\n }\n }\n emit(ev, code, signal) {\n if (this.emitted[ev]) {\n return false;\n }\n this.emitted[ev] = true;\n let ret = false;\n for (const fn of this.listeners[ev]) {\n ret = fn(code, signal) === true || ret;\n }\n if (ev === 'exit') {\n ret = this.emit('afterExit', code, signal) || ret;\n }\n return ret;\n }\n}\nclass SignalExitBase {\n}\nconst signalExitWrap = (handler) => {\n return {\n onExit(cb, opts) {\n return handler.onExit(cb, opts);\n },\n load() {\n return handler.load();\n },\n unload() {\n return handler.unload();\n },\n };\n};\nclass SignalExitFallback extends SignalExitBase {\n onExit() {\n return () => { };\n }\n load() { }\n unload() { }\n}\nclass SignalExit extends SignalExitBase {\n // \"SIGHUP\" throws an `ENOSYS` error on Windows,\n // so use a supported signal instead\n /* c8 ignore start */\n #hupSig = process.platform === 'win32' ? 'SIGINT' : 'SIGHUP';\n /* c8 ignore stop */\n #emitter = new Emitter();\n #process;\n #originalProcessEmit;\n #originalProcessReallyExit;\n #sigListeners = {};\n #loaded = false;\n constructor(process) {\n super();\n this.#process = process;\n // { <signal>: <listener fn>, ... }\n this.#sigListeners = {};\n for (const sig of signals) {\n this.#sigListeners[sig] = () => {\n // If there are no other listeners, an exit is coming!\n // Simplest way: remove us and then re-send the signal.\n // We know that this will kill the process, so we can\n // safely emit now.\n const listeners = this.#process.listeners(sig);\n let { count } = this.#emitter;\n // This is a workaround for the fact that signal-exit v3 and signal\n // exit v4 are not aware of each other, and each will attempt to let\n // the other handle it, so neither of them do. To correct this, we\n // detect if we're the only handler *except* for previous versions\n // of signal-exit, and increment by the count of listeners it has\n // created.\n /* c8 ignore start */\n const p = process;\n if (typeof p.__signal_exit_emitter__ === 'object' &&\n typeof p.__signal_exit_emitter__.count === 'number') {\n count += p.__signal_exit_emitter__.count;\n }\n /* c8 ignore stop */\n if (listeners.length === count) {\n this.unload();\n const ret = this.#emitter.emit('exit', null, sig);\n /* c8 ignore start */\n const s = sig === 'SIGHUP' ? this.#hupSig : sig;\n if (!ret)\n process.kill(process.pid, s);\n /* c8 ignore stop */\n }\n };\n }\n this.#originalProcessReallyExit = process.reallyExit;\n this.#originalProcessEmit = process.emit;\n }\n onExit(cb, opts) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return () => { };\n }\n /* c8 ignore stop */\n if (this.#loaded === false) {\n this.load();\n }\n const ev = opts?.alwaysLast ? 'afterExit' : 'exit';\n this.#emitter.on(ev, cb);\n return () => {\n this.#emitter.removeListener(ev, cb);\n if (this.#emitter.listeners['exit'].length === 0 &&\n this.#emitter.listeners['afterExit'].length === 0) {\n this.unload();\n }\n };\n }\n load() {\n if (this.#loaded) {\n return;\n }\n this.#loaded = true;\n // This is the number of onSignalExit's that are in play.\n // It's important so that we can count the correct number of\n // listeners on signals, and don't wait for the other one to\n // handle it instead of us.\n this.#emitter.count += 1;\n for (const sig of signals) {\n try {\n const fn = this.#sigListeners[sig];\n if (fn)\n this.#process.on(sig, fn);\n }\n catch (_) { }\n }\n this.#process.emit = (ev, ...a) => {\n return this.#processEmit(ev, ...a);\n };\n this.#process.reallyExit = (code) => {\n return this.#processReallyExit(code);\n };\n }\n unload() {\n if (!this.#loaded) {\n return;\n }\n this.#loaded = false;\n signals.forEach(sig => {\n const listener = this.#sigListeners[sig];\n /* c8 ignore start */\n if (!listener) {\n throw new Error('Listener not defined for signal: ' + sig);\n }\n /* c8 ignore stop */\n try {\n this.#process.removeListener(sig, listener);\n /* c8 ignore start */\n }\n catch (_) { }\n /* c8 ignore stop */\n });\n this.#process.emit = this.#originalProcessEmit;\n this.#process.reallyExit = this.#originalProcessReallyExit;\n this.#emitter.count -= 1;\n }\n #processReallyExit(code) {\n /* c8 ignore start */\n if (!processOk(this.#process)) {\n return 0;\n }\n this.#process.exitCode = code || 0;\n /* c8 ignore stop */\n this.#emitter.emit('exit', this.#process.exitCode, null);\n return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);\n }\n #processEmit(ev, ...args) {\n const og = this.#originalProcessEmit;\n if (ev === 'exit' && processOk(this.#process)) {\n if (typeof args[0] === 'number') {\n this.#process.exitCode = args[0];\n /* c8 ignore start */\n }\n /* c8 ignore start */\n const ret = og.call(this.#process, ev, ...args);\n /* c8 ignore start */\n this.#emitter.emit('exit', this.#process.exitCode, null);\n /* c8 ignore stop */\n return ret;\n }\n else {\n return og.call(this.#process, ev, ...args);\n }\n }\n}\nconst process = globalThis.process;\n// wrap so that we call the method on the actual handler, without\n// exporting it directly.\nexport const { \n/**\n * Called when the process is exiting, whether via signal, explicit\n * exit, or running out of stuff to do.\n *\n * If the global process object is not suitable for instrumentation,\n * then this will be a no-op.\n *\n * Returns a function that may be used to unload signal-exit.\n */\nonExit, \n/**\n * Load the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\nload, \n/**\n * Unload the listeners. Likely you never need to call this, unless\n * doing a rather deep integration with signal-exit functionality.\n * Mostly exposed for the benefit of testing.\n *\n * @internal\n */\nunload, } = signalExitWrap(processOk(process) ? new SignalExit(process) : new SignalExitFallback());\n//# sourceMappingURL=index.js.map","const ESC = '\\u001B[';\n/** Move cursor to first column */\nexport const cursorLeft = ESC + 'G';\n/** Hide the cursor */\nexport const cursorHide = ESC + '?25l';\n/** Show the cursor */\nexport const cursorShow = ESC + '?25h';\n/** Move cursor up by count rows */\nexport const cursorUp = (rows = 1) => (rows > 0 ? `${ESC}${rows}A` : '');\n/** Move cursor down by count rows */\nexport const cursorDown = (rows = 1) => rows > 0 ? `${ESC}${rows}B` : '';\n/** Move cursor to position (x, y) */\nexport const cursorTo = (x, y) => {\n if (typeof y === 'number' && !Number.isNaN(y)) {\n return `${ESC}${y + 1};${x + 1}H`;\n }\n return `${ESC}${x + 1}G`;\n};\nconst eraseLine = ESC + '2K';\n/** Erase the specified number of lines above the cursor */\nexport const eraseLines = (lines) => lines > 0 ? (eraseLine + cursorUp(1)).repeat(lines - 1) + eraseLine + cursorLeft : '';\n","import { stripVTControlCharacters } from 'node:util';\nimport { breakLines, readlineWidth } from \"./utils.js\";\nimport { cursorDown, cursorLeft, cursorUp, cursorTo, cursorShow, eraseLines, } from '@inquirer/ansi';\nconst height = (content) => content.split('\\n').length;\nconst lastLine = (content) => content.split('\\n').pop() ?? '';\nexport default class ScreenManager {\n // These variables are keeping information to allow correct prompt re-rendering\n height = 0;\n extraLinesUnderPrompt = 0;\n cursorPos;\n rl;\n constructor(rl) {\n this.rl = rl;\n this.cursorPos = rl.getCursorPos();\n }\n write(content) {\n this.rl.output.unmute();\n this.rl.output.write(content);\n this.rl.output.mute();\n }\n render(content, bottomContent = '') {\n // Write message to screen and setPrompt to control backspace\n const promptLine = lastLine(content);\n const rawPromptLine = stripVTControlCharacters(promptLine);\n // Remove the rl.line from our prompt. We can't rely on the content of\n // rl.line (mainly because of the password prompt), so just rely on it's\n // length.\n let prompt = rawPromptLine;\n if (this.rl.line.length > 0) {\n prompt = prompt.slice(0, -this.rl.line.length);\n }\n this.rl.setPrompt(prompt);\n // SetPrompt will change cursor position, now we can get correct value\n this.cursorPos = this.rl.getCursorPos();\n const width = readlineWidth();\n content = breakLines(content, width);\n bottomContent = breakLines(bottomContent, width);\n // Manually insert an extra line if we're at the end of the line.\n // This prevent the cursor from appearing at the beginning of the\n // current line.\n if (rawPromptLine.length % width === 0) {\n content += '\\n';\n }\n let output = content + (bottomContent ? '\\n' + bottomContent : '');\n /**\n * Re-adjust the cursor at the correct position.\n */\n // We need to consider parts of the prompt under the cursor as part of the bottom\n // content in order to correctly cleanup and re-render.\n const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows;\n const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0);\n // Return cursor to the input position (on top of the bottomContent)\n if (bottomContentHeight > 0)\n output += cursorUp(bottomContentHeight);\n // Return cursor to the initial left offset.\n output += cursorTo(this.cursorPos.cols);\n /**\n * Render and store state for future re-rendering\n */\n this.write(cursorDown(this.extraLinesUnderPrompt) + eraseLines(this.height) + output);\n this.extraLinesUnderPrompt = bottomContentHeight;\n this.height = height(output);\n }\n checkCursorPos() {\n const cursorPos = this.rl.getCursorPos();\n if (cursorPos.cols !== this.cursorPos.cols) {\n this.write(cursorTo(cursorPos.cols));\n this.cursorPos = cursorPos;\n }\n }\n done({ clearContent }) {\n this.rl.setPrompt('');\n let output = cursorDown(this.extraLinesUnderPrompt);\n output += clearContent ? eraseLines(this.height) : '\\n';\n // Reset cursor to column 0. On Windows terminals, \\n moves the cursor\n // down without resetting the column when the rendered prompt+answer\n // wraps past the terminal width. Without this, all subsequent output\n // starts at the wrong horizontal offset.\n output += cursorLeft;\n output += cursorShow;\n this.write(output);\n this.rl.close();\n }\n}\n","// TODO: Remove this class once Node 22 becomes the minimum supported version.\nexport class PromisePolyfill extends Promise {\n // Available starting from Node 22\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers\n static withResolver() {\n let resolve;\n let reject;\n const promise = new Promise((res, rej) => {\n resolve = res;\n reject = rej;\n });\n return { promise, resolve: resolve, reject: reject };\n }\n}\n","import * as readline from 'node:readline';\nimport { AsyncResource } from 'node:async_hooks';\nimport MuteStream from 'mute-stream';\nimport { onExit as onSignalExit } from 'signal-exit';\nimport ScreenManager from \"./screen-manager.js\";\nimport { PromisePolyfill } from \"./promise-polyfill.js\";\nimport { withHooks, effectScheduler } from \"./hook-engine.js\";\nimport { AbortPromptError, CancelPromptError, ExitPromptError } from \"./errors.js\";\nimport path from 'node:path';\n// Capture the real setImmediate at module load time so it works even when test\n// frameworks mock timers with vi.useFakeTimers() or similar.\nconst nativeSetImmediate = globalThis.setImmediate;\nfunction getCallSites() {\n // oxlint-disable-next-line typescript/unbound-method\n const savedPrepareStackTrace = Error.prepareStackTrace;\n let result = [];\n try {\n Error.prepareStackTrace = (_, callSites) => {\n const callSitesWithoutCurrent = callSites.slice(1);\n result = callSitesWithoutCurrent;\n return callSitesWithoutCurrent;\n };\n // oxlint-disable-next-line no-unused-expressions\n new Error().stack;\n }\n catch {\n // An error will occur if the Node flag --frozen-intrinsics is used.\n // https://nodejs.org/api/cli.html#--frozen-intrinsics\n return result;\n }\n Error.prepareStackTrace = savedPrepareStackTrace;\n return result;\n}\nexport function createPrompt(view) {\n const callSites = getCallSites();\n const prompt = (config, context = {}) => {\n // Default `input` to stdin\n const { input = process.stdin, signal } = context;\n const cleanups = new Set();\n // Add mute capabilities to the output\n const output = new MuteStream();\n output.pipe(context.output ?? process.stdout);\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion\n const rl = readline.createInterface({\n terminal: true,\n input,\n output,\n });\n // Mute the output after readline has initialized so readline can perform\n // any terminal setup writes (e.g. Windows Console API initialization)\n // before suppressing output. ScreenManager will unmute/mute around each\n // render call as needed.\n output.mute();\n const screen = new ScreenManager(rl);\n const { promise, resolve, reject } = PromisePolyfill.withResolver();\n const cancel = () => reject(new CancelPromptError());\n if (signal) {\n const abort = () => reject(new AbortPromptError({ cause: signal.reason }));\n if (signal.aborted) {\n abort();\n return Object.assign(promise, { cancel });\n }\n signal.addEventListener('abort', abort);\n cleanups.add(() => signal.removeEventListener('abort', abort));\n }\n cleanups.add(onSignalExit((code, signal) => {\n reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`));\n }));\n // SIGINT must be explicitly handled by the prompt so the ExitPromptError can be handled.\n // Otherwise, the prompt will stop and in some scenarios never resolve.\n // Ref issue #1741\n const sigint = () => reject(new ExitPromptError(`User force closed the prompt with SIGINT`));\n rl.on('SIGINT', sigint);\n cleanups.add(() => rl.removeListener('SIGINT', sigint));\n return withHooks(rl, (cycle) => {\n // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand\n // triggers after the process is done (which happens after timeouts are done triggering.)\n // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared.\n const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll());\n rl.on('close', hooksCleanup);\n cleanups.add(() => rl.removeListener('close', hooksCleanup));\n const startCycle = () => {\n // Re-renders only happen when the state change; but the readline cursor could\n // change position and that also requires a re-render (and a manual one because\n // we mute the streams). We set the listener after the initial workLoop to avoid\n // a double render if render triggered by a state change sets the cursor to the\n // right position.\n const checkCursorPos = () => screen.checkCursorPos();\n rl.input.on('keypress', checkCursorPos);\n cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos));\n let pendingDone = null;\n cycle(() => {\n let effectsSettled = false;\n try {\n const nextView = view(config, (value) => {\n if (effectsSettled) {\n // After the cycle completes (async validation path), the \"done\"\n // render already flushed via setStatus → handleChange, so resolve\n // immediately.\n resolve(value);\n }\n else {\n pendingDone = { value };\n }\n });\n // Typescript won't allow this, but not all users rely on typescript.\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (nextView === undefined) {\n let callerFilename = callSites[1]?.getFileName();\n if (callerFilename && !callerFilename.startsWith('file://')) {\n callerFilename = path.resolve(callerFilename);\n }\n throw new Error(`Prompt functions must return a string.\\n at ${callerFilename}`);\n }\n const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView;\n screen.render(content, bottomContent);\n effectScheduler.run();\n }\n catch (error) {\n reject(error);\n }\n effectsSettled = true;\n if (pendingDone !== null) {\n const { value } = pendingDone;\n pendingDone = null;\n resolve(value);\n }\n });\n };\n // Proper Readable streams (like process.stdin) may have OS-level buffered\n // data that arrives in the poll phase when readline resumes the stream.\n // Deferring the first render by one setImmediate tick (check phase, after\n // poll) lets that stale data flow through readline harmlessly—no keypress\n // handlers are registered yet and the output is muted, so the stale\n // keystrokes are silently discarded.\n // Old-style streams (like MuteStream) have no such buffering, so the\n // render cycle starts immediately.\n //\n // @see https://github.com/SBoudrias/Inquirer.js/issues/1303\n if ('readableFlowing' in input) {\n nativeSetImmediate(startCycle);\n }\n else {\n startCycle();\n }\n return Object.assign(promise\n .then((answer) => {\n effectScheduler.clearAll();\n return answer;\n }, (error) => {\n effectScheduler.clearAll();\n throw error;\n })\n // Wait for the promise to settle, then cleanup.\n .finally(() => {\n cleanups.forEach((cleanup) => cleanup());\n screen.done({ clearContent: Boolean(context.clearPromptOnDone) });\n output.end();\n })\n // Once cleanup is done, let the expose promise resolve/reject to the internal one.\n .then(() => promise), { cancel });\n });\n };\n return prompt;\n}\n","import { styleText } from 'node:util';\nimport figures from '@inquirer/figures';\n/**\n * Separator object\n * Used to space/separate choices group\n */\nexport class Separator {\n separator = styleText('dim', Array.from({ length: 15 }).join(figures.line));\n type = 'separator';\n constructor(separator) {\n if (separator) {\n this.separator = separator;\n }\n }\n static isSeparator(choice) {\n return Boolean(choice &&\n typeof choice === 'object' &&\n 'type' in choice &&\n choice.type === 'separator');\n }\n}\n","import { createPrompt, useState, useKeypress, isEnterKey, isTabKey, usePrefix, makeTheme, } from '@inquirer/core';\nfunction getBooleanValue(value, defaultValue) {\n let answer = defaultValue !== false;\n if (/^(y|yes)/i.test(value))\n answer = true;\n else if (/^(n|no)/i.test(value))\n answer = false;\n return answer;\n}\nfunction boolToString(value) {\n return value ? 'Yes' : 'No';\n}\nexport default createPrompt((config, done) => {\n const { transformer = boolToString } = config;\n const [status, setStatus] = useState('idle');\n const [value, setValue] = useState('');\n const theme = makeTheme(config.theme);\n const prefix = usePrefix({ status, theme });\n useKeypress((key, rl) => {\n if (status !== 'idle')\n return;\n if (isEnterKey(key)) {\n const answer = getBooleanValue(value, config.default);\n setValue(transformer(answer));\n setStatus('done');\n done(answer);\n }\n else if (isTabKey(key)) {\n const answer = boolToString(!getBooleanValue(value, config.default));\n rl.clearLine(0); // Remove the tab character.\n rl.write(answer);\n setValue(answer);\n }\n else {\n setValue(rl.line);\n }\n });\n let formattedValue = value;\n let defaultValue = '';\n if (status === 'done') {\n formattedValue = theme.style.answer(value);\n }\n else {\n defaultValue = ` ${theme.style.defaultAnswer(config.default === false ? 'y/N' : 'Y/n')}`;\n }\n const message = theme.style.message(config.message, status);\n return `${prefix} ${message}${defaultValue} ${formattedValue}`;\n});\n","import { createPrompt, useState, useKeypress, useEffect, usePrefix, isBackspaceKey, isEnterKey, isTabKey, makeTheme, } from '@inquirer/core';\nconst inputTheme = {\n validationFailureMode: 'keep',\n};\nexport default createPrompt((config, done) => {\n const { prefill = 'tab' } = config;\n const theme = makeTheme(inputTheme, config.theme);\n const [status, setStatus] = useState('idle');\n // Coerce to string to handle runtime values that may be numbers despite TypeScript types\n // oxlint-disable-next-line typescript/no-unnecessary-type-conversion\n const [defaultValue, setDefaultValue] = useState(String(config.default ?? ''));\n const [errorMsg, setError] = useState();\n const [value, setValue] = useState('');\n const prefix = usePrefix({ status, theme });\n async function validate(value) {\n const { required, pattern, patternError = 'Invalid input' } = config;\n if (required && !value) {\n return 'You must provide a value';\n }\n if (pattern && !pattern.test(value)) {\n return patternError;\n }\n if (typeof config.validate === 'function') {\n return (await config.validate(value)) || 'You must provide a valid value';\n }\n return true;\n }\n useKeypress(async (key, rl) => {\n // Ignore keypress while our prompt is doing other processing.\n if (status !== 'idle') {\n return;\n }\n if (isEnterKey(key)) {\n const answer = value || defaultValue;\n setStatus('loading');\n const isValid = await validate(answer);\n if (isValid === true) {\n setValue(answer);\n setStatus('done');\n done(answer);\n }\n else {\n if (theme.validationFailureMode === 'clear') {\n setValue('');\n }\n else {\n // Reset the readline line value to the previous value. On line event, the value\n // get cleared, forcing the user to re-enter the value instead of fixing it.\n rl.write(value);\n }\n setError(isValid);\n setStatus('idle');\n }\n }\n else if (isBackspaceKey(key) && !value) {\n setDefaultValue('');\n }\n else if (isTabKey(key) && !value) {\n setDefaultValue('');\n rl.clearLine(0); // Remove the tab character.\n rl.write(defaultValue);\n setValue(defaultValue);\n }\n else {\n setValue(rl.line);\n setError(undefined);\n }\n });\n // If prefill is set to 'editable' cut out the default value and paste into current state and the user's cli buffer\n // They can edit the value immediately instead of needing to press 'tab'\n useEffect((rl) => {\n if (prefill === 'editable' && defaultValue) {\n rl.write(defaultValue);\n setValue(defaultValue);\n }\n }, []);\n const message = theme.style.message(config.message, status);\n let formattedValue = value;\n if (typeof config.transformer === 'function') {\n formattedValue = config.transformer(value, { isFinal: status === 'done' });\n }\n else if (status === 'done') {\n formattedValue = theme.style.answer(value);\n }\n let defaultStr;\n if (defaultValue && status !== 'done' && !value) {\n defaultStr = theme.style.defaultAnswer(defaultValue);\n }\n let error = '';\n if (errorMsg) {\n error = theme.style.error(errorMsg);\n }\n return [\n [prefix, message, defaultStr, formattedValue]\n .filter((v) => v !== undefined)\n .join(' '),\n error,\n ];\n});\n","import { createPrompt, useState, useKeypress, usePrefix, isEnterKey, makeTheme, } from '@inquirer/core';\nimport { cursorHide } from '@inquirer/ansi';\nconst passwordTheme = {\n style: {\n maskedText: '[input is masked]',\n },\n};\nexport default createPrompt((config, done) => {\n const { validate = () => true } = config;\n const theme = makeTheme(passwordTheme, config.theme);\n const [status, setStatus] = useState('idle');\n const [errorMsg, setError] = useState();\n const [value, setValue] = useState('');\n const prefix = usePrefix({ status, theme });\n useKeypress(async (key, rl) => {\n // Ignore keypress while our prompt is doing other processing.\n if (status !== 'idle') {\n return;\n }\n if (isEnterKey(key)) {\n const answer = value;\n setStatus('loading');\n const isValid = await validate(answer);\n if (isValid === true) {\n setValue(answer);\n setStatus('done');\n done(answer);\n }\n else {\n // Reset the readline line value to the previous value. On line event, the value\n // get cleared, forcing the user to re-enter the value instead of fixing it.\n rl.write(value);\n setError(isValid || 'You must provide a valid value');\n setStatus('idle');\n }\n }\n else {\n setValue(rl.line);\n setError(undefined);\n }\n });\n const message = theme.style.message(config.message, status);\n let formattedValue = '';\n let helpTip;\n if (config.mask) {\n const maskChar = typeof config.mask === 'string' ? config.mask : '*';\n formattedValue = maskChar.repeat(value.length);\n }\n else if (status !== 'done') {\n helpTip = `${theme.style.help(theme.style.maskedText)}${cursorHide}`;\n }\n if (status === 'done') {\n formattedValue = theme.style.answer(formattedValue);\n }\n let error = '';\n if (errorMsg) {\n error = theme.style.error(errorMsg);\n }\n return [[prefix, message, config.mask ? formattedValue : helpTip].join(' '), error];\n});\n","import { createPrompt, useState, useKeypress, usePrefix, usePagination, useRef, useMemo, useEffect, isBackspaceKey, isEnterKey, isUpKey, isDownKey, isNumberKey, Separator, ValidationError, makeTheme, } from '@inquirer/core';\nimport { cursorHide } from '@inquirer/ansi';\nimport { styleText } from 'node:util';\nimport figures from '@inquirer/figures';\nconst selectTheme = {\n icon: { cursor: figures.pointer },\n style: {\n disabled: (text) => styleText('dim', text),\n description: (text) => styleText('cyan', text),\n keysHelpTip: (keys) => keys\n .map(([key, action]) => `${styleText('bold', key)} ${styleText('dim', action)}`)\n .join(styleText('dim', ' • ')),\n },\n i18n: { disabledError: 'This option is disabled and cannot be selected.' },\n indexMode: 'hidden',\n};\nfunction isSelectable(item) {\n return !Separator.isSeparator(item) && !item.disabled;\n}\nfunction isNavigable(item) {\n return !Separator.isSeparator(item);\n}\nfunction normalizeChoices(choices) {\n return choices.map((choice) => {\n if (Separator.isSeparator(choice))\n return choice;\n if (typeof choice !== 'object' || choice === null || !('value' in choice)) {\n // It's a raw value (string, number, etc.)\n const name = String(choice);\n return {\n value: choice,\n name,\n short: name,\n disabled: false,\n };\n }\n const name = choice.name ?? String(choice.value);\n const normalizedChoice = {\n value: choice.value,\n name,\n short: choice.short ?? name,\n disabled: choice.disabled ?? false,\n };\n if (choice.description) {\n normalizedChoice.description = choice.description;\n }\n return normalizedChoice;\n });\n}\nexport default createPrompt((config, done) => {\n const { loop = true, pageSize = 7 } = config;\n const theme = makeTheme(selectTheme, config.theme);\n const { keybindings } = theme;\n const [status, setStatus] = useState('idle');\n const prefix = usePrefix({ status, theme });\n const searchTimeoutRef = useRef();\n // Vim keybindings (j/k) conflict with typing those letters in search.\n const searchEnabled = !keybindings.includes('vim');\n const items = useMemo(() => normalizeChoices(config.choices), [config.choices]);\n const bounds = useMemo(() => {\n const first = items.findIndex(isNavigable);\n const last = items.findLastIndex(isNavigable);\n if (first === -1) {\n throw new ValidationError('[select prompt] No selectable choices. All choices are disabled.');\n }\n return { first, last };\n }, [items]);\n const defaultItemIndex = useMemo(() => {\n if (!('default' in config))\n return -1;\n return items.findIndex((item) => isSelectable(item) && item.value === config.default);\n }, [config.default, items]);\n const [active, setActive] = useState(defaultItemIndex === -1 ? bounds.first : defaultItemIndex);\n const selectedChoice = items[active];\n if (selectedChoice == null || Separator.isSeparator(selectedChoice)) {\n throw new Error('Active index does not point to a choice');\n }\n const [errorMsg, setError] = useState();\n useKeypress((key, rl) => {\n clearTimeout(searchTimeoutRef.current);\n if (errorMsg) {\n setError(undefined);\n }\n if (isEnterKey(key)) {\n if (selectedChoice.disabled) {\n setError(theme.i18n.disabledError);\n }\n else {\n setStatus('done');\n done(selectedChoice.value);\n }\n }\n else if (isUpKey(key, keybindings) || isDownKey(key, keybindings)) {\n rl.clearLine(0);\n if (loop ||\n (isUpKey(key, keybindings) && active !== bounds.first) ||\n (isDownKey(key, keybindings) && active !== bounds.last)) {\n const offset = isUpKey(key, keybindings) ? -1 : 1;\n let next = active;\n do {\n next = (next + offset + items.length) % items.length;\n } while (!isNavigable(items[next]));\n setActive(next);\n }\n }\n else if (isNumberKey(key) && !Number.isNaN(Number(rl.line))) {\n const selectedIndex = Number(rl.line) - 1;\n // Find the nth item (ignoring separators)\n let selectableIndex = -1;\n const position = items.findIndex((item) => {\n if (Separator.isSeparator(item))\n return false;\n selectableIndex++;\n return selectableIndex === selectedIndex;\n });\n const item = items[position];\n if (item != null && isSelectable(item)) {\n setActive(position);\n }\n searchTimeoutRef.current = setTimeout(() => {\n rl.clearLine(0);\n }, 700);\n }\n else if (isBackspaceKey(key)) {\n rl.clearLine(0);\n }\n else if (searchEnabled) {\n const searchTerm = rl.line.toLowerCase();\n const matchIndex = items.findIndex((item) => {\n if (Separator.isSeparator(item) || !isSelectable(item))\n return false;\n return item.name.toLowerCase().startsWith(searchTerm);\n });\n if (matchIndex !== -1) {\n setActive(matchIndex);\n }\n searchTimeoutRef.current = setTimeout(() => {\n rl.clearLine(0);\n }, 700);\n }\n });\n useEffect(() => () => {\n clearTimeout(searchTimeoutRef.current);\n }, []);\n const message = theme.style.message(config.message, status);\n const helpLine = theme.style.keysHelpTip([\n ['↑↓', 'navigate'],\n ['⏎', 'select'],\n ]);\n let separatorCount = 0;\n const page = usePagination({\n items,\n active,\n renderItem({ item, isActive, index }) {\n if (Separator.isSeparator(item)) {\n separatorCount++;\n return ` ${item.separator}`;\n }\n const cursor = isActive ? theme.icon.cursor : ' ';\n const indexLabel = theme.indexMode === 'number' ? `${index + 1 - separatorCount}. ` : '';\n if (item.disabled) {\n const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)';\n const disabledCursor = isActive ? theme.icon.cursor : '-';\n return theme.style.disabled(`${disabledCursor} ${indexLabel}${item.name} ${disabledLabel}`);\n }\n const color = isActive ? theme.style.highlight : (x) => x;\n return color(`${cursor} ${indexLabel}${item.name}`);\n },\n pageSize,\n loop,\n });\n if (status === 'done') {\n return [prefix, message, theme.style.answer(selectedChoice.short)]\n .filter(Boolean)\n .join(' ');\n }\n const { description } = selectedChoice;\n const lines = [\n [prefix, message].filter(Boolean).join(' '),\n page,\n ' ',\n description ? theme.style.description(description) : '',\n errorMsg ? theme.style.error(errorMsg) : '',\n helpLine,\n ]\n .filter(Boolean)\n .join('\\n')\n .trimEnd();\n return `${lines}${cursorHide}`;\n});\nexport { Separator } from '@inquirer/core';\n","{\n \"name\": \"@blotout/qinto-cli\",\n \"version\": \"0.1.0\",\n \"type\": \"module\",\n \"description\": \"Qinto CLI: authenticate against the Qinto platform and operate it from the terminal or from an agent.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/blotoutio/qinto.git\",\n \"directory\": \"projects/cli\"\n },\n \"engines\": {\n \"node\": \">=24\"\n },\n \"bin\": {\n \"qinto\": \"./bin/qinto.js\"\n },\n \"files\": [\n \"bin\",\n \"dist\",\n \"templates\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"scripts\": {\n \"build\": \"vite build\",\n \"prepack\": \"pnpm run build\",\n \"dev\": \"tsx src/index.ts\",\n \"generate:api\": \"tsx scripts/generate-api.ts\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\"\n },\n \"dependencies\": {\n \"@inquirer/prompts\": \"catalog:\",\n \"commander\": \"catalog:\",\n \"esbuild\": \"catalog:\",\n \"jsonc-parser\": \"catalog:\",\n \"miniflare\": \"catalog:\",\n \"open\": \"catalog:\",\n \"proper-lockfile\": \"catalog:\"\n },\n \"devDependencies\": {\n \"@qinto/app-build\": \"workspace:*\",\n \"@qinto/app-dev\": \"workspace:*\",\n \"@qinto/app-manifest\": \"workspace:*\",\n \"@qinto/oauth-grammar\": \"workspace:*\",\n \"@types/node\": \"catalog:\",\n \"@types/proper-lockfile\": \"catalog:\",\n \"@vitest/coverage-v8\": \"catalog:\",\n \"openapi-typescript\": \"catalog:\",\n \"tsx\": \"catalog:\",\n \"typescript\": \"catalog:\",\n \"vite\": \"catalog:\",\n \"vitest\": \"catalog:\"\n }\n}\n","export class CliError extends Error {}\n\nexport class CliUsageError extends CliError {}\n\nexport class ApiResponseError extends CliError {\n readonly status: number\n readonly code: string | null\n\n constructor(message: string, status: number, code: string | null) {\n super(message)\n this.status = status\n this.code = code\n }\n}\n\nexport class TokenEndpointError extends CliError {\n readonly code: string\n\n constructor(code: string, message: string) {\n super(message)\n this.code = code\n }\n}\n","import type { CommandSpec, EnvironmentSpec } from './command-spec'\n\nexport const MANIFEST_SCHEMA_VERSION = 2\n\ntype ArgumentDescriptor = Record<string, unknown>\n\nexport type Manifest = {\n schemaVersion: number\n commands: {\n path: readonly string[]\n description: string\n arguments: Record<string, ArgumentDescriptor>\n environment: EnvironmentSpec[]\n result?: Record<string, unknown>\n }[]\n}\n\nconst pruned = (descriptor: Record<string, unknown>): ArgumentDescriptor => {\n return Object.fromEntries(Object.entries(descriptor).filter(([, value]) => value !== undefined))\n}\n\nexport const flagName = (flag: string): string => {\n return String(flag.split(' ').at(0)).slice('--'.length)\n}\n\nexport const buildManifest = (commands: CommandSpec[]): Manifest => {\n return {\n schemaVersion: MANIFEST_SCHEMA_VERSION,\n commands: commands.map((command) => {\n return {\n path: command.path,\n description: command.description,\n environment: command.environment ?? [],\n ...(command.result === undefined ? {} : { result: command.result }),\n arguments: {\n ...Object.fromEntries(\n command.positionals.map((positional) => {\n return [\n positional.name,\n pruned({\n type: 'string',\n description: positional.description,\n required: positional.required ? true : undefined,\n positional: true,\n variadic: positional.variadic\n })\n ]\n })\n ),\n ...Object.fromEntries(\n command.options.map((option) => {\n return [\n flagName(option.flag),\n pruned({\n type: option.type,\n description: option.description,\n required: option.required,\n enum: option.enum,\n default: option.default,\n env: option.env\n })\n ]\n })\n )\n }\n }\n })\n }\n}\n","/** Reports an app build that failed, carrying a message safe to show the developer who ran it. */\nexport class AppBuildError extends Error {}\n","import { join } from 'node:path'\n\nimport type { AppManifest } from '@qinto/app-manifest'\nimport type { BuildOptions } from 'esbuild'\nimport { build } from 'esbuild'\n\nimport { AppBuildError } from './errors'\n\nexport type BuiltBundles = { server: string; browser: string | null }\n\nconst compile = async (label: string, options: BuildOptions): Promise<void> => {\n try {\n await build({ ...options, bundle: true, logLevel: 'silent' })\n } catch (error) {\n throw new AppBuildError(`The ${label} bundle failed to build: ${(error as Error).message}`)\n }\n}\n\nconst REGISTER_BANNER =\n '(function(d){var s=d.currentScript,g=(s&&s.dataset?s.dataset.qintoGlobal:void 0)||\"qinto\";var q=window[g];if(!q||!q._q){return;}var l=function(){'\n\nconst registerFooter = (slug: string): string => {\n return `var f=m.default&&m.default.__qintoBrowserApp?m.default.factory:null;return f;};(q._apps=q._apps||[]).push([${JSON.stringify(slug)},l]);})(document);`\n}\n\n/**\n * Builds an app's server bundle, and its browser bundle when the manifest declares one.\n * @param input The app directory, its manifest, and the directory the bundles are written to.\n * @returns The absolute path of each bundle; `browser` is `null` when the manifest declares no browser entry.\n * @throws {AppBuildError} when either entry point fails to bundle.\n */\nexport const buildBundles = async (input: { dir: string; manifest: AppManifest; outDir: string }): Promise<BuiltBundles> => {\n const server = join(input.outDir, 'server.js')\n await compile('server', {\n entryPoints: [join(input.dir, input.manifest.server.entry)],\n format: 'esm',\n platform: 'neutral',\n conditions: ['workerd'],\n external: ['cloudflare:*'],\n outfile: server,\n absWorkingDir: input.dir\n })\n\n // An app may declare `browser.capture` with no entry at all; it ships no browser code.\n const entry = input.manifest.browser?.entry\n if (entry === undefined) {\n return { server, browser: null }\n }\n\n const browser = join(input.outDir, 'browser.js')\n await compile('browser', {\n entryPoints: [join(input.dir, entry)],\n format: 'iife',\n globalName: 'm',\n target: 'es2022',\n minify: true,\n banner: { js: REGISTER_BANNER },\n footer: { js: registerFooter(input.manifest.slug) },\n outfile: browser,\n absWorkingDir: input.dir\n })\n return { server, browser }\n}\n","import { readdir } from 'node:fs/promises'\nimport { join, relative, sep } from 'node:path'\n\n/**\n * Lists every file under a directory, recursively.\n * @param root The directory to walk.\n * @returns Sorted paths relative to `root`, always with forward slashes.\n */\nexport const walkFiles = async (root: string): Promise<string[]> => {\n const entries = await readdir(root, { recursive: true, withFileTypes: true })\n return entries\n .filter((entry) => entry.isFile())\n .map((entry) => relative(root, join(entry.parentPath, entry.name)).split(sep).join('/'))\n .sort()\n}\n","import { readFile } from 'node:fs/promises'\nimport { basename, dirname, join } from 'node:path'\n\nimport type { AppManifest } from '@qinto/app-manifest'\nimport { Miniflare } from 'miniflare'\n\nimport { AppBuildError } from './errors'\n\nconst sortedJson = (value: unknown): string => {\n return Array.isArray(value) ? JSON.stringify([...value].sort()) : JSON.stringify(value)\n}\n\ntype ServerSurface = {\n hooks: Record<string, unknown> | null\n migrations: string[]\n schedules: string[]\n workflows: string[]\n ui: boolean\n}\n\nconst loadServerSurface = async (serverBundle: string): Promise<ServerSurface> => {\n const root = dirname(serverBundle)\n const validatorPath = join(root, '__qinto_hook_validator__.js')\n const validator = `import app from ${JSON.stringify(`./${basename(serverBundle)}`)};export default{fetch(){return Response.json({hooks:app?.__hooks??null,migrations:Object.keys(app?.migrations??{}),schedules:Object.keys(app?.schedules??{}),workflows:Object.keys(app?.workflows??{}),ui:typeof app?.ui==='function'})}}`\n try {\n const runtime = new Miniflare({\n workers: [\n {\n config: {\n type: 'worker',\n name: 'qinto-hook-validator',\n compatibilityDate: '2026-07-01',\n manifest: {\n mainModule: basename(validatorPath),\n modulesRoot: root,\n modules: {\n [basename(validatorPath)]: { type: 'esm', contents: validator },\n [basename(serverBundle)]: { type: 'esm', contents: await readFile(serverBundle, 'utf8') }\n }\n }\n }\n }\n ]\n })\n try {\n const response = await runtime.dispatchFetch('http://qinto-hook-validator.local')\n // `hooks` is whatever the developer's bundle exported, so it is checked; `workflows` is this\n // module's own `Object.keys`, so it is always an array of names.\n const surface = (await response.json()) as {\n hooks: unknown\n migrations: string[]\n schedules: string[]\n workflows: string[]\n ui: boolean\n }\n return {\n hooks: surface.hooks !== null && typeof surface.hooks === 'object' ? (surface.hooks as Record<string, unknown>) : null,\n migrations: surface.migrations,\n schedules: surface.schedules,\n workflows: surface.workflows,\n ui: surface.ui\n }\n } finally {\n await runtime.dispose()\n }\n } catch (error) {\n throw new AppBuildError(`The built server bundle could not be imported by Workerd: ${(error as Error).message}`)\n }\n}\n\n// A manifest class with no handler behind it fails at upload with an opaque Cloudflare error, and a\n// handler with no manifest resource is simply never reachable — both are worth catching here, and\n// the same holds for backfill handlers and schedules.\ntype RegisteredSurface = {\n // Names the error message: \"… do not match the manifest\".\n label: string\n noun: string\n // What a bundle-side extra is orphaned by, which differs from the noun for the two that hang off\n // a resource rather than their own manifest block.\n owner: string\n declared: (manifest: AppManifest) => string[]\n exported: (surface: ServerSurface) => string[]\n}\n\nconst REGISTERED_SURFACES: RegisteredSurface[] = [\n {\n label: 'migrations',\n noun: 'backfill handler',\n owner: 'manifest migration',\n declared: (manifest) => {\n return manifest.resources.flatMap((resource) => {\n return resource.type === 'd1'\n ? resource.migrations.flatMap((migration) => {\n return migration.phase === 'backfill' ? [migration.handler] : []\n })\n : []\n })\n },\n exported: (surface) => {\n return surface.migrations\n }\n },\n {\n label: 'schedules',\n noun: 'schedule',\n owner: 'manifest schedule',\n declared: (manifest) => {\n return (manifest.server.schedules ?? []).map((schedule) => schedule.id)\n },\n exported: (surface) => {\n return surface.schedules\n }\n },\n {\n label: 'workflows',\n noun: 'workflow',\n owner: 'manifest resource',\n declared: (manifest) => {\n return manifest.resources.flatMap((resource) => {\n return resource.type === 'workflow' ? [resource.className] : []\n })\n },\n exported: (surface) => {\n return surface.workflows\n }\n }\n]\n\nconst surfaceDifferences = (surface: RegisteredSurface, manifest: AppManifest, exported: string[]): string[] => {\n const declared = surface.declared(manifest)\n\n return [\n ...declared\n .filter((name) => !exported.includes(name))\n .map((name) => `the manifest declares ${surface.noun} ${name}, which the bundle does not register`),\n ...exported\n .filter((name) => !declared.includes(name))\n .map((name) => `the bundle registers ${surface.noun} ${name}, which no ${surface.owner} declares`)\n ]\n}\n\n// `onLifecycle` is optional on both sides, so an absent block and an empty list must compare equal.\nconst hookDifferences = (declared: AppManifest['server']['hooks'], exported: Record<string, unknown>): string[] => {\n const differences: string[] = []\n for (const key of ['transform', 'onEvent', 'onConnect', 'onLifecycle'] as const) {\n const manifestValue = key === 'onLifecycle' ? (declared[key] ?? []) : declared[key]\n const bundleValue = key === 'onLifecycle' ? (exported[key] ?? []) : exported[key]\n if (sortedJson(manifestValue) !== sortedJson(bundleValue)) {\n differences.push(`${key}: the manifest declares ${JSON.stringify(manifestValue)}, the bundle exports ${JSON.stringify(bundleValue)}`)\n }\n }\n\n return differences\n}\n\n/**\n * Runs the built server bundle in workerd and checks the hooks, migrations, schedules, and workflow classes it registers against the manifest.\n * @param input The manifest to check against and the absolute path of the built server bundle.\n * @returns Resolves when the bundle and the manifest agree.\n * @throws {AppBuildError} when the bundle cannot be imported, exports no `__hooks`, or disagrees with the manifest.\n */\nexport const validateServerHooks = async (input: { manifest: AppManifest; serverBundle: string }): Promise<void> => {\n const { hooks, migrations, schedules, workflows, ui } = await loadServerSurface(input.serverBundle)\n if (hooks === null) {\n throw new AppBuildError('The server bundle default export carries no __hooks metadata to validate against the manifest.')\n }\n\n const hookIssues = hookDifferences(input.manifest.server.hooks, hooks)\n if (hookIssues.length > 0) {\n throw new AppBuildError(`The built server bundle's __hooks do not match the manifest — ${hookIssues.join('; ')}.`)\n }\n\n for (const surface of REGISTERED_SURFACES) {\n const issues = surfaceDifferences(surface, input.manifest, surface.exported({ hooks, migrations, schedules, workflows, ui }))\n if (issues.length > 0) {\n throw new AppBuildError(`The built server bundle's ${surface.label} do not match the manifest — ${issues.join('; ')}.`)\n }\n }\n\n // A `ui` handler with no `ui` block is invalid everywhere: it 404s in `qinto app dev`, and on the\n // platform the panel iframe points at a bucket object the publish never uploaded. The converse — a\n // `ui` block with no handler — is legal: a panel that only renders its context is common.\n if (ui && input.manifest.ui === undefined) {\n throw new AppBuildError(\n 'The server bundle exports a ui handler, but the manifest declares no ui block. Add one, or remove the handler.'\n )\n }\n}\n","import { exec } from 'node:child_process'\nimport { existsSync } from 'node:fs'\nimport { readFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport { promisify } from 'node:util'\n\nimport type { AppManifest } from '@qinto/app-manifest'\n\nimport { AppBuildError } from './errors'\nimport { walkFiles } from './files'\n\nconst execAsync = promisify(exec)\n\nconst UI_ORIGIN = 'https://app-ui.invalid'\n\nclass AppUiReferenceError extends AppBuildError {\n constructor(input: { file: string; reference: string; resolved: string; basePath: string }) {\n super(`${input.file} references ${input.reference}, which resolves to ${input.resolved} outside the served prefix ${input.basePath}.`)\n }\n}\n\n/**\n * Runs the UI panel's own build command with the served base path injected, or does nothing when the manifest declares none.\n * @param input The app directory, the manifest's `ui` block, and the base path the panel is served under.\n * @returns Resolves once the build command exits successfully.\n * @throws {AppBuildError} when the build command fails.\n */\nexport const runUiBuild = async (input: { dir: string; ui: NonNullable<AppManifest['ui']>; basePath: string }): Promise<void> => {\n if (input.ui.build === undefined) {\n return\n }\n\n const command = /\\bastro\\b/.test(input.ui.build) ? `${input.ui.build} --base=${input.basePath}` : input.ui.build\n const cwd = dirname(resolve(input.dir, input.ui.dir))\n try {\n await execAsync(command, { cwd, env: { ...process.env, BASE_PATH: input.basePath } })\n } catch (error) {\n throw new AppBuildError(`The UI build failed: ${(error as Error).message}`)\n }\n}\n\nconst EXEMPT_REFERENCE = /^(?:(?:https?:)?\\/\\/|data:|mailto:|#)/i\nconst REFERENCE = /(?:src|href)\\s*=\\s*[\"']([^\"']+)[\"']/gi\n\n/**\n * Checks that every relative asset an HTML file references resolves under the base path it is served from.\n * @param input The file's path relative to the UI root, its markup, and the base path.\n * @returns Resolves when every reference stays inside the prefix; external and data references are exempt.\n * @throws {AppBuildError} naming the first reference that escapes the prefix.\n */\nexport const validateHtmlReferences = (input: { file: string; content: string; basePath: string }): void => {\n const fileUrl = new URL(input.file, `${UI_ORIGIN}${input.basePath}`)\n for (const match of input.content.matchAll(REFERENCE)) {\n const reference = match[1] as string\n if (EXEMPT_REFERENCE.test(reference)) {\n continue\n }\n\n const resolved = new URL(reference, fileUrl)\n if (resolved.origin !== UI_ORIGIN || !resolved.pathname.startsWith(input.basePath)) {\n throw new AppUiReferenceError({\n file: input.file,\n reference,\n resolved: resolved.origin === UI_ORIGIN ? resolved.pathname : resolved.href,\n basePath: input.basePath\n })\n }\n }\n}\n\n/**\n * Validates a built UI directory: it exists, has a root `index.html`, and no HTML file references an asset outside the base path.\n * @param input The built UI root and the base path it is served under.\n * @returns Every file under the root, as sorted relative paths.\n * @throws {AppBuildError} when the directory or its `index.html` is missing, or a reference escapes the prefix.\n */\nexport const validateUiAssets = async (input: { uiRoot: string; basePath: string }): Promise<string[]> => {\n if (!existsSync(input.uiRoot)) {\n throw new AppBuildError(`The UI directory ${input.uiRoot} does not exist. Check ui.dir in qinto.app.jsonc, or its build output.`)\n }\n\n const files = await walkFiles(input.uiRoot)\n if (!files.includes('index.html')) {\n throw new AppBuildError(`index.html is missing from the root of ${input.uiRoot}.`)\n }\n\n for (const file of files.filter((candidate) => candidate.endsWith('.html'))) {\n const content = await readFile(join(input.uiRoot, file), 'utf8')\n validateHtmlReferences({ file, content, basePath: input.basePath })\n }\n\n return files\n}\n","import { existsSync } from 'node:fs'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, join, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport { walkFiles } from '@qinto/app-build'\nimport { applyEdits, modify } from 'jsonc-parser'\n\nimport { CliError } from '../../../lib/errors'\n\nexport type ScaffoldValues = { slug: string; name: string }\n\nconst APP_SDK_PACKAGE = '@blotout/qinto-sdk-app'\nconst PUBLISHED_APP_SDK_RANGE = '^0.1.0'\n\nexport const templatesRoot = (from = dirname(fileURLToPath(import.meta.url))): string => {\n let directory = from\n while (!existsSync(join(directory, 'templates'))) {\n const parent = dirname(directory)\n if (parent === directory) {\n throw new CliError('The Qinto CLI templates are missing from this installation.')\n }\n\n directory = parent\n }\n\n return join(directory, 'templates')\n}\n\nexport const appSdkSpecifier = async (templates = templatesRoot()): Promise<string> => {\n const sibling = resolve(templates, '..', '..', 'app', 'sdk', 'package.json')\n if (!existsSync(sibling)) {\n return PUBLISHED_APP_SDK_RANGE\n }\n\n const parsed = JSON.parse(await readFile(sibling, 'utf8')) as { name?: string }\n return parsed.name === APP_SDK_PACKAGE ? 'workspace:*' : PUBLISHED_APP_SDK_RANGE\n}\n\nconst interpolate = (text: string, values: ScaffoldValues & { sdkSpecifier: string }): string => {\n const slug = JSON.stringify(values.slug).slice(1, -1)\n const name = JSON.stringify(values.name).slice(1, -1)\n return text.replaceAll('__APP_SLUG__', slug).replaceAll('__APP_NAME__', name).replaceAll('__APP_SDK_SPECIFIER__', values.sdkSpecifier)\n}\n\nexport const applyTemplate = async (input: { templateDir: string; targetDir: string; values: ScaffoldValues }): Promise<string[]> => {\n const files = await walkFiles(input.templateDir)\n const sdkSpecifier = await appSdkSpecifier()\n const written: string[] = []\n for (const file of files) {\n // npm drops a literal .gitignore from a package tarball, so the template ships it under a plain name.\n const name = file === 'gitignore' ? '.gitignore' : file\n const target = join(input.targetDir, name)\n await mkdir(dirname(target), { recursive: true })\n const text = await readFile(join(input.templateDir, file), 'utf8')\n await writeFile(target, interpolate(text, { ...input.values, sdkSpecifier }))\n written.push(name)\n }\n\n return written\n}\n\nexport const scaffoldUi = async (input: { dir: string; values: ScaffoldValues }): Promise<string[]> => {\n const files = await applyTemplate({ templateDir: join(templatesRoot(), 'ui'), targetDir: join(input.dir, 'ui'), values: input.values })\n return files.map((file) => `ui/${file}`)\n}\n\nexport const setManifestUi = async (manifestPath: string): Promise<void> => {\n const text = await readFile(manifestPath, 'utf8')\n const edits = modify(text, ['ui'], { dir: 'ui/dist', build: 'npm run build' }, { formattingOptions: { insertSpaces: true, tabSize: 2 } })\n await writeFile(manifestPath, applyEdits(text, edits))\n}\n","import { exec } from 'node:child_process'\nimport { promisify } from 'node:util'\n\nimport { appSdkSpecifier } from './scaffold'\n\nconst execAsync = promisify(exec)\n\nexport type InstallCommands = { root: string; ui: string }\n\nexport const scaffoldInstallCommands = async (templates?: string): Promise<InstallCommands> => {\n if ((await appSdkSpecifier(templates)) === 'workspace:*') {\n // ui/ matches no workspace glob, and a plain `pnpm install` there installs the workspace and skips it.\n return { root: 'pnpm install', ui: 'pnpm install --ignore-workspace' }\n }\n\n return { root: 'npm install', ui: 'npm install' }\n}\n\nexport const installDependencies = async (input: { dir: string; command: string }): Promise<boolean> => {\n try {\n await execAsync(input.command, { cwd: input.dir })\n return true\n } catch {\n return false\n }\n}\n","export const MAX_CRON_LENGTH = 128\n\nexport type CronFields = {\n minute: number\n hour: Set<number>\n dayOfMonth: Set<number>\n month: Set<number>\n dayOfWeek: Set<number>\n}\n\nconst MINUTE_LITERAL = /^([0-9]|[1-5][0-9])$/\n\nconst TERM = /^(\\*|\\d{1,2}(-\\d{1,2})?)(\\/\\d{1,2})?$/\n\nconst range = (min: number, max: number): number[] => {\n return Array.from({ length: max - min + 1 }, (_, index) => {\n return min + index\n })\n}\n\nconst parseTerm = (term: string, min: number, max: number): number[] | null => {\n const match = TERM.exec(term)\n if (match === null) {\n return null\n }\n\n const step = match[3] === undefined ? 1 : Number(match[3].slice(1))\n if (step < 1) {\n return null\n }\n\n const spec = match[1] as string\n const [first, last] = spec === '*' ? [min, max] : spec.split('-').map(Number)\n const from = first as number\n // `n/step` means \"from n through the field maximum, every step\" — a bare `n` is the single value.\n const to = last ?? (step === 1 ? from : max)\n if (from < min || to > max || from > to) {\n return null\n }\n\n return range(from, to).filter((value) => {\n return (value - from) % step === 0\n })\n}\n\nconst parseField = (field: string, min: number, max: number): Set<number> | null => {\n const values = new Set<number>()\n for (const term of field.split(',')) {\n const parsed = parseTerm(term, min, max)\n if (parsed === null) {\n return null\n }\n\n for (const value of parsed) {\n values.add(value)\n }\n }\n\n return values\n}\n\n/**\n * Parses one of Qinto's app schedule cron expressions into the value sets a due check matches against.\n * @param value The five-field expression, single-space separated: minute, hour, day of month, month, day of week (0 = Sunday).\n * @returns The parsed fields, or null when the expression is malformed, over `MAX_CRON_LENGTH`, has a non-literal minute, or restricts both day fields.\n */\nexport const parseCron = (value: string): CronFields | null => {\n if (value.length > MAX_CRON_LENGTH) {\n return null\n }\n\n const fields = value.split(' ')\n if (fields.length !== 5) {\n return null\n }\n\n const [minute, hour, dayOfMonth, month, dayOfWeek] = fields as [string, string, string, string, string]\n // A literal minute is what bounds a schedule to once an hour, and what lets a fixed sweep window\n // decide due-ness without storing a next-run time.\n if (!MINUTE_LITERAL.test(minute)) {\n return null\n }\n\n // POSIX ORs the two day fields when both are restricted. Matching that would make every call site\n // read as a bug, so the combination is refused and the sets below can be intersected.\n if (dayOfMonth !== '*' && dayOfWeek !== '*') {\n return null\n }\n\n const hours = parseField(hour, 0, 23)\n const daysOfMonth = parseField(dayOfMonth, 1, 31)\n const months = parseField(month, 1, 12)\n const daysOfWeek = parseField(dayOfWeek, 0, 6)\n if (hours === null || daysOfMonth === null || months === null || daysOfWeek === null) {\n return null\n }\n\n return { minute: Number(minute), hour: hours, dayOfMonth: daysOfMonth, month: months, dayOfWeek: daysOfWeek }\n}\n\nconst matches = (cron: CronFields, at: Date): boolean => {\n return (\n at.getUTCMinutes() === cron.minute &&\n cron.hour.has(at.getUTCHours()) &&\n cron.dayOfMonth.has(at.getUTCDate()) &&\n cron.month.has(at.getUTCMonth() + 1) &&\n cron.dayOfWeek.has(at.getUTCDay())\n )\n}\n\n/**\n * Finds the instant a schedule fires inside a dispatch window, evaluated in UTC.\n * @param cron The parsed expression.\n * @param windowStart The instant the window opens; the caller floors it to the window size.\n * @param windowMs The window's length in milliseconds.\n * @returns The matching instant, which is the run's nominal time, or null when the expression does not fire in this window.\n */\nexport const cronInstantInWindow = (cron: CronFields, windowStart: Date, windowMs: number): Date | null => {\n const minutes = Math.floor(windowMs / 60_000)\n for (let offset = 0; offset < minutes; offset += 1) {\n const at = new Date(windowStart.getTime() + offset * 60_000)\n if (matches(cron, at)) {\n return at\n }\n }\n\n return null\n}\n","const canonicalize = (value: unknown): unknown => {\n if (Array.isArray(value)) {\n return value.map(canonicalize)\n }\n\n if (value !== null && typeof value === 'object') {\n const entries = Object.entries(value as Record<string, unknown>)\n .sort(([left], [right]) => (left < right ? -1 : 1))\n .map(([key, entry]) => [key, canonicalize(entry)])\n return Object.fromEntries(entries)\n }\n\n return value\n}\n\n/**\n * Computes the canonical digest of a manifest document — key order does not affect it, so a jsonb round-trip digests identically.\n * @param manifest The manifest document (validated or raw).\n * @returns The lowercase hex SHA-256 of the canonical JSON serialization.\n */\nexport const appManifestDigest = async (manifest: unknown): Promise<string> => {\n const bytes = new TextEncoder().encode(JSON.stringify(canonicalize(manifest)))\n const digest = await crypto.subtle.digest('SHA-256', bytes)\n return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n","var _a;\n/** A special constant with type `never` */\nexport const NEVER = /*@__PURE__*/ Object.freeze({\n status: \"aborted\",\n});\nexport /*@__NO_SIDE_EFFECTS__*/ function $constructor(name, initializer, params) {\n function init(inst, def) {\n if (!inst._zod) {\n Object.defineProperty(inst, \"_zod\", {\n value: {\n def,\n constr: _,\n traits: new Set(),\n },\n enumerable: false,\n });\n }\n if (inst._zod.traits.has(name)) {\n return;\n }\n inst._zod.traits.add(name);\n initializer(inst, def);\n // support prototype modifications\n const proto = _.prototype;\n const keys = Object.keys(proto);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n if (!(k in inst)) {\n inst[k] = proto[k].bind(inst);\n }\n }\n }\n // doesn't work if Parent has a constructor with arguments\n const Parent = params?.Parent ?? Object;\n class Definition extends Parent {\n }\n Object.defineProperty(Definition, \"name\", { value: name });\n function _(def) {\n var _a;\n const inst = params?.Parent ? new Definition() : this;\n init(inst, def);\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n for (const fn of inst._zod.deferred) {\n fn();\n }\n return inst;\n }\n Object.defineProperty(_, \"init\", { value: init });\n Object.defineProperty(_, Symbol.hasInstance, {\n value: (inst) => {\n if (params?.Parent && inst instanceof params.Parent)\n return true;\n return inst?._zod?.traits?.has(name);\n },\n });\n Object.defineProperty(_, \"name\", { value: name });\n return _;\n}\n////////////////////////////// UTILITIES ///////////////////////////////////////\nexport const $brand = Symbol(\"zod_brand\");\nexport class $ZodAsyncError extends Error {\n constructor() {\n super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);\n }\n}\nexport class $ZodEncodeError extends Error {\n constructor(name) {\n super(`Encountered unidirectional transform during encode: ${name}`);\n this.name = \"ZodEncodeError\";\n }\n}\n(_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {});\nexport const globalConfig = globalThis.__zod_globalConfig;\nexport function config(newConfig) {\n if (newConfig)\n Object.assign(globalConfig, newConfig);\n return globalConfig;\n}\n","import { globalConfig } from \"./core.js\";\n// functions\nexport function assertEqual(val) {\n return val;\n}\nexport function assertNotEqual(val) {\n return val;\n}\nexport function assertIs(_arg) { }\nexport function assertNever(_x) {\n throw new Error(\"Unexpected value in exhaustive check\");\n}\nexport function assert(_) { }\nexport function getEnumValues(entries) {\n const numericValues = Object.values(entries).filter((v) => typeof v === \"number\");\n const values = Object.entries(entries)\n .filter(([k, _]) => numericValues.indexOf(+k) === -1)\n .map(([_, v]) => v);\n return values;\n}\nexport function joinValues(array, separator = \"|\") {\n return array.map((val) => stringifyPrimitive(val)).join(separator);\n}\nexport function jsonStringifyReplacer(_, value) {\n if (typeof value === \"bigint\")\n return value.toString();\n return value;\n}\nexport function cached(getter) {\n const set = false;\n return {\n get value() {\n if (!set) {\n const value = getter();\n Object.defineProperty(this, \"value\", { value });\n return value;\n }\n throw new Error(\"cached value already set\");\n },\n };\n}\nexport function nullish(input) {\n return input === null || input === undefined;\n}\nexport function cleanRegex(source) {\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n return source.slice(start, end);\n}\nexport function floatSafeRemainder(val, step) {\n const ratio = val / step;\n const roundedRatio = Math.round(ratio);\n // Use a relative epsilon scaled to the magnitude of the result\n const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);\n if (Math.abs(ratio - roundedRatio) < tolerance)\n return 0;\n return ratio - roundedRatio;\n}\nconst EVALUATING = /* @__PURE__*/ Symbol(\"evaluating\");\nexport function defineLazy(object, key, getter) {\n let value = undefined;\n Object.defineProperty(object, key, {\n get() {\n if (value === EVALUATING) {\n // Circular reference detected, return undefined to break the cycle\n return undefined;\n }\n if (value === undefined) {\n value = EVALUATING;\n value = getter();\n }\n return value;\n },\n set(v) {\n Object.defineProperty(object, key, {\n value: v,\n // configurable: true,\n });\n // object[key] = v;\n },\n configurable: true,\n });\n}\nexport function objectClone(obj) {\n return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));\n}\nexport function assignProp(target, prop, value) {\n Object.defineProperty(target, prop, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n}\nexport function mergeDefs(...defs) {\n const mergedDescriptors = {};\n for (const def of defs) {\n const descriptors = Object.getOwnPropertyDescriptors(def);\n Object.assign(mergedDescriptors, descriptors);\n }\n return Object.defineProperties({}, mergedDescriptors);\n}\nexport function cloneDef(schema) {\n return mergeDefs(schema._zod.def);\n}\nexport function getElementAtPath(obj, path) {\n if (!path)\n return obj;\n return path.reduce((acc, key) => acc?.[key], obj);\n}\nexport function promiseAllObject(promisesObj) {\n const keys = Object.keys(promisesObj);\n const promises = keys.map((key) => promisesObj[key]);\n return Promise.all(promises).then((results) => {\n const resolvedObj = {};\n for (let i = 0; i < keys.length; i++) {\n resolvedObj[keys[i]] = results[i];\n }\n return resolvedObj;\n });\n}\nexport function randomString(length = 10) {\n const chars = \"abcdefghijklmnopqrstuvwxyz\";\n let str = \"\";\n for (let i = 0; i < length; i++) {\n str += chars[Math.floor(Math.random() * chars.length)];\n }\n return str;\n}\nexport function esc(str) {\n return JSON.stringify(str);\n}\nexport function slugify(input) {\n return input\n .toLowerCase()\n .trim()\n .replace(/[^\\w\\s-]/g, \"\")\n .replace(/[\\s_-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\nexport const captureStackTrace = (\"captureStackTrace\" in Error ? Error.captureStackTrace : (..._args) => { });\nexport function isObject(data) {\n return typeof data === \"object\" && data !== null && !Array.isArray(data);\n}\nexport const allowsEval = /* @__PURE__*/ cached(() => {\n // Skip the probe under `jitless`: strict CSPs report the caught `new Function`\n // as a `securitypolicyviolation` even though the throw is swallowed.\n if (globalConfig.jitless) {\n return false;\n }\n // @ts-ignore\n if (typeof navigator !== \"undefined\" && navigator?.userAgent?.includes(\"Cloudflare\")) {\n return false;\n }\n try {\n const F = Function;\n new F(\"\");\n return true;\n }\n catch (_) {\n return false;\n }\n});\nexport function isPlainObject(o) {\n if (isObject(o) === false)\n return false;\n // modified constructor\n const ctor = o.constructor;\n if (ctor === undefined)\n return true;\n if (typeof ctor !== \"function\")\n return true;\n // modified prototype\n const prot = ctor.prototype;\n if (isObject(prot) === false)\n return false;\n // ctor doesn't have static `isPrototypeOf`\n if (Object.prototype.hasOwnProperty.call(prot, \"isPrototypeOf\") === false) {\n return false;\n }\n return true;\n}\nexport function shallowClone(o) {\n if (isPlainObject(o))\n return { ...o };\n if (Array.isArray(o))\n return [...o];\n if (o instanceof Map)\n return new Map(o);\n if (o instanceof Set)\n return new Set(o);\n return o;\n}\nexport function numKeys(data) {\n let keyCount = 0;\n for (const key in data) {\n if (Object.prototype.hasOwnProperty.call(data, key)) {\n keyCount++;\n }\n }\n return keyCount;\n}\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return \"undefined\";\n case \"string\":\n return \"string\";\n case \"number\":\n return Number.isNaN(data) ? \"nan\" : \"number\";\n case \"boolean\":\n return \"boolean\";\n case \"function\":\n return \"function\";\n case \"bigint\":\n return \"bigint\";\n case \"symbol\":\n return \"symbol\";\n case \"object\":\n if (Array.isArray(data)) {\n return \"array\";\n }\n if (data === null) {\n return \"null\";\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return \"promise\";\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return \"map\";\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return \"set\";\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return \"date\";\n }\n // @ts-ignore\n if (typeof File !== \"undefined\" && data instanceof File) {\n return \"file\";\n }\n return \"object\";\n default:\n throw new Error(`Unknown data type: ${t}`);\n }\n};\nexport const propertyKeyTypes = /* @__PURE__*/ new Set([\"string\", \"number\", \"symbol\"]);\nexport const primitiveTypes = /* @__PURE__*/ new Set([\n \"string\",\n \"number\",\n \"bigint\",\n \"boolean\",\n \"symbol\",\n \"undefined\",\n]);\nexport function escapeRegex(str) {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n// zod-specific utils\nexport function clone(inst, def, params) {\n const cl = new inst._zod.constr(def ?? inst._zod.def);\n if (!def || params?.parent)\n cl._zod.parent = inst;\n return cl;\n}\nexport function normalizeParams(_params) {\n const params = _params;\n if (!params)\n return {};\n if (typeof params === \"string\")\n return { error: () => params };\n if (params?.message !== undefined) {\n if (params?.error !== undefined)\n throw new Error(\"Cannot specify both `message` and `error` params\");\n params.error = params.message;\n }\n delete params.message;\n if (typeof params.error === \"string\")\n return { ...params, error: () => params.error };\n return params;\n}\nexport function createTransparentProxy(getter) {\n let target;\n return new Proxy({}, {\n get(_, prop, receiver) {\n target ?? (target = getter());\n return Reflect.get(target, prop, receiver);\n },\n set(_, prop, value, receiver) {\n target ?? (target = getter());\n return Reflect.set(target, prop, value, receiver);\n },\n has(_, prop) {\n target ?? (target = getter());\n return Reflect.has(target, prop);\n },\n deleteProperty(_, prop) {\n target ?? (target = getter());\n return Reflect.deleteProperty(target, prop);\n },\n ownKeys(_) {\n target ?? (target = getter());\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(_, prop) {\n target ?? (target = getter());\n return Reflect.getOwnPropertyDescriptor(target, prop);\n },\n defineProperty(_, prop, descriptor) {\n target ?? (target = getter());\n return Reflect.defineProperty(target, prop, descriptor);\n },\n });\n}\nexport function stringifyPrimitive(value) {\n if (typeof value === \"bigint\")\n return value.toString() + \"n\";\n if (typeof value === \"string\")\n return `\"${value}\"`;\n return `${value}`;\n}\nexport function optionalKeys(shape) {\n return Object.keys(shape).filter((k) => {\n return shape[k]._zod.optin === \"optional\" && shape[k]._zod.optout === \"optional\";\n });\n}\nexport const NUMBER_FORMAT_RANGES = {\n safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n int32: [-2147483648, 2147483647],\n uint32: [0, 4294967295],\n float32: [-3.4028234663852886e38, 3.4028234663852886e38],\n float64: [-Number.MAX_VALUE, Number.MAX_VALUE],\n};\nexport const BIGINT_FORMAT_RANGES = {\n int64: [/* @__PURE__*/ BigInt(\"-9223372036854775808\"), /* @__PURE__*/ BigInt(\"9223372036854775807\")],\n uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt(\"18446744073709551615\")],\n};\nexport function pick(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".pick() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = {};\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n newShape[key] = currDef.shape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function omit(schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".omit() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const newShape = { ...schema._zod.def.shape };\n for (const key in mask) {\n if (!(key in currDef.shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n delete newShape[key];\n }\n assignProp(this, \"shape\", newShape); // self-caching\n return newShape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function extend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to extend: expected a plain object\");\n }\n const checks = schema._zod.def.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n // Only throw if new shape overlaps with existing shape\n // Use getOwnPropertyDescriptor to check key existence without accessing values\n const existingShape = schema._zod.def.shape;\n for (const key in shape) {\n if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) {\n throw new Error(\"Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.\");\n }\n }\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function safeExtend(schema, shape) {\n if (!isPlainObject(shape)) {\n throw new Error(\"Invalid input to safeExtend: expected a plain object\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const _shape = { ...schema._zod.def.shape, ...shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n });\n return clone(schema, def);\n}\nexport function merge(a, b) {\n if (a._zod.def.checks?.length) {\n throw new Error(\".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.\");\n }\n const def = mergeDefs(a._zod.def, {\n get shape() {\n const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };\n assignProp(this, \"shape\", _shape); // self-caching\n return _shape;\n },\n get catchall() {\n return b._zod.def.catchall;\n },\n checks: b._zod.def.checks ?? [],\n });\n return clone(a, def);\n}\nexport function partial(Class, schema, mask) {\n const currDef = schema._zod.def;\n const checks = currDef.checks;\n const hasChecks = checks && checks.length > 0;\n if (hasChecks) {\n throw new Error(\".partial() cannot be used on object schemas containing refinements\");\n }\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in oldShape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n else {\n for (const key in oldShape) {\n // if (oldShape[key]!._zod.optin === \"optional\") continue;\n shape[key] = Class\n ? new Class({\n type: \"optional\",\n innerType: oldShape[key],\n })\n : oldShape[key];\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n checks: [],\n });\n return clone(schema, def);\n}\nexport function required(Class, schema, mask) {\n const def = mergeDefs(schema._zod.def, {\n get shape() {\n const oldShape = schema._zod.def.shape;\n const shape = { ...oldShape };\n if (mask) {\n for (const key in mask) {\n if (!(key in shape)) {\n throw new Error(`Unrecognized key: \"${key}\"`);\n }\n if (!mask[key])\n continue;\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n else {\n for (const key in oldShape) {\n // overwrite with non-optional\n shape[key] = new Class({\n type: \"nonoptional\",\n innerType: oldShape[key],\n });\n }\n }\n assignProp(this, \"shape\", shape); // self-caching\n return shape;\n },\n });\n return clone(schema, def);\n}\n// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom\nexport function aborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue !== true) {\n return true;\n }\n }\n return false;\n}\n// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined).\n// Used to respect `abort: true` in .refine() even for checks that have a `when` function.\nexport function explicitlyAborted(x, startIndex = 0) {\n if (x.aborted === true)\n return true;\n for (let i = startIndex; i < x.issues.length; i++) {\n if (x.issues[i]?.continue === false) {\n return true;\n }\n }\n return false;\n}\nexport function prefixIssues(path, issues) {\n return issues.map((iss) => {\n var _a;\n (_a = iss).path ?? (_a.path = []);\n iss.path.unshift(path);\n return iss;\n });\n}\nexport function unwrapMessage(message) {\n return typeof message === \"string\" ? message : message?.message;\n}\nexport function finalizeIssue(iss, ctx, config) {\n const message = iss.message\n ? iss.message\n : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ??\n unwrapMessage(ctx?.error?.(iss)) ??\n unwrapMessage(config.customError?.(iss)) ??\n unwrapMessage(config.localeError?.(iss)) ??\n \"Invalid input\");\n const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;\n rest.path ?? (rest.path = []);\n rest.message = message;\n if (ctx?.reportInput) {\n rest.input = _input;\n }\n return rest;\n}\nexport function getSizableOrigin(input) {\n if (input instanceof Set)\n return \"set\";\n if (input instanceof Map)\n return \"map\";\n // @ts-ignore\n if (input instanceof File)\n return \"file\";\n return \"unknown\";\n}\nexport function getLengthableOrigin(input) {\n if (Array.isArray(input))\n return \"array\";\n if (typeof input === \"string\")\n return \"string\";\n return \"unknown\";\n}\nexport function parsedType(data) {\n const t = typeof data;\n switch (t) {\n case \"number\": {\n return Number.isNaN(data) ? \"nan\" : \"number\";\n }\n case \"object\": {\n if (data === null) {\n return \"null\";\n }\n if (Array.isArray(data)) {\n return \"array\";\n }\n const obj = data;\n if (obj && Object.getPrototypeOf(obj) !== Object.prototype && \"constructor\" in obj && obj.constructor) {\n return obj.constructor.name;\n }\n }\n }\n return t;\n}\nexport function issue(...args) {\n const [iss, input, inst] = args;\n if (typeof iss === \"string\") {\n return {\n message: iss,\n code: \"custom\",\n input,\n inst,\n };\n }\n return { ...iss };\n}\nexport function cleanEnum(obj) {\n return Object.entries(obj)\n .filter(([k, _]) => {\n // return true if NaN, meaning it's not a number, thus a string key\n return Number.isNaN(Number.parseInt(k, 10));\n })\n .map((el) => el[1]);\n}\n// Codec utility functions\nexport function base64ToUint8Array(base64) {\n const binaryString = atob(base64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\nexport function uint8ArrayToBase64(bytes) {\n let binaryString = \"\";\n for (let i = 0; i < bytes.length; i++) {\n binaryString += String.fromCharCode(bytes[i]);\n }\n return btoa(binaryString);\n}\nexport function base64urlToUint8Array(base64url) {\n const base64 = base64url.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padding = \"=\".repeat((4 - (base64.length % 4)) % 4);\n return base64ToUint8Array(base64 + padding);\n}\nexport function uint8ArrayToBase64url(bytes) {\n return uint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=/g, \"\");\n}\nexport function hexToUint8Array(hex) {\n const cleanHex = hex.replace(/^0x/, \"\");\n if (cleanHex.length % 2 !== 0) {\n throw new Error(\"Invalid hex string length\");\n }\n const bytes = new Uint8Array(cleanHex.length / 2);\n for (let i = 0; i < cleanHex.length; i += 2) {\n bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);\n }\n return bytes;\n}\nexport function uint8ArrayToHex(bytes) {\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n// instanceof\nexport class Class {\n constructor(..._args) { }\n}\n","import { $constructor } from \"./core.js\";\nimport * as util from \"./util.js\";\nconst initializer = (inst, def) => {\n inst.name = \"$ZodError\";\n Object.defineProperty(inst, \"_zod\", {\n value: inst._zod,\n enumerable: false,\n });\n Object.defineProperty(inst, \"issues\", {\n value: def,\n enumerable: false,\n });\n inst.message = JSON.stringify(def, util.jsonStringifyReplacer, 2);\n Object.defineProperty(inst, \"toString\", {\n value: () => inst.message,\n enumerable: false,\n });\n};\nexport const $ZodError = $constructor(\"$ZodError\", initializer);\nexport const $ZodRealError = $constructor(\"$ZodError\", initializer, { Parent: Error });\nexport function flattenError(error, mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of error.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n}\nexport function formatError(error, mapper = (issue) => issue.message) {\n const fieldErrors = { _errors: [] };\n const processError = (error, path = []) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n }\n };\n processError(error);\n return fieldErrors;\n}\nexport function treeifyError(error, mapper = (issue) => issue.message) {\n const result = { errors: [] };\n const processError = (error, path = []) => {\n var _a, _b;\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\" && issue.errors.length) {\n // regular union error\n issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path]));\n }\n else if (issue.code === \"invalid_key\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else if (issue.code === \"invalid_element\") {\n processError({ issues: issue.issues }, [...path, ...issue.path]);\n }\n else {\n const fullpath = [...path, ...issue.path];\n if (fullpath.length === 0) {\n result.errors.push(mapper(issue));\n continue;\n }\n let curr = result;\n let i = 0;\n while (i < fullpath.length) {\n const el = fullpath[i];\n const terminal = i === fullpath.length - 1;\n if (typeof el === \"string\") {\n curr.properties ?? (curr.properties = {});\n (_a = curr.properties)[el] ?? (_a[el] = { errors: [] });\n curr = curr.properties[el];\n }\n else {\n curr.items ?? (curr.items = []);\n (_b = curr.items)[el] ?? (_b[el] = { errors: [] });\n curr = curr.items[el];\n }\n if (terminal) {\n curr.errors.push(mapper(issue));\n }\n i++;\n }\n }\n }\n };\n processError(error);\n return result;\n}\n/** Format a ZodError as a human-readable string in the following form.\n *\n * From\n *\n * ```ts\n * ZodError {\n * issues: [\n * {\n * expected: 'string',\n * code: 'invalid_type',\n * path: [ 'username' ],\n * message: 'Invalid input: expected string'\n * },\n * {\n * expected: 'number',\n * code: 'invalid_type',\n * path: [ 'favoriteNumbers', 1 ],\n * message: 'Invalid input: expected number'\n * }\n * ];\n * }\n * ```\n *\n * to\n *\n * ```\n * username\n * ✖ Expected number, received string at \"username\n * favoriteNumbers[0]\n * ✖ Invalid input: expected number\n * ```\n */\nexport function toDotPath(_path) {\n const segs = [];\n const path = _path.map((seg) => (typeof seg === \"object\" ? seg.key : seg));\n for (const seg of path) {\n if (typeof seg === \"number\")\n segs.push(`[${seg}]`);\n else if (typeof seg === \"symbol\")\n segs.push(`[${JSON.stringify(String(seg))}]`);\n else if (/[^\\w$]/.test(seg))\n segs.push(`[${JSON.stringify(seg)}]`);\n else {\n if (segs.length)\n segs.push(\".\");\n segs.push(seg);\n }\n }\n return segs.join(\"\");\n}\nexport function prettifyError(error) {\n const lines = [];\n // sort by path length\n const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length);\n // Process each issue\n for (const issue of issues) {\n lines.push(`✖ ${issue.message}`);\n if (issue.path?.length)\n lines.push(` → at ${toDotPath(issue.path)}`);\n }\n // Convert Map to formatted string\n return lines.join(\"\\n\");\n}\n","import * as core from \"./core.js\";\nimport * as errors from \"./errors.js\";\nimport * as util from \"./util.js\";\nexport const _parse = (_Err) => (schema, value, _ctx, _params) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n if (result.issues.length) {\n const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, _params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parse = /* @__PURE__*/ _parse(errors.$ZodRealError);\nexport const _parseAsync = (_Err) => async (schema, value, _ctx, params) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n if (result.issues.length) {\n const e = new (params?.Err ?? _Err)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())));\n util.captureStackTrace(e, params?.callee);\n throw e;\n }\n return result.value;\n};\nexport const parseAsync = /* @__PURE__*/ _parseAsync(errors.$ZodRealError);\nexport const _safeParse = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: false } : { async: false };\n const result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n return result.issues.length\n ? {\n success: false,\n error: new (_Err ?? errors.$ZodError)(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParse = /* @__PURE__*/ _safeParse(errors.$ZodRealError);\nexport const _safeParseAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, async: true } : { async: true };\n let result = schema._zod.run({ value, issues: [] }, ctx);\n if (result instanceof Promise)\n result = await result;\n return result.issues.length\n ? {\n success: false,\n error: new _Err(result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n }\n : { success: true, data: result.value };\n};\nexport const safeParseAsync = /* @__PURE__*/ _safeParseAsync(errors.$ZodRealError);\nexport const _encode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parse(_Err)(schema, value, ctx);\n};\nexport const encode = /* @__PURE__*/ _encode(errors.$ZodRealError);\nexport const _decode = (_Err) => (schema, value, _ctx) => {\n return _parse(_Err)(schema, value, _ctx);\n};\nexport const decode = /* @__PURE__*/ _decode(errors.$ZodRealError);\nexport const _encodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _parseAsync(_Err)(schema, value, ctx);\n};\nexport const encodeAsync = /* @__PURE__*/ _encodeAsync(errors.$ZodRealError);\nexport const _decodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _parseAsync(_Err)(schema, value, _ctx);\n};\nexport const decodeAsync = /* @__PURE__*/ _decodeAsync(errors.$ZodRealError);\nexport const _safeEncode = (_Err) => (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParse(_Err)(schema, value, ctx);\n};\nexport const safeEncode = /* @__PURE__*/ _safeEncode(errors.$ZodRealError);\nexport const _safeDecode = (_Err) => (schema, value, _ctx) => {\n return _safeParse(_Err)(schema, value, _ctx);\n};\nexport const safeDecode = /* @__PURE__*/ _safeDecode(errors.$ZodRealError);\nexport const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {\n const ctx = _ctx ? { ..._ctx, direction: \"backward\" } : { direction: \"backward\" };\n return _safeParseAsync(_Err)(schema, value, ctx);\n};\nexport const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync(errors.$ZodRealError);\nexport const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {\n return _safeParseAsync(_Err)(schema, value, _ctx);\n};\nexport const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync(errors.$ZodRealError);\n","import * as util from \"./util.js\";\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const cuid = /^[cC][0-9a-z]{6,}$/;\nexport const cuid2 = /^[0-9a-z]+$/;\nexport const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;\nexport const xid = /^[0-9a-vA-V]{20}$/;\nexport const ksuid = /^[A-Za-z0-9]{27}$/;\nexport const nanoid = /^[a-zA-Z0-9_-]{21}$/;\n/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */\nexport const duration = /^P(?:(\\d+W)|(?!.*W)(?=\\d|T\\d)(\\d+Y)?(\\d+M)?(\\d+D)?(T(?=\\d)(\\d+H)?(\\d+M)?(\\d+([.,]\\d+)?S)?)?)$/;\n/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */\nexport const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */\nexport const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;\n/** Returns a regex for validating an RFC 9562/4122 UUID.\n *\n * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */\nexport const uuid = (version) => {\n if (!version)\n return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;\n return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);\n};\nexport const uuid4 = /*@__PURE__*/ uuid(4);\nexport const uuid6 = /*@__PURE__*/ uuid(6);\nexport const uuid7 = /*@__PURE__*/ uuid(7);\n/** Practical email validation */\nexport const email = /^(?!\\.)(?!.*\\.\\.)([A-Za-z0-9_'+\\-\\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\\-]*\\.)+[A-Za-z]{2,}$/;\n/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */\nexport const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n/** The classic emailregex.com regex for RFC 5322-compliant emails */\nexport const rfc5322Email = /^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$/;\n/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */\nexport const unicodeEmail = /^[^\\s@\"]{1,64}@[^\\s@]{1,255}$/u;\nexport const idnEmail = unicodeEmail;\nexport const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emoji = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nexport function emoji() {\n return new RegExp(_emoji, \"u\");\n}\nexport const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nexport const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;\nexport const mac = (delimiter) => {\n const escapedDelim = util.escapeRegex(delimiter ?? \":\");\n return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);\n};\nexport const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/([0-9]|[1-2][0-9]|3[0-2])$/;\nexport const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nexport const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;\nexport const base64url = /^[A-Za-z0-9_-]*$/;\n// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address\n// export const hostname: RegExp = /^([a-zA-Z0-9-]+\\.)*[a-zA-Z0-9-]+$/;\nexport const hostname = /^(?=.{1,253}\\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\\.?$/;\nexport const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,}$/;\nexport const httpProtocol = /^https?$/;\n// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces)\n// E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15\nexport const e164 = /^\\+[1-9]\\d{6,14}$/;\n// const dateSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateSource = `(?:(?:\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\\\d|30)|(?:02)-(?:0[1-9]|1\\\\d|2[0-8])))`;\nexport const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`);\nfunction timeSource(args) {\n const hhmm = `(?:[01]\\\\d|2[0-3]):[0-5]\\\\d`;\n const regex = typeof args.precision === \"number\"\n ? args.precision === -1\n ? `${hhmm}`\n : args.precision === 0\n ? `${hhmm}:[0-5]\\\\d`\n : `${hhmm}:[0-5]\\\\d\\\\.\\\\d{${args.precision}}`\n : `${hhmm}(?::[0-5]\\\\d(?:\\\\.\\\\d+)?)?`;\n return regex;\n}\nexport function time(args) {\n return new RegExp(`^${timeSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetime(args) {\n const time = timeSource({ precision: args.precision });\n const opts = [\"Z\"];\n if (args.local)\n opts.push(\"\");\n // if (args.offset) opts.push(`([+-]\\\\d{2}:\\\\d{2})`);\n if (args.offset)\n opts.push(`([+-](?:[01]\\\\d|2[0-3]):[0-5]\\\\d)`);\n const timeRegex = `${time}(?:${opts.join(\"|\")})`;\n return new RegExp(`^${dateSource}T(?:${timeRegex})$`);\n}\nexport const string = (params) => {\n const regex = params ? `[\\\\s\\\\S]{${params?.minimum ?? 0},${params?.maximum ?? \"\"}}` : `[\\\\s\\\\S]*`;\n return new RegExp(`^${regex}$`);\n};\nexport const bigint = /^-?\\d+n?$/;\nexport const integer = /^-?\\d+$/;\nexport const number = /^-?\\d+(?:\\.\\d+)?$/;\nexport const boolean = /^(?:true|false)$/i;\nconst _null = /^null$/i;\nexport { _null as null };\nconst _undefined = /^undefined$/i;\nexport { _undefined as undefined };\n// regex for string with no uppercase letters\nexport const lowercase = /^[^A-Z]*$/;\n// regex for string with no lowercase letters\nexport const uppercase = /^[^a-z]*$/;\n// regex for hexadecimal strings (any length)\nexport const hex = /^[0-9a-fA-F]*$/;\n// Hash regexes for different algorithms and encodings\n// Helper function to create base64 regex with exact length and padding\nfunction fixedBase64(bodyLength, padding) {\n return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);\n}\n// Helper function to create base64url regex with exact length (no padding)\nfunction fixedBase64url(length) {\n return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);\n}\n// MD5 (16 bytes): base64 = 24 chars total (22 + \"==\")\nexport const md5_hex = /^[0-9a-fA-F]{32}$/;\nexport const md5_base64 = /*@__PURE__*/ fixedBase64(22, \"==\");\nexport const md5_base64url = /*@__PURE__*/ fixedBase64url(22);\n// SHA1 (20 bytes): base64 = 28 chars total (27 + \"=\")\nexport const sha1_hex = /^[0-9a-fA-F]{40}$/;\nexport const sha1_base64 = /*@__PURE__*/ fixedBase64(27, \"=\");\nexport const sha1_base64url = /*@__PURE__*/ fixedBase64url(27);\n// SHA256 (32 bytes): base64 = 44 chars total (43 + \"=\")\nexport const sha256_hex = /^[0-9a-fA-F]{64}$/;\nexport const sha256_base64 = /*@__PURE__*/ fixedBase64(43, \"=\");\nexport const sha256_base64url = /*@__PURE__*/ fixedBase64url(43);\n// SHA384 (48 bytes): base64 = 64 chars total (no padding)\nexport const sha384_hex = /^[0-9a-fA-F]{96}$/;\nexport const sha384_base64 = /*@__PURE__*/ fixedBase64(64, \"\");\nexport const sha384_base64url = /*@__PURE__*/ fixedBase64url(64);\n// SHA512 (64 bytes): base64 = 88 chars total (86 + \"==\")\nexport const sha512_hex = /^[0-9a-fA-F]{128}$/;\nexport const sha512_base64 = /*@__PURE__*/ fixedBase64(86, \"==\");\nexport const sha512_base64url = /*@__PURE__*/ fixedBase64url(86);\n","// import { $ZodType } from \"./schemas.js\";\nimport * as core from \"./core.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nexport const $ZodCheck = /*@__PURE__*/ core.$constructor(\"$ZodCheck\", (inst, def) => {\n var _a;\n inst._zod ?? (inst._zod = {});\n inst._zod.def = def;\n (_a = inst._zod).onattach ?? (_a.onattach = []);\n});\nconst numericOriginMap = {\n number: \"number\",\n bigint: \"bigint\",\n object: \"date\",\n};\nexport const $ZodCheckLessThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckLessThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY;\n if (def.value < curr) {\n if (def.inclusive)\n bag.maximum = def.value;\n else\n bag.exclusiveMaximum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckGreaterThan = /*@__PURE__*/ core.$constructor(\"$ZodCheckGreaterThan\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const origin = numericOriginMap[typeof def.value];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY;\n if (def.value > curr) {\n if (def.inclusive)\n bag.minimum = def.value;\n else\n bag.exclusiveMinimum = def.value;\n }\n });\n inst._zod.check = (payload) => {\n if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {\n return;\n }\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: typeof def.value === \"object\" ? def.value.getTime() : def.value,\n input: payload.value,\n inclusive: def.inclusive,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMultipleOf = \n/*@__PURE__*/ core.$constructor(\"$ZodCheckMultipleOf\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n var _a;\n (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value);\n });\n inst._zod.check = (payload) => {\n if (typeof payload.value !== typeof def.value)\n throw new Error(\"Cannot mix number and bigint in multiple_of check.\");\n const isMultiple = typeof payload.value === \"bigint\"\n ? payload.value % def.value === BigInt(0)\n : util.floatSafeRemainder(payload.value, def.value) === 0;\n if (isMultiple)\n return;\n payload.issues.push({\n origin: typeof payload.value,\n code: \"not_multiple_of\",\n divisor: def.value,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckNumberFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n def.format = def.format || \"float64\";\n const isInt = def.format?.includes(\"int\");\n const origin = isInt ? \"int\" : \"number\";\n const [minimum, maximum] = util.NUMBER_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n if (isInt)\n bag.pattern = regexes.integer;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (isInt) {\n if (!Number.isInteger(input)) {\n // invalid_format issue\n // payload.issues.push({\n // expected: def.format,\n // format: def.format,\n // code: \"invalid_format\",\n // input,\n // inst,\n // });\n // invalid_type issue\n payload.issues.push({\n expected: origin,\n format: def.format,\n code: \"invalid_type\",\n continue: false,\n input,\n inst,\n });\n return;\n // not_multiple_of issue\n // payload.issues.push({\n // code: \"not_multiple_of\",\n // origin: \"number\",\n // input,\n // inst,\n // divisor: 1,\n // });\n }\n if (!Number.isSafeInteger(input)) {\n if (input > 0) {\n // too_big\n payload.issues.push({\n input,\n code: \"too_big\",\n maximum: Number.MAX_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n else {\n // too_small\n payload.issues.push({\n input,\n code: \"too_small\",\n minimum: Number.MIN_SAFE_INTEGER,\n note: \"Integers must be within the safe integer range.\",\n inst,\n origin,\n inclusive: true,\n continue: !def.abort,\n });\n }\n return;\n }\n }\n if (input < minimum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_small\",\n minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"number\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckBigIntFormat\", (inst, def) => {\n $ZodCheck.init(inst, def); // no format checks\n const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format];\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n bag.minimum = minimum;\n bag.maximum = maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n if (input < minimum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_small\",\n minimum: minimum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n if (input > maximum) {\n payload.issues.push({\n origin: \"bigint\",\n input,\n code: \"too_big\",\n maximum,\n inclusive: true,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodCheckMaxSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size <= def.maximum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinSize = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinSize\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size >= def.minimum)\n return;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckSizeEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckSizeEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.size !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.size;\n bag.maximum = def.size;\n bag.size = def.size;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const size = input.size;\n if (size === def.size)\n return;\n const tooBig = size > def.size;\n payload.issues.push({\n origin: util.getSizableOrigin(input),\n ...(tooBig ? { code: \"too_big\", maximum: def.size } : { code: \"too_small\", minimum: def.size }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMaxLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMaxLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY);\n if (def.maximum < curr)\n inst._zod.bag.maximum = def.maximum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length <= def.maximum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_big\",\n maximum: def.maximum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckMinLength = /*@__PURE__*/ core.$constructor(\"$ZodCheckMinLength\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY);\n if (def.minimum > curr)\n inst._zod.bag.minimum = def.minimum;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length >= def.minimum)\n return;\n const origin = util.getLengthableOrigin(input);\n payload.issues.push({\n origin,\n code: \"too_small\",\n minimum: def.minimum,\n inclusive: true,\n input,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLengthEquals = /*@__PURE__*/ core.$constructor(\"$ZodCheckLengthEquals\", (inst, def) => {\n var _a;\n $ZodCheck.init(inst, def);\n (_a = inst._zod.def).when ?? (_a.when = (payload) => {\n const val = payload.value;\n return !util.nullish(val) && val.length !== undefined;\n });\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.minimum = def.length;\n bag.maximum = def.length;\n bag.length = def.length;\n });\n inst._zod.check = (payload) => {\n const input = payload.value;\n const length = input.length;\n if (length === def.length)\n return;\n const origin = util.getLengthableOrigin(input);\n const tooBig = length > def.length;\n payload.issues.push({\n origin,\n ...(tooBig ? { code: \"too_big\", maximum: def.length } : { code: \"too_small\", minimum: def.length }),\n inclusive: true,\n exact: true,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCheckStringFormat\", (inst, def) => {\n var _a, _b;\n $ZodCheck.init(inst, def);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.format = def.format;\n if (def.pattern) {\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(def.pattern);\n }\n });\n if (def.pattern)\n (_a = inst._zod).check ?? (_a.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n ...(def.pattern ? { pattern: def.pattern.toString() } : {}),\n inst,\n continue: !def.abort,\n });\n });\n else\n (_b = inst._zod).check ?? (_b.check = () => { });\n});\nexport const $ZodCheckRegex = /*@__PURE__*/ core.$constructor(\"$ZodCheckRegex\", (inst, def) => {\n $ZodCheckStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n def.pattern.lastIndex = 0;\n if (def.pattern.test(payload.value))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"regex\",\n input: payload.value,\n pattern: def.pattern.toString(),\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckLowerCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckLowerCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.lowercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckUpperCase = /*@__PURE__*/ core.$constructor(\"$ZodCheckUpperCase\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.uppercase);\n $ZodCheckStringFormat.init(inst, def);\n});\nexport const $ZodCheckIncludes = /*@__PURE__*/ core.$constructor(\"$ZodCheckIncludes\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const escapedRegex = util.escapeRegex(def.includes);\n const pattern = new RegExp(typeof def.position === \"number\" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);\n def.pattern = pattern;\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.includes(def.includes, def.position))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"includes\",\n includes: def.includes,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckStartsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckStartsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`^${util.escapeRegex(def.prefix)}.*`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.startsWith(def.prefix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"starts_with\",\n prefix: def.prefix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckEndsWith = /*@__PURE__*/ core.$constructor(\"$ZodCheckEndsWith\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const pattern = new RegExp(`.*${util.escapeRegex(def.suffix)}$`);\n def.pattern ?? (def.pattern = pattern);\n inst._zod.onattach.push((inst) => {\n const bag = inst._zod.bag;\n bag.patterns ?? (bag.patterns = new Set());\n bag.patterns.add(pattern);\n });\n inst._zod.check = (payload) => {\n if (payload.value.endsWith(def.suffix))\n return;\n payload.issues.push({\n origin: \"string\",\n code: \"invalid_format\",\n format: \"ends_with\",\n suffix: def.suffix,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n///////////////////////////////////\n///// $ZodCheckProperty /////\n///////////////////////////////////\nfunction handleCheckPropertyResult(result, payload, property) {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(property, result.issues));\n }\n}\nexport const $ZodCheckProperty = /*@__PURE__*/ core.$constructor(\"$ZodCheckProperty\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n const result = def.schema._zod.run({\n value: payload.value[def.property],\n issues: [],\n }, {});\n if (result instanceof Promise) {\n return result.then((result) => handleCheckPropertyResult(result, payload, def.property));\n }\n handleCheckPropertyResult(result, payload, def.property);\n return;\n };\n});\nexport const $ZodCheckMimeType = /*@__PURE__*/ core.$constructor(\"$ZodCheckMimeType\", (inst, def) => {\n $ZodCheck.init(inst, def);\n const mimeSet = new Set(def.mime);\n inst._zod.onattach.push((inst) => {\n inst._zod.bag.mime = def.mime;\n });\n inst._zod.check = (payload) => {\n if (mimeSet.has(payload.value.type))\n return;\n payload.issues.push({\n code: \"invalid_value\",\n values: def.mime,\n input: payload.value.type,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCheckOverwrite = /*@__PURE__*/ core.$constructor(\"$ZodCheckOverwrite\", (inst, def) => {\n $ZodCheck.init(inst, def);\n inst._zod.check = (payload) => {\n payload.value = def.tx(payload.value);\n };\n});\n","export class Doc {\n constructor(args = []) {\n this.content = [];\n this.indent = 0;\n if (this)\n this.args = args;\n }\n indented(fn) {\n this.indent += 1;\n fn(this);\n this.indent -= 1;\n }\n write(arg) {\n if (typeof arg === \"function\") {\n arg(this, { execution: \"sync\" });\n arg(this, { execution: \"async\" });\n return;\n }\n const content = arg;\n const lines = content.split(\"\\n\").filter((x) => x);\n const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));\n const dedented = lines.map((x) => x.slice(minIndent)).map((x) => \" \".repeat(this.indent * 2) + x);\n for (const line of dedented) {\n this.content.push(line);\n }\n }\n compile() {\n const F = Function;\n const args = this?.args;\n const content = this?.content ?? [``];\n const lines = [...content.map((x) => ` ${x}`)];\n // console.log(lines.join(\"\\n\"));\n return new F(...args, lines.join(\"\\n\"));\n }\n}\n","export const version = {\n major: 4,\n minor: 4,\n patch: 3,\n};\n","import * as checks from \"./checks.js\";\nimport * as core from \"./core.js\";\nimport { Doc } from \"./doc.js\";\nimport { parse, parseAsync, safeParse, safeParseAsync } from \"./parse.js\";\nimport * as regexes from \"./regexes.js\";\nimport * as util from \"./util.js\";\nimport { version } from \"./versions.js\";\nexport const $ZodType = /*@__PURE__*/ core.$constructor(\"$ZodType\", (inst, def) => {\n var _a;\n inst ?? (inst = {});\n inst._zod.def = def; // set _def property\n inst._zod.bag = inst._zod.bag || {}; // initialize _bag object\n inst._zod.version = version;\n const checks = [...(inst._zod.def.checks ?? [])];\n // if inst is itself a checks.$ZodCheck, run it as a check\n if (inst._zod.traits.has(\"$ZodCheck\")) {\n checks.unshift(inst);\n }\n for (const ch of checks) {\n for (const fn of ch._zod.onattach) {\n fn(inst);\n }\n }\n if (checks.length === 0) {\n // deferred initializer\n // inst._zod.parse is not yet defined\n (_a = inst._zod).deferred ?? (_a.deferred = []);\n inst._zod.deferred?.push(() => {\n inst._zod.run = inst._zod.parse;\n });\n }\n else {\n const runChecks = (payload, checks, ctx) => {\n let isAborted = util.aborted(payload);\n let asyncResult;\n for (const ch of checks) {\n if (ch._zod.def.when) {\n if (util.explicitlyAborted(payload))\n continue;\n const shouldRun = ch._zod.def.when(payload);\n if (!shouldRun)\n continue;\n }\n else if (isAborted) {\n continue;\n }\n const currLen = payload.issues.length;\n const _ = ch._zod.check(payload);\n if (_ instanceof Promise && ctx?.async === false) {\n throw new core.$ZodAsyncError();\n }\n if (asyncResult || _ instanceof Promise) {\n asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {\n await _;\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n return;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n });\n }\n else {\n const nextLen = payload.issues.length;\n if (nextLen === currLen)\n continue;\n if (!isAborted)\n isAborted = util.aborted(payload, currLen);\n }\n }\n if (asyncResult) {\n return asyncResult.then(() => {\n return payload;\n });\n }\n return payload;\n };\n const handleCanaryResult = (canary, payload, ctx) => {\n // abort if the canary is aborted\n if (util.aborted(canary)) {\n canary.aborted = true;\n return canary;\n }\n // run checks first, then\n const checkResult = runChecks(payload, checks, ctx);\n if (checkResult instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx));\n }\n return inst._zod.parse(checkResult, ctx);\n };\n inst._zod.run = (payload, ctx) => {\n if (ctx.skipChecks) {\n return inst._zod.parse(payload, ctx);\n }\n if (ctx.direction === \"backward\") {\n // run canary\n // initial pass (no checks)\n const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });\n if (canary instanceof Promise) {\n return canary.then((canary) => {\n return handleCanaryResult(canary, payload, ctx);\n });\n }\n return handleCanaryResult(canary, payload, ctx);\n }\n // forward\n const result = inst._zod.parse(payload, ctx);\n if (result instanceof Promise) {\n if (ctx.async === false)\n throw new core.$ZodAsyncError();\n return result.then((result) => runChecks(result, checks, ctx));\n }\n return runChecks(result, checks, ctx);\n };\n }\n // Lazy initialize ~standard to avoid creating objects for every schema\n util.defineLazy(inst, \"~standard\", () => ({\n validate: (value) => {\n try {\n const r = safeParse(inst, value);\n return r.success ? { value: r.data } : { issues: r.error?.issues };\n }\n catch (_) {\n return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues }));\n }\n },\n vendor: \"zod\",\n version: 1,\n }));\n});\nexport { clone } from \"./util.js\";\nexport const $ZodString = /*@__PURE__*/ core.$constructor(\"$ZodString\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes.string(inst._zod.bag);\n inst._zod.parse = (payload, _) => {\n if (def.coerce)\n try {\n payload.value = String(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"string\")\n return payload;\n payload.issues.push({\n expected: \"string\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodStringFormat\", (inst, def) => {\n // check initialization must come first\n checks.$ZodCheckStringFormat.init(inst, def);\n $ZodString.init(inst, def);\n});\nexport const $ZodGUID = /*@__PURE__*/ core.$constructor(\"$ZodGUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.guid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodUUID = /*@__PURE__*/ core.$constructor(\"$ZodUUID\", (inst, def) => {\n if (def.version) {\n const versionMap = {\n v1: 1,\n v2: 2,\n v3: 3,\n v4: 4,\n v5: 5,\n v6: 6,\n v7: 7,\n v8: 8,\n };\n const v = versionMap[def.version];\n if (v === undefined)\n throw new Error(`Invalid UUID version: \"${def.version}\"`);\n def.pattern ?? (def.pattern = regexes.uuid(v));\n }\n else\n def.pattern ?? (def.pattern = regexes.uuid());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodEmail = /*@__PURE__*/ core.$constructor(\"$ZodEmail\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.email);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodURL = /*@__PURE__*/ core.$constructor(\"$ZodURL\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n try {\n // Trim whitespace from input\n const trimmed = payload.value.trim();\n // When normalize is off, require :// for http/https URLs\n // This prevents strings like \"http:example.com\" or \"https:/path\" from being silently accepted\n if (!def.normalize && def.protocol?.source === regexes.httpProtocol.source) {\n if (!/^https?:\\/\\//i.test(trimmed)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid URL format\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n return;\n }\n }\n // @ts-ignore\n const url = new URL(trimmed);\n if (def.hostname) {\n def.hostname.lastIndex = 0;\n if (!def.hostname.test(url.hostname)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid hostname\",\n pattern: def.hostname.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n if (def.protocol) {\n def.protocol.lastIndex = 0;\n if (!def.protocol.test(url.protocol.endsWith(\":\") ? url.protocol.slice(0, -1) : url.protocol)) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n note: \"Invalid protocol\",\n pattern: def.protocol.source,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n }\n // Set the output value based on normalize flag\n if (def.normalize) {\n // Use normalized URL\n payload.value = url.href;\n }\n else {\n // Preserve the original input (trimmed)\n payload.value = trimmed;\n }\n return;\n }\n catch (_) {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodEmoji = /*@__PURE__*/ core.$constructor(\"$ZodEmoji\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.emoji());\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodNanoID = /*@__PURE__*/ core.$constructor(\"$ZodNanoID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.nanoid);\n $ZodStringFormat.init(inst, def);\n});\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link $ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const $ZodCUID = /*@__PURE__*/ core.$constructor(\"$ZodCUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCUID2 = /*@__PURE__*/ core.$constructor(\"$ZodCUID2\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cuid2);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodULID = /*@__PURE__*/ core.$constructor(\"$ZodULID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ulid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodXID = /*@__PURE__*/ core.$constructor(\"$ZodXID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.xid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodKSUID = /*@__PURE__*/ core.$constructor(\"$ZodKSUID\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ksuid);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODateTime = /*@__PURE__*/ core.$constructor(\"$ZodISODateTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.datetime(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODate = /*@__PURE__*/ core.$constructor(\"$ZodISODate\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.date);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISOTime = /*@__PURE__*/ core.$constructor(\"$ZodISOTime\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.time(def));\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodISODuration = /*@__PURE__*/ core.$constructor(\"$ZodISODuration\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.duration);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodIPv4 = /*@__PURE__*/ core.$constructor(\"$ZodIPv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv4);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv4`;\n});\nexport const $ZodIPv6 = /*@__PURE__*/ core.$constructor(\"$ZodIPv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.ipv6);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `ipv6`;\n inst._zod.check = (payload) => {\n try {\n // @ts-ignore\n new URL(`http://[${payload.value}]`);\n // return;\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"ipv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\nexport const $ZodMAC = /*@__PURE__*/ core.$constructor(\"$ZodMAC\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.mac(def.delimiter));\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.format = `mac`;\n});\nexport const $ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv4\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv4);\n $ZodStringFormat.init(inst, def);\n});\nexport const $ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"$ZodCIDRv6\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.cidrv6); // not used for validation\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n const parts = payload.value.split(\"/\");\n try {\n if (parts.length !== 2)\n throw new Error();\n const [address, prefix] = parts;\n if (!prefix)\n throw new Error();\n const prefixNum = Number(prefix);\n if (`${prefixNum}` !== prefix)\n throw new Error();\n if (prefixNum < 0 || prefixNum > 128)\n throw new Error();\n // @ts-ignore\n new URL(`http://[${address}]`);\n }\n catch {\n payload.issues.push({\n code: \"invalid_format\",\n format: \"cidrv6\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n }\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64(data) {\n if (data === \"\")\n return true;\n // atob ignores whitespace, so reject it up front.\n if (/\\s/.test(data))\n return false;\n if (data.length % 4 !== 0)\n return false;\n try {\n // @ts-ignore\n atob(data);\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodBase64 = /*@__PURE__*/ core.$constructor(\"$ZodBase64\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64\";\n inst._zod.check = (payload) => {\n if (isValidBase64(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\n////////////////////////////// ZodBase64 //////////////////////////////\nexport function isValidBase64URL(data) {\n if (!regexes.base64url.test(data))\n return false;\n const base64 = data.replace(/[-_]/g, (c) => (c === \"-\" ? \"+\" : \"/\"));\n const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, \"=\");\n return isValidBase64(padded);\n}\nexport const $ZodBase64URL = /*@__PURE__*/ core.$constructor(\"$ZodBase64URL\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.base64url);\n $ZodStringFormat.init(inst, def);\n inst._zod.bag.contentEncoding = \"base64url\";\n inst._zod.check = (payload) => {\n if (isValidBase64URL(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"base64url\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodE164 = /*@__PURE__*/ core.$constructor(\"$ZodE164\", (inst, def) => {\n def.pattern ?? (def.pattern = regexes.e164);\n $ZodStringFormat.init(inst, def);\n});\n////////////////////////////// ZodJWT //////////////////////////////\nexport function isValidJWT(token, algorithm = null) {\n try {\n const tokensParts = token.split(\".\");\n if (tokensParts.length !== 3)\n return false;\n const [header] = tokensParts;\n if (!header)\n return false;\n // @ts-ignore\n const parsedHeader = JSON.parse(atob(header));\n if (\"typ\" in parsedHeader && parsedHeader?.typ !== \"JWT\")\n return false;\n if (!parsedHeader.alg)\n return false;\n if (algorithm && (!(\"alg\" in parsedHeader) || parsedHeader.alg !== algorithm))\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nexport const $ZodJWT = /*@__PURE__*/ core.$constructor(\"$ZodJWT\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (isValidJWT(payload.value, def.alg))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: \"jwt\",\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"$ZodCustomStringFormat\", (inst, def) => {\n $ZodStringFormat.init(inst, def);\n inst._zod.check = (payload) => {\n if (def.fn(payload.value))\n return;\n payload.issues.push({\n code: \"invalid_format\",\n format: def.format,\n input: payload.value,\n inst,\n continue: !def.abort,\n });\n };\n});\nexport const $ZodNumber = /*@__PURE__*/ core.$constructor(\"$ZodNumber\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = inst._zod.bag.pattern ?? regexes.number;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Number(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"number\" && !Number.isNaN(input) && Number.isFinite(input)) {\n return payload;\n }\n const received = typeof input === \"number\"\n ? Number.isNaN(input)\n ? \"NaN\"\n : !Number.isFinite(input)\n ? \"Infinity\"\n : undefined\n : undefined;\n payload.issues.push({\n expected: \"number\",\n code: \"invalid_type\",\n input,\n inst,\n ...(received ? { received } : {}),\n });\n return payload;\n };\n});\nexport const $ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"$ZodNumberFormat\", (inst, def) => {\n checks.$ZodCheckNumberFormat.init(inst, def);\n $ZodNumber.init(inst, def); // no format checks\n});\nexport const $ZodBoolean = /*@__PURE__*/ core.$constructor(\"$ZodBoolean\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.boolean;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = Boolean(payload.value);\n }\n catch (_) { }\n const input = payload.value;\n if (typeof input === \"boolean\")\n return payload;\n payload.issues.push({\n expected: \"boolean\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigInt = /*@__PURE__*/ core.$constructor(\"$ZodBigInt\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.bigint;\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce)\n try {\n payload.value = BigInt(payload.value);\n }\n catch (_) { }\n if (typeof payload.value === \"bigint\")\n return payload;\n payload.issues.push({\n expected: \"bigint\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"$ZodBigIntFormat\", (inst, def) => {\n checks.$ZodCheckBigIntFormat.init(inst, def);\n $ZodBigInt.init(inst, def); // no format checks\n});\nexport const $ZodSymbol = /*@__PURE__*/ core.$constructor(\"$ZodSymbol\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"symbol\")\n return payload;\n payload.issues.push({\n expected: \"symbol\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodUndefined = /*@__PURE__*/ core.$constructor(\"$ZodUndefined\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.undefined;\n inst._zod.values = new Set([undefined]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"undefined\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodNull = /*@__PURE__*/ core.$constructor(\"$ZodNull\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.pattern = regexes.null;\n inst._zod.values = new Set([null]);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (input === null)\n return payload;\n payload.issues.push({\n expected: \"null\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodAny = /*@__PURE__*/ core.$constructor(\"$ZodAny\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodUnknown = /*@__PURE__*/ core.$constructor(\"$ZodUnknown\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload) => payload;\n});\nexport const $ZodNever = /*@__PURE__*/ core.$constructor(\"$ZodNever\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n payload.issues.push({\n expected: \"never\",\n code: \"invalid_type\",\n input: payload.value,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodVoid = /*@__PURE__*/ core.$constructor(\"$ZodVoid\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (typeof input === \"undefined\")\n return payload;\n payload.issues.push({\n expected: \"void\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodDate = /*@__PURE__*/ core.$constructor(\"$ZodDate\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (def.coerce) {\n try {\n payload.value = new Date(payload.value);\n }\n catch (_err) { }\n }\n const input = payload.value;\n const isDate = input instanceof Date;\n const isValidDate = isDate && !Number.isNaN(input.getTime());\n if (isValidDate)\n return payload;\n payload.issues.push({\n expected: \"date\",\n code: \"invalid_type\",\n input,\n ...(isDate ? { received: \"Invalid Date\" } : {}),\n inst,\n });\n return payload;\n };\n});\nfunction handleArrayResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nexport const $ZodArray = /*@__PURE__*/ core.$constructor(\"$ZodArray\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n expected: \"array\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = Array(input.length);\n const proms = [];\n for (let i = 0; i < input.length; i++) {\n const item = input[i];\n const result = def.element._zod.run({\n value: item,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleArrayResult(result, payload, i)));\n }\n else {\n handleArrayResult(result, payload, i);\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload; //handleArrayResultsAsync(parseResults, final);\n };\n});\nfunction handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {\n const isPresent = key in input;\n if (result.issues.length) {\n // For optional-in/out schemas, ignore errors on absent keys.\n if (isOptionalIn && isOptionalOut && !isPresent) {\n return;\n }\n final.issues.push(...util.prefixIssues(key, result.issues));\n }\n if (!isPresent && !isOptionalIn) {\n if (!result.issues.length) {\n final.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [key],\n });\n }\n return;\n }\n if (result.value === undefined) {\n if (isPresent) {\n final.value[key] = undefined;\n }\n }\n else {\n final.value[key] = result.value;\n }\n}\nfunction normalizeDef(def) {\n const keys = Object.keys(def.shape);\n for (const k of keys) {\n if (!def.shape?.[k]?._zod?.traits?.has(\"$ZodType\")) {\n throw new Error(`Invalid element at key \"${k}\": expected a Zod schema`);\n }\n }\n const okeys = util.optionalKeys(def.shape);\n return {\n ...def,\n keys,\n keySet: new Set(keys),\n numKeys: keys.length,\n optionalKeys: new Set(okeys),\n };\n}\nfunction handleCatchall(proms, input, payload, ctx, def, inst) {\n const unrecognized = [];\n const keySet = def.keySet;\n const _catchall = def.catchall._zod;\n const t = _catchall.def.type;\n const isOptionalIn = _catchall.optin === \"optional\";\n const isOptionalOut = _catchall.optout === \"optional\";\n for (const key in input) {\n // skip __proto__ so it can't replace the result prototype via the\n // assignment setter on the plain {} we build into\n if (key === \"__proto__\")\n continue;\n if (keySet.has(key))\n continue;\n if (t === \"never\") {\n unrecognized.push(key);\n continue;\n }\n const r = _catchall.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (unrecognized.length) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n keys: unrecognized,\n input,\n inst,\n });\n }\n if (!proms.length)\n return payload;\n return Promise.all(proms).then(() => {\n return payload;\n });\n}\nexport const $ZodObject = /*@__PURE__*/ core.$constructor(\"$ZodObject\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodType.init(inst, def);\n // const sh = def.shape;\n const desc = Object.getOwnPropertyDescriptor(def, \"shape\");\n if (!desc?.get) {\n const sh = def.shape;\n Object.defineProperty(def, \"shape\", {\n get: () => {\n const newSh = { ...sh };\n Object.defineProperty(def, \"shape\", {\n value: newSh,\n });\n return newSh;\n },\n });\n }\n const _normalized = util.cached(() => normalizeDef(def));\n util.defineLazy(inst._zod, \"propValues\", () => {\n const shape = def.shape;\n const propValues = {};\n for (const key in shape) {\n const field = shape[key]._zod;\n if (field.values) {\n propValues[key] ?? (propValues[key] = new Set());\n for (const v of field.values)\n propValues[key].add(v);\n }\n }\n return propValues;\n });\n const isObject = util.isObject;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n payload.value = {};\n const proms = [];\n const shape = value.shape;\n for (const key of value.keys) {\n const el = shape[key];\n const isOptionalIn = el._zod.optin === \"optional\";\n const isOptionalOut = el._zod.optout === \"optional\";\n const r = el._zod.run({ value: input[key], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut)));\n }\n else {\n handlePropertyResult(r, payload, key, input, isOptionalIn, isOptionalOut);\n }\n }\n if (!catchall) {\n return proms.length ? Promise.all(proms).then(() => payload) : payload;\n }\n return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);\n };\n});\nexport const $ZodObjectJIT = /*@__PURE__*/ core.$constructor(\"$ZodObjectJIT\", (inst, def) => {\n // requires cast because technically $ZodObject doesn't extend\n $ZodObject.init(inst, def);\n const superParse = inst._zod.parse;\n const _normalized = util.cached(() => normalizeDef(def));\n const generateFastpass = (shape) => {\n const doc = new Doc([\"shape\", \"payload\", \"ctx\"]);\n const normalized = _normalized.value;\n const parseStr = (key) => {\n const k = util.esc(key);\n return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`;\n };\n doc.write(`const input = payload.value;`);\n const ids = Object.create(null);\n let counter = 0;\n for (const key of normalized.keys) {\n ids[key] = `key_${counter++}`;\n }\n // A: preserve key order {\n doc.write(`const newResult = {};`);\n for (const key of normalized.keys) {\n const id = ids[key];\n const k = util.esc(key);\n const schema = shape[key];\n const isOptionalIn = schema?._zod?.optin === \"optional\";\n const isOptionalOut = schema?._zod?.optout === \"optional\";\n doc.write(`const ${id} = ${parseStr(key)};`);\n if (isOptionalIn && isOptionalOut) {\n // For optional-in/out schemas, ignore errors on absent keys\n doc.write(`\n if (${id}.issues.length) {\n if (${k} in input) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n else if (!isOptionalIn) {\n doc.write(`\n const ${id}_present = ${k} in input;\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n if (!${id}_present && !${id}.issues.length) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: undefined,\n path: [${k}]\n });\n }\n\n if (${id}_present) {\n if (${id}.value === undefined) {\n newResult[${k}] = undefined;\n } else {\n newResult[${k}] = ${id}.value;\n }\n }\n\n `);\n }\n else {\n doc.write(`\n if (${id}.issues.length) {\n payload.issues = payload.issues.concat(${id}.issues.map(iss => ({\n ...iss,\n path: iss.path ? [${k}, ...iss.path] : [${k}]\n })));\n }\n \n if (${id}.value === undefined) {\n if (${k} in input) {\n newResult[${k}] = undefined;\n }\n } else {\n newResult[${k}] = ${id}.value;\n }\n \n `);\n }\n }\n doc.write(`payload.value = newResult;`);\n doc.write(`return payload;`);\n const fn = doc.compile();\n return (payload, ctx) => fn(shape, payload, ctx);\n };\n let fastpass;\n const isObject = util.isObject;\n const jit = !core.globalConfig.jitless;\n const allowsEval = util.allowsEval;\n const fastEnabled = jit && allowsEval.value; // && !def.catchall;\n const catchall = def.catchall;\n let value;\n inst._zod.parse = (payload, ctx) => {\n value ?? (value = _normalized.value);\n const input = payload.value;\n if (!isObject(input)) {\n payload.issues.push({\n expected: \"object\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) {\n // always synchronous\n if (!fastpass)\n fastpass = generateFastpass(def.shape);\n payload = fastpass(payload, ctx);\n if (!catchall)\n return payload;\n return handleCatchall([], input, payload, ctx, value, inst);\n }\n return superParse(payload, ctx);\n };\n});\nfunction handleUnionResults(results, final, inst, ctx) {\n for (const result of results) {\n if (result.issues.length === 0) {\n final.value = result.value;\n return final;\n }\n }\n const nonaborted = results.filter((r) => !util.aborted(r));\n if (nonaborted.length === 1) {\n final.value = nonaborted[0].value;\n return nonaborted[0];\n }\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n return final;\n}\nexport const $ZodUnion = /*@__PURE__*/ core.$constructor(\"$ZodUnion\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.options.some((o) => o._zod.optin === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"optout\", () => def.options.some((o) => o._zod.optout === \"optional\") ? \"optional\" : undefined);\n util.defineLazy(inst._zod, \"values\", () => {\n if (def.options.every((o) => o._zod.values)) {\n return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));\n }\n return undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n if (def.options.every((o) => o._zod.pattern)) {\n const patterns = def.options.map((o) => o._zod.pattern);\n return new RegExp(`^(${patterns.map((p) => util.cleanRegex(p.source)).join(\"|\")})$`);\n }\n return undefined;\n });\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n if (result.issues.length === 0)\n return result;\n results.push(result);\n }\n }\n if (!async)\n return handleUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleUnionResults(results, payload, inst, ctx);\n });\n };\n});\nfunction handleExclusiveUnionResults(results, final, inst, ctx) {\n const successes = results.filter((r) => r.issues.length === 0);\n if (successes.length === 1) {\n final.value = successes[0].value;\n return final;\n }\n if (successes.length === 0) {\n // No matches - same as regular union\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))),\n });\n }\n else {\n // Multiple matches - exclusive union failure\n final.issues.push({\n code: \"invalid_union\",\n input: final.value,\n inst,\n errors: [],\n inclusive: false,\n });\n }\n return final;\n}\nexport const $ZodXor = /*@__PURE__*/ core.$constructor(\"$ZodXor\", (inst, def) => {\n $ZodUnion.init(inst, def);\n def.inclusive = false;\n const first = def.options.length === 1 ? def.options[0]._zod.run : null;\n inst._zod.parse = (payload, ctx) => {\n if (first) {\n return first(payload, ctx);\n }\n let async = false;\n const results = [];\n for (const option of def.options) {\n const result = option._zod.run({\n value: payload.value,\n issues: [],\n }, ctx);\n if (result instanceof Promise) {\n results.push(result);\n async = true;\n }\n else {\n results.push(result);\n }\n }\n if (!async)\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n return Promise.all(results).then((results) => {\n return handleExclusiveUnionResults(results, payload, inst, ctx);\n });\n };\n});\nexport const $ZodDiscriminatedUnion = \n/*@__PURE__*/\ncore.$constructor(\"$ZodDiscriminatedUnion\", (inst, def) => {\n def.inclusive = false;\n $ZodUnion.init(inst, def);\n const _super = inst._zod.parse;\n util.defineLazy(inst._zod, \"propValues\", () => {\n const propValues = {};\n for (const option of def.options) {\n const pv = option._zod.propValues;\n if (!pv || Object.keys(pv).length === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(option)}\"`);\n for (const [k, v] of Object.entries(pv)) {\n if (!propValues[k])\n propValues[k] = new Set();\n for (const val of v) {\n propValues[k].add(val);\n }\n }\n }\n return propValues;\n });\n const disc = util.cached(() => {\n const opts = def.options;\n const map = new Map();\n for (const o of opts) {\n const values = o._zod.propValues?.[def.discriminator];\n if (!values || values.size === 0)\n throw new Error(`Invalid discriminated union option at index \"${def.options.indexOf(o)}\"`);\n for (const v of values) {\n if (map.has(v)) {\n throw new Error(`Duplicate discriminator value \"${String(v)}\"`);\n }\n map.set(v, o);\n }\n }\n return map;\n });\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isObject(input)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"object\",\n input,\n inst,\n });\n return payload;\n }\n const opt = disc.value.get(input?.[def.discriminator]);\n if (opt) {\n return opt._zod.run(payload, ctx);\n }\n // Fall back to union matching when the fast discriminator path fails:\n // - explicitly enabled via unionFallback, or\n // - during backward direction (encode), since codec-based discriminators\n // have different values in forward vs backward directions\n if (def.unionFallback || ctx.direction === \"backward\") {\n return _super(payload, ctx);\n }\n // no matching discriminator\n payload.issues.push({\n code: \"invalid_union\",\n errors: [],\n note: \"No matching discriminator\",\n discriminator: def.discriminator,\n options: Array.from(disc.value.keys()),\n input,\n path: [def.discriminator],\n inst,\n });\n return payload;\n };\n});\nexport const $ZodIntersection = /*@__PURE__*/ core.$constructor(\"$ZodIntersection\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n const left = def.left._zod.run({ value: input, issues: [] }, ctx);\n const right = def.right._zod.run({ value: input, issues: [] }, ctx);\n const async = left instanceof Promise || right instanceof Promise;\n if (async) {\n return Promise.all([left, right]).then(([left, right]) => {\n return handleIntersectionResults(payload, left, right);\n });\n }\n return handleIntersectionResults(payload, left, right);\n };\n});\nfunction mergeValues(a, b) {\n // const aType = parse.t(a);\n // const bType = parse.t(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n if (a instanceof Date && b instanceof Date && +a === +b) {\n return { valid: true, data: a };\n }\n if (util.isPlainObject(a) && util.isPlainObject(b)) {\n const bKeys = Object.keys(b);\n const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [key, ...sharedValue.mergeErrorPath],\n };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return { valid: false, mergeErrorPath: [] };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return {\n valid: false,\n mergeErrorPath: [index, ...sharedValue.mergeErrorPath],\n };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n return { valid: false, mergeErrorPath: [] };\n}\nfunction handleIntersectionResults(result, left, right) {\n // Track which side(s) report each key as unrecognized\n const unrecKeys = new Map();\n let unrecIssue;\n for (const iss of left.issues) {\n if (iss.code === \"unrecognized_keys\") {\n unrecIssue ?? (unrecIssue = iss);\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).l = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n for (const iss of right.issues) {\n if (iss.code === \"unrecognized_keys\") {\n for (const k of iss.keys) {\n if (!unrecKeys.has(k))\n unrecKeys.set(k, {});\n unrecKeys.get(k).r = true;\n }\n }\n else {\n result.issues.push(iss);\n }\n }\n // Report only keys unrecognized by BOTH sides\n const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);\n if (bothKeys.length && unrecIssue) {\n result.issues.push({ ...unrecIssue, keys: bothKeys });\n }\n if (util.aborted(result))\n return result;\n const merged = mergeValues(left.value, right.value);\n if (!merged.valid) {\n throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`);\n }\n result.value = merged.data;\n return result;\n}\nexport const $ZodTuple = /*@__PURE__*/ core.$constructor(\"$ZodTuple\", (inst, def) => {\n $ZodType.init(inst, def);\n const items = def.items;\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!Array.isArray(input)) {\n payload.issues.push({\n input,\n inst,\n expected: \"tuple\",\n code: \"invalid_type\",\n });\n return payload;\n }\n payload.value = [];\n const proms = [];\n const optinStart = getTupleOptStart(items, \"optin\");\n const optoutStart = getTupleOptStart(items, \"optout\");\n if (!def.rest) {\n if (input.length < optinStart) {\n payload.issues.push({\n code: \"too_small\",\n minimum: optinStart,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n return payload;\n }\n if (input.length > items.length) {\n payload.issues.push({\n code: \"too_big\",\n maximum: items.length,\n inclusive: true,\n input,\n inst,\n origin: \"array\",\n });\n }\n }\n // Run every item in parallel, collecting results into an indexed\n // array. The post-processing in `handleTupleResults` walks them in\n // order so it can decide whether an absent optional-output error can\n // truncate the tail or must be reported to preserve required output.\n const itemResults = new Array(items.length);\n for (let i = 0; i < items.length; i++) {\n const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx);\n if (r instanceof Promise) {\n proms.push(r.then((rr) => {\n itemResults[i] = rr;\n }));\n }\n else {\n itemResults[i] = r;\n }\n }\n if (def.rest) {\n let i = items.length - 1;\n const rest = input.slice(items.length);\n for (const el of rest) {\n i++;\n const result = def.rest._zod.run({ value: el, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((r) => handleTupleResult(r, payload, i)));\n }\n else {\n handleTupleResult(result, payload, i);\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart));\n }\n return handleTupleResults(itemResults, payload, items, input, optoutStart);\n };\n});\nfunction getTupleOptStart(items, key) {\n for (let i = items.length - 1; i >= 0; i--) {\n if (items[i]._zod[key] !== \"optional\")\n return i + 1;\n }\n return 0;\n}\nfunction handleTupleResult(result, final, index) {\n if (result.issues.length) {\n final.issues.push(...util.prefixIssues(index, result.issues));\n }\n final.value[index] = result.value;\n}\nfunction handleTupleResults(itemResults, final, items, input, optoutStart) {\n // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional\n // rule, but only after `optoutStart`: the first index where the output\n // tuple tail can be absent.\n for (let i = 0; i < items.length; i++) {\n const r = itemResults[i];\n const isPresent = i < input.length;\n if (r.issues.length) {\n if (!isPresent && i >= optoutStart) {\n final.value.length = i;\n break;\n }\n final.issues.push(...util.prefixIssues(i, r.issues));\n }\n final.value[i] = r.value;\n }\n // Drop trailing slots that produced `undefined` for absent input\n // (the array analog of an absent optional key on an object). The\n // `i >= input.length` floor is critical: an explicit `undefined`\n // *inside* the input must be preserved even when the schema is\n // optional-out (e.g. `z.string().or(z.undefined())` accepting an\n // explicit undefined value).\n for (let i = final.value.length - 1; i >= input.length; i--) {\n if (items[i]._zod.optout === \"optional\" && final.value[i] === undefined) {\n final.value.length = i;\n }\n else {\n break;\n }\n }\n return final;\n}\nexport const $ZodRecord = /*@__PURE__*/ core.$constructor(\"$ZodRecord\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!util.isPlainObject(input)) {\n payload.issues.push({\n expected: \"record\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n const values = def.keyType._zod.values;\n if (values) {\n payload.value = {};\n const recordKeys = new Set();\n for (const key of values) {\n if (typeof key === \"string\" || typeof key === \"number\" || typeof key === \"symbol\") {\n recordKeys.add(typeof key === \"number\" ? key.toString() : key);\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (keyResult.issues.length) {\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n continue;\n }\n const outKey = keyResult.value;\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[outKey] = result.value;\n }\n }\n }\n let unrecognized;\n for (const key in input) {\n if (!recordKeys.has(key)) {\n unrecognized = unrecognized ?? [];\n unrecognized.push(key);\n }\n }\n if (unrecognized && unrecognized.length > 0) {\n payload.issues.push({\n code: \"unrecognized_keys\",\n input,\n inst,\n keys: unrecognized,\n });\n }\n }\n else {\n payload.value = {};\n // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object()\n for (const key of Reflect.ownKeys(input)) {\n if (key === \"__proto__\")\n continue;\n if (!Object.prototype.propertyIsEnumerable.call(input, key))\n continue;\n let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n if (keyResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n // Numeric string fallback: if key is a numeric string and failed, retry with Number(key)\n // This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals\n const checkNumericKey = typeof key === \"string\" && regexes.number.test(key) && keyResult.issues.length;\n if (checkNumericKey) {\n const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);\n if (retryResult instanceof Promise) {\n throw new Error(\"Async schemas not supported in object keys currently\");\n }\n if (retryResult.issues.length === 0) {\n keyResult = retryResult;\n }\n }\n if (keyResult.issues.length) {\n if (def.mode === \"loose\") {\n // Pass through unchanged\n payload.value[key] = input[key];\n }\n else {\n // Default \"strict\" behavior: error on invalid key\n payload.issues.push({\n code: \"invalid_key\",\n origin: \"record\",\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n input: key,\n path: [key],\n inst,\n });\n }\n continue;\n }\n const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }));\n }\n else {\n if (result.issues.length) {\n payload.issues.push(...util.prefixIssues(key, result.issues));\n }\n payload.value[keyResult.value] = result.value;\n }\n }\n }\n if (proms.length) {\n return Promise.all(proms).then(() => payload);\n }\n return payload;\n };\n});\nexport const $ZodMap = /*@__PURE__*/ core.$constructor(\"$ZodMap\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Map)) {\n payload.issues.push({\n expected: \"map\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n }\n const proms = [];\n payload.value = new Map();\n for (const [key, value] of input) {\n const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);\n const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx);\n if (keyResult instanceof Promise || valueResult instanceof Promise) {\n proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }));\n }\n else {\n handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);\n }\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {\n if (keyResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, keyResult.issues));\n }\n else {\n final.issues.push({\n code: \"invalid_key\",\n origin: \"map\",\n input,\n inst,\n issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n if (valueResult.issues.length) {\n if (util.propertyKeyTypes.has(typeof key)) {\n final.issues.push(...util.prefixIssues(key, valueResult.issues));\n }\n else {\n final.issues.push({\n origin: \"map\",\n code: \"invalid_element\",\n input,\n inst,\n key: key,\n issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n });\n }\n }\n final.value.set(keyResult.value, valueResult.value);\n}\nexport const $ZodSet = /*@__PURE__*/ core.$constructor(\"$ZodSet\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n const input = payload.value;\n if (!(input instanceof Set)) {\n payload.issues.push({\n input,\n inst,\n expected: \"set\",\n code: \"invalid_type\",\n });\n return payload;\n }\n const proms = [];\n payload.value = new Set();\n for (const item of input) {\n const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);\n if (result instanceof Promise) {\n proms.push(result.then((result) => handleSetResult(result, payload)));\n }\n else\n handleSetResult(result, payload);\n }\n if (proms.length)\n return Promise.all(proms).then(() => payload);\n return payload;\n };\n});\nfunction handleSetResult(result, final) {\n if (result.issues.length) {\n final.issues.push(...result.issues);\n }\n final.value.add(result.value);\n}\nexport const $ZodEnum = /*@__PURE__*/ core.$constructor(\"$ZodEnum\", (inst, def) => {\n $ZodType.init(inst, def);\n const values = util.getEnumValues(def.entries);\n const valuesSet = new Set(values);\n inst._zod.values = valuesSet;\n inst._zod.pattern = new RegExp(`^(${values\n .filter((k) => util.propertyKeyTypes.has(typeof k))\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o.toString()))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (valuesSet.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodLiteral = /*@__PURE__*/ core.$constructor(\"$ZodLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n if (def.values.length === 0) {\n throw new Error(\"Cannot create literal schema with no valid values\");\n }\n const values = new Set(def.values);\n inst._zod.values = values;\n inst._zod.pattern = new RegExp(`^(${def.values\n .map((o) => (typeof o === \"string\" ? util.escapeRegex(o) : o ? util.escapeRegex(o.toString()) : String(o)))\n .join(\"|\")})$`);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n if (values.has(input)) {\n return payload;\n }\n payload.issues.push({\n code: \"invalid_value\",\n values: def.values,\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodFile = /*@__PURE__*/ core.$constructor(\"$ZodFile\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n const input = payload.value;\n // @ts-ignore\n if (input instanceof File)\n return payload;\n payload.issues.push({\n expected: \"file\",\n code: \"invalid_type\",\n input,\n inst,\n });\n return payload;\n };\n});\nexport const $ZodTransform = /*@__PURE__*/ core.$constructor(\"$ZodTransform\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n const _out = def.transform(payload.value, payload);\n if (ctx.async) {\n const output = _out instanceof Promise ? _out : Promise.resolve(_out);\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n if (_out instanceof Promise) {\n throw new core.$ZodAsyncError();\n }\n payload.value = _out;\n payload.fallback = true;\n return payload;\n };\n});\nfunction handleOptionalResult(result, input) {\n if (input === undefined && (result.issues.length || result.fallback)) {\n return { issues: [], value: undefined };\n }\n return result;\n}\nexport const $ZodOptional = /*@__PURE__*/ core.$constructor(\"$ZodOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n inst._zod.optout = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined;\n });\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)})?$`) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n if (def.innerType._zod.optin === \"optional\") {\n const input = payload.value;\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise)\n return result.then((r) => handleOptionalResult(r, input));\n return handleOptionalResult(result, input);\n }\n if (payload.value === undefined) {\n return payload;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodExactOptional = /*@__PURE__*/ core.$constructor(\"$ZodExactOptional\", (inst, def) => {\n // Call parent init - inherits optin/optout = \"optional\"\n $ZodOptional.init(inst, def);\n // Override values/pattern to NOT add undefined\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"pattern\", () => def.innerType._zod.pattern);\n // Override parse to just delegate (no undefined handling)\n inst._zod.parse = (payload, ctx) => {\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNullable = /*@__PURE__*/ core.$constructor(\"$ZodNullable\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"pattern\", () => {\n const pattern = def.innerType._zod.pattern;\n return pattern ? new RegExp(`^(${util.cleanRegex(pattern.source)}|null)$`) : undefined;\n });\n util.defineLazy(inst._zod, \"values\", () => {\n return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n // Forward direction (decode): allow null to pass through\n if (payload.value === null)\n return payload;\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodDefault = /*@__PURE__*/ core.$constructor(\"$ZodDefault\", (inst, def) => {\n $ZodType.init(inst, def);\n // inst._zod.qin = \"true\";\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply defaults for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n /**\n * $ZodDefault returns the default value immediately in forward direction.\n * It doesn't pass the default value into the validator (\"prefault\"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a \"prefault\" for the pipe. */\n return payload;\n }\n // Forward direction: continue with default handling\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleDefaultResult(result, def));\n }\n return handleDefaultResult(result, def);\n };\n});\nfunction handleDefaultResult(payload, def) {\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return payload;\n}\nexport const $ZodPrefault = /*@__PURE__*/ core.$constructor(\"$ZodPrefault\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply prefault for undefined input\n if (payload.value === undefined) {\n payload.value = def.defaultValue;\n }\n return def.innerType._zod.run(payload, ctx);\n };\n});\nexport const $ZodNonOptional = /*@__PURE__*/ core.$constructor(\"$ZodNonOptional\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => {\n const v = def.innerType._zod.values;\n return v ? new Set([...v].filter((x) => x !== undefined)) : undefined;\n });\n inst._zod.parse = (payload, ctx) => {\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => handleNonOptionalResult(result, inst));\n }\n return handleNonOptionalResult(result, inst);\n };\n});\nfunction handleNonOptionalResult(payload, inst) {\n if (!payload.issues.length && payload.value === undefined) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"nonoptional\",\n input: payload.value,\n inst,\n });\n }\n return payload;\n}\nexport const $ZodSuccess = /*@__PURE__*/ core.$constructor(\"$ZodSuccess\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(\"ZodSuccess\");\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.issues.length === 0;\n return payload;\n });\n }\n payload.value = result.issues.length === 0;\n return payload;\n };\n});\nexport const $ZodCatch = /*@__PURE__*/ core.$constructor(\"$ZodCatch\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.optin = \"optional\";\n util.defineLazy(inst._zod, \"optout\", () => def.innerType._zod.optout);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n // Forward direction (decode): apply catch logic\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then((result) => {\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n });\n }\n payload.value = result.value;\n if (result.issues.length) {\n payload.value = def.catchValue({\n ...payload,\n error: {\n issues: result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())),\n },\n input: payload.value,\n });\n payload.issues = [];\n payload.fallback = true;\n }\n return payload;\n };\n});\nexport const $ZodNaN = /*@__PURE__*/ core.$constructor(\"$ZodNaN\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"number\" || !Number.isNaN(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"nan\",\n code: \"invalid_type\",\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodPipe = /*@__PURE__*/ core.$constructor(\"$ZodPipe\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handlePipeResult(right, def.in, ctx));\n }\n return handlePipeResult(right, def.in, ctx);\n }\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handlePipeResult(left, def.out, ctx));\n }\n return handlePipeResult(left, def.out, ctx);\n };\n});\nfunction handlePipeResult(left, next, ctx) {\n if (left.issues.length) {\n // prevent further checks\n left.aborted = true;\n return left;\n }\n return next._zod.run({ value: left.value, issues: left.issues, fallback: left.fallback }, ctx);\n}\nexport const $ZodCodec = /*@__PURE__*/ core.$constructor(\"$ZodCodec\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"values\", () => def.in._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.in._zod.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.out._zod.optout);\n util.defineLazy(inst._zod, \"propValues\", () => def.in._zod.propValues);\n inst._zod.parse = (payload, ctx) => {\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const left = def.in._zod.run(payload, ctx);\n if (left instanceof Promise) {\n return left.then((left) => handleCodecAResult(left, def, ctx));\n }\n return handleCodecAResult(left, def, ctx);\n }\n else {\n const right = def.out._zod.run(payload, ctx);\n if (right instanceof Promise) {\n return right.then((right) => handleCodecAResult(right, def, ctx));\n }\n return handleCodecAResult(right, def, ctx);\n }\n };\n});\nfunction handleCodecAResult(result, def, ctx) {\n if (result.issues.length) {\n // prevent further checks\n result.aborted = true;\n return result;\n }\n const direction = ctx.direction || \"forward\";\n if (direction === \"forward\") {\n const transformed = def.transform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));\n }\n return handleCodecTxResult(result, transformed, def.out, ctx);\n }\n else {\n const transformed = def.reverseTransform(result.value, result);\n if (transformed instanceof Promise) {\n return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));\n }\n return handleCodecTxResult(result, transformed, def.in, ctx);\n }\n}\nfunction handleCodecTxResult(left, value, nextSchema, ctx) {\n // Check if transform added any issues\n if (left.issues.length) {\n left.aborted = true;\n return left;\n }\n return nextSchema._zod.run({ value, issues: left.issues }, ctx);\n}\nexport const $ZodPreprocess = /*@__PURE__*/ core.$constructor(\"$ZodPreprocess\", (inst, def) => {\n $ZodPipe.init(inst, def);\n});\nexport const $ZodReadonly = /*@__PURE__*/ core.$constructor(\"$ZodReadonly\", (inst, def) => {\n $ZodType.init(inst, def);\n util.defineLazy(inst._zod, \"propValues\", () => def.innerType._zod.propValues);\n util.defineLazy(inst._zod, \"values\", () => def.innerType._zod.values);\n util.defineLazy(inst._zod, \"optin\", () => def.innerType?._zod?.optin);\n util.defineLazy(inst._zod, \"optout\", () => def.innerType?._zod?.optout);\n inst._zod.parse = (payload, ctx) => {\n if (ctx.direction === \"backward\") {\n return def.innerType._zod.run(payload, ctx);\n }\n const result = def.innerType._zod.run(payload, ctx);\n if (result instanceof Promise) {\n return result.then(handleReadonlyResult);\n }\n return handleReadonlyResult(result);\n };\n});\nfunction handleReadonlyResult(payload) {\n payload.value = Object.freeze(payload.value);\n return payload;\n}\nexport const $ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"$ZodTemplateLiteral\", (inst, def) => {\n $ZodType.init(inst, def);\n const regexParts = [];\n for (const part of def.parts) {\n if (typeof part === \"object\" && part !== null) {\n // is Zod schema\n if (!part._zod.pattern) {\n // if (!source)\n throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);\n }\n const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;\n if (!source)\n throw new Error(`Invalid template literal part: ${part._zod.traits}`);\n const start = source.startsWith(\"^\") ? 1 : 0;\n const end = source.endsWith(\"$\") ? source.length - 1 : source.length;\n regexParts.push(source.slice(start, end));\n }\n else if (part === null || util.primitiveTypes.has(typeof part)) {\n regexParts.push(util.escapeRegex(`${part}`));\n }\n else {\n throw new Error(`Invalid template literal part: ${part}`);\n }\n }\n inst._zod.pattern = new RegExp(`^${regexParts.join(\"\")}$`);\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"string\") {\n payload.issues.push({\n input: payload.value,\n inst,\n expected: \"string\",\n code: \"invalid_type\",\n });\n return payload;\n }\n inst._zod.pattern.lastIndex = 0;\n if (!inst._zod.pattern.test(payload.value)) {\n payload.issues.push({\n input: payload.value,\n inst,\n code: \"invalid_format\",\n format: def.format ?? \"template_literal\",\n pattern: inst._zod.pattern.source,\n });\n return payload;\n }\n return payload;\n };\n});\nexport const $ZodFunction = /*@__PURE__*/ core.$constructor(\"$ZodFunction\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._def = def;\n inst._zod.def = def;\n inst.implement = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implement() must be called with a function\");\n }\n return function (...args) {\n const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;\n const result = Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return parse(inst._def.output, result);\n }\n return result;\n };\n };\n inst.implementAsync = (func) => {\n if (typeof func !== \"function\") {\n throw new Error(\"implementAsync() must be called with a function\");\n }\n return async function (...args) {\n const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;\n const result = await Reflect.apply(func, this, parsedArgs);\n if (inst._def.output) {\n return await parseAsync(inst._def.output, result);\n }\n return result;\n };\n };\n inst._zod.parse = (payload, _ctx) => {\n if (typeof payload.value !== \"function\") {\n payload.issues.push({\n code: \"invalid_type\",\n expected: \"function\",\n input: payload.value,\n inst,\n });\n return payload;\n }\n // Check if output is a promise type to determine if we should use async implementation\n const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === \"promise\";\n if (hasPromiseOutput) {\n payload.value = inst.implementAsync(payload.value);\n }\n else {\n payload.value = inst.implement(payload.value);\n }\n return payload;\n };\n inst.input = (...args) => {\n const F = inst.constructor;\n if (Array.isArray(args[0])) {\n return new F({\n type: \"function\",\n input: new $ZodTuple({\n type: \"tuple\",\n items: args[0],\n rest: args[1],\n }),\n output: inst._def.output,\n });\n }\n return new F({\n type: \"function\",\n input: args[0],\n output: inst._def.output,\n });\n };\n inst.output = (output) => {\n const F = inst.constructor;\n return new F({\n type: \"function\",\n input: inst._def.input,\n output,\n });\n };\n return inst;\n});\nexport const $ZodPromise = /*@__PURE__*/ core.$constructor(\"$ZodPromise\", (inst, def) => {\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, ctx) => {\n return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));\n };\n});\nexport const $ZodLazy = /*@__PURE__*/ core.$constructor(\"$ZodLazy\", (inst, def) => {\n $ZodType.init(inst, def);\n // Cache the resolved inner type on the shared `def` so all clones of this\n // lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance,\n // preserving identity for cycle detection on recursive schemas.\n util.defineLazy(inst._zod, \"innerType\", () => {\n const d = def;\n if (!d._cachedInner)\n d._cachedInner = def.getter();\n return d._cachedInner;\n });\n util.defineLazy(inst._zod, \"pattern\", () => inst._zod.innerType?._zod?.pattern);\n util.defineLazy(inst._zod, \"propValues\", () => inst._zod.innerType?._zod?.propValues);\n util.defineLazy(inst._zod, \"optin\", () => inst._zod.innerType?._zod?.optin ?? undefined);\n util.defineLazy(inst._zod, \"optout\", () => inst._zod.innerType?._zod?.optout ?? undefined);\n inst._zod.parse = (payload, ctx) => {\n const inner = inst._zod.innerType;\n return inner._zod.run(payload, ctx);\n };\n});\nexport const $ZodCustom = /*@__PURE__*/ core.$constructor(\"$ZodCustom\", (inst, def) => {\n checks.$ZodCheck.init(inst, def);\n $ZodType.init(inst, def);\n inst._zod.parse = (payload, _) => {\n return payload;\n };\n inst._zod.check = (payload) => {\n const input = payload.value;\n const r = def.fn(input);\n if (r instanceof Promise) {\n return r.then((r) => handleRefineResult(r, payload, input, inst));\n }\n handleRefineResult(r, payload, input, inst);\n return;\n };\n});\nfunction handleRefineResult(result, payload, input, inst) {\n if (!result) {\n const _iss = {\n code: \"custom\",\n input,\n inst, // incorporates params.error into issue reporting\n path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting\n continue: !inst._zod.def.abort,\n // params: inst._zod.def.params,\n };\n if (inst._zod.def.params)\n _iss.params = inst._zod.def.params;\n payload.issues.push(util.issue(_iss));\n }\n}\n","var _a;\nexport const $output = Symbol(\"ZodOutput\");\nexport const $input = Symbol(\"ZodInput\");\nexport class $ZodRegistry {\n constructor() {\n this._map = new WeakMap();\n this._idmap = new Map();\n }\n add(schema, ..._meta) {\n const meta = _meta[0];\n this._map.set(schema, meta);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.set(meta.id, schema);\n }\n return this;\n }\n clear() {\n this._map = new WeakMap();\n this._idmap = new Map();\n return this;\n }\n remove(schema) {\n const meta = this._map.get(schema);\n if (meta && typeof meta === \"object\" && \"id\" in meta) {\n this._idmap.delete(meta.id);\n }\n this._map.delete(schema);\n return this;\n }\n get(schema) {\n // return this._map.get(schema) as any;\n // inherit metadata\n const p = schema._zod.parent;\n if (p) {\n const pm = { ...(this.get(p) ?? {}) };\n delete pm.id; // do not inherit id\n const f = { ...pm, ...this._map.get(schema) };\n return Object.keys(f).length ? f : undefined;\n }\n return this._map.get(schema);\n }\n has(schema) {\n return this._map.has(schema);\n }\n}\n// registries\nexport function registry() {\n return new $ZodRegistry();\n}\n(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());\nexport const globalRegistry = globalThis.__zod_globalRegistry;\n","import * as checks from \"./checks.js\";\nimport * as registries from \"./registries.js\";\nimport * as schemas from \"./schemas.js\";\nimport * as util from \"./util.js\";\n// @__NO_SIDE_EFFECTS__\nexport function _string(Class, params) {\n return new Class({\n type: \"string\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedString(Class, params) {\n return new Class({\n type: \"string\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _email(Class, params) {\n return new Class({\n type: \"string\",\n format: \"email\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _guid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"guid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v4\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v6\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uuidv7(Class, params) {\n return new Class({\n type: \"string\",\n format: \"uuid\",\n check: \"string_format\",\n abort: false,\n version: \"v7\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _emoji(Class, params) {\n return new Class({\n type: \"string\",\n format: \"emoji\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nanoid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"nanoid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link _cuid2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\n// @__NO_SIDE_EFFECTS__\nexport function _cuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cuid2(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cuid2\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ulid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ulid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _xid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"xid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ksuid(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ksuid\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _ipv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"ipv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mac(Class, params) {\n return new Class({\n type: \"string\",\n format: \"mac\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv4(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv4\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _cidrv6(Class, params) {\n return new Class({\n type: \"string\",\n format: \"cidrv6\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _base64url(Class, params) {\n return new Class({\n type: \"string\",\n format: \"base64url\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _e164(Class, params) {\n return new Class({\n type: \"string\",\n format: \"e164\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _jwt(Class, params) {\n return new Class({\n type: \"string\",\n format: \"jwt\",\n check: \"string_format\",\n abort: false,\n ...util.normalizeParams(params),\n });\n}\nexport const TimePrecision = {\n Any: null,\n Minute: -1,\n Second: 0,\n Millisecond: 3,\n Microsecond: 6,\n};\n// @__NO_SIDE_EFFECTS__\nexport function _isoDateTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"datetime\",\n check: \"string_format\",\n offset: false,\n local: false,\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDate(Class, params) {\n return new Class({\n type: \"string\",\n format: \"date\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoTime(Class, params) {\n return new Class({\n type: \"string\",\n format: \"time\",\n check: \"string_format\",\n precision: null,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _isoDuration(Class, params) {\n return new Class({\n type: \"string\",\n format: \"duration\",\n check: \"string_format\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _number(Class, params) {\n return new Class({\n type: \"number\",\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedNumber(Class, params) {\n return new Class({\n type: \"number\",\n coerce: true,\n checks: [],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"safeint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _float64(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"float64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"int32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint32(Class, params) {\n return new Class({\n type: \"number\",\n check: \"number_format\",\n abort: false,\n format: \"uint32\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _boolean(Class, params) {\n return new Class({\n type: \"boolean\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBoolean(Class, params) {\n return new Class({\n type: \"boolean\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _bigint(Class, params) {\n return new Class({\n type: \"bigint\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedBigint(Class, params) {\n return new Class({\n type: \"bigint\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _int64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"int64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uint64(Class, params) {\n return new Class({\n type: \"bigint\",\n check: \"bigint_format\",\n abort: false,\n format: \"uint64\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _symbol(Class, params) {\n return new Class({\n type: \"symbol\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _undefined(Class, params) {\n return new Class({\n type: \"undefined\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _null(Class, params) {\n return new Class({\n type: \"null\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _any(Class) {\n return new Class({\n type: \"any\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _unknown(Class) {\n return new Class({\n type: \"unknown\",\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _never(Class, params) {\n return new Class({\n type: \"never\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _void(Class, params) {\n return new Class({\n type: \"void\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _date(Class, params) {\n return new Class({\n type: \"date\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _coercedDate(Class, params) {\n return new Class({\n type: \"date\",\n coerce: true,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nan(Class, params) {\n return new Class({\n type: \"nan\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lt(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lte(value, params) {\n return new checks.$ZodCheckLessThan({\n check: \"less_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.lte()` instead. */\n_lte as _max, };\n// @__NO_SIDE_EFFECTS__\nexport function _gt(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: false,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _gte(value, params) {\n return new checks.$ZodCheckGreaterThan({\n check: \"greater_than\",\n ...util.normalizeParams(params),\n value,\n inclusive: true,\n });\n}\nexport { \n/** @deprecated Use `z.gte()` instead. */\n_gte as _min, };\n// @__NO_SIDE_EFFECTS__\nexport function _positive(params) {\n return _gt(0, params);\n}\n// negative\n// @__NO_SIDE_EFFECTS__\nexport function _negative(params) {\n return _lt(0, params);\n}\n// nonpositive\n// @__NO_SIDE_EFFECTS__\nexport function _nonpositive(params) {\n return _lte(0, params);\n}\n// nonnegative\n// @__NO_SIDE_EFFECTS__\nexport function _nonnegative(params) {\n return _gte(0, params);\n}\n// @__NO_SIDE_EFFECTS__\nexport function _multipleOf(value, params) {\n return new checks.$ZodCheckMultipleOf({\n check: \"multiple_of\",\n ...util.normalizeParams(params),\n value,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxSize(maximum, params) {\n return new checks.$ZodCheckMaxSize({\n check: \"max_size\",\n ...util.normalizeParams(params),\n maximum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minSize(minimum, params) {\n return new checks.$ZodCheckMinSize({\n check: \"min_size\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _size(size, params) {\n return new checks.$ZodCheckSizeEquals({\n check: \"size_equals\",\n ...util.normalizeParams(params),\n size,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _maxLength(maximum, params) {\n const ch = new checks.$ZodCheckMaxLength({\n check: \"max_length\",\n ...util.normalizeParams(params),\n maximum,\n });\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _minLength(minimum, params) {\n return new checks.$ZodCheckMinLength({\n check: \"min_length\",\n ...util.normalizeParams(params),\n minimum,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _length(length, params) {\n return new checks.$ZodCheckLengthEquals({\n check: \"length_equals\",\n ...util.normalizeParams(params),\n length,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _regex(pattern, params) {\n return new checks.$ZodCheckRegex({\n check: \"string_format\",\n format: \"regex\",\n ...util.normalizeParams(params),\n pattern,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lowercase(params) {\n return new checks.$ZodCheckLowerCase({\n check: \"string_format\",\n format: \"lowercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _uppercase(params) {\n return new checks.$ZodCheckUpperCase({\n check: \"string_format\",\n format: \"uppercase\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _includes(includes, params) {\n return new checks.$ZodCheckIncludes({\n check: \"string_format\",\n format: \"includes\",\n ...util.normalizeParams(params),\n includes,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _startsWith(prefix, params) {\n return new checks.$ZodCheckStartsWith({\n check: \"string_format\",\n format: \"starts_with\",\n ...util.normalizeParams(params),\n prefix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _endsWith(suffix, params) {\n return new checks.$ZodCheckEndsWith({\n check: \"string_format\",\n format: \"ends_with\",\n ...util.normalizeParams(params),\n suffix,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _property(property, schema, params) {\n return new checks.$ZodCheckProperty({\n check: \"property\",\n property,\n schema,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _mime(types, params) {\n return new checks.$ZodCheckMimeType({\n check: \"mime_type\",\n mime: types,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _overwrite(tx) {\n return new checks.$ZodCheckOverwrite({\n check: \"overwrite\",\n tx,\n });\n}\n// normalize\n// @__NO_SIDE_EFFECTS__\nexport function _normalize(form) {\n return _overwrite((input) => input.normalize(form));\n}\n// trim\n// @__NO_SIDE_EFFECTS__\nexport function _trim() {\n return _overwrite((input) => input.trim());\n}\n// toLowerCase\n// @__NO_SIDE_EFFECTS__\nexport function _toLowerCase() {\n return _overwrite((input) => input.toLowerCase());\n}\n// toUpperCase\n// @__NO_SIDE_EFFECTS__\nexport function _toUpperCase() {\n return _overwrite((input) => input.toUpperCase());\n}\n// slugify\n// @__NO_SIDE_EFFECTS__\nexport function _slugify() {\n return _overwrite((input) => util.slugify(input));\n}\n// @__NO_SIDE_EFFECTS__\nexport function _array(Class, element, params) {\n return new Class({\n type: \"array\",\n element,\n // get element() {\n // return element;\n // },\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _union(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n ...util.normalizeParams(params),\n });\n}\nexport function _xor(Class, options, params) {\n return new Class({\n type: \"union\",\n options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _discriminatedUnion(Class, discriminator, options, params) {\n return new Class({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _intersection(Class, left, right) {\n return new Class({\n type: \"intersection\",\n left,\n right,\n });\n}\n// export function _tuple(\n// Class: util.SchemaClass<schemas.$ZodTuple>,\n// items: [],\n// params?: string | $ZodTupleParams\n// ): schemas.$ZodTuple<[], null>;\n// @__NO_SIDE_EFFECTS__\nexport function _tuple(Class, items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof schemas.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new Class({\n type: \"tuple\",\n items,\n rest,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _record(Class, keyType, valueType, params) {\n return new Class({\n type: \"record\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _map(Class, keyType, valueType, params) {\n return new Class({\n type: \"map\",\n keyType,\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _set(Class, valueType, params) {\n return new Class({\n type: \"set\",\n valueType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _enum(Class, values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n // if (Array.isArray(values)) {\n // for (const value of values) {\n // entries[value] = value;\n // }\n // } else {\n // Object.assign(entries, values);\n // }\n // const entries: util.EnumLike = {};\n // for (const val of values) {\n // entries[val] = val;\n // }\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function _nativeEnum(Class, entries, params) {\n return new Class({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _literal(Class, value, params) {\n return new Class({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _file(Class, params) {\n return new Class({\n type: \"file\",\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _transform(Class, fn) {\n return new Class({\n type: \"transform\",\n transform: fn,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _optional(Class, innerType) {\n return new Class({\n type: \"optional\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nullable(Class, innerType) {\n return new Class({\n type: \"nullable\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _default(Class, innerType, defaultValue) {\n return new Class({\n type: \"default\",\n innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _nonoptional(Class, innerType, params) {\n return new Class({\n type: \"nonoptional\",\n innerType,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _success(Class, innerType) {\n return new Class({\n type: \"success\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _catch(Class, innerType, catchValue) {\n return new Class({\n type: \"catch\",\n innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _pipe(Class, in_, out) {\n return new Class({\n type: \"pipe\",\n in: in_,\n out,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _readonly(Class, innerType) {\n return new Class({\n type: \"readonly\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _templateLiteral(Class, parts, params) {\n return new Class({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _lazy(Class, getter) {\n return new Class({\n type: \"lazy\",\n getter,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _promise(Class, innerType) {\n return new Class({\n type: \"promise\",\n innerType,\n });\n}\n// @__NO_SIDE_EFFECTS__\nexport function _custom(Class, fn, _params) {\n const norm = util.normalizeParams(_params);\n norm.abort ?? (norm.abort = true); // default to abort:false\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...norm,\n });\n return schema;\n}\n// same as _custom but defaults to abort:false\n// @__NO_SIDE_EFFECTS__\nexport function _refine(Class, fn, _params) {\n const schema = new Class({\n type: \"custom\",\n check: \"custom\",\n fn: fn,\n ...util.normalizeParams(_params),\n });\n return schema;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _superRefine(fn, params) {\n const ch = _check((payload) => {\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, ch._zod.def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = ch);\n _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true...\n payload.issues.push(util.issue(_issue));\n }\n };\n return fn(payload.value, payload);\n }, params);\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _check(fn, params) {\n const ch = new checks.$ZodCheck({\n check: \"custom\",\n ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function describe(description) {\n const ch = new checks.$ZodCheck({ check: \"describe\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, description });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function meta(metadata) {\n const ch = new checks.$ZodCheck({ check: \"meta\" });\n ch._zod.onattach = [\n (inst) => {\n const existing = registries.globalRegistry.get(inst) ?? {};\n registries.globalRegistry.add(inst, { ...existing, ...metadata });\n },\n ];\n ch._zod.check = () => { }; // no-op check\n return ch;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringbool(Classes, _params) {\n const params = util.normalizeParams(_params);\n let truthyArray = params.truthy ?? [\"true\", \"1\", \"yes\", \"on\", \"y\", \"enabled\"];\n let falsyArray = params.falsy ?? [\"false\", \"0\", \"no\", \"off\", \"n\", \"disabled\"];\n if (params.case !== \"sensitive\") {\n truthyArray = truthyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n falsyArray = falsyArray.map((v) => (typeof v === \"string\" ? v.toLowerCase() : v));\n }\n const truthySet = new Set(truthyArray);\n const falsySet = new Set(falsyArray);\n const _Codec = Classes.Codec ?? schemas.$ZodCodec;\n const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean;\n const _String = Classes.String ?? schemas.$ZodString;\n const stringSchema = new _String({ type: \"string\", error: params.error });\n const booleanSchema = new _Boolean({ type: \"boolean\", error: params.error });\n const codec = new _Codec({\n type: \"pipe\",\n in: stringSchema,\n out: booleanSchema,\n transform: ((input, payload) => {\n let data = input;\n if (params.case !== \"sensitive\")\n data = data.toLowerCase();\n if (truthySet.has(data)) {\n return true;\n }\n else if (falsySet.has(data)) {\n return false;\n }\n else {\n payload.issues.push({\n code: \"invalid_value\",\n expected: \"stringbool\",\n values: [...truthySet, ...falsySet],\n input: payload.value,\n inst: codec,\n continue: false,\n });\n return {};\n }\n }),\n reverseTransform: ((input, _payload) => {\n if (input === true) {\n return truthyArray[0] || \"true\";\n }\n else {\n return falsyArray[0] || \"false\";\n }\n }),\n error: params.error,\n });\n return codec;\n}\n// @__NO_SIDE_EFFECTS__\nexport function _stringFormat(Class, format, fnOrRegex, _params = {}) {\n const params = util.normalizeParams(_params);\n const def = {\n ...util.normalizeParams(_params),\n check: \"string_format\",\n type: \"string\",\n format,\n fn: typeof fnOrRegex === \"function\" ? fnOrRegex : (val) => fnOrRegex.test(val),\n ...params,\n };\n if (fnOrRegex instanceof RegExp) {\n def.pattern = fnOrRegex;\n }\n const inst = new Class(def);\n return inst;\n}\n","import { globalRegistry } from \"./registries.js\";\n// function initializeContext<T extends schemas.$ZodType>(inputs: JSONSchemaGeneratorParams<T>): ToJSONSchemaContext<T> {\n// return {\n// processor: inputs.processor,\n// metadataRegistry: inputs.metadata ?? globalRegistry,\n// target: inputs.target ?? \"draft-2020-12\",\n// unrepresentable: inputs.unrepresentable ?? \"throw\",\n// };\n// }\nexport function initializeContext(params) {\n // Normalize target: convert old non-hyphenated versions to hyphenated versions\n let target = params?.target ?? \"draft-2020-12\";\n if (target === \"draft-4\")\n target = \"draft-04\";\n if (target === \"draft-7\")\n target = \"draft-07\";\n return {\n processors: params.processors ?? {},\n metadataRegistry: params?.metadata ?? globalRegistry,\n target,\n unrepresentable: params?.unrepresentable ?? \"throw\",\n override: params?.override ?? (() => { }),\n io: params?.io ?? \"output\",\n counter: 0,\n seen: new Map(),\n cycles: params?.cycles ?? \"ref\",\n reused: params?.reused ?? \"inline\",\n external: params?.external ?? undefined,\n };\n}\nexport function process(schema, ctx, _params = { path: [], schemaPath: [] }) {\n var _a;\n const def = schema._zod.def;\n // check for schema in seens\n const seen = ctx.seen.get(schema);\n if (seen) {\n seen.count++;\n // check if cycle\n const isCycle = _params.schemaPath.includes(schema);\n if (isCycle) {\n seen.cycle = _params.path;\n }\n return seen.schema;\n }\n // initialize\n const result = { schema: {}, count: 1, cycle: undefined, path: _params.path };\n ctx.seen.set(schema, result);\n // custom method overrides default behavior\n const overrideSchema = schema._zod.toJSONSchema?.();\n if (overrideSchema) {\n result.schema = overrideSchema;\n }\n else {\n const params = {\n ..._params,\n schemaPath: [..._params.schemaPath, schema],\n path: _params.path,\n };\n if (schema._zod.processJSONSchema) {\n schema._zod.processJSONSchema(ctx, result.schema, params);\n }\n else {\n const _json = result.schema;\n const processor = ctx.processors[def.type];\n if (!processor) {\n throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);\n }\n processor(schema, ctx, _json, params);\n }\n const parent = schema._zod.parent;\n if (parent) {\n // Also set ref if processor didn't (for inheritance)\n if (!result.ref)\n result.ref = parent;\n process(parent, ctx, params);\n ctx.seen.get(parent).isParent = true;\n }\n }\n // metadata\n const meta = ctx.metadataRegistry.get(schema);\n if (meta)\n Object.assign(result.schema, meta);\n if (ctx.io === \"input\" && isTransforming(schema)) {\n // examples/defaults only apply to output type of pipe\n delete result.schema.examples;\n delete result.schema.default;\n }\n // set prefault as default\n if (ctx.io === \"input\" && \"_prefault\" in result.schema)\n (_a = result.schema).default ?? (_a.default = result.schema._prefault);\n delete result.schema._prefault;\n // pulling fresh from ctx.seen in case it was overwritten\n const _result = ctx.seen.get(schema);\n return _result.schema;\n}\nexport function extractDefs(ctx, schema\n// params: EmitParams\n) {\n // iterate over seen map;\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // Track ids to detect duplicates across different schemas\n const idToSchema = new Map();\n for (const entry of ctx.seen.entries()) {\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n const existing = idToSchema.get(id);\n if (existing && existing !== entry[0]) {\n throw new Error(`Duplicate schema id \"${id}\" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);\n }\n idToSchema.set(id, entry[0]);\n }\n }\n // returns a ref to the schema\n // defId will be empty if the ref points to an external schema (or #)\n const makeURI = (entry) => {\n // comparing the seen objects because sometimes\n // multiple schemas map to the same seen object.\n // e.g. lazy\n // external is configured\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n if (ctx.external) {\n const externalId = ctx.external.registry.get(entry[0])?.id; // ?? \"__shared\";// `__schema${ctx.counter++}`;\n // check if schema is in the external registry\n const uriGenerator = ctx.external.uri ?? ((id) => id);\n if (externalId) {\n return { ref: uriGenerator(externalId) };\n }\n // otherwise, add to __shared\n const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`;\n entry[1].defId = id; // set defId so it will be reused if needed\n return { defId: id, ref: `${uriGenerator(\"__shared\")}#/${defsSegment}/${id}` };\n }\n if (entry[1] === root) {\n return { ref: \"#\" };\n }\n // self-contained schema\n const uriPrefix = `#`;\n const defUriPrefix = `${uriPrefix}/${defsSegment}/`;\n const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`;\n return { defId, ref: defUriPrefix + defId };\n };\n // stored cached version in `def` property\n // remove all properties, set $ref\n const extractToDef = (entry) => {\n // if the schema is already a reference, do not extract it\n if (entry[1].schema.$ref) {\n return;\n }\n const seen = entry[1];\n const { ref, defId } = makeURI(entry);\n seen.def = { ...seen.schema };\n // defId won't be set if the schema is a reference to an external schema\n // or if the schema is the root schema\n if (defId)\n seen.defId = defId;\n // wipe away all properties except $ref\n const schema = seen.schema;\n for (const key in schema) {\n delete schema[key];\n }\n schema.$ref = ref;\n };\n // throw on cycles\n // break cycles\n if (ctx.cycles === \"throw\") {\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.cycle) {\n throw new Error(\"Cycle detected: \" +\n `#/${seen.cycle?.join(\"/\")}/<root>` +\n '\\n\\nSet the `cycles` parameter to `\"ref\"` to resolve cyclical schemas with defs.');\n }\n }\n }\n // extract schemas into $defs\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n // convert root schema to # $ref\n if (schema === entry[0]) {\n extractToDef(entry); // this has special handling for the root schema\n continue;\n }\n // extract schemas that are in the external registry\n if (ctx.external) {\n const ext = ctx.external.registry.get(entry[0])?.id;\n if (schema !== entry[0] && ext) {\n extractToDef(entry);\n continue;\n }\n }\n // extract schemas with `id` meta\n const id = ctx.metadataRegistry.get(entry[0])?.id;\n if (id) {\n extractToDef(entry);\n continue;\n }\n // break cycles\n if (seen.cycle) {\n // any\n extractToDef(entry);\n continue;\n }\n // extract reused schemas\n if (seen.count > 1) {\n if (ctx.reused === \"ref\") {\n extractToDef(entry);\n // biome-ignore lint:\n continue;\n }\n }\n }\n}\nexport function finalize(ctx, schema) {\n const root = ctx.seen.get(schema);\n if (!root)\n throw new Error(\"Unprocessed schema. This is a bug in Zod.\");\n // flatten refs - inherit properties from parent schemas\n const flattenRef = (zodSchema) => {\n const seen = ctx.seen.get(zodSchema);\n // already processed\n if (seen.ref === null)\n return;\n const schema = seen.def ?? seen.schema;\n const _cached = { ...schema };\n const ref = seen.ref;\n seen.ref = null; // prevent infinite recursion\n if (ref) {\n flattenRef(ref);\n const refSeen = ctx.seen.get(ref);\n const refSchema = refSeen.schema;\n // merge referenced schema into current\n if (refSchema.$ref && (ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\")) {\n // older drafts can't combine $ref with other properties\n schema.allOf = schema.allOf ?? [];\n schema.allOf.push(refSchema);\n }\n else {\n Object.assign(schema, refSchema);\n }\n // restore child's own properties (child wins)\n Object.assign(schema, _cached);\n const isParentRef = zodSchema._zod.parent === ref;\n // For parent chain, child is a refinement - remove parent-only properties\n if (isParentRef) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (!(key in _cached)) {\n delete schema[key];\n }\n }\n }\n // When ref was extracted to $defs, remove properties that match the definition\n if (refSchema.$ref && refSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n // If parent was extracted (has $ref), propagate $ref to this schema\n // This handles cases like: readonly().meta({id}).describe()\n // where processor sets ref to innerType but parent should be referenced\n const parent = zodSchema._zod.parent;\n if (parent && parent !== ref) {\n // Ensure parent is processed first so its def has inherited properties\n flattenRef(parent);\n const parentSeen = ctx.seen.get(parent);\n if (parentSeen?.schema.$ref) {\n schema.$ref = parentSeen.schema.$ref;\n // De-duplicate with parent's definition\n if (parentSeen.def) {\n for (const key in schema) {\n if (key === \"$ref\" || key === \"allOf\")\n continue;\n if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) {\n delete schema[key];\n }\n }\n }\n }\n }\n // execute overrides\n ctx.override({\n zodSchema: zodSchema,\n jsonSchema: schema,\n path: seen.path ?? [],\n });\n };\n for (const entry of [...ctx.seen.entries()].reverse()) {\n flattenRef(entry[0]);\n }\n const result = {};\n if (ctx.target === \"draft-2020-12\") {\n result.$schema = \"https://json-schema.org/draft/2020-12/schema\";\n }\n else if (ctx.target === \"draft-07\") {\n result.$schema = \"http://json-schema.org/draft-07/schema#\";\n }\n else if (ctx.target === \"draft-04\") {\n result.$schema = \"http://json-schema.org/draft-04/schema#\";\n }\n else if (ctx.target === \"openapi-3.0\") {\n // OpenAPI 3.0 schema objects should not include a $schema property\n }\n else {\n // Arbitrary string values are allowed but won't have a $schema property set\n }\n if (ctx.external?.uri) {\n const id = ctx.external.registry.get(schema)?.id;\n if (!id)\n throw new Error(\"Schema is missing an `id` property\");\n result.$id = ctx.external.uri(id);\n }\n Object.assign(result, root.def ?? root.schema);\n // The `id` in `.meta()` is a Zod-specific registration tag used to extract\n // schemas into $defs — it is not user-facing JSON Schema metadata. Strip it\n // from the output body where it would otherwise leak. The id is preserved\n // implicitly via the $defs key (and via $ref paths).\n const rootMetaId = ctx.metadataRegistry.get(schema)?.id;\n if (rootMetaId !== undefined && result.id === rootMetaId)\n delete result.id;\n // build defs object\n const defs = ctx.external?.defs ?? {};\n for (const entry of ctx.seen.entries()) {\n const seen = entry[1];\n if (seen.def && seen.defId) {\n if (seen.def.id === seen.defId)\n delete seen.def.id;\n defs[seen.defId] = seen.def;\n }\n }\n // set definitions in result\n if (ctx.external) {\n }\n else {\n if (Object.keys(defs).length > 0) {\n if (ctx.target === \"draft-2020-12\") {\n result.$defs = defs;\n }\n else {\n result.definitions = defs;\n }\n }\n }\n try {\n // this \"finalizes\" this schema and ensures all cycles are removed\n // each call to finalize() is functionally independent\n // though the seen map is shared\n const finalized = JSON.parse(JSON.stringify(result));\n Object.defineProperty(finalized, \"~standard\", {\n value: {\n ...schema[\"~standard\"],\n jsonSchema: {\n input: createStandardJSONSchemaMethod(schema, \"input\", ctx.processors),\n output: createStandardJSONSchemaMethod(schema, \"output\", ctx.processors),\n },\n },\n enumerable: false,\n writable: false,\n });\n return finalized;\n }\n catch (_err) {\n throw new Error(\"Error converting schema to JSON.\");\n }\n}\nfunction isTransforming(_schema, _ctx) {\n const ctx = _ctx ?? { seen: new Set() };\n if (ctx.seen.has(_schema))\n return false;\n ctx.seen.add(_schema);\n const def = _schema._zod.def;\n if (def.type === \"transform\")\n return true;\n if (def.type === \"array\")\n return isTransforming(def.element, ctx);\n if (def.type === \"set\")\n return isTransforming(def.valueType, ctx);\n if (def.type === \"lazy\")\n return isTransforming(def.getter(), ctx);\n if (def.type === \"promise\" ||\n def.type === \"optional\" ||\n def.type === \"nonoptional\" ||\n def.type === \"nullable\" ||\n def.type === \"readonly\" ||\n def.type === \"default\" ||\n def.type === \"prefault\") {\n return isTransforming(def.innerType, ctx);\n }\n if (def.type === \"intersection\") {\n return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);\n }\n if (def.type === \"record\" || def.type === \"map\") {\n return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);\n }\n if (def.type === \"pipe\") {\n if (_schema._zod.traits.has(\"$ZodCodec\"))\n return true;\n return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);\n }\n if (def.type === \"object\") {\n for (const key in def.shape) {\n if (isTransforming(def.shape[key], ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"union\") {\n for (const option of def.options) {\n if (isTransforming(option, ctx))\n return true;\n }\n return false;\n }\n if (def.type === \"tuple\") {\n for (const item of def.items) {\n if (isTransforming(item, ctx))\n return true;\n }\n if (def.rest && isTransforming(def.rest, ctx))\n return true;\n return false;\n }\n return false;\n}\n/**\n * Creates a toJSONSchema method for a schema instance.\n * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing.\n */\nexport const createToJSONSchemaMethod = (schema, processors = {}) => (params) => {\n const ctx = initializeContext({ ...params, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\nexport const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {\n const { libraryOptions, target } = params ?? {};\n const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors });\n process(schema, ctx);\n extractDefs(ctx, schema);\n return finalize(ctx, schema);\n};\n","import { extractDefs, finalize, initializeContext, process, } from \"./to-json-schema.js\";\nimport { getEnumValues } from \"./util.js\";\nconst formatMap = {\n guid: \"uuid\",\n url: \"uri\",\n datetime: \"date-time\",\n json_string: \"json-string\",\n regex: \"\", // do not set\n};\n// ==================== SIMPLE TYPE PROCESSORS ====================\nexport const stringProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n json.type = \"string\";\n const { minimum, maximum, format, patterns, contentEncoding } = schema._zod\n .bag;\n if (typeof minimum === \"number\")\n json.minLength = minimum;\n if (typeof maximum === \"number\")\n json.maxLength = maximum;\n // custom pattern overrides format\n if (format) {\n json.format = formatMap[format] ?? format;\n if (json.format === \"\")\n delete json.format; // empty format is not valid\n // JSON Schema format: \"time\" requires a full time with offset or Z\n // z.iso.time() does not include timezone information, so format: \"time\" should never be used\n if (format === \"time\") {\n delete json.format;\n }\n }\n if (contentEncoding)\n json.contentEncoding = contentEncoding;\n if (patterns && patterns.size > 0) {\n const regexes = [...patterns];\n if (regexes.length === 1)\n json.pattern = regexes[0].source;\n else if (regexes.length > 1) {\n json.allOf = [\n ...regexes.map((regex) => ({\n ...(ctx.target === \"draft-07\" || ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\"\n ? { type: \"string\" }\n : {}),\n pattern: regex.source,\n })),\n ];\n }\n }\n};\nexport const numberProcessor = (schema, ctx, _json, _params) => {\n const json = _json;\n const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;\n if (typeof format === \"string\" && format.includes(\"int\"))\n json.type = \"integer\";\n else\n json.type = \"number\";\n // when both minimum and exclusiveMinimum exist, pick the more restrictive one\n const exMin = typeof exclusiveMinimum === \"number\" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);\n const exMax = typeof exclusiveMaximum === \"number\" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);\n const legacy = ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\";\n if (exMin) {\n if (legacy) {\n json.minimum = exclusiveMinimum;\n json.exclusiveMinimum = true;\n }\n else {\n json.exclusiveMinimum = exclusiveMinimum;\n }\n }\n else if (typeof minimum === \"number\") {\n json.minimum = minimum;\n }\n if (exMax) {\n if (legacy) {\n json.maximum = exclusiveMaximum;\n json.exclusiveMaximum = true;\n }\n else {\n json.exclusiveMaximum = exclusiveMaximum;\n }\n }\n else if (typeof maximum === \"number\") {\n json.maximum = maximum;\n }\n if (typeof multipleOf === \"number\")\n json.multipleOf = multipleOf;\n};\nexport const booleanProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const bigintProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt cannot be represented in JSON Schema\");\n }\n};\nexport const symbolProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Symbols cannot be represented in JSON Schema\");\n }\n};\nexport const nullProcessor = (_schema, ctx, json, _params) => {\n if (ctx.target === \"openapi-3.0\") {\n json.type = \"string\";\n json.nullable = true;\n json.enum = [null];\n }\n else {\n json.type = \"null\";\n }\n};\nexport const undefinedProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Undefined cannot be represented in JSON Schema\");\n }\n};\nexport const voidProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Void cannot be represented in JSON Schema\");\n }\n};\nexport const neverProcessor = (_schema, _ctx, json, _params) => {\n json.not = {};\n};\nexport const anyProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const unknownProcessor = (_schema, _ctx, _json, _params) => {\n // empty schema accepts anything\n};\nexport const dateProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Date cannot be represented in JSON Schema\");\n }\n};\nexport const enumProcessor = (schema, _ctx, json, _params) => {\n const def = schema._zod.def;\n const values = getEnumValues(def.entries);\n // Number enums can have both string and number values\n if (values.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (values.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n json.enum = values;\n};\nexport const literalProcessor = (schema, ctx, json, _params) => {\n const def = schema._zod.def;\n const vals = [];\n for (const val of def.values) {\n if (val === undefined) {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Literal `undefined` cannot be represented in JSON Schema\");\n }\n else {\n // do not add to vals\n }\n }\n else if (typeof val === \"bigint\") {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"BigInt literals cannot be represented in JSON Schema\");\n }\n else {\n vals.push(Number(val));\n }\n }\n else {\n vals.push(val);\n }\n }\n if (vals.length === 0) {\n // do nothing (an undefined literal was stripped)\n }\n else if (vals.length === 1) {\n const val = vals[0];\n json.type = val === null ? \"null\" : typeof val;\n if (ctx.target === \"draft-04\" || ctx.target === \"openapi-3.0\") {\n json.enum = [val];\n }\n else {\n json.const = val;\n }\n }\n else {\n if (vals.every((v) => typeof v === \"number\"))\n json.type = \"number\";\n if (vals.every((v) => typeof v === \"string\"))\n json.type = \"string\";\n if (vals.every((v) => typeof v === \"boolean\"))\n json.type = \"boolean\";\n if (vals.every((v) => v === null))\n json.type = \"null\";\n json.enum = vals;\n }\n};\nexport const nanProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"NaN cannot be represented in JSON Schema\");\n }\n};\nexport const templateLiteralProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const pattern = schema._zod.pattern;\n if (!pattern)\n throw new Error(\"Pattern not found in template literal\");\n _json.type = \"string\";\n _json.pattern = pattern.source;\n};\nexport const fileProcessor = (schema, _ctx, json, _params) => {\n const _json = json;\n const file = {\n type: \"string\",\n format: \"binary\",\n contentEncoding: \"binary\",\n };\n const { minimum, maximum, mime } = schema._zod.bag;\n if (minimum !== undefined)\n file.minLength = minimum;\n if (maximum !== undefined)\n file.maxLength = maximum;\n if (mime) {\n if (mime.length === 1) {\n file.contentMediaType = mime[0];\n Object.assign(_json, file);\n }\n else {\n Object.assign(_json, file); // shared props at root\n _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs\n }\n }\n else {\n Object.assign(_json, file);\n }\n};\nexport const successProcessor = (_schema, _ctx, json, _params) => {\n json.type = \"boolean\";\n};\nexport const customProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Custom types cannot be represented in JSON Schema\");\n }\n};\nexport const functionProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Function types cannot be represented in JSON Schema\");\n }\n};\nexport const transformProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Transforms cannot be represented in JSON Schema\");\n }\n};\nexport const mapProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Map cannot be represented in JSON Schema\");\n }\n};\nexport const setProcessor = (_schema, ctx, _json, _params) => {\n if (ctx.unrepresentable === \"throw\") {\n throw new Error(\"Set cannot be represented in JSON Schema\");\n }\n};\n// ==================== COMPOSITE TYPE PROCESSORS ====================\nexport const arrayProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n json.type = \"array\";\n json.items = process(def.element, ctx, {\n ...params,\n path: [...params.path, \"items\"],\n });\n};\nexport const objectProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n json.properties = {};\n const shape = def.shape;\n for (const key in shape) {\n json.properties[key] = process(shape[key], ctx, {\n ...params,\n path: [...params.path, \"properties\", key],\n });\n }\n // required keys\n const allKeys = new Set(Object.keys(shape));\n const requiredKeys = new Set([...allKeys].filter((key) => {\n const v = def.shape[key]._zod;\n if (ctx.io === \"input\") {\n return v.optin === undefined;\n }\n else {\n return v.optout === undefined;\n }\n }));\n if (requiredKeys.size > 0) {\n json.required = Array.from(requiredKeys);\n }\n // catchall\n if (def.catchall?._zod.def.type === \"never\") {\n // strict\n json.additionalProperties = false;\n }\n else if (!def.catchall) {\n // regular\n if (ctx.io === \"output\")\n json.additionalProperties = false;\n }\n else if (def.catchall) {\n json.additionalProperties = process(def.catchall, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n};\nexport const unionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches)\n // This includes both z.xor() and discriminated unions\n const isExclusive = def.inclusive === false;\n const options = def.options.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, isExclusive ? \"oneOf\" : \"anyOf\", i],\n }));\n if (isExclusive) {\n json.oneOf = options;\n }\n else {\n json.anyOf = options;\n }\n};\nexport const intersectionProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const a = process(def.left, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 0],\n });\n const b = process(def.right, ctx, {\n ...params,\n path: [...params.path, \"allOf\", 1],\n });\n const isSimpleIntersection = (val) => \"allOf\" in val && Object.keys(val).length === 1;\n const allOf = [\n ...(isSimpleIntersection(a) ? a.allOf : [a]),\n ...(isSimpleIntersection(b) ? b.allOf : [b]),\n ];\n json.allOf = allOf;\n};\nexport const tupleProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"array\";\n const prefixPath = ctx.target === \"draft-2020-12\" ? \"prefixItems\" : \"items\";\n const restPath = ctx.target === \"draft-2020-12\" ? \"items\" : ctx.target === \"openapi-3.0\" ? \"items\" : \"additionalItems\";\n const prefixItems = def.items.map((x, i) => process(x, ctx, {\n ...params,\n path: [...params.path, prefixPath, i],\n }));\n const rest = def.rest\n ? process(def.rest, ctx, {\n ...params,\n path: [...params.path, restPath, ...(ctx.target === \"openapi-3.0\" ? [def.items.length] : [])],\n })\n : null;\n if (ctx.target === \"draft-2020-12\") {\n json.prefixItems = prefixItems;\n if (rest) {\n json.items = rest;\n }\n }\n else if (ctx.target === \"openapi-3.0\") {\n json.items = {\n anyOf: prefixItems,\n };\n if (rest) {\n json.items.anyOf.push(rest);\n }\n json.minItems = prefixItems.length;\n if (!rest) {\n json.maxItems = prefixItems.length;\n }\n }\n else {\n json.items = prefixItems;\n if (rest) {\n json.additionalItems = rest;\n }\n }\n // length\n const { minimum, maximum } = schema._zod.bag;\n if (typeof minimum === \"number\")\n json.minItems = minimum;\n if (typeof maximum === \"number\")\n json.maxItems = maximum;\n};\nexport const recordProcessor = (schema, ctx, _json, params) => {\n const json = _json;\n const def = schema._zod.def;\n json.type = \"object\";\n // For looseRecord with regex patterns, use patternProperties\n // This correctly represents \"only validate keys matching the pattern\" semantics\n // and composes well with allOf (intersections)\n const keyType = def.keyType;\n const keyBag = keyType._zod.bag;\n const patterns = keyBag?.patterns;\n if (def.mode === \"loose\" && patterns && patterns.size > 0) {\n // Use patternProperties for looseRecord with regex patterns\n const valueSchema = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"patternProperties\", \"*\"],\n });\n json.patternProperties = {};\n for (const pattern of patterns) {\n json.patternProperties[pattern.source] = valueSchema;\n }\n }\n else {\n // Default behavior: use propertyNames + additionalProperties\n if (ctx.target === \"draft-07\" || ctx.target === \"draft-2020-12\") {\n json.propertyNames = process(def.keyType, ctx, {\n ...params,\n path: [...params.path, \"propertyNames\"],\n });\n }\n json.additionalProperties = process(def.valueType, ctx, {\n ...params,\n path: [...params.path, \"additionalProperties\"],\n });\n }\n // Add required for keys with discrete values (enum, literal, etc.)\n const keyValues = keyType._zod.values;\n if (keyValues) {\n const validKeyValues = [...keyValues].filter((v) => typeof v === \"string\" || typeof v === \"number\");\n if (validKeyValues.length > 0) {\n json.required = validKeyValues;\n }\n }\n};\nexport const nullableProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n const inner = process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n if (ctx.target === \"openapi-3.0\") {\n seen.ref = def.innerType;\n json.nullable = true;\n }\n else {\n json.anyOf = [inner, { type: \"null\" }];\n }\n};\nexport const nonoptionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const defaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.default = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const prefaultProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n if (ctx.io === \"input\")\n json._prefault = JSON.parse(JSON.stringify(def.defaultValue));\n};\nexport const catchProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n let catchValue;\n try {\n catchValue = def.catchValue(undefined);\n }\n catch {\n throw new Error(\"Dynamic catch values are not supported in JSON Schema\");\n }\n json.default = catchValue;\n};\nexport const pipeProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n const inIsTransform = def.in._zod.traits.has(\"$ZodTransform\");\n const innerType = ctx.io === \"input\" ? (inIsTransform ? def.out : def.in) : def.out;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\nexport const readonlyProcessor = (schema, ctx, json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n json.readOnly = true;\n};\nexport const promiseProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const optionalProcessor = (schema, ctx, _json, params) => {\n const def = schema._zod.def;\n process(def.innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = def.innerType;\n};\nexport const lazyProcessor = (schema, ctx, _json, params) => {\n const innerType = schema._zod.innerType;\n process(innerType, ctx, params);\n const seen = ctx.seen.get(schema);\n seen.ref = innerType;\n};\n// ==================== ALL PROCESSORS ====================\nexport const allProcessors = {\n string: stringProcessor,\n number: numberProcessor,\n boolean: booleanProcessor,\n bigint: bigintProcessor,\n symbol: symbolProcessor,\n null: nullProcessor,\n undefined: undefinedProcessor,\n void: voidProcessor,\n never: neverProcessor,\n any: anyProcessor,\n unknown: unknownProcessor,\n date: dateProcessor,\n enum: enumProcessor,\n literal: literalProcessor,\n nan: nanProcessor,\n template_literal: templateLiteralProcessor,\n file: fileProcessor,\n success: successProcessor,\n custom: customProcessor,\n function: functionProcessor,\n transform: transformProcessor,\n map: mapProcessor,\n set: setProcessor,\n array: arrayProcessor,\n object: objectProcessor,\n union: unionProcessor,\n intersection: intersectionProcessor,\n tuple: tupleProcessor,\n record: recordProcessor,\n nullable: nullableProcessor,\n nonoptional: nonoptionalProcessor,\n default: defaultProcessor,\n prefault: prefaultProcessor,\n catch: catchProcessor,\n pipe: pipeProcessor,\n readonly: readonlyProcessor,\n promise: promiseProcessor,\n optional: optionalProcessor,\n lazy: lazyProcessor,\n};\nexport function toJSONSchema(input, params) {\n if (\"_idmap\" in input) {\n // Registry case\n const registry = input;\n const ctx = initializeContext({ ...params, processors: allProcessors });\n const defs = {};\n // First pass: process all schemas to build the seen map\n for (const entry of registry._idmap.entries()) {\n const [_, schema] = entry;\n process(schema, ctx);\n }\n const schemas = {};\n const external = {\n registry,\n uri: params?.uri,\n defs,\n };\n // Update the context with external configuration\n ctx.external = external;\n // Second pass: emit each schema\n for (const entry of registry._idmap.entries()) {\n const [key, schema] = entry;\n extractDefs(ctx, schema);\n schemas[key] = finalize(ctx, schema);\n }\n if (Object.keys(defs).length > 0) {\n const defsSegment = ctx.target === \"draft-2020-12\" ? \"$defs\" : \"definitions\";\n schemas.__shared = {\n [defsSegment]: defs,\n };\n }\n return { schemas };\n }\n // Single schema case\n const ctx = initializeContext({ ...params, processors: allProcessors });\n process(input, ctx);\n extractDefs(ctx, input);\n return finalize(ctx, input);\n}\n","import * as core from \"../core/index.js\";\nimport * as schemas from \"./schemas.js\";\nexport const ZodISODateTime = /*@__PURE__*/ core.$constructor(\"ZodISODateTime\", (inst, def) => {\n core.$ZodISODateTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function datetime(params) {\n return core._isoDateTime(ZodISODateTime, params);\n}\nexport const ZodISODate = /*@__PURE__*/ core.$constructor(\"ZodISODate\", (inst, def) => {\n core.$ZodISODate.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function date(params) {\n return core._isoDate(ZodISODate, params);\n}\nexport const ZodISOTime = /*@__PURE__*/ core.$constructor(\"ZodISOTime\", (inst, def) => {\n core.$ZodISOTime.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function time(params) {\n return core._isoTime(ZodISOTime, params);\n}\nexport const ZodISODuration = /*@__PURE__*/ core.$constructor(\"ZodISODuration\", (inst, def) => {\n core.$ZodISODuration.init(inst, def);\n schemas.ZodStringFormat.init(inst, def);\n});\nexport function duration(params) {\n return core._isoDuration(ZodISODuration, params);\n}\n","import * as core from \"../core/index.js\";\nimport { $ZodError } from \"../core/index.js\";\nimport * as util from \"../core/util.js\";\nconst initializer = (inst, issues) => {\n $ZodError.init(inst, issues);\n inst.name = \"ZodError\";\n Object.defineProperties(inst, {\n format: {\n value: (mapper) => core.formatError(inst, mapper),\n // enumerable: false,\n },\n flatten: {\n value: (mapper) => core.flattenError(inst, mapper),\n // enumerable: false,\n },\n addIssue: {\n value: (issue) => {\n inst.issues.push(issue);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n addIssues: {\n value: (issues) => {\n inst.issues.push(...issues);\n inst.message = JSON.stringify(inst.issues, util.jsonStringifyReplacer, 2);\n },\n // enumerable: false,\n },\n isEmpty: {\n get() {\n return inst.issues.length === 0;\n },\n // enumerable: false,\n },\n });\n // Object.defineProperty(inst, \"isEmpty\", {\n // get() {\n // return inst.issues.length === 0;\n // },\n // });\n};\nexport const ZodError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer);\nexport const ZodRealError = /*@__PURE__*/ core.$constructor(\"ZodError\", initializer, {\n Parent: Error,\n});\n// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */\n// export type ErrorMapCtx = core.$ZodErrorMapCtx;\n","import * as core from \"../core/index.js\";\nimport { ZodRealError } from \"./errors.js\";\nexport const parse = /* @__PURE__ */ core._parse(ZodRealError);\nexport const parseAsync = /* @__PURE__ */ core._parseAsync(ZodRealError);\nexport const safeParse = /* @__PURE__ */ core._safeParse(ZodRealError);\nexport const safeParseAsync = /* @__PURE__ */ core._safeParseAsync(ZodRealError);\n// Codec functions\nexport const encode = /* @__PURE__ */ core._encode(ZodRealError);\nexport const decode = /* @__PURE__ */ core._decode(ZodRealError);\nexport const encodeAsync = /* @__PURE__ */ core._encodeAsync(ZodRealError);\nexport const decodeAsync = /* @__PURE__ */ core._decodeAsync(ZodRealError);\nexport const safeEncode = /* @__PURE__ */ core._safeEncode(ZodRealError);\nexport const safeDecode = /* @__PURE__ */ core._safeDecode(ZodRealError);\nexport const safeEncodeAsync = /* @__PURE__ */ core._safeEncodeAsync(ZodRealError);\nexport const safeDecodeAsync = /* @__PURE__ */ core._safeDecodeAsync(ZodRealError);\n","import * as core from \"../core/index.js\";\nimport { util } from \"../core/index.js\";\nimport * as processors from \"../core/json-schema-processors.js\";\nimport { createStandardJSONSchemaMethod, createToJSONSchemaMethod } from \"../core/to-json-schema.js\";\nimport * as checks from \"./checks.js\";\nimport * as iso from \"./iso.js\";\nimport * as parse from \"./parse.js\";\n// Lazy-bind builder methods.\n//\n// Builder methods (`.optional`, `.array`, `.refine`, ...) live as\n// non-enumerable getters on each concrete schema constructor's\n// prototype. On first access from an instance the getter allocates\n// `fn.bind(this)` and caches it as an own property on that instance,\n// so detached usage (`const m = schema.optional; m()`) still works\n// and the per-instance allocation only happens for methods actually\n// touched.\n//\n// One install per (prototype, group), memoized by `_installedGroups`.\nconst _installedGroups = /* @__PURE__ */ new WeakMap();\nfunction _installLazyMethods(inst, group, methods) {\n const proto = Object.getPrototypeOf(inst);\n let installed = _installedGroups.get(proto);\n if (!installed) {\n installed = new Set();\n _installedGroups.set(proto, installed);\n }\n if (installed.has(group))\n return;\n installed.add(group);\n for (const key in methods) {\n const fn = methods[key];\n Object.defineProperty(proto, key, {\n configurable: true,\n enumerable: false,\n get() {\n const bound = fn.bind(this);\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: bound,\n });\n return bound;\n },\n set(v) {\n Object.defineProperty(this, key, {\n configurable: true,\n writable: true,\n enumerable: true,\n value: v,\n });\n },\n });\n }\n}\nexport const ZodType = /*@__PURE__*/ core.$constructor(\"ZodType\", (inst, def) => {\n core.$ZodType.init(inst, def);\n Object.assign(inst[\"~standard\"], {\n jsonSchema: {\n input: createStandardJSONSchemaMethod(inst, \"input\"),\n output: createStandardJSONSchemaMethod(inst, \"output\"),\n },\n });\n inst.toJSONSchema = createToJSONSchemaMethod(inst, {});\n inst.def = def;\n inst.type = def.type;\n Object.defineProperty(inst, \"_def\", { value: def });\n // Parse-family is intentionally kept as per-instance closures: these are\n // the hot path AND the most-detached methods (`arr.map(schema.parse)`,\n // `const { parse } = schema`, etc.). Eager closures here mean callers pay\n // ~12 closure allocations per schema but get monomorphic call sites and\n // detached usage that \"just works\".\n inst.parse = (data, params) => parse.parse(inst, data, params, { callee: inst.parse });\n inst.safeParse = (data, params) => parse.safeParse(inst, data, params);\n inst.parseAsync = async (data, params) => parse.parseAsync(inst, data, params, { callee: inst.parseAsync });\n inst.safeParseAsync = async (data, params) => parse.safeParseAsync(inst, data, params);\n inst.spa = inst.safeParseAsync;\n inst.encode = (data, params) => parse.encode(inst, data, params);\n inst.decode = (data, params) => parse.decode(inst, data, params);\n inst.encodeAsync = async (data, params) => parse.encodeAsync(inst, data, params);\n inst.decodeAsync = async (data, params) => parse.decodeAsync(inst, data, params);\n inst.safeEncode = (data, params) => parse.safeEncode(inst, data, params);\n inst.safeDecode = (data, params) => parse.safeDecode(inst, data, params);\n inst.safeEncodeAsync = async (data, params) => parse.safeEncodeAsync(inst, data, params);\n inst.safeDecodeAsync = async (data, params) => parse.safeDecodeAsync(inst, data, params);\n // All builder methods are placed on the internal prototype as lazy-bind\n // getters. On first access per-instance, a bound thunk is allocated and\n // cached as an own property; subsequent accesses skip the getter. This\n // means: no per-instance allocation for unused methods, full\n // detachability preserved (`const m = schema.optional; m()` works), and\n // shared underlying function references across all instances.\n _installLazyMethods(inst, \"ZodType\", {\n check(...chks) {\n const def = this.def;\n return this.clone(util.mergeDefs(def, {\n checks: [\n ...(def.checks ?? []),\n ...chks.map((ch) => typeof ch === \"function\" ? { _zod: { check: ch, def: { check: \"custom\" }, onattach: [] } } : ch),\n ],\n }), { parent: true });\n },\n with(...chks) {\n return this.check(...chks);\n },\n clone(def, params) {\n return core.clone(this, def, params);\n },\n brand() {\n return this;\n },\n register(reg, meta) {\n reg.add(this, meta);\n return this;\n },\n refine(check, params) {\n return this.check(refine(check, params));\n },\n superRefine(refinement, params) {\n return this.check(superRefine(refinement, params));\n },\n overwrite(fn) {\n return this.check(checks.overwrite(fn));\n },\n optional() {\n return optional(this);\n },\n exactOptional() {\n return exactOptional(this);\n },\n nullable() {\n return nullable(this);\n },\n nullish() {\n return optional(nullable(this));\n },\n nonoptional(params) {\n return nonoptional(this, params);\n },\n array() {\n return array(this);\n },\n or(arg) {\n return union([this, arg]);\n },\n and(arg) {\n return intersection(this, arg);\n },\n transform(tx) {\n return pipe(this, transform(tx));\n },\n default(d) {\n return _default(this, d);\n },\n prefault(d) {\n return prefault(this, d);\n },\n catch(params) {\n return _catch(this, params);\n },\n pipe(target) {\n return pipe(this, target);\n },\n readonly() {\n return readonly(this);\n },\n describe(description) {\n const cl = this.clone();\n core.globalRegistry.add(cl, { description });\n return cl;\n },\n meta(...args) {\n // overloaded: meta() returns the registered metadata, meta(data)\n // returns a clone with `data` registered. The mapped type picks\n // up the second overload, so we accept variadic any-args and\n // return `any` to satisfy both at runtime.\n if (args.length === 0)\n return core.globalRegistry.get(this);\n const cl = this.clone();\n core.globalRegistry.add(cl, args[0]);\n return cl;\n },\n isOptional() {\n return this.safeParse(undefined).success;\n },\n isNullable() {\n return this.safeParse(null).success;\n },\n apply(fn) {\n return fn(this);\n },\n });\n Object.defineProperty(inst, \"description\", {\n get() {\n return core.globalRegistry.get(inst)?.description;\n },\n configurable: true,\n });\n return inst;\n});\n/** @internal */\nexport const _ZodString = /*@__PURE__*/ core.$constructor(\"_ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.stringProcessor(inst, ctx, json, params);\n const bag = inst._zod.bag;\n inst.format = bag.format ?? null;\n inst.minLength = bag.minimum ?? null;\n inst.maxLength = bag.maximum ?? null;\n _installLazyMethods(inst, \"_ZodString\", {\n regex(...args) {\n return this.check(checks.regex(...args));\n },\n includes(...args) {\n return this.check(checks.includes(...args));\n },\n startsWith(...args) {\n return this.check(checks.startsWith(...args));\n },\n endsWith(...args) {\n return this.check(checks.endsWith(...args));\n },\n min(...args) {\n return this.check(checks.minLength(...args));\n },\n max(...args) {\n return this.check(checks.maxLength(...args));\n },\n length(...args) {\n return this.check(checks.length(...args));\n },\n nonempty(...args) {\n return this.check(checks.minLength(1, ...args));\n },\n lowercase(params) {\n return this.check(checks.lowercase(params));\n },\n uppercase(params) {\n return this.check(checks.uppercase(params));\n },\n trim() {\n return this.check(checks.trim());\n },\n normalize(...args) {\n return this.check(checks.normalize(...args));\n },\n toLowerCase() {\n return this.check(checks.toLowerCase());\n },\n toUpperCase() {\n return this.check(checks.toUpperCase());\n },\n slugify() {\n return this.check(checks.slugify());\n },\n });\n});\nexport const ZodString = /*@__PURE__*/ core.$constructor(\"ZodString\", (inst, def) => {\n core.$ZodString.init(inst, def);\n _ZodString.init(inst, def);\n inst.email = (params) => inst.check(core._email(ZodEmail, params));\n inst.url = (params) => inst.check(core._url(ZodURL, params));\n inst.jwt = (params) => inst.check(core._jwt(ZodJWT, params));\n inst.emoji = (params) => inst.check(core._emoji(ZodEmoji, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.uuid = (params) => inst.check(core._uuid(ZodUUID, params));\n inst.uuidv4 = (params) => inst.check(core._uuidv4(ZodUUID, params));\n inst.uuidv6 = (params) => inst.check(core._uuidv6(ZodUUID, params));\n inst.uuidv7 = (params) => inst.check(core._uuidv7(ZodUUID, params));\n inst.nanoid = (params) => inst.check(core._nanoid(ZodNanoID, params));\n inst.guid = (params) => inst.check(core._guid(ZodGUID, params));\n inst.cuid = (params) => inst.check(core._cuid(ZodCUID, params));\n inst.cuid2 = (params) => inst.check(core._cuid2(ZodCUID2, params));\n inst.ulid = (params) => inst.check(core._ulid(ZodULID, params));\n inst.base64 = (params) => inst.check(core._base64(ZodBase64, params));\n inst.base64url = (params) => inst.check(core._base64url(ZodBase64URL, params));\n inst.xid = (params) => inst.check(core._xid(ZodXID, params));\n inst.ksuid = (params) => inst.check(core._ksuid(ZodKSUID, params));\n inst.ipv4 = (params) => inst.check(core._ipv4(ZodIPv4, params));\n inst.ipv6 = (params) => inst.check(core._ipv6(ZodIPv6, params));\n inst.cidrv4 = (params) => inst.check(core._cidrv4(ZodCIDRv4, params));\n inst.cidrv6 = (params) => inst.check(core._cidrv6(ZodCIDRv6, params));\n inst.e164 = (params) => inst.check(core._e164(ZodE164, params));\n // iso\n inst.datetime = (params) => inst.check(iso.datetime(params));\n inst.date = (params) => inst.check(iso.date(params));\n inst.time = (params) => inst.check(iso.time(params));\n inst.duration = (params) => inst.check(iso.duration(params));\n});\nexport function string(params) {\n return core._string(ZodString, params);\n}\nexport const ZodStringFormat = /*@__PURE__*/ core.$constructor(\"ZodStringFormat\", (inst, def) => {\n core.$ZodStringFormat.init(inst, def);\n _ZodString.init(inst, def);\n});\nexport const ZodEmail = /*@__PURE__*/ core.$constructor(\"ZodEmail\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmail.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function email(params) {\n return core._email(ZodEmail, params);\n}\nexport const ZodGUID = /*@__PURE__*/ core.$constructor(\"ZodGUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodGUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function guid(params) {\n return core._guid(ZodGUID, params);\n}\nexport const ZodUUID = /*@__PURE__*/ core.$constructor(\"ZodUUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodUUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function uuid(params) {\n return core._uuid(ZodUUID, params);\n}\nexport function uuidv4(params) {\n return core._uuidv4(ZodUUID, params);\n}\n// ZodUUIDv6\nexport function uuidv6(params) {\n return core._uuidv6(ZodUUID, params);\n}\n// ZodUUIDv7\nexport function uuidv7(params) {\n return core._uuidv7(ZodUUID, params);\n}\nexport const ZodURL = /*@__PURE__*/ core.$constructor(\"ZodURL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodURL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function url(params) {\n return core._url(ZodURL, params);\n}\nexport function httpUrl(params) {\n return core._url(ZodURL, {\n protocol: core.regexes.httpProtocol,\n hostname: core.regexes.domain,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEmoji = /*@__PURE__*/ core.$constructor(\"ZodEmoji\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodEmoji.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function emoji(params) {\n return core._emoji(ZodEmoji, params);\n}\nexport const ZodNanoID = /*@__PURE__*/ core.$constructor(\"ZodNanoID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodNanoID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function nanoid(params) {\n return core._nanoid(ZodNanoID, params);\n}\n/**\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link ZodCUID2} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport const ZodCUID = /*@__PURE__*/ core.$constructor(\"ZodCUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\n/**\n * Validates a CUID v1 string.\n *\n * @deprecated CUID v1 is deprecated by its authors due to information leakage\n * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead.\n * See https://github.com/paralleldrive/cuid.\n */\nexport function cuid(params) {\n return core._cuid(ZodCUID, params);\n}\nexport const ZodCUID2 = /*@__PURE__*/ core.$constructor(\"ZodCUID2\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCUID2.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cuid2(params) {\n return core._cuid2(ZodCUID2, params);\n}\nexport const ZodULID = /*@__PURE__*/ core.$constructor(\"ZodULID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodULID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ulid(params) {\n return core._ulid(ZodULID, params);\n}\nexport const ZodXID = /*@__PURE__*/ core.$constructor(\"ZodXID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodXID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function xid(params) {\n return core._xid(ZodXID, params);\n}\nexport const ZodKSUID = /*@__PURE__*/ core.$constructor(\"ZodKSUID\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodKSUID.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ksuid(params) {\n return core._ksuid(ZodKSUID, params);\n}\nexport const ZodIPv4 = /*@__PURE__*/ core.$constructor(\"ZodIPv4\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv4(params) {\n return core._ipv4(ZodIPv4, params);\n}\nexport const ZodMAC = /*@__PURE__*/ core.$constructor(\"ZodMAC\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodMAC.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function mac(params) {\n return core._mac(ZodMAC, params);\n}\nexport const ZodIPv6 = /*@__PURE__*/ core.$constructor(\"ZodIPv6\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodIPv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function ipv6(params) {\n return core._ipv6(ZodIPv6, params);\n}\nexport const ZodCIDRv4 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv4\", (inst, def) => {\n core.$ZodCIDRv4.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv4(params) {\n return core._cidrv4(ZodCIDRv4, params);\n}\nexport const ZodCIDRv6 = /*@__PURE__*/ core.$constructor(\"ZodCIDRv6\", (inst, def) => {\n core.$ZodCIDRv6.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function cidrv6(params) {\n return core._cidrv6(ZodCIDRv6, params);\n}\nexport const ZodBase64 = /*@__PURE__*/ core.$constructor(\"ZodBase64\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64(params) {\n return core._base64(ZodBase64, params);\n}\nexport const ZodBase64URL = /*@__PURE__*/ core.$constructor(\"ZodBase64URL\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodBase64URL.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function base64url(params) {\n return core._base64url(ZodBase64URL, params);\n}\nexport const ZodE164 = /*@__PURE__*/ core.$constructor(\"ZodE164\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodE164.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function e164(params) {\n return core._e164(ZodE164, params);\n}\nexport const ZodJWT = /*@__PURE__*/ core.$constructor(\"ZodJWT\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodJWT.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function jwt(params) {\n return core._jwt(ZodJWT, params);\n}\nexport const ZodCustomStringFormat = /*@__PURE__*/ core.$constructor(\"ZodCustomStringFormat\", (inst, def) => {\n // ZodStringFormat.init(inst, def);\n core.$ZodCustomStringFormat.init(inst, def);\n ZodStringFormat.init(inst, def);\n});\nexport function stringFormat(format, fnOrRegex, _params = {}) {\n return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);\n}\nexport function hostname(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hostname\", core.regexes.hostname, _params);\n}\nexport function hex(_params) {\n return core._stringFormat(ZodCustomStringFormat, \"hex\", core.regexes.hex, _params);\n}\nexport function hash(alg, params) {\n const enc = params?.enc ?? \"hex\";\n const format = `${alg}_${enc}`;\n const regex = core.regexes[format];\n if (!regex)\n throw new Error(`Unrecognized hash format: ${format}`);\n return core._stringFormat(ZodCustomStringFormat, format, regex, params);\n}\nexport const ZodNumber = /*@__PURE__*/ core.$constructor(\"ZodNumber\", (inst, def) => {\n core.$ZodNumber.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.numberProcessor(inst, ctx, json, params);\n _installLazyMethods(inst, \"ZodNumber\", {\n gt(value, params) {\n return this.check(checks.gt(value, params));\n },\n gte(value, params) {\n return this.check(checks.gte(value, params));\n },\n min(value, params) {\n return this.check(checks.gte(value, params));\n },\n lt(value, params) {\n return this.check(checks.lt(value, params));\n },\n lte(value, params) {\n return this.check(checks.lte(value, params));\n },\n max(value, params) {\n return this.check(checks.lte(value, params));\n },\n int(params) {\n return this.check(int(params));\n },\n safe(params) {\n return this.check(int(params));\n },\n positive(params) {\n return this.check(checks.gt(0, params));\n },\n nonnegative(params) {\n return this.check(checks.gte(0, params));\n },\n negative(params) {\n return this.check(checks.lt(0, params));\n },\n nonpositive(params) {\n return this.check(checks.lte(0, params));\n },\n multipleOf(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n step(value, params) {\n return this.check(checks.multipleOf(value, params));\n },\n finite() {\n return this;\n },\n });\n const bag = inst._zod.bag;\n inst.minValue =\n Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;\n inst.maxValue =\n Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;\n inst.isInt = (bag.format ?? \"\").includes(\"int\") || Number.isSafeInteger(bag.multipleOf ?? 0.5);\n inst.isFinite = true;\n inst.format = bag.format ?? null;\n});\nexport function number(params) {\n return core._number(ZodNumber, params);\n}\nexport const ZodNumberFormat = /*@__PURE__*/ core.$constructor(\"ZodNumberFormat\", (inst, def) => {\n core.$ZodNumberFormat.init(inst, def);\n ZodNumber.init(inst, def);\n});\nexport function int(params) {\n return core._int(ZodNumberFormat, params);\n}\nexport function float32(params) {\n return core._float32(ZodNumberFormat, params);\n}\nexport function float64(params) {\n return core._float64(ZodNumberFormat, params);\n}\nexport function int32(params) {\n return core._int32(ZodNumberFormat, params);\n}\nexport function uint32(params) {\n return core._uint32(ZodNumberFormat, params);\n}\nexport const ZodBoolean = /*@__PURE__*/ core.$constructor(\"ZodBoolean\", (inst, def) => {\n core.$ZodBoolean.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.booleanProcessor(inst, ctx, json, params);\n});\nexport function boolean(params) {\n return core._boolean(ZodBoolean, params);\n}\nexport const ZodBigInt = /*@__PURE__*/ core.$constructor(\"ZodBigInt\", (inst, def) => {\n core.$ZodBigInt.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params);\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.gt = (value, params) => inst.check(checks.gt(value, params));\n inst.gte = (value, params) => inst.check(checks.gte(value, params));\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.lt = (value, params) => inst.check(checks.lt(value, params));\n inst.lte = (value, params) => inst.check(checks.lte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n inst.positive = (params) => inst.check(checks.gt(BigInt(0), params));\n inst.negative = (params) => inst.check(checks.lt(BigInt(0), params));\n inst.nonpositive = (params) => inst.check(checks.lte(BigInt(0), params));\n inst.nonnegative = (params) => inst.check(checks.gte(BigInt(0), params));\n inst.multipleOf = (value, params) => inst.check(checks.multipleOf(value, params));\n const bag = inst._zod.bag;\n inst.minValue = bag.minimum ?? null;\n inst.maxValue = bag.maximum ?? null;\n inst.format = bag.format ?? null;\n});\nexport function bigint(params) {\n return core._bigint(ZodBigInt, params);\n}\nexport const ZodBigIntFormat = /*@__PURE__*/ core.$constructor(\"ZodBigIntFormat\", (inst, def) => {\n core.$ZodBigIntFormat.init(inst, def);\n ZodBigInt.init(inst, def);\n});\n// int64\nexport function int64(params) {\n return core._int64(ZodBigIntFormat, params);\n}\n// uint64\nexport function uint64(params) {\n return core._uint64(ZodBigIntFormat, params);\n}\nexport const ZodSymbol = /*@__PURE__*/ core.$constructor(\"ZodSymbol\", (inst, def) => {\n core.$ZodSymbol.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params);\n});\nexport function symbol(params) {\n return core._symbol(ZodSymbol, params);\n}\nexport const ZodUndefined = /*@__PURE__*/ core.$constructor(\"ZodUndefined\", (inst, def) => {\n core.$ZodUndefined.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params);\n});\nfunction _undefined(params) {\n return core._undefined(ZodUndefined, params);\n}\nexport { _undefined as undefined };\nexport const ZodNull = /*@__PURE__*/ core.$constructor(\"ZodNull\", (inst, def) => {\n core.$ZodNull.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullProcessor(inst, ctx, json, params);\n});\nfunction _null(params) {\n return core._null(ZodNull, params);\n}\nexport { _null as null };\nexport const ZodAny = /*@__PURE__*/ core.$constructor(\"ZodAny\", (inst, def) => {\n core.$ZodAny.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.anyProcessor(inst, ctx, json, params);\n});\nexport function any() {\n return core._any(ZodAny);\n}\nexport const ZodUnknown = /*@__PURE__*/ core.$constructor(\"ZodUnknown\", (inst, def) => {\n core.$ZodUnknown.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unknownProcessor(inst, ctx, json, params);\n});\nexport function unknown() {\n return core._unknown(ZodUnknown);\n}\nexport const ZodNever = /*@__PURE__*/ core.$constructor(\"ZodNever\", (inst, def) => {\n core.$ZodNever.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.neverProcessor(inst, ctx, json, params);\n});\nexport function never(params) {\n return core._never(ZodNever, params);\n}\nexport const ZodVoid = /*@__PURE__*/ core.$constructor(\"ZodVoid\", (inst, def) => {\n core.$ZodVoid.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params);\n});\nfunction _void(params) {\n return core._void(ZodVoid, params);\n}\nexport { _void as void };\nexport const ZodDate = /*@__PURE__*/ core.$constructor(\"ZodDate\", (inst, def) => {\n core.$ZodDate.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params);\n inst.min = (value, params) => inst.check(checks.gte(value, params));\n inst.max = (value, params) => inst.check(checks.lte(value, params));\n const c = inst._zod.bag;\n inst.minDate = c.minimum ? new Date(c.minimum) : null;\n inst.maxDate = c.maximum ? new Date(c.maximum) : null;\n});\nexport function date(params) {\n return core._date(ZodDate, params);\n}\nexport const ZodArray = /*@__PURE__*/ core.$constructor(\"ZodArray\", (inst, def) => {\n core.$ZodArray.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.arrayProcessor(inst, ctx, json, params);\n inst.element = def.element;\n _installLazyMethods(inst, \"ZodArray\", {\n min(n, params) {\n return this.check(checks.minLength(n, params));\n },\n nonempty(params) {\n return this.check(checks.minLength(1, params));\n },\n max(n, params) {\n return this.check(checks.maxLength(n, params));\n },\n length(n, params) {\n return this.check(checks.length(n, params));\n },\n unwrap() {\n return this.element;\n },\n });\n});\nexport function array(element, params) {\n return core._array(ZodArray, element, params);\n}\n// .keyof\nexport function keyof(schema) {\n const shape = schema._zod.def.shape;\n return _enum(Object.keys(shape));\n}\nexport const ZodObject = /*@__PURE__*/ core.$constructor(\"ZodObject\", (inst, def) => {\n core.$ZodObjectJIT.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.objectProcessor(inst, ctx, json, params);\n util.defineLazy(inst, \"shape\", () => {\n return def.shape;\n });\n _installLazyMethods(inst, \"ZodObject\", {\n keyof() {\n return _enum(Object.keys(this._zod.def.shape));\n },\n catchall(catchall) {\n return this.clone({ ...this._zod.def, catchall: catchall });\n },\n passthrough() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n loose() {\n return this.clone({ ...this._zod.def, catchall: unknown() });\n },\n strict() {\n return this.clone({ ...this._zod.def, catchall: never() });\n },\n strip() {\n return this.clone({ ...this._zod.def, catchall: undefined });\n },\n extend(incoming) {\n return util.extend(this, incoming);\n },\n safeExtend(incoming) {\n return util.safeExtend(this, incoming);\n },\n merge(other) {\n return util.merge(this, other);\n },\n pick(mask) {\n return util.pick(this, mask);\n },\n omit(mask) {\n return util.omit(this, mask);\n },\n partial(...args) {\n return util.partial(ZodOptional, this, args[0]);\n },\n required(...args) {\n return util.required(ZodNonOptional, this, args[0]);\n },\n });\n});\nexport function object(shape, params) {\n const def = {\n type: \"object\",\n shape: shape ?? {},\n ...util.normalizeParams(params),\n };\n return new ZodObject(def);\n}\n// strictObject\nexport function strictObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: never(),\n ...util.normalizeParams(params),\n });\n}\n// looseObject\nexport function looseObject(shape, params) {\n return new ZodObject({\n type: \"object\",\n shape,\n catchall: unknown(),\n ...util.normalizeParams(params),\n });\n}\nexport const ZodUnion = /*@__PURE__*/ core.$constructor(\"ZodUnion\", (inst, def) => {\n core.$ZodUnion.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\nexport function union(options, params) {\n return new ZodUnion({\n type: \"union\",\n options: options,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodXor = /*@__PURE__*/ core.$constructor(\"ZodXor\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodXor.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params);\n inst.options = def.options;\n});\n/** Creates an exclusive union (XOR) where exactly one option must match.\n * Unlike regular unions that succeed when any option matches, xor fails if\n * zero or more than one option matches the input. */\nexport function xor(options, params) {\n return new ZodXor({\n type: \"union\",\n options: options,\n inclusive: false,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodDiscriminatedUnion = /*@__PURE__*/ core.$constructor(\"ZodDiscriminatedUnion\", (inst, def) => {\n ZodUnion.init(inst, def);\n core.$ZodDiscriminatedUnion.init(inst, def);\n});\nexport function discriminatedUnion(discriminator, options, params) {\n // const [options, params] = args;\n return new ZodDiscriminatedUnion({\n type: \"union\",\n options,\n discriminator,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodIntersection = /*@__PURE__*/ core.$constructor(\"ZodIntersection\", (inst, def) => {\n core.$ZodIntersection.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.intersectionProcessor(inst, ctx, json, params);\n});\nexport function intersection(left, right) {\n return new ZodIntersection({\n type: \"intersection\",\n left: left,\n right: right,\n });\n}\nexport const ZodTuple = /*@__PURE__*/ core.$constructor(\"ZodTuple\", (inst, def) => {\n core.$ZodTuple.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params);\n inst.rest = (rest) => inst.clone({\n ...inst._zod.def,\n rest: rest,\n });\n});\nexport function tuple(items, _paramsOrRest, _params) {\n const hasRest = _paramsOrRest instanceof core.$ZodType;\n const params = hasRest ? _params : _paramsOrRest;\n const rest = hasRest ? _paramsOrRest : null;\n return new ZodTuple({\n type: \"tuple\",\n items: items,\n rest,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodRecord = /*@__PURE__*/ core.$constructor(\"ZodRecord\", (inst, def) => {\n core.$ZodRecord.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.recordProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n});\nexport function record(keyType, valueType, params) {\n // v3-compat: z.record(valueType, params?) — defaults keyType to z.string()\n if (!valueType || !valueType._zod) {\n return new ZodRecord({\n type: \"record\",\n keyType: string(),\n valueType: keyType,\n ...util.normalizeParams(valueType),\n });\n }\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\n// type alksjf = core.output<core.$ZodRecordKey>;\nexport function partialRecord(keyType, valueType, params) {\n const k = core.clone(keyType);\n k._zod.values = undefined;\n return new ZodRecord({\n type: \"record\",\n keyType: k,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport function looseRecord(keyType, valueType, params) {\n return new ZodRecord({\n type: \"record\",\n keyType,\n valueType: valueType,\n mode: \"loose\",\n ...util.normalizeParams(params),\n });\n}\nexport const ZodMap = /*@__PURE__*/ core.$constructor(\"ZodMap\", (inst, def) => {\n core.$ZodMap.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params);\n inst.keyType = def.keyType;\n inst.valueType = def.valueType;\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function map(keyType, valueType, params) {\n return new ZodMap({\n type: \"map\",\n keyType: keyType,\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSet = /*@__PURE__*/ core.$constructor(\"ZodSet\", (inst, def) => {\n core.$ZodSet.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params);\n inst.min = (...args) => inst.check(core._minSize(...args));\n inst.nonempty = (params) => inst.check(core._minSize(1, params));\n inst.max = (...args) => inst.check(core._maxSize(...args));\n inst.size = (...args) => inst.check(core._size(...args));\n});\nexport function set(valueType, params) {\n return new ZodSet({\n type: \"set\",\n valueType: valueType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodEnum = /*@__PURE__*/ core.$constructor(\"ZodEnum\", (inst, def) => {\n core.$ZodEnum.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.enumProcessor(inst, ctx, json, params);\n inst.enum = def.entries;\n inst.options = Object.values(def.entries);\n const keys = new Set(Object.keys(def.entries));\n inst.extract = (values, params) => {\n const newEntries = {};\n for (const value of values) {\n if (keys.has(value)) {\n newEntries[value] = def.entries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n inst.exclude = (values, params) => {\n const newEntries = { ...def.entries };\n for (const value of values) {\n if (keys.has(value)) {\n delete newEntries[value];\n }\n else\n throw new Error(`Key ${value} not found in enum`);\n }\n return new ZodEnum({\n ...def,\n checks: [],\n ...util.normalizeParams(params),\n entries: newEntries,\n });\n };\n});\nfunction _enum(values, params) {\n const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport { _enum as enum };\n/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead.\n *\n * ```ts\n * enum Colors { red, green, blue }\n * z.enum(Colors);\n * ```\n */\nexport function nativeEnum(entries, params) {\n return new ZodEnum({\n type: \"enum\",\n entries,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLiteral = /*@__PURE__*/ core.$constructor(\"ZodLiteral\", (inst, def) => {\n core.$ZodLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.literalProcessor(inst, ctx, json, params);\n inst.values = new Set(def.values);\n Object.defineProperty(inst, \"value\", {\n get() {\n if (def.values.length > 1) {\n throw new Error(\"This schema contains multiple valid literal values. Use `.values` instead.\");\n }\n return def.values[0];\n },\n });\n});\nexport function literal(value, params) {\n return new ZodLiteral({\n type: \"literal\",\n values: Array.isArray(value) ? value : [value],\n ...util.normalizeParams(params),\n });\n}\nexport const ZodFile = /*@__PURE__*/ core.$constructor(\"ZodFile\", (inst, def) => {\n core.$ZodFile.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params);\n inst.min = (size, params) => inst.check(core._minSize(size, params));\n inst.max = (size, params) => inst.check(core._maxSize(size, params));\n inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params));\n});\nexport function file(params) {\n return core._file(ZodFile, params);\n}\nexport const ZodTransform = /*@__PURE__*/ core.$constructor(\"ZodTransform\", (inst, def) => {\n core.$ZodTransform.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.transformProcessor(inst, ctx, json, params);\n inst._zod.parse = (payload, _ctx) => {\n if (_ctx.direction === \"backward\") {\n throw new core.$ZodEncodeError(inst.constructor.name);\n }\n payload.addIssue = (issue) => {\n if (typeof issue === \"string\") {\n payload.issues.push(util.issue(issue, payload.value, def));\n }\n else {\n // for Zod 3 backwards compatibility\n const _issue = issue;\n if (_issue.fatal)\n _issue.continue = false;\n _issue.code ?? (_issue.code = \"custom\");\n _issue.input ?? (_issue.input = payload.value);\n _issue.inst ?? (_issue.inst = inst);\n // _issue.continue ??= true;\n payload.issues.push(util.issue(_issue));\n }\n };\n const output = def.transform(payload.value, payload);\n if (output instanceof Promise) {\n return output.then((output) => {\n payload.value = output;\n payload.fallback = true;\n return payload;\n });\n }\n payload.value = output;\n payload.fallback = true;\n return payload;\n };\n});\nexport function transform(fn) {\n return new ZodTransform({\n type: \"transform\",\n transform: fn,\n });\n}\nexport const ZodOptional = /*@__PURE__*/ core.$constructor(\"ZodOptional\", (inst, def) => {\n core.$ZodOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function optional(innerType) {\n return new ZodOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodExactOptional = /*@__PURE__*/ core.$constructor(\"ZodExactOptional\", (inst, def) => {\n core.$ZodExactOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.optionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function exactOptional(innerType) {\n return new ZodExactOptional({\n type: \"optional\",\n innerType: innerType,\n });\n}\nexport const ZodNullable = /*@__PURE__*/ core.$constructor(\"ZodNullable\", (inst, def) => {\n core.$ZodNullable.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nullableProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nullable(innerType) {\n return new ZodNullable({\n type: \"nullable\",\n innerType: innerType,\n });\n}\n// nullish\nexport function nullish(innerType) {\n return optional(nullable(innerType));\n}\nexport const ZodDefault = /*@__PURE__*/ core.$constructor(\"ZodDefault\", (inst, def) => {\n core.$ZodDefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.defaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeDefault = inst.unwrap;\n});\nexport function _default(innerType, defaultValue) {\n return new ZodDefault({\n type: \"default\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodPrefault = /*@__PURE__*/ core.$constructor(\"ZodPrefault\", (inst, def) => {\n core.$ZodPrefault.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.prefaultProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function prefault(innerType, defaultValue) {\n return new ZodPrefault({\n type: \"prefault\",\n innerType: innerType,\n get defaultValue() {\n return typeof defaultValue === \"function\" ? defaultValue() : util.shallowClone(defaultValue);\n },\n });\n}\nexport const ZodNonOptional = /*@__PURE__*/ core.$constructor(\"ZodNonOptional\", (inst, def) => {\n core.$ZodNonOptional.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nonoptionalProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function nonoptional(innerType, params) {\n return new ZodNonOptional({\n type: \"nonoptional\",\n innerType: innerType,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodSuccess = /*@__PURE__*/ core.$constructor(\"ZodSuccess\", (inst, def) => {\n core.$ZodSuccess.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function success(innerType) {\n return new ZodSuccess({\n type: \"success\",\n innerType: innerType,\n });\n}\nexport const ZodCatch = /*@__PURE__*/ core.$constructor(\"ZodCatch\", (inst, def) => {\n core.$ZodCatch.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.catchProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n inst.removeCatch = inst.unwrap;\n});\nfunction _catch(innerType, catchValue) {\n return new ZodCatch({\n type: \"catch\",\n innerType: innerType,\n catchValue: (typeof catchValue === \"function\" ? catchValue : () => catchValue),\n });\n}\nexport { _catch as catch };\nexport const ZodNaN = /*@__PURE__*/ core.$constructor(\"ZodNaN\", (inst, def) => {\n core.$ZodNaN.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params);\n});\nexport function nan(params) {\n return core._nan(ZodNaN, params);\n}\nexport const ZodPipe = /*@__PURE__*/ core.$constructor(\"ZodPipe\", (inst, def) => {\n core.$ZodPipe.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.pipeProcessor(inst, ctx, json, params);\n inst.in = def.in;\n inst.out = def.out;\n});\nexport function pipe(in_, out) {\n return new ZodPipe({\n type: \"pipe\",\n in: in_,\n out: out,\n // ...util.normalizeParams(params),\n });\n}\nexport const ZodCodec = /*@__PURE__*/ core.$constructor(\"ZodCodec\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodCodec.init(inst, def);\n});\nexport function codec(in_, out, params) {\n return new ZodCodec({\n type: \"pipe\",\n in: in_,\n out: out,\n transform: params.decode,\n reverseTransform: params.encode,\n });\n}\nexport function invertCodec(codec) {\n const def = codec._zod.def;\n return new ZodCodec({\n type: \"pipe\",\n in: def.out,\n out: def.in,\n transform: def.reverseTransform,\n reverseTransform: def.transform,\n });\n}\nexport const ZodPreprocess = /*@__PURE__*/ core.$constructor(\"ZodPreprocess\", (inst, def) => {\n ZodPipe.init(inst, def);\n core.$ZodPreprocess.init(inst, def);\n});\nexport const ZodReadonly = /*@__PURE__*/ core.$constructor(\"ZodReadonly\", (inst, def) => {\n core.$ZodReadonly.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.readonlyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function readonly(innerType) {\n return new ZodReadonly({\n type: \"readonly\",\n innerType: innerType,\n });\n}\nexport const ZodTemplateLiteral = /*@__PURE__*/ core.$constructor(\"ZodTemplateLiteral\", (inst, def) => {\n core.$ZodTemplateLiteral.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params);\n});\nexport function templateLiteral(parts, params) {\n return new ZodTemplateLiteral({\n type: \"template_literal\",\n parts,\n ...util.normalizeParams(params),\n });\n}\nexport const ZodLazy = /*@__PURE__*/ core.$constructor(\"ZodLazy\", (inst, def) => {\n core.$ZodLazy.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.lazyProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.getter();\n});\nexport function lazy(getter) {\n return new ZodLazy({\n type: \"lazy\",\n getter: getter,\n });\n}\nexport const ZodPromise = /*@__PURE__*/ core.$constructor(\"ZodPromise\", (inst, def) => {\n core.$ZodPromise.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params);\n inst.unwrap = () => inst._zod.def.innerType;\n});\nexport function promise(innerType) {\n return new ZodPromise({\n type: \"promise\",\n innerType: innerType,\n });\n}\nexport const ZodFunction = /*@__PURE__*/ core.$constructor(\"ZodFunction\", (inst, def) => {\n core.$ZodFunction.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params);\n});\nexport function _function(params) {\n return new ZodFunction({\n type: \"function\",\n input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())),\n output: params?.output ?? unknown(),\n });\n}\nexport { _function as function };\nexport const ZodCustom = /*@__PURE__*/ core.$constructor(\"ZodCustom\", (inst, def) => {\n core.$ZodCustom.init(inst, def);\n ZodType.init(inst, def);\n inst._zod.processJSONSchema = (ctx, json, params) => processors.customProcessor(inst, ctx, json, params);\n});\n// custom checks\nexport function check(fn) {\n const ch = new core.$ZodCheck({\n check: \"custom\",\n // ...util.normalizeParams(params),\n });\n ch._zod.check = fn;\n return ch;\n}\nexport function custom(fn, _params) {\n return core._custom(ZodCustom, fn ?? (() => true), _params);\n}\nexport function refine(fn, _params = {}) {\n return core._refine(ZodCustom, fn, _params);\n}\n// superRefine\nexport function superRefine(fn, params) {\n return core._superRefine(fn, params);\n}\n// Re-export describe and meta from core\nexport const describe = core.describe;\nexport const meta = core.meta;\nfunction _instanceof(cls, params = {}) {\n const inst = new ZodCustom({\n type: \"custom\",\n check: \"custom\",\n fn: (data) => data instanceof cls,\n abort: true,\n ...util.normalizeParams(params),\n });\n inst._zod.bag.Class = cls;\n // Override check to emit invalid_type instead of custom\n inst._zod.check = (payload) => {\n if (!(payload.value instanceof cls)) {\n payload.issues.push({\n code: \"invalid_type\",\n expected: cls.name,\n input: payload.value,\n inst,\n path: [...(inst._zod.def.path ?? [])],\n });\n }\n };\n return inst;\n}\nexport { _instanceof as instanceof };\n// stringbool\nexport const stringbool = (...args) => core._stringbool({\n Codec: ZodCodec,\n Boolean: ZodBoolean,\n String: ZodString,\n}, ...args);\nexport function json(params) {\n const jsonSchema = lazy(() => {\n return union([string(params), number(), boolean(), _null(), array(jsonSchema), record(string(), jsonSchema)]);\n });\n return jsonSchema;\n}\n// preprocess\nexport function preprocess(fn, schema) {\n return new ZodPreprocess({\n type: \"pipe\",\n in: transform(fn),\n out: schema,\n });\n}\n","import { z } from 'zod'\n\nimport { MAX_CRON_LENGTH, parseCron } from './cron'\n\n// Mirrors the runtime's CONSENT_CATEGORIES (projects/worker/src/id-graph/consent.ts); the manifest\n// gate and the tag both key on these exact values.\nexport const CONSENT_CATEGORIES = ['necessary', 'functional', 'analytics', 'marketing', 'salesOfData'] as const\n\nexport const APP_FLOWS = ['transform', 'destination'] as const\n\nexport const TRANSFORM_ACTION_TYPES = ['track', 'identify'] as const\n\nexport const EVENT_ACTION_TYPES = ['track', 'identify', 'consent'] as const\n\nconst BROWSER_RESULT_ACTION_TYPES = ['track', 'identify'] as const\n\nexport const APP_LIFECYCLE_TYPES = ['installed', 'configurationChanged', 'enabled', 'disabled', 'versionChanged', 'uninstalled'] as const\n\nexport const API_CAPABILITIES = ['track', 'identify', 'alias', 'consentWrite', 'consentRead', 'propertiesRead', 'sessionRead'] as const\n\n// `sharedContext` is the one entry that authorizes a write as well as a read: it grants both halves\n// of the shared level, because what a site manager approves is that this app exchanges visitor data\n// with the other apps on the site, which is one decision rather than two.\nexport const DATA_CAPABILITIES = ['pii', 'customProperties', 'consentState', 'geo', 'eventContext', 'sharedContext'] as const\n\nexport const APP_RESOURCE_TYPES = [\n 'kv',\n 'd1',\n 'r2',\n 'durable_object',\n 'workflow',\n 'analytics_engine',\n 'ai',\n 'vectorize',\n 'hyperdrive'\n] as const\n\nexport const MAX_APP_VARIABLES = 32\nexport const MAX_APP_SCOPE_VARIABLES = 16\nexport const MAX_APP_SCHEDULES = 5\nexport const MAX_VARIABLE_HELP_TEXT = 280\nexport const MAX_CAPTURE_QUERY_PARAMS = 8\nexport const MAX_CAPTURE_COOKIES = 8\nexport const MAX_CAPTURE_NAME_LENGTH = 64\nconst MAX_PUBLISHED_TOPICS = 32\n// Bounded by the envelope's own topic cap, so a declarable topic is always a pushable one.\nconst MAX_EVENT_TOPIC_LENGTH = 64\n// The list is append-only for the life of the app, so these bound what a schema history may grow to,\n// never what one version holds. The byte cap is the binding one, and it spans the whole manifest: a\n// deploy unions this version with up to two retained ones into the engine's 5 MB manifest, so 1 MB\n// here leaves the worst-case union at 3 MB with room for the bindings and variables beside it.\nexport const MAX_D1_MIGRATIONS = 1000\nexport const MAX_D1_MIGRATION_LENGTH = 20_000\nexport const MAX_MANIFEST_MIGRATION_BYTES = 1024 * 1024\n\nexport const APP_SLUG_PATTERN = /^[a-z][a-z0-9-]{2,29}$/\n\nconst BINDING_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/\nconst CLASS_NAME = /^[A-Za-z_$][A-Za-z0-9_$]*$/\nconst IDENTIFIER = /^[a-z][a-z0-9-]*$/\nconst MIGRATION_ID = /^[a-z0-9][a-z0-9-]*$/\nconst VARIABLE_NAME = /^[A-Z][A-Z0-9_]*$/\nconst FUNCTION_NAME = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/\n// Colons and hyphens are the conventional separators in the topics apps already push (`order:synced`).\nconst EVENT_TOPIC = /^[a-z][a-z0-9:_-]*$/\n// Every real click id is this shape; anything needing percent-encoding to express is excluded.\nconst QUERY_PARAM_NAME = /^[A-Za-z0-9_.-]+$/\n// The RFC 6265 token class. Mirrors COOKIE_NAME_SHAPE in portal services' fallback-cookie-settings;\n// the manifest must not depend on that package, so the bound is restated here.\nconst COOKIE_NAME = /^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/\n\nconst RESERVED_CAPTURE_PREFIXES = ['q_', 'qinto'] as const\n\n// The only machine-checkable \"this cookie is security-scoped\" signal that exists.\nconst RESERVED_COOKIE_PREFIXES = ['__host-', '__secure-'] as const\n\n// Deliberately short and unambiguous. `code`, `state` and `token` are NOT here: `?code=SUMMER` and\n// `?state=CA` are ordinary marketing params, and a denylist that blocks them buys a false sense of\n// safety it cannot deliver. The real protections are the public manifest disclosure and the fact\n// that capture reads document.cookie, so an HttpOnly session cookie is structurally invisible.\nconst RESERVED_CAPTURE_NAMES = new Set([\n 'access_token',\n 'id_token',\n 'refresh_token',\n 'client_secret',\n 'api_key',\n 'apikey',\n 'password',\n 'jwt'\n])\n\nexport const PLATFORM_APP_BINDING_NAMES = {\n appContext: 'APP_CONTEXT',\n internalKey: 'QINTO_INTERNAL_KEY',\n installToken: 'QINTO_INSTALL_TOKEN',\n site: 'QINTO_SITE',\n siteNamespace: 'QINTO_SITE_NS',\n siteScript: 'QINTO_SITE_SCRIPT',\n platformApi: 'QINTO_PLATFORM_API',\n deployTarget: 'DEPLOY_TARGET'\n} as const\n\nexport const PLATFORM_APP_BINDINGS = Object.values(PLATFORM_APP_BINDING_NAMES)\n\nexport const PLATFORM_APP_RESOURCE_IDENTIFIERS = {\n appContext: 'app-context',\n internalKey: 'qinto-internal-key',\n installToken: 'qinto-install-token',\n site: 'qinto-site',\n siteNamespace: 'qinto-site-ns',\n siteScript: 'qinto-site-script',\n platformApi: 'qinto-platform-api'\n} as const\n\nexport const PLATFORM_APP_VARIABLE_IDENTIFIER_PREFIX = 'var-'\n\nexport const PLATFORM_APP_SCOPE_VARIABLE_IDENTIFIER_PREFIX = 'appvar-'\n\nconst httpsUrl = (field: string) => {\n return z\n .url()\n .max(2048)\n .refine((value) => value.startsWith('https://'), `${field} must be an HTTPS URL`)\n}\n\nconst legalUrl = (field: string) => {\n return httpsUrl(field).refine((value) => {\n const host = new URL(value).hostname\n return host !== 'qinto.io' && !host.endsWith('.qinto.io')\n }, `${field} must be the developer's own document, not a Qinto platform URL`)\n}\n\nconst bindingField = z.string().min(1).max(255).regex(BINDING_NAME)\nconst identifierField = z.string().min(1).max(64).regex(IDENTIFIER)\nconst migrationIdField = z.string().min(1).max(64).regex(MIGRATION_ID)\nconst classNameField = z.string().min(1).max(128).regex(CLASS_NAME)\n\nconst plainResource = <T extends (typeof APP_RESOURCE_TYPES)[number]>(type: T) => {\n return z.object({ type: z.literal(type), identifier: identifierField, binding: bindingField }).strict()\n}\n\n// Mirrors the engine's HYPERDRIVE_SCHEMES, VECTORIZE_METRICS, and MAX_VECTORIZE_DIMENSIONS\n// (libs/cloudflare); the manifest must not depend on the engine package, so the bounds are\n// restated here.\nconst HYPERDRIVE_SCHEMES = ['postgres', 'postgresql', 'mysql'] as const\n\nconst VECTORIZE_METRICS = ['cosine', 'euclidean', 'dot-product'] as const\n\nconst MAX_VECTORIZE_DIMENSIONS = 1536\n\nconst hyperdriveOrigin = z\n .object({\n scheme: z.enum(HYPERDRIVE_SCHEMES).default('postgres'),\n host: z.string().min(1).max(255),\n port: z.number().int().min(1).max(65535),\n database: z.string().min(1).max(255),\n user: z.string().min(1).max(255),\n // A literal password is rejected outright: the manifest is an immutable, readable snapshot.\n passwordVariable: z.string().regex(VARIABLE_NAME)\n })\n .strict()\n\nconst d1StatementMigration = z\n .object({\n id: migrationIdField,\n phase: z.enum(['expand', 'contract']),\n statements: z.array(z.string().min(1).max(MAX_D1_MIGRATION_LENGTH)).min(1).max(100)\n })\n .strict()\n\nconst d1BackfillMigration = z\n .object({ id: migrationIdField, phase: z.literal('backfill'), handler: z.string().min(1).max(128).regex(FUNCTION_NAME) })\n .strict()\n\nconst d1Resource = z\n .object({\n type: z.literal('d1'),\n identifier: identifierField,\n binding: bindingField,\n migrations: z\n .array(z.discriminatedUnion('phase', [d1StatementMigration, d1BackfillMigration]))\n .max(MAX_D1_MIGRATIONS)\n .default([])\n })\n .strict()\n .superRefine((resource, ctx) => {\n uniqueOrIssue(\n ctx,\n resource.migrations.map((migration) => migration.id),\n ['migrations'],\n 'migration id'\n )\n })\n\nconst resourceSchema = z.discriminatedUnion('type', [\n plainResource('kv'),\n d1Resource,\n plainResource('r2'),\n plainResource('analytics_engine'),\n plainResource('ai'),\n z\n .object({\n type: z.literal('vectorize'),\n identifier: identifierField,\n binding: bindingField,\n dimensions: z.number().int().min(1).max(MAX_VECTORIZE_DIMENSIONS),\n metric: z.enum(VECTORIZE_METRICS)\n })\n .strict(),\n z\n .object({\n type: z.literal('durable_object'),\n identifier: identifierField,\n binding: bindingField,\n className: classNameField\n })\n .strict(),\n z\n .object({\n type: z.literal('workflow'),\n identifier: identifierField,\n binding: bindingField,\n className: classNameField\n })\n .strict(),\n z.object({ type: z.literal('hyperdrive'), identifier: identifierField, binding: bindingField, origin: hyperdriveOrigin }).strict()\n])\n\nconst variableSchema = z\n .object({\n name: z.string().min(1).max(64).regex(VARIABLE_NAME),\n kind: z.enum(['plain', 'secret']),\n type: z.enum(['text', 'password', 'toggle']),\n label: z.string().min(1).max(100),\n required: z.boolean().optional(),\n browser: z.boolean().optional(),\n helpText: z.string().min(1).max(MAX_VARIABLE_HELP_TEXT).optional(),\n helpUrl: httpsUrl('helpUrl').optional()\n })\n .strict()\n .refine((variable) => !(variable.kind === 'secret' && variable.browser === true), {\n message: 'A secret variable can never be browser-exposed'\n })\n\n// No `browser` key and no `toggle` type: an app-scope value is delivered as one raw string binding,\n// and a page constant belongs in the developer's own browser entry.\nconst appVariableSchema = z\n .object({\n name: z.string().min(1).max(64).regex(VARIABLE_NAME),\n kind: z.enum(['plain', 'secret']),\n type: z.enum(['text', 'password']),\n label: z.string().min(1).max(100),\n required: z.boolean().optional(),\n helpText: z.string().min(1).max(MAX_VARIABLE_HELP_TEXT).optional(),\n helpUrl: httpsUrl('helpUrl').optional()\n })\n .strict()\n\nconst captureNames = (shape: RegExp, max: number) => {\n return z.array(z.string().min(1).max(MAX_CAPTURE_NAME_LENGTH).regex(shape)).max(max).default([])\n}\n\nconst captureSchema = z\n .object({\n queryParams: captureNames(QUERY_PARAM_NAME, MAX_CAPTURE_QUERY_PARAMS),\n cookies: captureNames(COOKIE_NAME, MAX_CAPTURE_COOKIES)\n })\n .strict()\n\nconst endpointSchema = z\n .object({\n path: z\n .string()\n .min(1)\n .max(255)\n .regex(/^\\/[a-zA-Z0-9\\-_/]*$/, 'Endpoint paths are absolute and may not contain wildcards'),\n methods: z\n .array(z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']))\n .min(1)\n .max(5),\n auth: z.enum(['public', 'token']),\n mode: z.enum(['webhook', 'api'])\n })\n .strict()\n\n// The topics this app pushes with `broadcast: 'site'`, where every app on the site may listen.\n// A topic left out is private to the app that sends it, which is what an undeclared push already is.\nconst eventsSchema = z\n .object({\n publishes: z.array(z.string().min(1).max(MAX_EVENT_TOPIC_LENGTH).regex(EVENT_TOPIC)).max(MAX_PUBLISHED_TOPICS).default([])\n })\n .strict()\n\nconst rpcSchema = z\n .object({\n exposes: z\n .array(z.object({ name: z.string().regex(FUNCTION_NAME).max(64), visibility: z.enum(['public', 'private']) }).strict())\n .max(32)\n .optional(),\n calls: z\n .array(z.object({ app: z.string().regex(APP_SLUG_PATTERN), fn: z.string().regex(FUNCTION_NAME).max(64) }).strict())\n .max(64)\n .optional()\n })\n .strict()\n\nconst scheduleSchema = z\n .object({\n id: z.string().min(1).max(32).regex(IDENTIFIER),\n cron: z\n .string()\n .max(MAX_CRON_LENGTH)\n .refine(\n (value) => parseCron(value) !== null,\n 'cron must be five space-separated fields with a literal minute, so a schedule runs at most once an hour'\n ),\n description: z.string().min(1).max(200).optional()\n })\n .strict()\n\nconst baseSchema = z\n .object({\n $schema: z\n .string()\n .min(1)\n .max(255)\n .optional()\n .meta({ description: 'Path or URL of the JSON Schema an editor completes this file against.' }),\n slug: z\n .string()\n .regex(APP_SLUG_PATTERN)\n .refine((slug) => !slug.endsWith('-'), 'Slug must not end with a hyphen')\n .meta({ description: 'The immutable identifier of the app on the Qinto platform.' }),\n name: z.string().min(1).max(100).meta({ description: 'The display name a site manager sees.' }),\n description: z.string().min(1).max(500).optional().meta({ description: 'One paragraph explaining what the app does.' }),\n flows: z\n .array(z.enum(APP_FLOWS))\n .min(1)\n .max(2)\n .refine((flows) => new Set(flows).size === flows.length, 'Flows may not repeat')\n .meta({ description: 'Where the app plugs into the event pipeline.' }),\n consent: z\n .object({ category: z.enum(CONSENT_CATEGORIES) })\n .strict()\n .meta({ description: 'The single consent category a visitor must have granted before events reach the app.' }),\n legal: z\n .object({ termsUrl: legalUrl('legal.termsUrl'), privacyUrl: legalUrl('legal.privacyUrl') })\n .strict()\n .meta({ description: \"The developer's own terms and privacy documents, served over HTTPS.\" }),\n server: z\n .object({\n entry: z.string().min(1).max(255),\n hooks: z\n .object({\n transform: z.array(z.enum(TRANSFORM_ACTION_TYPES)).max(2).default([]),\n onEvent: z.array(z.enum(EVENT_ACTION_TYPES)).max(EVENT_ACTION_TYPES.length).default([]),\n onConnect: z.boolean().default(false),\n onLifecycle: z.array(z.enum(APP_LIFECYCLE_TYPES)).max(APP_LIFECYCLE_TYPES.length).optional()\n })\n .strict(),\n schedules: z.array(scheduleSchema).max(MAX_APP_SCHEDULES).optional()\n })\n .strict()\n .meta({ description: 'The server entry, the hooks it exports, and the schedules it runs on.' }),\n capabilities: z\n .object({\n api: z.array(z.enum(API_CAPABILITIES)).max(API_CAPABILITIES.length).default([]),\n data: z.array(z.enum(DATA_CAPABILITIES)).max(DATA_CAPABILITIES.length).default([])\n })\n .strict()\n .default({ api: [], data: [] })\n .meta({ description: 'The platform calls the app may make, and the event data it may read.' }),\n browser: z\n .object({\n entry: z.string().min(1).max(255).optional(),\n capture: captureSchema.optional(),\n eventResults: z.array(z.enum(BROWSER_RESULT_ACTION_TYPES)).max(BROWSER_RESULT_ACTION_TYPES.length).optional()\n })\n .strict()\n .optional()\n .meta({\n description:\n \"The app's browser surface: an optional entry for the bundle that ships inside the site's q.js, and the query params and cookies it declares for attribution capture.\"\n }),\n resources: z.array(resourceSchema).max(32).default([]).meta({ description: 'The Cloudflare bindings the app worker is given.' }),\n rpc: rpcSchema.optional().meta({ description: 'The functions this app exposes to other apps, and the ones it calls on them.' }),\n events: eventsSchema.optional().meta({\n description:\n 'The push topics this app broadcasts to every app on the site. Requires the `sharedContext` data capability; a topic left out reaches only this app’s own browser code.'\n }),\n endpoints: z\n .array(endpointSchema)\n .max(16)\n .default([])\n .meta({ description: 'The HTTP routes served at https://<site>/app/<slug><path>.' }),\n ui: z\n .object({\n dir: z.string().min(1).max(255),\n build: z.string().min(1).max(255).optional(),\n writesSettings: z.boolean().default(false)\n })\n .strict()\n .optional()\n .meta({\n description:\n 'The directory holding the built panel, the command that produces it, and whether the panel may change this site’s settings for the app.'\n }),\n install: z\n .object({ multiple: z.boolean().default(false), labelHint: z.string().min(1).max(100).optional() })\n .strict()\n .default({ multiple: false })\n .meta({ description: 'Whether a site may install the app more than once.' }),\n variables: z\n .array(variableSchema)\n .max(MAX_APP_VARIABLES)\n .default([])\n .meta({ description: 'The per-install settings a site manager fills in.' }),\n appVariables: z\n .array(appVariableSchema)\n .max(MAX_APP_SCOPE_VARIABLES)\n .default([])\n .meta({ description: 'The settings the developer fills in once for the app; the same value reaches every install.' })\n })\n .strict()\n\nconst uniqueOrIssue = (ctx: z.core.$RefinementCtx, values: string[], path: (string | number)[], label: string): void => {\n const seen = new Set<string>()\n for (const [index, value] of values.entries()) {\n if (seen.has(value)) {\n ctx.addIssue({ code: 'custom', path: [...path, index], message: `Duplicate ${label}: ${value}` })\n }\n\n seen.add(value)\n }\n}\n\nconst validateBindings = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n const reserved = new Set<string>(PLATFORM_APP_BINDINGS)\n const reservedIdentifiers = new Set<string>(Object.values(PLATFORM_APP_RESOURCE_IDENTIFIERS))\n uniqueOrIssue(\n ctx,\n manifest.resources.map((resource) => resource.binding),\n ['resources'],\n 'binding'\n )\n uniqueOrIssue(\n ctx,\n manifest.resources.map((resource) => resource.identifier),\n ['resources'],\n 'identifier'\n )\n uniqueOrIssue(\n ctx,\n manifest.variables.map((variable) => variable.name),\n ['variables'],\n 'variable name'\n )\n for (const [index, resource] of manifest.resources.entries()) {\n if (reserved.has(resource.binding) || resource.binding.startsWith('VAR_') || resource.binding.startsWith('APPVAR_')) {\n ctx.addIssue({ code: 'custom', path: ['resources', index, 'binding'], message: `Binding ${resource.binding} is reserved` })\n }\n\n if (\n reservedIdentifiers.has(resource.identifier) ||\n resource.identifier.startsWith(PLATFORM_APP_VARIABLE_IDENTIFIER_PREFIX) ||\n resource.identifier.startsWith(PLATFORM_APP_SCOPE_VARIABLE_IDENTIFIER_PREFIX)\n ) {\n ctx.addIssue({ code: 'custom', path: ['resources', index, 'identifier'], message: `Identifier ${resource.identifier} is reserved` })\n }\n }\n\n const bindings = new Set(manifest.resources.map((resource) => resource.binding))\n for (const [index, variable] of manifest.variables.entries()) {\n if (bindings.has(`VAR_${variable.name}`)) {\n ctx.addIssue({\n code: 'custom',\n path: ['variables', index, 'name'],\n message: `Variable ${variable.name} collides with the ${`VAR_${variable.name}`} resource binding`\n })\n }\n }\n}\n\nconst validateAppVariables = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n uniqueOrIssue(\n ctx,\n manifest.appVariables.map((variable) => variable.name),\n ['appVariables'],\n 'app variable name'\n )\n\n const bindings = new Set(manifest.resources.map((resource) => resource.binding))\n const installNames = new Set(manifest.variables.map((variable) => variable.name))\n for (const [index, variable] of manifest.appVariables.entries()) {\n if (bindings.has(`APPVAR_${variable.name}`)) {\n ctx.addIssue({\n code: 'custom',\n path: ['appVariables', index, 'name'],\n message: `App variable ${variable.name} collides with the ${`APPVAR_${variable.name}`} resource binding`\n })\n }\n\n if (installNames.has(variable.name)) {\n ctx.addIssue({\n code: 'custom',\n path: ['appVariables', index, 'name'],\n message: `${variable.name} is declared as both a per-install and an app variable; each name has one scope`\n })\n }\n }\n}\n\n// Durable Object and Workflow classes are both plain exports of the one app worker script, so their\n// names share a single namespace even though they are different resource types.\nconst validateClassNames = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n const owners = new Map<string, string>()\n for (const [index, resource] of manifest.resources.entries()) {\n if (resource.type !== 'durable_object' && resource.type !== 'workflow') {\n continue\n }\n\n const owner = owners.get(resource.className)\n if (owner !== undefined) {\n ctx.addIssue({\n code: 'custom',\n path: ['resources', index, 'className'],\n message: `Class ${resource.className} is already declared by ${owner}; one worker exports each class once`\n })\n }\n\n owners.set(resource.className, resource.identifier)\n }\n}\n\nconst validateHyperdrive = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n for (const [index, resource] of manifest.resources.entries()) {\n if (resource.type !== 'hyperdrive') {\n continue\n }\n\n const appVariable = manifest.appVariables.find((candidate) => candidate.name === resource.origin.passwordVariable)\n // An app secret is one value for every install, so the single-install rule — one worker, one\n // origin password — is already satisfied and the install cap does not apply.\n const appScoped = appVariable !== undefined && appVariable.kind === 'secret' && appVariable.required === true\n if (manifest.install.multiple && !appScoped) {\n ctx.addIssue({\n code: 'custom',\n path: ['resources', index],\n message: 'A hyperdrive app must be single-install: one worker holds one origin while secrets are per install'\n })\n }\n\n if (appScoped) {\n continue\n }\n\n const variable = manifest.variables.find((candidate) => candidate.name === resource.origin.passwordVariable)\n if (variable === undefined || variable.kind !== 'secret' || variable.required !== true) {\n ctx.addIssue({\n code: 'custom',\n path: ['resources', index, 'origin', 'passwordVariable'],\n message: `passwordVariable must name a declared required secret variable, in variables or appVariables`\n })\n }\n }\n}\n\nconst validateEndpoints = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n uniqueOrIssue(\n ctx,\n manifest.endpoints.map((endpoint) => endpoint.path),\n ['endpoints'],\n 'endpoint path'\n )\n for (const [index, endpoint] of manifest.endpoints.entries()) {\n if (endpoint.mode === 'api' && manifest.install.multiple) {\n ctx.addIssue({\n code: 'custom',\n path: ['endpoints', index, 'mode'],\n message: 'An api endpoint needs a single response, so it cannot combine with install.multiple'\n })\n }\n }\n}\n\nconst reservedCaptureReason = (name: string, cookie: boolean): string | undefined => {\n const lower = name.toLowerCase()\n if (RESERVED_CAPTURE_PREFIXES.some((prefix) => lower.startsWith(prefix))) {\n return 'the q_ and qinto prefixes are reserved for the platform'\n }\n\n if (cookie && RESERVED_COOKIE_PREFIXES.some((prefix) => lower.startsWith(prefix))) {\n return '__Host- and __Secure- cookies are security-scoped'\n }\n\n if (RESERVED_CAPTURE_NAMES.has(lower)) {\n return 'it names a credential'\n }\n\n return undefined\n}\n\nconst validateCaptureNames = (ctx: z.core.$RefinementCtx, names: string[], path: (string | number)[], cookie: boolean): void => {\n for (const [index, name] of names.entries()) {\n const reason = reservedCaptureReason(name, cookie)\n if (reason !== undefined) {\n ctx.addIssue({ code: 'custom', path: [...path, index], message: `${name} may not be captured: ${reason}` })\n }\n }\n}\n\nconst validateCapture = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n const browser = manifest.browser\n if (browser === undefined) {\n return\n }\n\n if (browser.entry === undefined && browser.capture === undefined) {\n ctx.addIssue({ code: 'custom', path: ['browser'], message: 'browser needs an entry, a capture block, or both' })\n }\n\n const eventResults = browser.eventResults ?? []\n uniqueOrIssue(ctx, eventResults, ['browser', 'eventResults'], 'browser event result')\n if (eventResults.length > 0 && browser.entry === undefined) {\n ctx.addIssue({ code: 'custom', path: ['browser', 'eventResults'], message: 'eventResults needs a browser entry' })\n }\n\n const capture = browser.capture\n if (capture === undefined) {\n return\n }\n\n if (capture.queryParams.length === 0 && capture.cookies.length === 0) {\n ctx.addIssue({ code: 'custom', path: ['browser', 'capture'], message: 'capture must name at least one query param or cookie' })\n }\n\n uniqueOrIssue(ctx, capture.queryParams, ['browser', 'capture', 'queryParams'], 'query param')\n uniqueOrIssue(ctx, capture.cookies, ['browser', 'capture', 'cookies'], 'cookie')\n validateCaptureNames(ctx, capture.queryParams, ['browser', 'capture', 'queryParams'], false)\n validateCaptureNames(ctx, capture.cookies, ['browser', 'capture', 'cookies'], true)\n\n const params = new Set(capture.queryParams)\n for (const [index, name] of capture.cookies.entries()) {\n if (params.has(name)) {\n ctx.addIssue({\n code: 'custom',\n path: ['browser', 'capture', 'cookies', index],\n message: `${name} is declared as both a query param and a cookie; each name has one source`\n })\n }\n }\n}\n\nconst validateRpc = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n const exposes = manifest.rpc?.exposes ?? []\n uniqueOrIssue(\n ctx,\n exposes.map((fn) => fn.name),\n ['rpc', 'exposes'],\n 'function'\n )\n for (const [index, call] of (manifest.rpc?.calls ?? []).entries()) {\n if (call.app === manifest.slug) {\n ctx.addIssue({ code: 'custom', path: ['rpc', 'calls', index, 'app'], message: 'An app cannot declare an RPC call to itself' })\n }\n }\n}\n\n// Schedule ids are unique because each one keys a handler. Cron expressions are not: two separately\n// named handlers on the same cadence is ordinary, and the envelope carries the id.\nconst validateServer = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n uniqueOrIssue(ctx, manifest.server.hooks.transform, ['server', 'hooks', 'transform'], 'transform hook')\n uniqueOrIssue(ctx, manifest.server.hooks.onEvent, ['server', 'hooks', 'onEvent'], 'event hook')\n uniqueOrIssue(ctx, manifest.server.hooks.onLifecycle ?? [], ['server', 'hooks', 'onLifecycle'], 'lifecycle hook')\n uniqueOrIssue(\n ctx,\n (manifest.server.schedules ?? []).map((schedule) => schedule.id),\n ['server', 'schedules'],\n 'schedule id'\n )\n}\n\nconst validateMigrationSize = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n const bytes = manifest.resources.reduce((total, resource) => {\n return resource.type === 'd1' ? total + new TextEncoder().encode(JSON.stringify(resource.migrations)).byteLength : total\n }, 0)\n if (bytes > MAX_MANIFEST_MIGRATION_BYTES) {\n ctx.addIssue({\n code: 'custom',\n path: ['resources'],\n message: `Migrations total ${bytes} bytes across every database; the cap is ${MAX_MANIFEST_MIGRATION_BYTES}`\n })\n }\n}\n\n// Broadcasting to every app on the site is the `sharedContext` decision — \"this app exchanges\n// visitor data with the other apps on the site\" — so declaring topics without it is refused at the\n// manifest rather than silently dropped at delivery.\nconst validateEvents = (manifest: z.output<typeof baseSchema>, ctx: z.core.$RefinementCtx): void => {\n const publishes = manifest.events?.publishes ?? []\n uniqueOrIssue(ctx, publishes, ['events', 'publishes'], 'topic')\n if (publishes.length > 0 && !manifest.capabilities.data.includes('sharedContext')) {\n ctx.addIssue({\n code: 'custom',\n path: ['events', 'publishes'],\n message: 'Publishing a topic site-wide requires the sharedContext data capability'\n })\n }\n}\n\nexport const appManifestSchema = baseSchema.superRefine((manifest, ctx) => {\n validateMigrationSize(manifest, ctx)\n validateBindings(manifest, ctx)\n validateAppVariables(manifest, ctx)\n validateClassNames(manifest, ctx)\n validateHyperdrive(manifest, ctx)\n validateEndpoints(manifest, ctx)\n validateCapture(manifest, ctx)\n validateRpc(manifest, ctx)\n validateEvents(manifest, ctx)\n validateServer(manifest, ctx)\n})\n\nexport type AppManifest = z.output<typeof appManifestSchema>\nexport type AppManifestInput = z.input<typeof appManifestSchema>\nexport type AppFlow = (typeof APP_FLOWS)[number]\nexport type AppConsentCategory = (typeof CONSENT_CATEGORIES)[number]\nexport type AppManifestResource = AppManifest['resources'][number]\nexport type AppManifestD1Migration = Extract<AppManifestResource, { type: 'd1' }>['migrations'][number]\nexport type AppManifestVariable = AppManifest['variables'][number]\nexport type AppManifestAppVariable = AppManifest['appVariables'][number]\nexport type AppManifestEndpoint = AppManifest['endpoints'][number]\nexport type AppManifestSchedule = NonNullable<AppManifest['server']['schedules']>[number]\nexport type AppManifestCapture = NonNullable<NonNullable<AppManifest['browser']>['capture']>\n\nexport type ParseAppManifestResult = { ok: true; manifest: AppManifest } | { ok: false; issues: string[] }\n\n/**\n * Validates a parsed `qinto.app.jsonc` document against the manifest schema, including its cross-field rules.\n * @param value The parsed manifest document.\n * @returns The validated manifest, or the flattened issue list when it is invalid.\n */\nexport const parseAppManifest = (value: unknown): ParseAppManifestResult => {\n const result = appManifestSchema.safeParse(value)\n if (result.success) {\n return { ok: true, manifest: result.data }\n }\n\n return {\n ok: false,\n issues: result.error.issues.map((issue) => (issue.path.length === 0 ? issue.message : `${issue.path.join('.')}: ${issue.message}`))\n }\n}\n","import { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport type { AppManifest } from '@qinto/app-manifest'\nimport { parseAppManifest } from '@qinto/app-manifest'\nimport type { ParseError } from 'jsonc-parser'\nimport { parse } from 'jsonc-parser'\n\nimport { CliUsageError } from '../../../lib/errors'\n\nexport const APP_MANIFEST_FILENAME = 'qinto.app.jsonc'\n\nexport type AppManifestFile = { path: string; manifest: AppManifest }\n\nexport const readAppManifestFile = async (dir: string): Promise<AppManifestFile> => {\n const path = join(dir, APP_MANIFEST_FILENAME)\n let text: string\n try {\n text = await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new CliUsageError(`No ${APP_MANIFEST_FILENAME} in ${dir}. Run \\`qinto app create\\` first.`)\n }\n\n throw error\n }\n\n const errors: ParseError[] = []\n const raw: unknown = parse(text, errors, { allowTrailingComma: true })\n if (errors.length > 0) {\n throw new CliUsageError(`${APP_MANIFEST_FILENAME} is not valid JSONC.`)\n }\n\n const result = parseAppManifest(raw)\n if (!result.ok) {\n throw new CliUsageError(`${APP_MANIFEST_FILENAME} is invalid:\\n${result.issues.map((issue) => ` - ${issue}`).join('\\n')}`)\n }\n\n return { path, manifest: result.manifest }\n}\n","import { join, resolve } from 'node:path'\n\nimport type { CommandInput, CommandSpec } from '../../command-spec'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliError } from '../../lib/errors'\nimport { installDependencies, scaffoldInstallCommands } from './common/install'\nimport { readAppManifestFile } from './common/manifest-file'\nimport { scaffoldUi, setManifestUi } from './common/scaffold'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as { json?: boolean; install?: boolean }\n const dir = resolve(input.positionals.at(0) ?? '.')\n const manifestFile = await readAppManifestFile(dir)\n if (manifestFile.manifest.ui !== undefined) {\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ added: false, files: [] }, null, 2)}\\n`)\n return\n }\n\n deps.stdout('This app already has a UI panel — nothing to add.\\n')\n return\n }\n\n const files = await scaffoldUi({ dir, values: { slug: manifestFile.manifest.slug, name: manifestFile.manifest.name } })\n await setManifestUi(manifestFile.path)\n const uiDir = join(dir, 'ui')\n const command = (await scaffoldInstallCommands()).ui\n let installed = false\n if (options.install !== false) {\n installed = await installDependencies({ dir: uiDir, command })\n }\n\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ added: true, installed, files }, null, 2)}\\n`)\n } else {\n deps.stdout(`Added the UI panel scaffold to '${manifestFile.manifest.slug}':\\n`)\n for (const file of files) {\n deps.stdout(` ${file}\\n`)\n }\n\n deps.stdout(\n installed ? `Installed its dependencies with \\`${command}\\`.\\n` : `Run \\`${command}\\` in ${uiDir} before the first publish.\\n`\n )\n }\n\n if (options.install !== false && !installed) {\n throw new CliError(`The panel is in ${uiDir}, but \\`${command}\\` failed there. Run it yourself before \\`qinto app publish\\`.`)\n }\n}\n\nexport const appAddUiCommand: CommandSpec = {\n path: ['app', 'add', 'ui'],\n description: 'Add the Astro UI panel scaffold to an existing app and install its dependencies',\n positionals: [{ name: 'dir', description: 'App directory holding qinto.app.jsonc (defaults to the current one)', required: false }],\n options: [\n { flag: '--no-install', description: 'Skip installing the panel dependencies', type: 'boolean' },\n { flag: '--json', description: 'Print the added files as JSON', type: 'boolean' }\n ],\n result: { type: 'app-add-ui' },\n run\n}\n","import { randomUUID } from 'node:crypto'\nimport { chmod, mkdir, rename, writeFile } from 'node:fs/promises'\nimport { dirname } from 'node:path'\n\nexport const ensureFileDirectory = async (path: string): Promise<void> => {\n const directory = dirname(path)\n await mkdir(directory, { recursive: true, mode: 0o700 })\n await chmod(directory, 0o700)\n}\n\nexport const writeJsonFile = async (path: string, value: unknown): Promise<void> => {\n await ensureFileDirectory(path)\n // Written aside and renamed so a crash mid-write leaves the previous file, never a truncated one.\n const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`\n await writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600 })\n await chmod(temporary, 0o600)\n await rename(temporary, path)\n}\n","import { readFile } from 'node:fs/promises'\n\nimport type { CliDeps } from './deps'\nimport { CliError } from './errors'\nimport { writeJsonFile } from './json-file'\n\nexport const ENVIRONMENTS = ['production', 'sandbox'] as const\n\nexport type QintoEnvironment = (typeof ENVIRONMENTS)[number]\n\nexport const API_ORIGINS: Record<QintoEnvironment, string> = {\n production: 'https://api.qinto.io',\n sandbox: 'https://api.qinto.tech'\n}\n\nexport const DEFAULT_ENVIRONMENT: QintoEnvironment = 'production'\n\nexport type ApiTarget = { env?: QintoEnvironment; apiUrl?: string }\n\ntype SettingsFile = { environment?: string }\n\nexport const parseHttpUrl = (value: string, label: string): URL => {\n let parsed: URL\n try {\n parsed = new URL(value)\n } catch {\n throw new CliError(`Invalid ${label}: ${value}`)\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new CliError(`Invalid ${label}: ${value}`)\n }\n\n return parsed\n}\n\nexport const loadEnvironment = async (deps: CliDeps): Promise<QintoEnvironment | null> => {\n let raw: string\n try {\n raw = await readFile(deps.settingsPath, 'utf8')\n } catch (error) {\n const readError = error as NodeJS.ErrnoException\n if (readError.code === 'ENOENT') {\n return null\n }\n\n throw new CliError(`Could not read ${deps.settingsPath}: ${readError.message}`)\n }\n\n let settings: SettingsFile\n try {\n settings = JSON.parse(raw) as SettingsFile\n } catch {\n throw new CliError(`${deps.settingsPath} is corrupted. Delete it and run \\`qinto env\\` again.`)\n }\n\n const stored = settings.environment\n if (stored === undefined) {\n return null\n }\n\n const known = ENVIRONMENTS.find((name) => {\n return name === stored\n })\n if (known === undefined) {\n throw new CliError(`${deps.settingsPath} names an unknown environment '${stored}'. Run \\`qinto env\\` to choose one.`)\n }\n\n return known\n}\n\nexport const saveEnvironment = async (deps: CliDeps, environment: QintoEnvironment): Promise<void> => {\n await writeJsonFile(deps.settingsPath, { environment } satisfies SettingsFile)\n}\n\nexport const resolveApiOrigin = async (deps: CliDeps, target: ApiTarget): Promise<string> => {\n if (target.apiUrl !== undefined) {\n return parseHttpUrl(target.apiUrl, 'API URL').origin\n }\n\n return API_ORIGINS[target.env ?? (await loadEnvironment(deps)) ?? DEFAULT_ENVIRONMENT]\n}\n\n// Always explicit: a printed command with no target resolves against whatever `qinto env` saved.\nexport const targetFlags = (origin: string): string[] => {\n const named = ENVIRONMENTS.find((name) => {\n return API_ORIGINS[name] === origin\n })\n\n return named === undefined ? ['--api-url', origin] : ['--env', named]\n}\n\nexport const loginHint = (origin: string): string => {\n return ['qinto', 'login', ...targetFlags(origin)].join(' ')\n}\n","import { ENVIRONMENTS } from './lib/config'\nimport type { CliDeps } from './lib/deps'\n\nexport type OptionSpec = {\n flag: string\n description: string\n type: 'string' | 'boolean'\n required?: boolean\n enum?: readonly string[]\n default?: string | boolean\n env?: string\n}\n\ntype PositionalSpec = { name: string; description: string; required: boolean; variadic?: boolean }\n\nexport type EnvironmentSpec = { name: string; description: string; secret?: boolean }\n\nexport type CommandInput = { options: Record<string, unknown>; positionals: string[] }\n\nexport type CommandSpec = {\n path: readonly string[]\n description: string\n positionals: PositionalSpec[]\n options: OptionSpec[]\n environment?: EnvironmentSpec[]\n result?: Record<string, unknown>\n run: (input: CommandInput, deps: CliDeps) => Promise<void>\n}\n\nexport const API_TARGET_OPTIONS: OptionSpec[] = [\n {\n flag: '--env <name>',\n description: 'Qinto environment to talk to, instead of the one `qinto env` saved',\n type: 'string',\n enum: ENVIRONMENTS,\n env: 'QINTO_ENV'\n },\n {\n flag: '--api-url <url>',\n description: 'Qinto API origin to talk to, instead of any environment',\n type: 'string',\n env: 'QINTO_API_URL'\n }\n]\n","import type { CliDeps } from './deps'\n\nexport const machineMode = (options: { json?: boolean; input?: boolean }, deps: CliDeps): boolean => {\n return options.json === true || options.input === false || !deps.interactive\n}\n","import { chmod, readFile, writeFile } from 'node:fs/promises'\n\nimport { lock } from 'proper-lockfile'\n\nimport type { CliDeps } from './deps'\nimport { CliError } from './errors'\nimport { ensureFileDirectory, writeJsonFile } from './json-file'\n\nexport type StoredCredentials = {\n accessToken: string\n refreshToken: string | null\n expiresAt: number\n scope: string\n tokenEndpoint: string\n revocationEndpoint: string\n}\n\n// Kept separately so refreshing or invalidating the current login cannot discard failed revocations.\nexport type PendingRevocation = { token: string; revocationEndpoint: string }\n\nexport type CredentialState = { login: StoredCredentials | null; pendingRevocations: PendingRevocation[]; activeTeamId: string | null }\n\ntype OriginState = { login?: StoredCredentials; pendingRevocations?: PendingRevocation[]; activeTeamId?: string }\ntype CredentialsFile = Record<string, OriginState>\n\nexport type CredentialTransaction = {\n load: (origin: string) => CredentialState\n save: (origin: string, state: CredentialState) => Promise<void>\n}\n\nconst readStore = async (path: string): Promise<CredentialsFile> => {\n let raw: string\n try {\n raw = await readFile(path, 'utf8')\n } catch (error) {\n const readError = error as NodeJS.ErrnoException\n if (readError.code === 'ENOENT') {\n return {}\n }\n\n throw new CliError(`Could not read ${path}: ${readError.message}`)\n }\n\n try {\n return JSON.parse(raw) as CredentialsFile\n } catch {\n throw new CliError(`${path} is corrupted. Delete it and log in again.`)\n }\n}\n\nconst credentialState = (store: CredentialsFile, origin: string): CredentialState => {\n return {\n login: store[origin]?.login ?? null,\n pendingRevocations: [...(store[origin]?.pendingRevocations ?? [])],\n activeTeamId: store[origin]?.activeTeamId ?? null\n }\n}\n\nconst nextStore = (store: CredentialsFile, origin: string, state: CredentialState): CredentialsFile => {\n const next = { ...store }\n if (state.login === null && state.pendingRevocations.length === 0 && state.activeTeamId === null) {\n delete next[origin]\n return next\n }\n\n next[origin] = {\n ...(state.login === null ? {} : { login: state.login }),\n ...(state.pendingRevocations.length === 0 ? {} : { pendingRevocations: state.pendingRevocations }),\n ...(state.activeTeamId === null ? {} : { activeTeamId: state.activeTeamId })\n }\n return next\n}\n\nexport const withCredentialsLock = async <T>(deps: CliDeps, operation: (transaction: CredentialTransaction) => Promise<T>): Promise<T> => {\n await ensureFileDirectory(deps.credentialsPath)\n const lockTarget = `${deps.credentialsPath}.guard`\n await writeFile(lockTarget, '', { flag: 'a', mode: 0o600 })\n await chmod(lockTarget, 0o600)\n\n let release: () => Promise<void>\n try {\n release = await lock(lockTarget, {\n stale: 120_000,\n update: 10_000,\n retries: { retries: 600, factor: 1, minTimeout: 100, maxTimeout: 100, randomize: false }\n })\n } catch (error) {\n throw new CliError(`Could not lock ${deps.credentialsPath}: ${(error as Error).message}`)\n }\n\n try {\n let store = await readStore(deps.credentialsPath)\n const transaction: CredentialTransaction = {\n load: (origin) => {\n return credentialState(store, origin)\n },\n save: async (origin, state) => {\n const next = nextStore(store, origin, state)\n await writeJsonFile(deps.credentialsPath, next)\n store = next\n }\n }\n\n return await operation(transaction)\n } finally {\n await release()\n }\n}\n\nexport const loadCredentials = async (deps: CliDeps, origin: string): Promise<StoredCredentials | null> => {\n const store = await readStore(deps.credentialsPath)\n return store[origin]?.login ?? null\n}\n\nexport const saveCredentials = async (deps: CliDeps, origin: string, credentials: StoredCredentials): Promise<void> => {\n await withCredentialsLock(deps, async (transaction) => {\n const state = transaction.load(origin)\n await transaction.save(origin, { login: credentials, pendingRevocations: state.pendingRevocations, activeTeamId: state.activeTeamId })\n })\n}\n\nexport const deleteCredentials = async (deps: CliDeps, origin: string): Promise<void> => {\n await withCredentialsLock(deps, async (transaction) => {\n const state = transaction.load(origin)\n await transaction.save(origin, { login: null, pendingRevocations: state.pendingRevocations, activeTeamId: state.activeTeamId })\n })\n}\n\nexport const loadPendingRevocations = async (deps: CliDeps, origin: string): Promise<PendingRevocation[]> => {\n const store = await readStore(deps.credentialsPath)\n return [...(store[origin]?.pendingRevocations ?? [])]\n}\n\nexport const savePendingRevocations = async (deps: CliDeps, origin: string, pendingRevocations: PendingRevocation[]): Promise<void> => {\n await withCredentialsLock(deps, async (transaction) => {\n const state = transaction.load(origin)\n await transaction.save(origin, { login: state.login, pendingRevocations, activeTeamId: state.activeTeamId })\n })\n}\n\nexport const loadActiveTeam = async (deps: CliDeps, origin: string): Promise<string | null> => {\n const store = await readStore(deps.credentialsPath)\n return store[origin]?.activeTeamId ?? null\n}\n\nexport const saveActiveTeam = async (deps: CliDeps, origin: string, activeTeamId: string): Promise<void> => {\n await withCredentialsLock(deps, async (transaction) => {\n const state = transaction.load(origin)\n await transaction.save(origin, { ...state, activeTeamId })\n })\n}\n","export type PermissionAction = 'read' | 'write' | 'delete' | 'admin'\n\nexport const ACTION_RANK: Record<PermissionAction, number> = { read: 0, write: 1, delete: 2, admin: 3 }\n\nexport type ScopeToken = { category: string; action: string }\n\n/**\n * Splits a scope token into its category and action at the last `:` separator.\n * @param token The scope token to split, e.g. `team:write` or `feature:consent:read`.\n * @returns The category and action parts, or null when the token carries no separator (an auxiliary scope like `profile`).\n */\nexport const parseScopeToken = (token: string): ScopeToken | null => {\n const separator = token.lastIndexOf(':')\n if (separator === -1) {\n return null\n }\n\n return { category: token.slice(0, separator), action: token.slice(separator + 1) }\n}\n\n/**\n * Narrows a scope action string to a ranked permission action.\n * @param action The action part of a scope token.\n * @returns Whether the action is one of the ranked permission actions in `ACTION_RANK`.\n */\nexport const isPermissionAction = (action: string): action is PermissionAction => {\n return action in ACTION_RANK\n}\n","import type { CliDeps } from './deps'\nimport { CliError } from './errors'\n\nconst REQUEST_TIMEOUT_MS = 30_000\n\nexport const request = async (\n deps: CliDeps,\n input: Parameters<typeof fetch>[0],\n init?: Parameters<typeof fetch>[1],\n timeoutMs = REQUEST_TIMEOUT_MS\n): Promise<Response> => {\n try {\n return await deps.fetch(input, { ...init, signal: AbortSignal.timeout(timeoutMs) })\n } catch (error) {\n if (error instanceof DOMException && error.name === 'TimeoutError') {\n throw new CliError(`The Qinto API did not respond within ${Math.round(timeoutMs / 1000)} seconds.`)\n }\n\n throw error\n }\n}\n","import type { PermissionAction } from '@qinto/oauth-grammar'\nimport { ACTION_RANK, isPermissionAction, parseScopeToken } from '@qinto/oauth-grammar'\n\nimport { parseHttpUrl } from './config'\nimport type { CliDeps } from './deps'\nimport { CliError, TokenEndpointError } from './errors'\nimport { request } from './request'\n\nconst CLI_CLIENT_ID = 'qinto-cli'\n\nexport type Discovery = {\n authorizationEndpoint: string\n tokenEndpoint: string\n revocationEndpoint: string\n scopesSupported: string[]\n}\n\nconst parseJson = async (response: Response, origin: string): Promise<Record<string, unknown>> => {\n try {\n return (await response.json()) as Record<string, unknown>\n } catch {\n throw new CliError(`${origin} did not answer with JSON. Is this a Qinto API?`)\n }\n}\n\nexport const fetchDiscovery = async (deps: CliDeps, apiOrigin: string): Promise<Discovery> => {\n const response = await request(deps, `${apiOrigin}/.well-known/oauth-authorization-server`)\n if (!response.ok) {\n throw new CliError(`Could not discover the Qinto OAuth server at ${apiOrigin}: status ${response.status}.`)\n }\n\n const body = await parseJson(response, apiOrigin)\n const { issuer, authorization_endpoint, token_endpoint, revocation_endpoint, scopes_supported } = body\n if (\n typeof issuer !== 'string' ||\n typeof authorization_endpoint !== 'string' ||\n typeof token_endpoint !== 'string' ||\n typeof revocation_endpoint !== 'string' ||\n !Array.isArray(scopes_supported) ||\n !scopes_supported.every((scope) => typeof scope === 'string')\n ) {\n throw new CliError(`${apiOrigin} did not answer with a valid OAuth discovery document.`)\n }\n\n const issuerUrl = parseHttpUrl(issuer, 'OAuth issuer')\n const authorizationUrl = parseHttpUrl(authorization_endpoint, 'OAuth authorization endpoint')\n const tokenUrl = parseHttpUrl(token_endpoint, 'OAuth token endpoint')\n const revocationUrl = parseHttpUrl(revocation_endpoint, 'OAuth revocation endpoint')\n if (issuerUrl.href !== `${apiOrigin}/` || tokenUrl.origin !== apiOrigin || revocationUrl.origin !== apiOrigin) {\n throw new CliError(`${apiOrigin} did not answer with a valid OAuth discovery document.`)\n }\n\n return {\n authorizationEndpoint: authorizationUrl.href,\n tokenEndpoint: tokenUrl.href,\n revocationEndpoint: revocationUrl.href,\n scopesSupported: scopes_supported\n }\n}\n\nexport const maximalScopes = (scopesSupported: string[]): string[] => {\n const best = new Map<string, PermissionAction>()\n const auxiliaries: string[] = []\n for (const token of scopesSupported) {\n const parsed = parseScopeToken(token)\n if (parsed === null) {\n auxiliaries.push(token)\n continue\n }\n\n if (!isPermissionAction(parsed.action)) {\n continue\n }\n\n const current = best.get(parsed.category)\n if (current === undefined || ACTION_RANK[parsed.action] > ACTION_RANK[current]) {\n best.set(parsed.category, parsed.action)\n }\n }\n\n return [...[...best.entries()].map(([category, action]) => `${category}:${action}`), ...auxiliaries]\n}\n\nexport type AuthorizeRequest = {\n authorizationEndpoint: string\n redirectUri: string\n scope: string\n state: string\n challenge: string\n team?: string\n reauthorize?: boolean\n}\n\nexport const buildAuthorizeUrl = (request: AuthorizeRequest): string => {\n const url = new URL(request.authorizationEndpoint)\n url.searchParams.set('client_id', CLI_CLIENT_ID)\n url.searchParams.set('redirect_uri', request.redirectUri)\n url.searchParams.set('response_type', 'code')\n url.searchParams.set('scope', request.scope)\n url.searchParams.set('state', request.state)\n url.searchParams.set('code_challenge', request.challenge)\n url.searchParams.set('code_challenge_method', 'S256')\n // Any team parameter makes the consent screen render instead of auto-skipping a covering prior grant.\n if (request.team !== undefined) {\n url.searchParams.set('team', request.team)\n }\n\n if (request.reauthorize === true) {\n url.searchParams.set('prompt', 'consent')\n }\n\n return url.toString()\n}\n\nexport type TokenResponse = { accessToken: string; refreshToken: string | null; expiresIn: number; scope: string }\n\nexport const postToken = async (deps: CliDeps, tokenEndpoint: string, params: Record<string, string>): Promise<TokenResponse> => {\n const response = await request(deps, tokenEndpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ ...params, client_id: CLI_CLIENT_ID }).toString()\n })\n const body = await parseJson(response, tokenEndpoint)\n if (!response.ok) {\n const code = typeof body['error'] === 'string' ? body['error'] : `status_${response.status}`\n const description =\n typeof body['error_description'] === 'string' ? body['error_description'] : `The token endpoint answered ${response.status}.`\n throw new TokenEndpointError(code, description)\n }\n\n const { access_token, expires_in, scope, refresh_token } = body\n if (typeof access_token !== 'string' || typeof expires_in !== 'number' || typeof scope !== 'string') {\n throw new CliError('The token endpoint answered with an unexpected shape.')\n }\n\n return {\n accessToken: access_token,\n refreshToken: typeof refresh_token === 'string' ? refresh_token : null,\n expiresIn: expires_in,\n scope\n }\n}\n\nexport const revokeToken = async (deps: CliDeps, revocationEndpoint: string, token: string): Promise<void> => {\n const response = await request(deps, revocationEndpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({ token, client_id: CLI_CLIENT_ID }).toString()\n })\n if (!response.ok) {\n throw new CliError(`The revocation endpoint answered ${response.status}.`)\n }\n}\n\nexport type RevocationTarget = { token: string; revocationEndpoint: string }\nexport type RevocationFailure = { target: RevocationTarget; error: Error }\n\nexport const failedRevocations = async (deps: CliDeps, targets: RevocationTarget[]): Promise<RevocationFailure[]> => {\n const results = await Promise.all(\n targets.map(async (target) => {\n try {\n await revokeToken(deps, target.revocationEndpoint, target.token)\n return null\n } catch (error) {\n return { target, error: error as Error }\n }\n })\n )\n return results.filter((failure): failure is RevocationFailure => failure !== null)\n}\n","import { loginHint } from './config'\nimport type { CredentialState, CredentialTransaction, StoredCredentials } from './credentials'\nimport { loadCredentials, withCredentialsLock } from './credentials'\nimport type { CliDeps } from './deps'\nimport { ApiResponseError, CliError, TokenEndpointError } from './errors'\nimport type { TokenResponse } from './oauth'\nimport { postToken } from './oauth'\nimport { request } from './request'\n\nconst EXPIRY_SKEW_MS = 30_000\n\nexport type ApiRequestOptions = { method?: string; body?: unknown; timeoutMs?: number }\n\nconst authedFetch = (input: {\n deps: CliDeps\n apiOrigin: string\n path: string\n token: string\n options: ApiRequestOptions\n}): Promise<Response> => {\n const { deps, apiOrigin, path, token, options } = input\n const headers: Record<string, string> = { authorization: `Bearer ${token}` }\n if (options.body !== undefined) {\n headers['content-type'] = 'application/json'\n }\n\n return request(\n deps,\n new URL(path, apiOrigin),\n { method: options.method, headers, body: options.body === undefined ? undefined : JSON.stringify(options.body) },\n options.timeoutMs\n )\n}\n\nconst expireSession = async (transaction: CredentialTransaction, origin: string, state: CredentialState): Promise<never> => {\n await transaction.save(origin, { login: null, pendingRevocations: state.pendingRevocations, activeTeamId: state.activeTeamId })\n throw new CliError(`Your session expired. Run \\`${loginHint(origin)}\\` again.`)\n}\n\nconst refreshStored = async (deps: CliDeps, origin: string, observedAccessToken: string, force: boolean): Promise<StoredCredentials> => {\n return withCredentialsLock(deps, async (transaction) => {\n const state = transaction.load(origin)\n const stored = state.login\n if (stored === null) {\n throw new CliError(`Your session expired. Run \\`${loginHint(origin)}\\` again.`)\n }\n\n if (stored.accessToken !== observedAccessToken || (!force && stored.expiresAt > deps.now() + EXPIRY_SKEW_MS)) {\n return stored\n }\n\n if (stored.refreshToken === null) {\n return expireSession(transaction, origin, state)\n }\n\n let response: TokenResponse\n try {\n response = await postToken(deps, stored.tokenEndpoint, { grant_type: 'refresh_token', refresh_token: stored.refreshToken })\n } catch (error) {\n if (error instanceof TokenEndpointError && error.code === 'invalid_grant') {\n return expireSession(transaction, origin, state)\n }\n\n throw error\n }\n\n const next: StoredCredentials = {\n accessToken: response.accessToken,\n // Rotation invalidates the presented token, so persist its successor before using it.\n refreshToken: response.refreshToken ?? stored.refreshToken,\n expiresAt: deps.now() + response.expiresIn * 1000,\n scope: response.scope,\n tokenEndpoint: stored.tokenEndpoint,\n revocationEndpoint: stored.revocationEndpoint\n }\n await transaction.save(origin, { login: next, pendingRevocations: state.pendingRevocations, activeTeamId: state.activeTeamId })\n return next\n })\n}\n\nexport const apiRequest = async (deps: CliDeps, apiOrigin: string, path: string, options: ApiRequestOptions = {}): Promise<Response> => {\n const envToken = deps.env['QINTO_API_TOKEN']\n if (envToken !== undefined && envToken !== '') {\n const response = await authedFetch({ deps, apiOrigin, path, token: envToken, options })\n if (response.status === 401) {\n throw new CliError('The token in QINTO_API_TOKEN is invalid or expired.')\n }\n\n return response\n }\n\n let stored = await loadCredentials(deps, apiOrigin)\n if (stored === null) {\n throw new CliError(`Not logged in. Run \\`${loginHint(apiOrigin)}\\`.`)\n }\n\n if (stored.expiresAt <= deps.now() + EXPIRY_SKEW_MS) {\n stored = await refreshStored(deps, apiOrigin, stored.accessToken, false)\n }\n\n const response = await authedFetch({ deps, apiOrigin, path, token: stored.accessToken, options })\n if (response.status !== 401) {\n return response\n }\n\n stored = await refreshStored(deps, apiOrigin, stored.accessToken, true)\n return authedFetch({ deps, apiOrigin, path, token: stored.accessToken, options })\n}\n\ntype ValidationTree = { errors?: string[]; properties?: Record<string, ValidationTree>; items?: (ValidationTree | null)[] }\n\nconst firstFieldIssue = (node: ValidationTree, path: string): string | null => {\n const message = node.errors?.at(0)\n if (message !== undefined) {\n return path === '' ? message : `${path}: ${message}`\n }\n\n const children = [\n ...Object.entries(node.properties ?? {}),\n ...(node.items ?? []).flatMap((child, index) => (child === null ? [] : [[`${index}`, child] as const]))\n ]\n for (const [segment, child] of children) {\n const found = firstFieldIssue(child, path === '' ? segment : `${path}.${segment}`)\n if (found !== null) {\n return found\n }\n }\n\n return null\n}\n\nexport const apiJson = async <T>(deps: CliDeps, apiOrigin: string, path: string, options: ApiRequestOptions = {}): Promise<T> => {\n const response = await apiRequest(deps, apiOrigin, path, options)\n let body: unknown\n try {\n body = await response.json()\n } catch {\n throw new CliError(`The Qinto API answered ${response.status} without JSON.`)\n }\n\n if (!response.ok) {\n const error = body as { error?: unknown; message?: unknown; details?: unknown }\n const code = typeof error.error === 'string' ? error.error : null\n const base = typeof error.message === 'string' ? error.message : (code ?? `status ${response.status}`)\n const issue = typeof error.details === 'object' && error.details !== null ? firstFieldIssue(error.details as ValidationTree, '') : null\n const detail = issue === null ? base : `${base} (${issue})`\n throw new ApiResponseError(`The Qinto API rejected the request: ${detail}${detail.endsWith('.') ? '' : '.'}`, response.status, code)\n }\n\n return body as T\n}\n","import type { operations } from '../generated/api'\nimport { apiJson } from './api'\nimport type { CliDeps } from './deps'\nimport { CliUsageError } from './errors'\n\ntype MeResponse = operations['getMe']['responses']['200']['content']['application/json']\n\nexport type CallerOrganization = MeResponse['organizations'][number]\n\nexport const listCallerOrganizations = async (deps: CliDeps, origin: string): Promise<CallerOrganization[]> => {\n const identity = await apiJson<MeResponse>(deps, origin, '/me')\n return identity.organizations\n}\n\nexport const resolveCommandOrganization = async (input: {\n deps: CliDeps\n organizations: CallerOrganization[]\n requested?: string\n machine: boolean\n}): Promise<CallerOrganization> => {\n const { deps, organizations, requested, machine } = input\n if (requested !== undefined) {\n const match = organizations.find((organization) => organization.organizationId === requested || organization.name === requested)\n if (match === undefined) {\n throw new CliUsageError(`Organization ${requested} is not available to this credential.`)\n }\n\n return match\n }\n\n if (organizations.length === 0) {\n throw new CliUsageError('This credential has no organizations. Log in with `qinto login` first.')\n }\n\n const only = organizations.at(0)\n if (organizations.length === 1 && only !== undefined) {\n return only\n }\n\n if (machine) {\n throw new CliUsageError('Several organizations are available. Pass --org <organizationId>.')\n }\n\n const chosen = await deps.prompts.select(\n 'Which organization should own the app?',\n organizations.map((organization) => ({ name: `${organization.name} (${organization.role})`, value: organization.organizationId }))\n )\n const match = organizations.find((organization) => organization.organizationId === chosen)\n if (match === undefined) {\n throw new CliUsageError(`Organization ${chosen} is not available to this credential.`)\n }\n\n return match\n}\n","import type { operations } from '../../../generated/api'\nimport { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport type { CallerOrganization } from '../../../lib/organizations'\nimport { listCallerOrganizations, resolveCommandOrganization } from '../../../lib/organizations'\n\ntype CreateAppResponse = operations['createApp']['responses']['201']['content']['application/json']\n\nexport type RegisteredApp = { app: CreateAppResponse['app']; organization: CallerOrganization }\n\nexport const registerOrganizationApp = async (input: {\n deps: CliDeps\n origin: string\n machine: boolean\n slug: string\n name: string\n description?: string\n org?: string\n}): Promise<RegisteredApp> => {\n const { deps, origin, machine, slug, name, description, org } = input\n const organizations = await listCallerOrganizations(deps, origin)\n const organization = await resolveCommandOrganization({ deps, organizations, requested: org, machine })\n const body = { slug, name, ...(description === undefined ? {} : { description }) }\n const response = await apiJson<CreateAppResponse>(deps, origin, `/developer/organizations/${organization.organizationId}/apps`, {\n method: 'POST',\n body\n })\n return { app: response.app, organization }\n}\n\nexport const printRegisteredApp = (deps: CliDeps, registered: RegisteredApp): void => {\n deps.stdout(`Registered app '${registered.app.name}' (${registered.app.slug}) in ${registered.organization.name}.\\n`)\n deps.stdout(`App ID: ${registered.app.appId}\\n`)\n}\n","import { APP_SLUG_PATTERN } from '@qinto/app-manifest'\n\nimport type { operations } from '../../../generated/api'\nimport { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport { CliUsageError } from '../../../lib/errors'\n\ntype SlugCheck = operations['checkAppSlug']['responses']['200']['content']['application/json']\n\nconst MAX_SLUG_LENGTH = 30\n// No slug can carry a '!', so this can never collide with a suggestion.\nconst TYPE_ANOTHER = '!other'\n\nexport const slugFromName = (name: string): string => {\n const candidate = name\n .normalize('NFKD')\n .toLowerCase()\n .replaceAll(/[^a-z0-9]+/g, '-')\n .replace(/^[^a-z]+/, '')\n .slice(0, MAX_SLUG_LENGTH)\n .replace(/-+$/, '')\n return APP_SLUG_PATTERN.test(candidate) ? candidate : ''\n}\n\ntype SlugProblem = { message: string; suggestions: string[] }\n\nconst formatProblem = (slug: string): SlugProblem | null => {\n if (APP_SLUG_PATTERN.test(slug) && !slug.endsWith('-')) {\n return null\n }\n\n return {\n message: `'${slug}' is not a valid app slug. Slugs are 3-30 lowercase letters, digits, and hyphens, starting with a letter and not ending with a hyphen.`,\n suggestions: []\n }\n}\n\nconst availabilityProblem = async (deps: CliDeps, origin: string, slug: string): Promise<SlugProblem | null> => {\n let check: SlugCheck\n try {\n check = await apiJson<SlugCheck>(deps, origin, `/developer/app-slugs/${slug}`)\n } catch (error) {\n // Scaffolding works offline and before `qinto login`, so an unanswered check never stops it.\n deps.stderr(`Could not check whether '${slug}' is free: ${(error as Error).message}\\n`)\n return null\n }\n\n if (check.available) {\n return null\n }\n\n const message =\n check.reason === 'reserved'\n ? `Slug '${slug}' is reserved by the Qinto platform.`\n : `Slug '${slug}' is already registered, and slugs are never released.`\n return { message, suggestions: check.suggestions }\n}\n\nconst askForSlug = async (deps: CliDeps, suggestions: string[]): Promise<string> => {\n if (suggestions.length === 0) {\n return deps.prompts.input('App slug')\n }\n\n const choices = [\n ...suggestions.map((suggestion) => ({ name: suggestion, value: suggestion })),\n { name: 'Enter a different slug…', value: TYPE_ANOTHER }\n ]\n const chosen = await deps.prompts.select('These slugs are free', choices, suggestions[0])\n if (chosen === TYPE_ANOTHER) {\n return deps.prompts.input('App slug')\n }\n\n return chosen\n}\n\nconst proposeSlug = async (deps: CliDeps, origin: string, name: string): Promise<string> => {\n const derived = slugFromName(name)\n if (derived === '') {\n return deps.prompts.input('App slug')\n }\n\n const problem = await availabilityProblem(deps, origin, derived)\n if (problem === null) {\n return deps.prompts.input('App slug', derived)\n }\n\n deps.stderr(`${problem.message}\\n`)\n return askForSlug(deps, problem.suggestions)\n}\n\nexport const resolveAppSlug = async (input: {\n deps: CliDeps\n origin: string\n machine: boolean\n slug?: string\n name: string\n}): Promise<string> => {\n const { deps, origin, machine } = input\n const passed = input.slug === undefined || input.slug === '' ? null : input.slug\n // The derived slug is checked before it is offered, so the prompt never proposes a taken one.\n let slug = passed ?? (machine ? slugFromName(input.name) : await proposeSlug(deps, origin, input.name))\n\n for (;;) {\n const problem = formatProblem(slug) ?? (await availabilityProblem(deps, origin, slug))\n if (problem === null) {\n return slug\n }\n\n if (machine) {\n const alternatives = problem.suggestions.length === 0 ? '' : ` Free slugs: ${problem.suggestions.join(', ')}.`\n throw new CliUsageError(`${problem.message}${alternatives} Pass a different --slug.`)\n }\n\n deps.stderr(`${problem.message}\\n`)\n slug = await askForSlug(deps, problem.suggestions)\n }\n}\n","import { existsSync } from 'node:fs'\nimport { join, resolve } from 'node:path'\n\nimport type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliError, CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport { installDependencies, scaffoldInstallCommands } from './common/install'\nimport { APP_MANIFEST_FILENAME } from './common/manifest-file'\nimport type { RegisteredApp } from './common/register-app'\nimport { printRegisteredApp, registerOrganizationApp } from './common/register-app'\nimport { applyTemplate, scaffoldUi, setManifestUi, templatesRoot } from './common/scaffold'\nimport { resolveAppSlug } from './common/slug'\n\nconst TEMPLATES = ['minimal', 'full'] as const\n\ntype Template = (typeof TEMPLATES)[number]\n\nconst TEMPLATE_CHOICES = [\n { name: 'minimal', value: 'minimal', description: 'A server entry with one track hook.' },\n { name: 'full', value: 'full', description: 'Transform and destination hooks, a browser bundle, install variables, and the UI panel.' }\n]\n\nconst TEMPLATE_DECLARES_UI: Record<Template, boolean> = { minimal: false, full: true }\n\ntype CreateOptions = ApiTarget & {\n slug?: string\n name?: string\n template?: Template\n ui?: boolean\n install?: boolean\n register?: boolean\n org?: string\n json?: boolean\n input?: boolean\n}\n\nconst resolveName = async (input: { deps: CliDeps; machine: boolean; name?: string }): Promise<string> => {\n if (input.name !== undefined && input.name !== '') {\n return input.name\n }\n\n if (input.machine) {\n throw new CliUsageError('Pass --name <name>.')\n }\n\n return input.deps.prompts.input('App name')\n}\n\nconst resolveTemplate = async (input: { deps: CliDeps; machine: boolean; template?: Template }): Promise<Template> => {\n if (input.template !== undefined) {\n return input.template\n }\n\n if (input.machine) {\n return 'minimal'\n }\n\n return (await input.deps.prompts.select('Template', TEMPLATE_CHOICES, 'minimal')) as Template\n}\n\nconst shouldRegister = async (input: { deps: CliDeps; machine: boolean; register?: boolean; slug: string }): Promise<boolean> => {\n if (input.register !== undefined) {\n return input.register\n }\n\n if (input.machine) {\n return false\n }\n\n return input.deps.prompts.confirm(`Register '${input.slug}' with the Qinto platform now?`, true)\n}\n\nconst scaffold = async (input: { dir: string; template: Template; ui: boolean; slug: string; name: string }): Promise<string[]> => {\n const values = { slug: input.slug, name: input.name }\n const templates = templatesRoot()\n const files: string[] = []\n // The shared panel first, so a template that ships its own panel overwrites it rather than being\n // overwritten by the generic one — `full`'s panel calls a `ui` handler the generic one does not.\n if (input.ui) {\n files.push(...(await scaffoldUi({ dir: input.dir, values })))\n }\n\n files.push(\n ...(await applyTemplate({ templateDir: join(templates, 'project'), targetDir: input.dir, values })),\n ...(await applyTemplate({ templateDir: join(templates, 'app', input.template), targetDir: input.dir, values }))\n )\n if (input.ui && !TEMPLATE_DECLARES_UI[input.template]) {\n await setManifestUi(join(input.dir, APP_MANIFEST_FILENAME))\n }\n\n return [...new Set(files)].sort()\n}\n\nconst install = async (input: { deps: CliDeps; dir: string; ui: boolean; json: boolean }): Promise<string[]> => {\n const commands = await scaffoldInstallCommands()\n const targets = [{ dir: input.dir, command: commands.root }]\n if (input.ui) {\n targets.push({ dir: join(input.dir, 'ui'), command: commands.ui })\n }\n\n const failed: string[] = []\n for (const target of targets) {\n if (!input.json) {\n input.deps.stdout(`\\nInstalling dependencies: \\`${target.command}\\` in ${target.dir}\\n`)\n }\n\n if (!(await installDependencies(target))) {\n failed.push(`\\`${target.command}\\` in ${target.dir}`)\n }\n }\n\n return failed\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as CreateOptions\n const machine = machineMode(options, deps)\n const json = options.json === true\n const dir = resolve(input.positionals.at(0) ?? '.')\n if (existsSync(join(dir, APP_MANIFEST_FILENAME))) {\n throw new CliUsageError(`${dir} already contains ${APP_MANIFEST_FILENAME}. Scaffold into an empty directory instead.`)\n }\n\n const name = await resolveName({ deps, machine, name: options.name })\n const origin = await resolveApiOrigin(deps, options)\n const slug = await resolveAppSlug({ deps, origin, machine, slug: options.slug, name })\n const template = await resolveTemplate({ deps, machine, template: options.template })\n const ui = options.ui === true || TEMPLATE_DECLARES_UI[template]\n const files = await scaffold({ dir, template, ui, slug, name })\n if (!json) {\n deps.stdout(`Scaffolded '${slug}' (${template} template) in ${dir}:\\n`)\n for (const file of files) {\n deps.stdout(` ${file}\\n`)\n }\n }\n\n let failedInstalls: string[] = []\n if (options.install !== false) {\n failedInstalls = await install({ deps, dir, ui, json })\n }\n\n const installed = options.install !== false && failedInstalls.length === 0\n let registered: RegisteredApp | null = null\n if (await shouldRegister({ deps, machine, register: options.register, slug })) {\n registered = await registerOrganizationApp({ deps, origin, machine, slug, name, org: options.org })\n }\n\n if (json) {\n const app = registered === null ? {} : { app: { ...registered.app, organizationName: registered.organization.name } }\n deps.stdout(`${JSON.stringify({ dir, slug, name, template, ui, installed, files, ...app }, null, 2)}\\n`)\n } else if (registered === null) {\n deps.stdout('\\nNext: register it with `qinto app register`, then publish with `qinto app publish`.\\n')\n } else {\n printRegisteredApp(deps, registered)\n deps.stdout('Next: publish it with `qinto app publish`.\\n')\n }\n\n if (failedInstalls.length > 0) {\n throw new CliError(\n `The scaffold is in ${dir}, but ${failedInstalls.join(' and ')} failed. Run it yourself before \\`qinto app publish\\`.`\n )\n }\n}\n\nexport const appCreateCommand: CommandSpec = {\n path: ['app', 'create'],\n description: 'Scaffold a new Qinto app in a directory, install its dependencies, and optionally register it',\n positionals: [{ name: 'dir', description: 'Directory to scaffold into (defaults to the current one)', required: false }],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--name <name>', description: 'App display name', type: 'string' },\n {\n flag: '--slug <slug>',\n description: 'Immutable app slug (3-30 lowercase letters, digits, hyphens); derived from the name when omitted',\n type: 'string'\n },\n {\n flag: '--template <template>',\n description: 'Scaffold to start from (prompted when omitted; `minimal` without prompts)',\n type: 'string',\n enum: TEMPLATES\n },\n { flag: '--ui', description: 'Also scaffold the Astro UI panel under ui/ (the full template always has one)', type: 'boolean' },\n { flag: '--no-install', description: 'Skip installing the scaffold dependencies', type: 'boolean' },\n { flag: '--register', description: 'Register the app under an organization after scaffolding', type: 'boolean' },\n { flag: '--no-register', description: 'Scaffold only, without asking to register the app', type: 'boolean' },\n {\n flag: '--org <organization>',\n description: 'Owning organization id or name when registering (prompted when ambiguous)',\n type: 'string'\n },\n { flag: '--no-input', description: 'Disable all interactive prompts', type: 'boolean' },\n { flag: '--json', description: 'Print the scaffolded files as JSON', type: 'boolean' }\n ],\n result: { type: 'app-create' },\n run\n}\n","import type { DeployableApp } from '@qinto/app-deploy'\nimport type { AppManifest } from '@qinto/app-manifest'\n\nimport type { DevInstall, DevState } from '../state'\n\n// Plain values live on the install; secret values live in the dev secrets file, so completeness is\n// judged against both — the same split the platform makes between the jsonb column and the vault.\nexport type InstallSecrets = Record<string, Record<string, string>>\n\nconst isSet = (manifest: AppManifest, install: DevInstall, secrets: InstallSecrets, name: string): boolean => {\n const variable = manifest.variables.find((candidate) => candidate.name === name)\n if (variable?.kind === 'secret') {\n return secrets[install.appInstallId]?.[name] !== undefined\n }\n\n return install.variables[name] !== undefined\n}\n\nexport const missingRequiredVariables = (manifest: AppManifest, install: DevInstall, secrets: InstallSecrets): string[] => {\n return manifest.variables\n .filter((variable) => {\n return variable.required === true && !isSet(manifest, install, secrets, variable.name)\n })\n .map((variable) => variable.name)\n}\n\n// The dispatch predicate the platform uses: app enabled, install enabled, and every required\n// variable set. An inactive install stays in the registry but receives nothing.\nexport const isInstallActive = (manifest: AppManifest, state: DevState, install: DevInstall, secrets: InstallSecrets): boolean => {\n if (!state.enabled || !install.enabled) {\n return false\n }\n\n return missingRequiredVariables(manifest, install, secrets).length === 0\n}\n\ntype DeployableInput = {\n manifest: AppManifest\n state: DevState\n secrets: InstallSecrets\n version: string\n workerName: string\n}\n\nexport const devDeployableApp = (input: DeployableInput): DeployableApp => {\n return {\n domainAppId: input.state.appId,\n appId: input.state.appId,\n slug: input.manifest.slug,\n workerName: input.workerName,\n version: input.version,\n versionId: input.version,\n manifest: input.manifest,\n installs: input.state.installs.map((install) => ({\n appInstallId: install.appInstallId,\n ordinal: install.ordinal,\n label: install.label,\n active: isInstallActive(input.manifest, input.state, install, input.secrets),\n enabled: input.state.enabled && install.enabled,\n variables: install.variables\n })),\n grants: {}\n }\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, rm } from 'node:fs/promises'\nimport { homedir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nexport type DevPaths = {\n root: string\n state: string\n secrets: string\n appValues: string\n persist: string\n}\n\n// Outside the app directory on purpose: the secrets file is plaintext, and `qinto app dev` runs in\n// hand-written projects whose .gitignore we do not control.\nexport const devPaths = (projectDir: string): DevPaths => {\n const key = createHash('sha256').update(resolve(projectDir)).digest('hex').slice(0, 16)\n const root = join(homedir(), '.qinto', 'dev', key)\n\n return {\n root,\n state: join(root, 'state.json'),\n secrets: join(root, 'secrets.json'),\n appValues: join(root, 'app-values.json'),\n persist: join(root, 'persist')\n }\n}\n\nexport const ensureDevRoot = async (paths: DevPaths): Promise<void> => {\n await mkdir(paths.persist, { recursive: true, mode: 0o700 })\n}\n\nexport const resetDevRoot = async (paths: DevPaths): Promise<void> => {\n await rm(paths.root, { recursive: true, force: true })\n}\n","import { z } from 'zod'\n\nexport const ENVELOPE_VERSION = 2\n\n// One install per hook call is the developer contract; the platform batches an app's installs\n// into one invocation, so the arithmetic response bound is installs × the per-install caps.\nexport const MAX_INSTALLS_PER_APP = 15\n\nexport const MAX_EMITS_PER_INSTALL = 10\n\nexport const MAX_PUSHES_PER_INSTALL = 10\n\nexport const MAX_ATTRIBUTION_WRITES_PER_INSTALL = 10\n\n// There are exactly two writable levels, and repeat `set` calls on one level merge into a single\n// pending write, so a conforming runtime never produces a third.\nexport const MAX_CONTEXT_WRITES_PER_INSTALL = 2\n\nexport const CONTEXT_LEVELS = ['private', 'shared'] as const\n\n// How wide a push reaches. All three are nameable rather than leaving the narrowest implicit, so\n// every switch over the value has one case per member and no `undefined` branch.\nexport const PUSH_BROADCASTS = ['install', 'app', 'site'] as const\n\nexport type PushBroadcast = (typeof PUSH_BROADCASTS)[number]\n\n// Storage is not what these bound — a Durable Object holds 10 GB. Context is serialized into every\n// hook envelope, and the shared level is delivered to every app on the site, so the ceiling is\n// MAX_ENVELOPE_BYTES: shared is capped at a quarter of private because it is multiplied by the\n// apps-per-domain limit, and private is delivered only to the app that wrote it.\nexport const MAX_PRIVATE_CONTEXT_ENTRY_BYTES = 32 * 1024\n\nexport const MAX_SHARED_CONTEXT_ENTRY_BYTES = 4 * 1024\n\nexport const MAX_PUSH_BYTES = 16 * 1024\n\n// Defense in depth: a conforming runtime's largest legal response is far below this.\nexport const MAX_RESPONSE_BYTES = 1024 * 1024\n\nexport const MAX_RPC_BYTES = 128 * 1024\n\nconst installSchema = z.object({ id: z.string().min(1).max(64), ord: z.number().int().min(1), label: z.string().max(100) }).strict()\n\nconst emitSchema = z\n .object({ type: z.literal('track'), occurredAt: z.number().int().nonnegative().safe(), payload: z.record(z.string(), z.unknown()) })\n .strict()\n\nconst pushSchema = z\n .object({ topic: z.string().min(1).max(64), data: z.unknown(), broadcast: z.enum(PUSH_BROADCASTS).optional() })\n .strict()\n .refine((push) => {\n return new TextEncoder().encode(JSON.stringify(push.data ?? null)).length <= MAX_PUSH_BYTES\n }, 'Push data exceeds the per-message size cap')\n\nconst attributionWriteSchema = z.object({ key: z.string().min(1).max(64), value: z.string().max(512) }).strict()\n\nconst contextValueSchema = z.union([z.string(), z.number().finite(), z.boolean()])\n\n// A patch, not a replacement: an absent key keeps its stored value and a null one deletes it. No\n// per-field length here — the entry's serialized size is bounded where the merge happens, because a\n// patch that fits on its own can still overflow the entry it merges into.\nexport const contextWriteSchema = z\n .object({\n level: z.enum(CONTEXT_LEVELS),\n kv: z.record(z.string().min(1), contextValueSchema.nullable()).optional(),\n text: z.string().min(1).nullable().optional()\n })\n .strict()\n .refine((write) => {\n return write.kv !== undefined || write.text !== undefined\n }, 'A context write carries kv, text, or both')\n\nconst contextEntrySchema = z\n .object({ kv: z.record(z.string().min(1), contextValueSchema), text: z.string().nullable(), updatedAt: z.number().int() })\n .strict()\n\nconst effectGroupSchema = z\n .object({\n ord: z.number().int().min(1),\n emits: z.array(emitSchema).optional(),\n pushes: z.array(pushSchema).optional(),\n attribution: z.array(attributionWriteSchema).optional(),\n context: z.array(contextWriteSchema).optional()\n })\n .strict()\n\nconst attributionValueSchema = z.object({ value: z.string().max(512), createdAt: z.number().int(), updatedAt: z.number().int() }).strict()\n\nconst actionContextFields = {\n occurredAt: z.number().int().nonnegative().safe(),\n page: z\n .object({ url: z.string().min(1).max(4096), referrer: z.string().min(1).max(4096).optional() })\n .strict()\n .optional(),\n network: z\n .object({\n ip: z.string().min(1).max(64).optional(),\n userAgent: z.string().min(1).max(512).optional(),\n locale: z.string().min(1).max(64).optional(),\n provenance: z.enum(['edge', 'caller'])\n })\n .strict()\n .optional(),\n session: z\n .object({ id: z.string().min(1).max(64), isNew: z.boolean() })\n .strict()\n .optional()\n}\n\nconst actionContextSchema = z.discriminatedUnion('source', [\n z.object({ source: z.literal('browser'), ...actionContextFields }).strict(),\n z.object({ source: z.literal('server'), ...actionContextFields, offline: z.boolean(), replay: z.boolean() }).strict(),\n z.object({ source: z.literal('app'), ...actionContextFields, offline: z.boolean(), replay: z.boolean() }).strict()\n])\n\nexport const envelopeRequestSchema = z\n .object({\n v: z.literal(ENVELOPE_VERSION),\n kind: z.enum(['event', 'connect', 'transform', 'rpc']),\n site: z.object({ origin: z.string().min(1).max(255) }).strict(),\n app: z.object({ slug: z.string().min(1).max(30), version: z.string().min(1).max(32) }).strict(),\n installs: z.array(installSchema).min(1).max(MAX_INSTALLS_PER_APP),\n user: z\n .object({\n anonId: z.string().min(1).max(64),\n globalId: z.string().min(1).max(64).nullable(),\n properties: z.record(z.string(), z.unknown()),\n geo: z.record(z.string(), z.string()).optional()\n })\n .strict(),\n consent: z\n .object({ categories: z.record(z.string(), z.boolean()), apps: z.record(z.string(), z.boolean()) })\n .strict()\n .optional(),\n geo: z.record(z.string(), z.unknown()).optional(),\n // Only what this app captured or wrote for this visitor; `updatedAt` is when the current value\n // was first seen, which is the click time a CAPI `fbc` is built from.\n attribution: z.record(z.string().max(64), attributionValueSchema).optional(),\n // `shared` rides only with the `sharedContext` grant, applied per reader before delivery.\n context: z\n .object({ private: contextEntrySchema.optional(), shared: z.record(z.string().min(1).max(30), contextEntrySchema).optional() })\n .strict()\n .optional(),\n // RPC depth is capped at 3 by the broker; hook depth at 2 by the emit path.\n depth: z.number().int().min(0).max(3),\n rpc: z\n .object({ caller: z.string().min(1).max(30).nullable(), fn: z.string().min(1).max(64), args: z.unknown() })\n .strict()\n .refine((rpc) => {\n return new TextEncoder().encode(JSON.stringify(rpc.args ?? null)).length <= MAX_RPC_BYTES\n }, 'RPC args exceed the size cap')\n .optional(),\n action: z\n .object({\n actionId: z.string().min(1).max(64),\n type: z.enum(['track', 'identify', 'consent']),\n // The SDK's AppAction declares these; the handler receives this object verbatim.\n userId: z.string().min(1).max(64),\n payload: z.record(z.string(), z.unknown()),\n receivedAt: z.number().int(),\n context: actionContextSchema.optional(),\n browser: z.record(z.string().min(1).max(64), z.unknown()).optional(),\n origin: z\n .object({ app: z.string().min(1).max(30), install: z.number().int().min(1), depth: z.number().int().min(0) })\n .strict()\n .optional()\n })\n .strict()\n .optional()\n })\n .strict()\n\nexport const envelopeResponseSchema = z\n .object({\n v: z.literal(ENVELOPE_VERSION),\n // Transform invocations only: pass the action through, drop it, or replace its payload (§5.4).\n result: z.union([z.literal('pass'), z.literal('drop'), z.object({ payload: z.record(z.string(), z.unknown()) }).strict()]).optional(),\n effects: z.array(effectGroupSchema).optional(),\n rpc: z\n .object({ result: z.unknown() })\n .strict()\n .refine((rpc) => {\n return new TextEncoder().encode(JSON.stringify(rpc.result ?? null)).length <= MAX_RPC_BYTES\n }, 'RPC result exceeds the size cap')\n .optional(),\n error: z\n .object({ message: z.string().max(2048) })\n .strict()\n .optional()\n })\n .strict()\n\nexport type EnvelopeInstall = z.infer<typeof installSchema>\n\nexport type EnvelopeRequest = z.infer<typeof envelopeRequestSchema>\n\nexport type EnvelopeResponse = z.infer<typeof envelopeResponseSchema>\n\nexport type EnvelopeEmit = z.infer<typeof emitSchema>\n\nexport type EnvelopePush = z.infer<typeof pushSchema>\n\nexport type EnvelopeEffectGroup = z.infer<typeof effectGroupSchema>\n\nexport type EnvelopeAttributionWrite = z.infer<typeof attributionWriteSchema>\n\nexport type EnvelopeAttribution = NonNullable<EnvelopeRequest['attribution']>\n\nexport type ContextLevel = (typeof CONTEXT_LEVELS)[number]\n\nexport type EnvelopeContextValue = z.infer<typeof contextValueSchema>\n\nexport type EnvelopeContextWrite = z.infer<typeof contextWriteSchema>\n\nexport type EnvelopeContextEntry = z.infer<typeof contextEntrySchema>\n\nexport type EnvelopeContext = NonNullable<EnvelopeRequest['context']>\n\nexport type AcceptedEffects = {\n // Per-install groups that passed their caps; a group over its own limit is rejected whole.\n accepted: {\n ord: number\n emits: EnvelopeEmit[]\n pushes: EnvelopePush[]\n attribution: EnvelopeAttributionWrite[]\n context: EnvelopeContextWrite[]\n }[]\n rejectedOrds: number[]\n}\n\nexport type TransformResultValue = 'pass' | 'drop' | { payload: Record<string, unknown> }\n\nexport type EnvelopeResponseVerdict =\n | { ok: true; effects: AcceptedEffects; error: string | null; result: TransformResultValue | null; rpc: { result: unknown } | null }\n | { ok: false; reason: string }\n\nconst partitionEffectGroups = (groups: EnvelopeEffectGroup[]): AcceptedEffects => {\n const accepted: AcceptedEffects = { accepted: [], rejectedOrds: [] }\n for (const group of groups) {\n const emits = group.emits ?? []\n const pushes = group.pushes ?? []\n const attribution = group.attribution ?? []\n const context = group.context ?? []\n const levels = new Set(context.map((write) => write.level))\n if (\n emits.length > MAX_EMITS_PER_INSTALL ||\n pushes.length > MAX_PUSHES_PER_INSTALL ||\n attribution.length > MAX_ATTRIBUTION_WRITES_PER_INSTALL ||\n context.length > MAX_CONTEXT_WRITES_PER_INSTALL ||\n // Two writes for one level would make the merge order decide the result; a conforming runtime\n // merges them before it answers, so the pair is evidence the response was not built by one.\n levels.size !== context.length\n ) {\n accepted.rejectedOrds.push(group.ord)\n } else if (emits.length > 0 || pushes.length > 0 || attribution.length > 0 || context.length > 0) {\n accepted.accepted.push({ ord: group.ord, emits, pushes, attribution, context })\n }\n }\n\n return accepted\n}\n\n/**\n * Validates a hook response against the envelope schema and the effect-cap policy.\n * @param raw The parsed JSON body the app worker returned.\n * @param installCount How many installs the request carried; bounds the legal aggregate count of emits, pushes, attribution writes and context writes together.\n * @returns The accepted per-install effect groups with over-limit groups rejected whole, or a refusal when the response is malformed or beyond the arithmetic bound a conforming runtime can produce.\n */\nexport const validateEnvelopeResponse = (raw: unknown, installCount: number): EnvelopeResponseVerdict => {\n const parsed = envelopeResponseSchema.safeParse(raw)\n if (!parsed.success) {\n return { ok: false, reason: 'The response does not match the envelope schema.' }\n }\n\n const groups = parsed.data.effects ?? []\n const totalEffects = groups.reduce(\n (sum, group) =>\n sum + (group.emits?.length ?? 0) + (group.pushes?.length ?? 0) + (group.attribution?.length ?? 0) + (group.context?.length ?? 0),\n 0\n )\n const aggregateBound =\n installCount * (MAX_EMITS_PER_INSTALL + MAX_PUSHES_PER_INSTALL + MAX_ATTRIBUTION_WRITES_PER_INSTALL + MAX_CONTEXT_WRITES_PER_INSTALL)\n if (groups.length > installCount || totalEffects > aggregateBound) {\n return { ok: false, reason: 'The response carries more effects than a conforming runtime can produce.' }\n }\n\n return {\n ok: true,\n effects: partitionEffectGroups(groups),\n error: parsed.data.error?.message ?? null,\n result: parsed.data.result ?? null,\n rpc: parsed.data.rpc ?? null\n }\n}\n","// The leaf module, not the barrel: the barrel drags the manifest's Zod schema — and its top-level\n// construction — into every worker that carries this envelope.\nimport { MAX_CRON_LENGTH } from '@qinto/app-manifest/cron'\nimport { z } from 'zod'\n\nimport { MAX_INSTALLS_PER_APP } from './envelope'\n\nexport const CONTROL_ENVELOPE_VERSION = 1\n\nexport const MAX_CONTROL_BYTES = 256 * 1024\n\nexport const MAX_MIGRATION_CHECKPOINT_BYTES = 16 * 1024\n\nconst installSchema = z\n .object({\n id: z.string().min(1).max(64),\n ord: z.number().int().min(1),\n label: z.string().max(100),\n enabled: z.boolean(),\n configured: z.boolean(),\n active: z.boolean()\n })\n .strict()\n\nconst lifecycleBase = {\n eventId: z.string().min(1).max(64),\n occurredAt: z.number().int().nonnegative().safe(),\n sequence: z.number().int().min(1),\n install: installSchema\n}\n\nconst installStateSchema = installSchema.omit({ id: true, ord: true, label: true })\n\nconst lifecycleEventSchema = z.discriminatedUnion('type', [\n z.object({ ...lifecycleBase, type: z.literal('installed') }).strict(),\n z\n .object({\n ...lifecycleBase,\n type: z.literal('configurationChanged'),\n scope: z.enum(['app', 'install']),\n changedVariables: z.array(z.string().min(1).max(64)),\n changedSecrets: z.array(z.string().min(1).max(64)),\n previousVariables: z.record(z.string(), z.union([z.string(), z.boolean()])),\n previousSecrets: z.record(z.string(), z.string()),\n previousInstall: installStateSchema\n })\n .strict(),\n z.object({ ...lifecycleBase, type: z.literal('enabled'), scope: z.enum(['app', 'install']) }).strict(),\n z.object({ ...lifecycleBase, type: z.literal('disabled'), scope: z.enum(['app', 'install']) }).strict(),\n z\n .object({\n ...lifecycleBase,\n type: z.literal('versionChanged'),\n fromVersion: z.string().min(1).max(32),\n toVersion: z.string().min(1).max(32)\n })\n .strict(),\n z.object({ ...lifecycleBase, type: z.literal('uninstalled'), scope: z.enum(['app', 'install']) }).strict()\n])\n\nconst migrationSchema = z.discriminatedUnion('phase', [\n z\n .object({\n resource: z.string().min(1).max(64),\n binding: z.string().min(1).max(255),\n id: z.string().min(1).max(64),\n checksum: z.string().regex(/^[0-9a-f]{64}$/),\n phase: z.enum(['expand', 'contract']),\n statements: z\n .array(\n z\n .string()\n .min(1)\n .max(100 * 1024)\n )\n .min(1)\n })\n .strict(),\n z\n .object({\n resource: z.string().min(1).max(64),\n binding: z.string().min(1).max(255),\n id: z.string().min(1).max(64),\n checksum: z.string().regex(/^[0-9a-f]{64}$/),\n phase: z.literal('backfill'),\n handler: z.string().min(1).max(128),\n checkpoint: z.unknown().nullable()\n })\n .strict()\n .refine((migration) => {\n return new TextEncoder().encode(JSON.stringify(migration.checkpoint)).length <= MAX_MIGRATION_CHECKPOINT_BYTES\n }, 'Migration checkpoint exceeds the size cap')\n])\n\n// One delivery carries every install of the app that is due on this site, so installs never multiply\n// worker invocations — the same rule the hook envelope's `installs` follows.\nconst scheduleSchema = z\n .object({\n id: z.string().min(1).max(32),\n cron: z.string().min(1).max(MAX_CRON_LENGTH),\n scheduledTime: z.number().int().nonnegative().safe(),\n installs: z\n .array(z.object({ id: z.string().min(1).max(64), ord: z.number().int().min(1), label: z.string().max(100) }).strict())\n .min(1)\n .max(MAX_INSTALLS_PER_APP)\n })\n .strict()\n\nexport const controlEnvelopeSchema = z\n .object({\n v: z.literal(CONTROL_ENVELOPE_VERSION),\n kind: z.enum(['noop', 'lifecycle', 'migration', 'schedule']),\n site: z.object({ origin: z.string().min(1).max(255) }).strict(),\n app: z.object({ slug: z.string().min(1).max(30), version: z.string().min(1).max(32) }).strict(),\n install: z\n .object({ id: z.string().min(1).max(64), ord: z.number().int().min(1), label: z.string().max(100) })\n .strict()\n .optional(),\n lifecycle: lifecycleEventSchema.optional(),\n migration: migrationSchema.optional(),\n schedule: scheduleSchema.optional()\n })\n .strict()\n .superRefine((envelope, ctx) => {\n if ((envelope.kind === 'lifecycle') !== (envelope.lifecycle !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['lifecycle'], message: 'Lifecycle payload must match the control kind' })\n }\n\n if ((envelope.kind === 'migration') !== (envelope.migration !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['migration'], message: 'Migration payload must match the control kind' })\n }\n\n if ((envelope.kind === 'schedule') !== (envelope.schedule !== undefined)) {\n ctx.addIssue({ code: 'custom', path: ['schedule'], message: 'Schedule payload must match the control kind' })\n }\n\n if (envelope.kind === 'lifecycle' && envelope.install === undefined) {\n ctx.addIssue({ code: 'custom', path: ['install'], message: 'Lifecycle control needs an install' })\n }\n })\n\nexport const controlResponseSchema = z\n .object({\n v: z.literal(CONTROL_ENVELOPE_VERSION),\n ok: z.boolean(),\n migration: z\n .union([\n z.object({ done: z.literal(true) }).strict(),\n z\n .object({ done: z.literal(false), checkpoint: z.unknown() })\n .strict()\n .refine((result) => {\n return new TextEncoder().encode(JSON.stringify(result.checkpoint)).length <= MAX_MIGRATION_CHECKPOINT_BYTES\n }, 'Migration checkpoint exceeds the size cap')\n ])\n .optional(),\n error: z\n .object({ message: z.string().max(2048) })\n .strict()\n .optional()\n })\n .strict()\n\nexport type ControlEnvelope = z.infer<typeof controlEnvelopeSchema>\n\nexport type ControlResponse = z.infer<typeof controlResponseSchema>\n\nexport type ControlSchedule = z.infer<typeof scheduleSchema>\n\nexport type ControlLifecycleEvent = z.infer<typeof lifecycleEventSchema>\n\nexport type ControlMigration = z.infer<typeof migrationSchema>\n","import { z } from 'zod'\n\nexport const ENDPOINT_CONTEXT_HEADER = 'x-qinto-endpoint-context'\n\nexport const ENDPOINT_OUTCOMES_HEADER = 'x-qinto-endpoint-outcomes'\n\n// The main worker buffers the body once and hands every install's handler the same bytes, so the\n// cap bounds one buffer per invocation rather than one per install.\nexport const MAX_ENDPOINT_BODY_BYTES = 1024 * 1024\n\nexport const MAX_ENDPOINT_OUTCOMES_BYTES = 64 * 1024\n\nconst installSchema = z.object({ id: z.string().min(1).max(64), ord: z.number().int().min(1), label: z.string().max(100) }).strict()\n\nexport const endpointContextSchema = z\n .object({\n path: z.string().min(1).max(255),\n method: z.enum(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']),\n mode: z.enum(['webhook', 'api']),\n version: z.string().min(1).max(32),\n installs: z.array(installSchema).min(1).max(15)\n })\n .strict()\n .refine((context) => {\n return context.mode === 'webhook' || context.installs.length === 1\n }, 'An api endpoint carries exactly one install')\n\nexport const endpointOutcomesSchema = z\n .object({\n outcomes: z\n .array(\n z\n .object({\n ord: z.number().int().min(1),\n outcome: z.enum(['handled', 'skipped']),\n status: z.number().int().min(100).max(599)\n })\n .strict()\n )\n .max(15)\n })\n .strict()\n\nexport type EndpointContext = z.infer<typeof endpointContextSchema>\n\nexport type EndpointOutcome = z.infer<typeof endpointOutcomesSchema>['outcomes'][number]\n\nexport type EndpointVerdict = { status: 200 | 404 | 502 }\n\n/**\n * Aggregates a webhook fan-out's per-install outcomes into the status the caller receives.\n * @param outcomes Each install's handled/skipped outcome with the status its handler produced.\n * @returns 200 when every handled install succeeded, 404 when no install handled the request, and 502 when any handled install failed — a success never masks another install's failure, so the vendor's retry fires.\n */\nexport const aggregateEndpointOutcomes = (outcomes: EndpointOutcome[]): EndpointVerdict => {\n const handled = outcomes.filter((outcome) => {\n return outcome.outcome === 'handled'\n })\n if (handled.length === 0) {\n return { status: 404 }\n }\n\n const failed = handled.some((outcome) => {\n return outcome.status < 200 || outcome.status > 299\n })\n\n return { status: failed ? 502 : 200 }\n}\n","import { z } from 'zod'\n\nimport { MAX_INSTALLS_PER_APP } from './envelope'\n\nexport const UI_CONTEXT_HEADER = 'x-qinto-ui-context'\n\nexport const MAX_UI_BODY_BYTES = 1024 * 1024\n\n/**\n * The path a `ui` handler writes one install's settings to, on the portal API and on the local\n * console standing in for it.\n * @param domainId The site the panel is open on.\n * @param appSlug The app whose panel is writing.\n * @returns The absolute path, to resolve against `QINTO_PLATFORM_API`.\n */\nexport const appUiWritePath = (domainId: string, appSlug: string): string => {\n return `/app-ui/sites/${domainId}/apps/${appSlug}/install-variables`\n}\n\nconst uiInstallSchema = z\n .object({ id: z.string().min(1).max(64), ord: z.number().int().min(1), label: z.string().max(100), enabled: z.boolean() })\n .strict()\n\n// One `.strict()` definition for both sides: the proxy that builds this header and the runtime that\n// parses it are separate deployables, so a field added to only one of them 400s every panel request.\nexport const uiContextSchema = z\n .object({\n version: z.string().min(1).max(32),\n viewer: z.object({ userId: z.string().min(1).max(64), access: z.enum(['read', 'write']) }).strict(),\n install: uiInstallSchema,\n installs: z.array(uiInstallSchema).min(1).max(MAX_INSTALLS_PER_APP),\n writeTicket: z.string().min(1).max(2048).optional()\n })\n .strict()\n\nexport type UiContext = z.infer<typeof uiContextSchema>\n\nexport type UiContextInstall = z.infer<typeof uiInstallSchema>\n\n/**\n * Parses the `x-qinto-ui-context` header the main worker's ui proxy sends.\n * @param raw The raw header value, or `null` when the header is absent.\n * @returns The validated context, or `null` when the header is absent, unparseable, or fails the schema.\n */\nexport const parseUiContext = (raw: string | null): UiContext | null => {\n if (raw === null) {\n return null\n }\n\n let json: unknown\n try {\n json = JSON.parse(raw)\n } catch {\n return null\n }\n\n const parsed = uiContextSchema.safeParse(json)\n\n return parsed.success ? parsed.data : null\n}\n","export const base64UrlEncode = (bytes: Uint8Array): string => {\n let binary = ''\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '')\n}\n\nexport const base64UrlDecode = (text: string): Uint8Array<ArrayBuffer> | null => {\n const padded = text\n .replaceAll('-', '+')\n .replaceAll('_', '/')\n .padEnd(text.length + ((4 - (text.length % 4)) % 4), '=')\n let binary: string\n try {\n binary = atob(padded)\n } catch {\n return null\n }\n\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index)\n }\n\n return bytes\n}\n","import { z } from 'zod'\n\nimport { base64UrlDecode, base64UrlEncode } from './base64url'\n\nconst envSchema = z\n .object({\n v: z.literal(1),\n keys: z.record(z.string().min(1).max(16), z.string().min(1))\n })\n .strict()\n\n/**\n * Serializes the `kid`-indexed verification keys into the APP_UI_KEY env value the site worker receives.\n * @param keys The verification keys by `kid`.\n * @returns The JSON env value for `parseAppUiKeyEnv` to read back.\n */\nexport const buildAppUiKeyEnv = (keys: Record<string, Uint8Array<ArrayBuffer>>): string => {\n return JSON.stringify({ v: 1, keys: Object.fromEntries(Object.entries(keys).map(([kid, key]) => [kid, base64UrlEncode(key)])) })\n}\n\n/**\n * Parses an APP_UI_KEY env value back into `kid`-indexed verification keys.\n * @param raw The env value.\n * @returns The keys by `kid`, or `null` when the value is malformed — the caller must refuse verification rather than proceed with no keys.\n */\nexport const parseAppUiKeyEnv = (raw: string): Record<string, Uint8Array<ArrayBuffer>> | null => {\n let json: unknown\n try {\n json = JSON.parse(raw)\n } catch {\n return null\n }\n\n const parsed = envSchema.safeParse(json)\n if (!parsed.success) {\n return null\n }\n\n const keys: Record<string, Uint8Array<ArrayBuffer>> = {}\n for (const [kid, encoded] of Object.entries(parsed.data.keys)) {\n const bytes = base64UrlDecode(encoded)\n if (bytes === null) {\n return null\n }\n\n keys[kid] = bytes\n }\n\n return keys\n}\n","import { z } from 'zod'\n\nimport { base64UrlDecode, base64UrlEncode } from './base64url'\n\nconst headerSchema = z\n .object({\n alg: z.literal('HS256'),\n typ: z.literal('JWT'),\n kid: z.string().min(1).max(16)\n })\n .strict()\n\nexport type SignatureRefusal = 'malformed' | 'unknown_kid' | 'bad_signature'\n\nexport type SignatureCheck =\n | { ok: true; claims: unknown; kid: string; key: Uint8Array<ArrayBuffer> }\n | { ok: false; reason: SignatureRefusal }\n\nconst encodeJsonPart = (value: unknown): string => {\n return base64UrlEncode(new TextEncoder().encode(JSON.stringify(value)))\n}\n\nconst parseJsonPart = (part: string): unknown => {\n const bytes = base64UrlDecode(part)\n if (bytes === null) {\n return null\n }\n\n try {\n return JSON.parse(new TextDecoder().decode(bytes))\n } catch {\n return null\n }\n}\n\nconst hmacKey = (key: Uint8Array<ArrayBuffer>, usage: 'sign' | 'verify'): Promise<CryptoKey> => {\n return crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, [usage])\n}\n\nexport const signCompact = async (kid: string, key: Uint8Array<ArrayBuffer>, claims: unknown): Promise<string> => {\n const signingInput = `${encodeJsonPart({ alg: 'HS256', typ: 'JWT', kid })}.${encodeJsonPart(claims)}`\n const signature = await crypto.subtle.sign('HMAC', await hmacKey(key, 'sign'), new TextEncoder().encode(signingInput))\n\n return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`\n}\n\n// The algorithm is pinned to HS256 here rather than read from the header, so a token's own `alg`\n// can never select the verification path (§5.9.2 item 7).\nexport const verifyCompactSignature = async (token: string, keys: Record<string, Uint8Array<ArrayBuffer>>): Promise<SignatureCheck> => {\n const [headerPart, claimsPart, signaturePart, extra] = token.split('.')\n if (headerPart === undefined || claimsPart === undefined || signaturePart === undefined || extra !== undefined) {\n return { ok: false, reason: 'malformed' }\n }\n\n const header = headerSchema.safeParse(parseJsonPart(headerPart))\n if (!header.success) {\n return { ok: false, reason: 'malformed' }\n }\n\n const key = keys[header.data.kid]\n if (key === undefined) {\n return { ok: false, reason: 'unknown_kid' }\n }\n\n const signature = base64UrlDecode(signaturePart)\n if (signature === null) {\n return { ok: false, reason: 'malformed' }\n }\n\n const signed = await crypto.subtle.verify(\n 'HMAC',\n await hmacKey(key, 'verify'),\n signature,\n new TextEncoder().encode(`${headerPart}.${claimsPart}`)\n )\n if (!signed) {\n return { ok: false, reason: 'bad_signature' }\n }\n\n return { ok: true, claims: parseJsonPart(claimsPart), kid: header.data.kid, key }\n}\n","import { z } from 'zod'\n\nimport type { SignatureRefusal } from './jwt'\nimport { signCompact, verifyCompactSignature } from './jwt'\n\nexport const APP_UI_TOKEN_TTL_SECONDS = 600\n\nexport const APP_UI_TOKEN_SKEW_SECONDS = 60\n\nexport const APP_UI_TOKEN_ISSUER = 'qinto-portal'\n\nconst claimsSchema = z\n .object({\n iss: z.literal(APP_UI_TOKEN_ISSUER),\n aud: z.string().min(1),\n sub: z.string().min(1),\n userId: z.string().min(1),\n iat: z.number().int(),\n exp: z.number().int(),\n domainId: z.string().min(1),\n appId: z.string().min(1),\n appInstallId: z.string().min(1),\n appVersionId: z.string().min(1),\n access: z.enum(['read', 'write'])\n })\n .strict()\n\nexport type AppUiAccess = z.infer<typeof claimsSchema>['access']\n\nexport type AppUiClaims = z.infer<typeof claimsSchema>\n\nexport type AppUiTokenRefusal = SignatureRefusal | 'bad_claims' | 'wrong_app' | 'future_iat' | 'expired'\n\n// The verifying key rides on the verdict so the caller can sign a write ticket with the same key it\n// just proved the token against, rather than re-indexing the map behind an unreachable guard.\nexport type AppUiTokenVerdict =\n | { ok: true; claims: AppUiClaims; kid: string; key: Uint8Array<ArrayBuffer> }\n | { ok: false; reason: AppUiTokenRefusal }\n\nexport type MintAppUiTokenInput = {\n kid: string\n key: Uint8Array<ArrayBuffer>\n now: Date\n slug: string\n userId: string\n domainId: string\n appId: string\n appInstallId: string\n appVersionId: string\n access: AppUiAccess\n ttlSeconds?: number\n}\n\nexport type VerifyAppUiTokenInput = {\n token: string\n keys: Record<string, Uint8Array<ArrayBuffer>>\n slug: string\n now: Date\n skewSeconds?: number\n}\n\n/**\n * Builds the audience claim binding an app-UI token to one app.\n * @param slug The app's slug.\n * @returns The `aud` value minted into and required from the token — mint and verify must derive it here, never inline.\n */\nexport const appUiAudience = (slug: string): string => {\n return `app-ui:${slug}`\n}\n\n/**\n * Mints the short-lived HS256 app-UI token the portal hands an iframe (§10.3).\n * @param input The signing key with its `kid`, the claim values, the mint instant, and an optional TTL override (default 10 minutes).\n * @returns The compact JWT.\n */\nexport const mintAppUiToken = async (input: MintAppUiTokenInput): Promise<string> => {\n const iat = Math.floor(input.now.getTime() / 1000)\n const claims: AppUiClaims = {\n iss: APP_UI_TOKEN_ISSUER,\n aud: appUiAudience(input.slug),\n sub: input.userId,\n userId: input.userId,\n iat,\n exp: iat + (input.ttlSeconds ?? APP_UI_TOKEN_TTL_SECONDS),\n domainId: input.domainId,\n appId: input.appId,\n appInstallId: input.appInstallId,\n appVersionId: input.appVersionId,\n access: input.access\n }\n return signCompact(input.kid, input.key, claims)\n}\n\n/**\n * Verifies an app-UI token with the algorithm pinned to HS256 — the header's `alg` never selects the verification path (§5.9.2 item 7).\n * @param input The token, the `kid`-indexed verification keys, the route's app slug, the verification instant, and an optional future-`iat` skew allowance (default 60 seconds).\n * @returns The verified claims, or a typed refusal naming the first check that failed.\n */\nexport const verifyAppUiToken = async (input: VerifyAppUiTokenInput): Promise<AppUiTokenVerdict> => {\n const signature = await verifyCompactSignature(input.token, input.keys)\n if (!signature.ok) {\n return signature\n }\n\n const claims = claimsSchema.safeParse(signature.claims)\n if (!claims.success) {\n return { ok: false, reason: 'bad_claims' }\n }\n\n if (claims.data.aud !== appUiAudience(input.slug)) {\n return { ok: false, reason: 'wrong_app' }\n }\n\n const now = Math.floor(input.now.getTime() / 1000)\n if (claims.data.iat > now + (input.skewSeconds ?? APP_UI_TOKEN_SKEW_SECONDS)) {\n return { ok: false, reason: 'future_iat' }\n }\n\n if (claims.data.exp <= now) {\n return { ok: false, reason: 'expired' }\n }\n\n return { ok: true, claims: claims.data, kid: signature.kid, key: signature.key }\n}\n","import { z } from 'zod'\n\nimport type { SignatureRefusal } from './jwt'\nimport { signCompact, verifyCompactSignature } from './jwt'\n\nexport const APP_UI_WRITE_TICKET_TTL_SECONDS = 60\n\nexport const APP_UI_WRITE_TICKET_ISSUER = 'qinto-site'\n\n// No `access` claim: the ticket's existence is the write grant, so a check on one would be\n// unreachable. The claim set is disjoint from the UI token's, which is one of the four things that\n// keep either from being replayed as the other.\nconst claimsSchema = z\n .object({\n iss: z.literal(APP_UI_WRITE_TICKET_ISSUER),\n aud: z.string().min(1),\n sub: z.string().min(1),\n iat: z.number().int(),\n exp: z.number().int(),\n domainId: z.string().min(1),\n appId: z.string().min(1),\n appVersionId: z.string().min(1)\n })\n .strict()\n\nexport type AppUiWriteTicketClaims = z.infer<typeof claimsSchema>\n\nexport type AppUiWriteTicketRefusal = SignatureRefusal | 'bad_claims' | 'wrong_app' | 'future_iat' | 'expired'\n\nexport type AppUiWriteTicketVerdict = { ok: true; claims: AppUiWriteTicketClaims } | { ok: false; reason: AppUiWriteTicketRefusal }\n\nexport type MintAppUiWriteTicketInput = {\n kid: string\n key: Uint8Array<ArrayBuffer>\n now: Date\n slug: string\n userId: string\n domainId: string\n appId: string\n appVersionId: string\n ttlSeconds?: number\n}\n\nexport type VerifyAppUiWriteTicketInput = {\n ticket: string\n keys: Record<string, Uint8Array<ArrayBuffer>>\n slug: string\n now: Date\n skewSeconds?: number\n}\n\nconst SKEW_SECONDS = 60\n\n/**\n * Builds the audience claim binding a write ticket to one app.\n * @param slug The app's slug.\n * @returns The `aud` value minted into and required from the ticket — mint and verify must derive it here, never inline.\n */\nexport const appUiWriteAudience = (slug: string): string => {\n return `app-ui-write:${slug}`\n}\n\n/**\n * Mints the 60-second ticket the main worker hands a ui handler so it can write this site's install settings.\n * @param input The signing key with its `kid`, the site and app the ticket authorizes, the version the proxy served, the viewer it acts for, the mint instant, and an optional TTL override.\n * @returns The compact JWT.\n */\nexport const mintAppUiWriteTicket = async (input: MintAppUiWriteTicketInput): Promise<string> => {\n const iat = Math.floor(input.now.getTime() / 1000)\n const claims: AppUiWriteTicketClaims = {\n iss: APP_UI_WRITE_TICKET_ISSUER,\n aud: appUiWriteAudience(input.slug),\n sub: input.userId,\n iat,\n exp: iat + (input.ttlSeconds ?? APP_UI_WRITE_TICKET_TTL_SECONDS),\n domainId: input.domainId,\n appId: input.appId,\n appVersionId: input.appVersionId\n }\n\n return signCompact(input.kid, input.key, claims)\n}\n\n/**\n * Verifies a write ticket with the algorithm pinned to HS256, against the per-domain app-UI keys that minted it.\n * @param input The ticket, the `kid`-indexed verification keys, the route's app slug, the verification instant, and an optional future-`iat` skew allowance (default 60 seconds).\n * @returns The verified claims, or a typed refusal naming the first check that failed — callers report every refusal identically so nothing is enumerable.\n */\nexport const verifyAppUiWriteTicket = async (input: VerifyAppUiWriteTicketInput): Promise<AppUiWriteTicketVerdict> => {\n const signature = await verifyCompactSignature(input.ticket, input.keys)\n if (!signature.ok) {\n return signature\n }\n\n const claims = claimsSchema.safeParse(signature.claims)\n if (!claims.success) {\n return { ok: false, reason: 'bad_claims' }\n }\n\n if (claims.data.aud !== appUiWriteAudience(input.slug)) {\n return { ok: false, reason: 'wrong_app' }\n }\n\n const now = Math.floor(input.now.getTime() / 1000)\n if (claims.data.iat > now + (input.skewSeconds ?? SKEW_SECONDS)) {\n return { ok: false, reason: 'future_iat' }\n }\n\n if (claims.data.exp <= now) {\n return { ok: false, reason: 'expired' }\n }\n\n return { ok: true, claims: claims.data }\n}\n","import { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nexport type ArtifactModule = { name: string; type: 'esm' | 'text'; contents: string }\n\nexport type WorkerArtifact = {\n version: string\n compatibilityDate: string\n compatibilityFlags: string[]\n mainModule: string\n modules: ArtifactModule[]\n}\n\nexport type ArtifactName = 'main' | 'app-runtime'\n\ntype VersionEntry = {\n version: string\n compatibilityDate: string\n compatibilityFlags: string[]\n mainModule: string\n modules: { name: string; path: string; contentType: string }[]\n}\n\nconst moduleType = (contentType: string): 'esm' | 'text' => {\n return contentType === 'application/javascript+module' ? 'esm' : 'text'\n}\n\nexport const loadWorkerArtifact = async (root: string, name: ArtifactName): Promise<WorkerArtifact> => {\n const manifest = JSON.parse(await readFile(join(root, 'version.json'), 'utf8')) as Record<string, VersionEntry | undefined>\n const entry = manifest[name]\n if (entry === undefined) {\n throw new Error(`The artifact directory ${root} carries no ${name} worker.`)\n }\n\n const modules: ArtifactModule[] = []\n for (const module of entry.modules) {\n modules.push({ name: module.name, type: moduleType(module.contentType), contents: await readFile(join(root, module.path), 'utf8') })\n }\n\n return {\n version: entry.version,\n compatibilityDate: entry.compatibilityDate,\n compatibilityFlags: entry.compatibilityFlags,\n mainModule: entry.mainModule,\n modules\n }\n}\n","export const APPS_CONTROL_MODULE = 'apps-control.json'\n\nexport const CONTROL_TIMESTAMP_HEADER = 'x-qinto-control-timestamp'\n\nexport const CONTROL_SIGNATURE_HEADER = 'x-qinto-control-signature'\n\nexport type DeployableControlApp = {\n slug: string\n workerName: string\n versions: { version: string; versionId: string }[]\n}\n\nconst base64Url = (bytes: Uint8Array): string => {\n return btoa(String.fromCharCode(...bytes))\n .replaceAll('+', '-')\n .replaceAll('/', '_')\n .replaceAll('=', '')\n}\n\nconst keyBytes = (key: string): Uint8Array<ArrayBuffer> => {\n const binary = atob(key.replaceAll('-', '+').replaceAll('_', '/'))\n const bytes = new Uint8Array(new ArrayBuffer(binary.length))\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index)\n }\n\n return bytes\n}\n\n/**\n * Signs a site-control request body and timestamp with the domain control key.\n * @param key Base64url-encoded HMAC key.\n * @param timestamp Timestamp header included in the signature input.\n * @param body Exact request body sent to the site worker.\n * @returns Base64url-encoded HMAC-SHA256 signature.\n */\nexport const signControlRequest = async (key: string, timestamp: string, body: string): Promise<string> => {\n const imported = await crypto.subtle.importKey('raw', keyBytes(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n const signature = await crypto.subtle.sign('HMAC', imported, new TextEncoder().encode(`${timestamp}.${body}`))\n\n return base64Url(new Uint8Array(signature))\n}\n\n/**\n * Verifies a site-control signature without an early-return byte comparison.\n * @param key Base64url-encoded HMAC key.\n * @param timestamp Timestamp header included in the signature input.\n * @param body Exact request body received by the site worker.\n * @param signature Base64url-encoded signature supplied by the caller.\n * @returns Whether the signature matches.\n */\nexport const verifyControlRequestSignature = async (key: string, timestamp: string, body: string, signature: string): Promise<boolean> => {\n const expected = await signControlRequest(key, timestamp, body)\n if (expected.length !== signature.length) {\n return false\n }\n\n let difference = 0\n for (let index = 0; index < expected.length; index += 1) {\n difference |= expected.charCodeAt(index) ^ signature.charCodeAt(index)\n }\n\n return difference === 0\n}\n\n/**\n * Serializes the app service bindings and deployable versions used by the site control route.\n * @param apps Apps deployed on the site and the versions each worker can dispatch.\n * @returns The generated control-target module contents.\n */\nexport const buildAppsControlTargets = (apps: DeployableControlApp[]): string => {\n return JSON.stringify({\n v: 1,\n apps: Object.fromEntries(\n apps.map((app) => [\n app.slug,\n {\n binding: `APP_${app.slug.toUpperCase().replaceAll('-', '_')}`,\n versions: app.versions\n }\n ])\n )\n })\n}\n","import type { AppManifest } from '@qinto/app-manifest'\n\nimport type { AppClassEntry, AppClassExports, AppClassKind, ClassGraceBundle, RetainedAppVersion } from './types'\n\nconst declaredClasses = (manifest: AppManifest): { className: string; kind: AppClassKind }[] => {\n return manifest.resources.flatMap((resource) => {\n if (resource.type !== 'durable_object' && resource.type !== 'workflow') {\n return []\n }\n\n return [{ className: resource.className, kind: resource.type }]\n })\n}\n\n/**\n * The upload name of one retained developer bundle inside the app worker's module graph.\n * @param version The bundle's version string.\n * @returns The module name, e.g. `app-1.2.0.js`.\n */\nexport const appBundleModuleName = (version: string): string => {\n return `app-${version}.js`\n}\n\n/**\n * Maps every Durable Object and Workflow class the current and retained versions declare to the bundle version it must export from (§5.10's one export model).\n * @param input The current version and manifest plus the retained older versions.\n * @returns Class name to the bundle version and kind: the current bundle when it still declares the class, otherwise the newest retained bundle that does.\n */\nexport const appClassExportSources = (input: {\n version: string\n manifest: AppManifest\n retained: RetainedAppVersion[]\n}): AppClassExports => {\n const sources: AppClassExports = {}\n for (const entry of [{ version: input.version, manifest: input.manifest }, ...input.retained].reverse()) {\n for (const declared of declaredClasses(entry.manifest)) {\n sources[declared.className] = { version: entry.version, kind: declared.kind }\n }\n }\n\n return sources\n}\n\n// A Durable Object is the developer's own class, so it is re-exported as-is. A workflow's handler is\n// a marker the runtime has to wrap in a WorkflowEntrypoint before Cloudflare can bind to it.\nconst exportLines = (version: string, classes: AppClassEntry[], identifier: (version: string) => string): string[] => {\n const module = appBundleModuleName(version)\n const durableObjects = classes.filter((entry) => entry.kind === 'durable_object').map((entry) => entry.className)\n const workflows = classes.filter((entry) => entry.kind === 'workflow').map((entry) => entry.className)\n\n return [\n ...(durableObjects.length === 0 ? [] : [`export { ${durableObjects.join(', ')} } from './${module}'`]),\n ...workflows.map((className) => `export const ${className} = createWorkflow(${JSON.stringify(className)}, ${identifier(version)})`)\n ]\n}\n\n/**\n * Generates the app worker's entry module: it hands the released runtime a version→bundle map, re-exports the Durable Object classes, and wraps the Workflow classes across the retained set and the grace-held bundles.\n * @param input The current version and manifest, the retained older versions, and the bundles kept only to keep a retiring class exported through its grace.\n * @returns The `index.js` module source.\n */\nexport const generateAppEntryModule = (input: {\n version: string\n manifest: AppManifest\n retained: RetainedAppVersion[]\n grace: ClassGraceBundle[]\n}): string => {\n const versions: RetainedAppVersion[] = [{ version: input.version, manifest: input.manifest }, ...input.retained]\n const identifier = (version: string): string => {\n return `app_${version.replaceAll(/[^a-zA-Z0-9]/g, '_')}`\n }\n\n const classesByVersion = new Map<string, AppClassEntry[]>()\n for (const [className, source] of Object.entries(appClassExportSources(input))) {\n classesByVersion.set(source.version, [...(classesByVersion.get(source.version) ?? []), { className, kind: source.kind }])\n }\n\n // A grace bundle is never invocable: it is on the worker only so its class keeps its storage. It\n // is still imported, because wrapping a workflow class needs the module's value, not just its name.\n const imported = [...versions.map((entry) => entry.version), ...input.grace.map((bundle) => bundle.version)]\n\n const lines = [\n \"import { createRuntime, createWorkflow } from './runtime.js'\",\n ...imported.map((version) => `import ${identifier(version)} from './${appBundleModuleName(version)}'`),\n ...versions.flatMap((entry) => {\n return exportLines(entry.version, classesByVersion.get(entry.version) ?? [], identifier)\n }),\n ...input.grace.flatMap((bundle) => exportLines(bundle.version, bundle.classes, identifier)),\n `export default createRuntime({ current: ${JSON.stringify(input.version)}, versions: { ${versions\n .map((entry) => `${JSON.stringify(entry.version)}: ${identifier(entry.version)}`)\n .join(', ')} } })`\n ]\n return `${lines.join('\\n')}\\n`\n}\n","/** Reports a deploy module this package refused to emit, carrying a `reason` safe to display to the user. */\nexport class AppDeployFormatError extends Error {\n reason: string\n constructor(reason: string) {\n super(reason)\n this.name = 'AppDeployFormatError'\n this.reason = reason\n }\n}\n","/**\n * Derives an app's internal key from the domain's key master: `HMAC-SHA256(master, domainId|slug)`, hex-encoded.\n * @param masterBase64 The domain's `apps-key-master` vault value (base64).\n * @param domainId The domain the key is scoped to.\n * @param slug The app slug.\n * @returns The derived key, as lowercase hex.\n */\nexport const deriveAppInternalKey = async (masterBase64: string, domainId: string, slug: string): Promise<string> => {\n const master = Uint8Array.from(atob(masterBase64), (char) => char.charCodeAt(0))\n const key = await crypto.subtle.importKey('raw', master, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])\n const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(`${domainId}|${slug}`))\n return [...new Uint8Array(signature)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n","import { AppDeployFormatError } from './errors'\nimport type { DeployableApp, DeployableAppInstall } from './types'\n\nexport const APPS_REGISTRY_MODULE = 'apps-registry.json'\n\n// Defense in depth under Cloudflare's script-size ceiling; capacity is enforced at install time.\nconst MAX_REGISTRY_BYTES = 256 * 1024\n\n/**\n * Builds the service-binding name a site worker reaches an app under.\n * @param slug The app slug.\n * @returns The binding name, e.g. `APP_FACEBOOK_CAPI`.\n */\nexport const appServiceBindingName = (slug: string): string => {\n return `APP_${slug.toUpperCase().replaceAll('-', '_')}`\n}\n\nconst registryEntry = (app: DeployableApp): Record<string, unknown> => {\n const capture = app.manifest.browser?.capture\n const eventResults = app.manifest.browser?.eventResults ?? []\n\n return {\n binding: appServiceBindingName(app.slug),\n version: app.version,\n versionId: app.versionId,\n consent: { category: app.manifest.consent.category },\n data: app.manifest.capabilities.data,\n hooks: app.manifest.server.hooks,\n installs: app.installs.map((install) => ({\n id: install.appInstallId,\n ord: install.ordinal,\n label: install.label,\n active: install.active,\n enabled: install.enabled\n })),\n rpc: {\n exposes: Object.fromEntries((app.manifest.rpc?.exposes ?? []).map((fn) => [fn.name, fn.visibility])),\n grants: app.grants\n },\n endpoints: app.manifest.endpoints,\n eventResults,\n // Always emitted, never defaulted on read: the worker requires it, so an app that declares no\n // topics is normalized here rather than every reader having to tolerate its absence.\n events: { publishes: app.manifest.events?.publishes ?? [] },\n // Omitted when empty so a site whose apps declare no capture serializes exactly as before.\n ...(capture === undefined ? {} : { capture })\n }\n}\n\n/**\n * Serializes the per-site apps registry the main worker ships as its `apps-registry.json` text module.\n * @param apps The enabled apps whose deployed versions the registry references, in install order.\n * @returns The registry JSON; `{\"v\":1,\"order\":[],\"apps\":{}}`-shaped when the site has no apps.\n * @throws {AppDeployFormatError} when the serialized registry exceeds its size budget.\n */\nexport const buildAppsRegistry = (apps: DeployableApp[]): string => {\n const registry = {\n v: 1,\n order: apps.map((app) => app.slug),\n apps: Object.fromEntries(apps.map((app) => [app.slug, registryEntry(app)]))\n }\n const serialized = JSON.stringify(registry)\n if (new TextEncoder().encode(serialized).length > MAX_REGISTRY_BYTES) {\n throw new AppDeployFormatError('The apps registry exceeds its size budget.')\n }\n\n return serialized\n}\n\n// A .json name on purpose: wrangler content-hashes a Text module at build time and rewrites the\n// worker's import to that name, which would pin the bundle to its empty placeholder. A JSON module\n// keeps its name, so the deploy's module is what the worker imports — the same mechanism the\n// registry relies on. The content is still the assembled script, uploaded as text.\nexport const APPS_Q_MODULE = 'apps-q.json'\n\n// Defense in depth under the script-size ceiling; the per-site sum is enforced at install/enable.\nconst MAX_APPS_Q_BYTES = 4 * 1024 * 1024\n\nconst browserVariables = (app: DeployableApp, install: DeployableAppInstall): Record<string, string | boolean> => {\n const exposed: Record<string, string | boolean> = {}\n for (const variable of app.manifest.variables) {\n const value = install.variables[variable.name]\n if (variable.browser === true && value !== undefined) {\n exposed[variable.name] = value\n }\n }\n\n return exposed\n}\n\n/**\n * Assembles the apps text module q.js appends after the tag: one instantiation-config line, then each browser app's self-registering bundle exactly once.\n * @param apps The enabled apps the registry references, in install order.\n * @param bundles Each app's deployed browser bundle, keyed by slug; an app without an entry contributes no code.\n * @returns The module text; empty for a site with no browser apps.\n * @throws {AppDeployFormatError} when the assembly exceeds its size budget.\n */\nexport const buildAppsQModule = (apps: DeployableApp[], bundles: Map<string, string>): string => {\n const withCode = apps.filter((app) => bundles.has(app.slug))\n if (withCode.length === 0) {\n return ''\n }\n\n const config = Object.fromEntries(\n withCode.map((app) => [\n app.slug,\n app.installs\n .filter((install) => install.active)\n .map((install) => ({\n id: install.appInstallId,\n ord: install.ordinal,\n label: install.label,\n variables: browserVariables(app, install)\n }))\n ])\n )\n const configLine =\n '(function(d){var s=d.currentScript,g=(s&&s.dataset?s.dataset.qintoGlobal:void 0)||\"qinto\";var q=window[g];' +\n `if(q&&q._q){q._appInstalls=${JSON.stringify(config)};}})(document);\\n`\n const assembled = configLine + withCode.map((app) => bundles.get(app.slug)).join('')\n if (new TextEncoder().encode(assembled).length > MAX_APPS_Q_BYTES) {\n throw new AppDeployFormatError('The assembled apps module exceeds its size budget.')\n }\n\n return assembled\n}\n","import type { AppManifest } from '@qinto/app-manifest'\n\nimport type { RetainedAppVersion } from './types'\n\nexport type UnionVariable = { name: string; kind: 'plain' | 'secret' }\n\ntype Declared = { name: string; kind: 'plain' | 'secret' }\n\nconst unionByName = (current: Declared[], retained: Declared[][]): UnionVariable[] => {\n const union = new Map<string, UnionVariable>()\n for (const declarations of [...retained].reverse()) {\n for (const variable of declarations) {\n union.set(variable.name, { name: variable.name, kind: variable.kind })\n }\n }\n\n for (const variable of current) {\n union.set(variable.name, { name: variable.name, kind: variable.kind })\n }\n\n return [...union.values()]\n}\n\n/**\n * Collapses the current and retained manifests' variables into one set; the current version wins a kind conflict.\n * @param manifest The current version's manifest.\n * @param retained The retained older versions.\n * @returns One entry per variable name across the retained set.\n */\nexport const unionAppVariables = (manifest: AppManifest, retained: RetainedAppVersion[]): UnionVariable[] => {\n return unionByName(\n manifest.variables,\n retained.map((entry) => entry.manifest.variables)\n )\n}\n\n/**\n * Collapses the current and retained manifests' app-scope variables into one set; the current version wins a kind conflict.\n * @param manifest The current version's manifest.\n * @param retained The retained older versions.\n * @returns One entry per app variable name across the retained set.\n */\nexport const unionAppScopeVariables = (manifest: AppManifest, retained: RetainedAppVersion[]): UnionVariable[] => {\n return unionByName(\n manifest.appVariables,\n retained.map((entry) => entry.manifest.appVariables)\n )\n}\n","import type { AppManifestResource } from '@qinto/app-manifest'\n\nimport type { DevMigrationPlan } from '../migrations'\n\nexport type DevBinding =\n | { type: 'text'; value: string }\n | { type: 'kv'; id: string }\n | { type: 'd1'; id: string }\n | { type: 'r2'; name: string }\n | { type: 'analytics-engine-dataset'; name: string }\n | { type: 'durable-object'; workerName: string; exportName: string }\n | { type: 'workflow'; name: string; workerName: string; exportName: string }\n | { type: 'worker'; workerName: string; exportName?: string }\n // Cloudflare's rate limiter offers only a 10- or 60-second window.\n | { type: 'rate-limit'; namespace: string; simple: { limit: number; period: 10 | 60 } }\n | { type: 'hyperdrive'; id: string; localConnectionString: string }\n\nexport type InertResource = { binding: string; identifier: string; reason: string }\n\nexport type MappedResources = {\n bindings: Record<string, DevBinding>\n // Every Durable Object class the worker must declare as a namespace of its own, beside binding it.\n exports: Record<string, { type: 'durable-object'; storage: 'sqlite' }>\n // Declared resources this local stack cannot stand up; the app boots without their bindings.\n inert: InertResource[]\n // Each D1 binding's declared migrations, in declaration order, for the ledger to apply.\n migrations: DevMigrationPlan[]\n}\n\n/* v8 ignore next 3 -- exhaustiveness guard: the manifest resource type is a closed union. */\nconst unsupportedResource = (resource: never): never => {\n throw new Error(`Unsupported app resource: ${String(resource)}`)\n}\n\ntype MapResourcesInput = {\n resources: AppManifestResource[]\n workerName: string\n // Local database URLs per hyperdrive identifier. A hyperdrive origin names the deployment's own\n // database, so it is never used to build a connection string here.\n hyperdrive: Record<string, string>\n}\n\nexport const mapAppResources = (input: MapResourcesInput): MappedResources => {\n const bindings: Record<string, DevBinding> = {}\n const exports: Record<string, { type: 'durable-object'; storage: 'sqlite' }> = {}\n const inert: InertResource[] = []\n const migrations: DevMigrationPlan[] = []\n\n for (const resource of input.resources) {\n switch (resource.type) {\n case 'kv': {\n bindings[resource.binding] = { type: 'kv', id: resource.identifier }\n break\n }\n case 'd1': {\n bindings[resource.binding] = { type: 'd1', id: resource.identifier }\n migrations.push({ resource: resource.identifier, binding: resource.binding, migrations: resource.migrations })\n break\n }\n case 'r2': {\n bindings[resource.binding] = { type: 'r2', name: resource.identifier }\n break\n }\n case 'analytics_engine': {\n bindings[resource.binding] = { type: 'analytics-engine-dataset', name: resource.identifier }\n break\n }\n case 'durable_object': {\n bindings[resource.binding] = { type: 'durable-object', workerName: input.workerName, exportName: resource.className }\n exports[resource.className] = { type: 'durable-object', storage: 'sqlite' }\n break\n }\n case 'workflow': {\n bindings[resource.binding] = {\n type: 'workflow',\n name: resource.identifier,\n workerName: input.workerName,\n exportName: resource.className\n }\n break\n }\n case 'hyperdrive': {\n const localConnectionString = input.hyperdrive[resource.identifier]\n if (localConnectionString === undefined) {\n inert.push({\n binding: resource.binding,\n identifier: resource.identifier,\n reason: `set a local database URL for ${resource.identifier} in the console — the manifest origin is the deployed database`\n })\n break\n }\n\n bindings[resource.binding] = { type: 'hyperdrive', id: resource.identifier, localConnectionString }\n break\n }\n case 'ai':\n case 'vectorize': {\n inert.push({\n binding: resource.binding,\n identifier: resource.identifier,\n reason: `${resource.type} runs only against a Cloudflare account, which this local stack does not reach`\n })\n break\n }\n /* v8 ignore next 3 -- the resource type is a closed union; a value outside it cannot reach here. */\n default: {\n return unsupportedResource(resource)\n }\n }\n }\n\n return { bindings, exports, inert, migrations }\n}\n","import {\n appBundleModuleName,\n deriveAppInternalKey,\n generateAppEntryModule,\n unionAppScopeVariables,\n unionAppVariables\n} from '@qinto/app-deploy'\nimport type { AppManifest } from '@qinto/app-manifest'\n\nimport type { ArtifactModule } from '../artifacts'\nimport type { DevKeys } from '../keys'\nimport type { DevMigrationPlan } from '../migrations'\nimport type { DevAppValues, DevState } from '../state'\nimport type { InstallSecrets } from './deployable'\nimport type { DevBinding, InertResource } from './resources'\nimport { mapAppResources } from './resources'\n\nexport const APP_WORKER_NAME = 'qinto-dev-app'\nexport const SITE_WORKER_NAME = 'qinto-dev-site'\n\nexport type AppWorkerComposition = {\n modules: ArtifactModule[]\n mainModule: string\n env: Record<string, DevBinding>\n exports: Record<string, { type: 'durable-object'; storage: 'sqlite' }>\n inert: InertResource[]\n migrations: DevMigrationPlan[]\n}\n\ntype VariableMaps = Record<string, Record<string, string | boolean>>\n\n// One VAR_<NAME> binding per variable, its value a JSON map keyed by install ordinal — the shape the\n// runtime splits ctx.variables and ctx.secrets out of.\nconst variableMaps = (manifest: AppManifest, state: DevState, secrets: InstallSecrets): VariableMaps => {\n const maps: VariableMaps = {}\n for (const variable of unionAppVariables(manifest, [])) {\n const values: Record<string, string | boolean> = {}\n for (const install of state.installs) {\n const value = variable.kind === 'secret' ? secrets[install.appInstallId]?.[variable.name] : install.variables[variable.name]\n if (value !== undefined) {\n values[String(install.ordinal)] = value\n }\n }\n\n if (Object.keys(values).length > 0) {\n maps[variable.name] = values\n }\n }\n\n return maps\n}\n\ntype AppWorkerInput = {\n manifest: AppManifest\n state: DevState\n secrets: InstallSecrets\n appValues: DevAppValues\n consoleOrigin: string\n keys: DevKeys\n version: string\n serverBundle: string\n runtimeModule: ArtifactModule\n installToken: string\n}\n\nexport const composeAppWorker = async (input: AppWorkerInput): Promise<AppWorkerComposition> => {\n const bundleName = appBundleModuleName(input.version)\n const entry = generateAppEntryModule({ version: input.version, manifest: input.manifest, retained: [], grace: [] })\n const resources = mapAppResources({\n resources: input.manifest.resources,\n workerName: APP_WORKER_NAME,\n hyperdrive: input.state.hyperdrive\n })\n\n const env: Record<string, DevBinding> = {\n ...resources.bindings,\n QINTO_INTERNAL_KEY: {\n type: 'text',\n value: await deriveAppInternalKey(input.keys.appsKeyMaster, input.state.domainId, input.manifest.slug)\n },\n QINTO_INSTALL_TOKEN: { type: 'text', value: input.installToken },\n APP_CONTEXT: {\n type: 'text',\n value: JSON.stringify({\n domainId: input.state.domainId,\n slug: input.manifest.slug,\n version: input.version,\n enabled: input.state.enabled,\n variableKinds: Object.fromEntries(unionAppVariables(input.manifest, []).map((entry) => [entry.name, entry.kind])),\n appVariableKinds: Object.fromEntries(unionAppScopeVariables(input.manifest, []).map((entry) => [entry.name, entry.kind]))\n })\n },\n QINTO_PLATFORM_API: { type: 'text', value: input.consoleOrigin },\n QINTO_SITE: { type: 'worker', workerName: SITE_WORKER_NAME, exportName: 'Broker' }\n }\n\n for (const [name, values] of Object.entries(variableMaps(input.manifest, input.state, input.secrets))) {\n env[`VAR_${name}`] = { type: 'text', value: JSON.stringify(values) }\n }\n\n // One binding per app variable, holding the raw value rather than an ordinal map: an app value is\n // the same for every install by construction.\n for (const variable of unionAppScopeVariables(input.manifest, [])) {\n const value = input.appValues[variable.name]\n if (value !== undefined) {\n env[`APPVAR_${variable.name}`] = { type: 'text', value }\n }\n }\n\n return {\n mainModule: 'index.js',\n modules: [\n { name: 'index.js', type: 'esm', contents: entry },\n { name: 'runtime.js', type: 'esm', contents: input.runtimeModule.contents },\n { name: bundleName, type: 'esm', contents: input.serverBundle }\n ],\n env,\n exports: resources.exports,\n inert: resources.inert,\n migrations: resources.migrations\n }\n}\n","export const APP_ENDPOINT_PREFIX = '/app/'\n\nexport const MAX_CUSTOM_ENDPOINT_LENGTH = 128\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\n// Persisted bit values: append methods without renumbering existing entries.\nexport const HTTP_METHODS: readonly HttpMethod[] = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']\n\nexport const HTTP_METHOD_BIT: Record<HttpMethod, number> = { GET: 1, POST: 2, PUT: 4, PATCH: 8, DELETE: 16 }\n\nexport const ALL_METHODS_MASK = HTTP_METHODS.reduce((mask, method) => mask | HTTP_METHOD_BIT[method], 0)\n\nexport type AppEndpoint = { methods: number; path: string }\n\ntype AppEndpointResult = { ok: true; value: AppEndpoint } | { ok: false; reason: string }\n\nconst ALLOWED_CHARS = /^[A-Za-z0-9._~/-]+$/\n\n/**\n * Renders a method bitmask for display.\n * @param mask The bitmask of HTTP method bits.\n * @returns `'ANY'` when every method is set, otherwise the set methods in `HTTP_METHODS` order, comma-separated.\n */\nexport const describeMethods = (mask: number): string => {\n if (mask === ALL_METHODS_MASK) {\n return 'ANY'\n }\n\n return HTTP_METHODS.filter((method) => (mask & HTTP_METHOD_BIT[method]) !== 0).join(', ')\n}\n\n/**\n * Tests a request against a token's endpoint grants.\n * @param endpoints The endpoint grants the token carries.\n * @param path The request path, without query string.\n * @param method The request's HTTP method; anything outside `HTTP_METHODS` matches nothing.\n * @returns Whether a grant covers the path and method; a grant ending in `/*` covers every path under its prefix, but not the prefix itself.\n */\nexport const matchesAppEndpoint = (endpoints: readonly AppEndpoint[], path: string, method: string): boolean => {\n const bit = HTTP_METHODS.includes(method as HttpMethod) ? HTTP_METHOD_BIT[method as HttpMethod] : 0\n\n return endpoints.some((endpoint) => {\n if ((endpoint.methods & bit) === 0) {\n return false\n }\n\n return endpoint.path.endsWith('/*') ? path.startsWith(endpoint.path.slice(0, -1)) : path === endpoint.path\n })\n}\n\n/**\n * Validates a custom app endpoint; never throws, and the accepted path is trimmed.\n * @param raw The requested method bitmask and endpoint path.\n * @returns `{ ok: true, value }` with the trimmed endpoint, or `{ ok: false, reason }` carrying a message safe to show the user.\n */\nexport const validateAppEndpoint = (raw: { methods: number; path: string }): AppEndpointResult => {\n if (!Number.isInteger(raw.methods) || raw.methods <= 0 || raw.methods > ALL_METHODS_MASK) {\n return { ok: false, reason: 'Choose at least one HTTP method.' }\n }\n\n const path = raw.path.trim()\n\n if (!path.startsWith(APP_ENDPOINT_PREFIX)) {\n return { ok: false, reason: 'Custom endpoints must start with /app/.' }\n }\n\n if (path.length > MAX_CUSTOM_ENDPOINT_LENGTH) {\n return { ok: false, reason: `Custom endpoint must be ${MAX_CUSTOM_ENDPOINT_LENGTH} characters or fewer.` }\n }\n\n const isWildcard = path.endsWith('/*')\n if (path.includes('*') && (!isWildcard || path.indexOf('*') !== path.length - 1)) {\n return { ok: false, reason: 'A wildcard is only allowed as a trailing /* (e.g. /app/reports/*).' }\n }\n\n if (!isWildcard && path.endsWith('/')) {\n return { ok: false, reason: 'Custom endpoint must not end with a slash.' }\n }\n\n // Keep the wildcard's slash in the character validation.\n const body = isWildcard ? path.slice(0, -1) : path\n if (!ALLOWED_CHARS.test(body)) {\n return { ok: false, reason: 'Custom endpoint contains invalid characters.' }\n }\n\n if (body.includes('..')) {\n return { ok: false, reason: 'Custom endpoint must not contain \"..\".' }\n }\n\n return { ok: true, value: { methods: raw.methods, path } }\n}\n","export const WORKER_ACCESS_TOKEN_PREFIX = 'qwat_'\n\nexport type WorkerAccessTokenScope =\n | 'track'\n | 'identify'\n | 'alias'\n | 'consentWrite'\n | 'propertiesRead'\n | 'consentRead'\n | 'sessionRead'\n | 'idGraphInspect'\n\n// Persisted bit values: append scopes without renumbering existing entries.\nexport const SCOPE: Record<WorkerAccessTokenScope, number> = {\n track: 1,\n identify: 2,\n alias: 4,\n consentWrite: 8,\n propertiesRead: 16,\n consentRead: 32,\n sessionRead: 64,\n idGraphInspect: 128\n}\n\n// The decodable bound, not the grantable one: `parseWorkerAccessTokensEnv` drops any mask above it,\n// so a platform-only scope missing here would make the deployed token unusable rather than unissuable.\nexport const ALL_SCOPE_MASK = Object.values(SCOPE).reduce((mask, bit) => mask | bit, 0)\n\n// `idGraphInspect` is platform-owned: the portal mints its token itself and puts the hash in the same\n// env map, so a customer must never be able to select it.\nexport type GrantableScope = Exclude<WorkerAccessTokenScope, 'idGraphInspect'>\n\nexport type WorkerAccessTokenScopeDefinition = { key: GrantableScope; bit: number; label: string; description: string }\n\n// Array order is the order the UI renders the permission checkboxes.\nexport const WORKER_ACCESS_TOKEN_SCOPES: readonly WorkerAccessTokenScopeDefinition[] = [\n { key: 'track', bit: SCOPE.track, label: 'Track events', description: 'POST /v1/track — record events a user performed.' },\n { key: 'identify', bit: SCOPE.identify, label: 'Identify users', description: 'POST /v1/identify — attach identity traits to a user.' },\n { key: 'alias', bit: SCOPE.alias, label: 'Link identifiers', description: 'POST /v1/alias — link a custom identifier to a user.' },\n {\n key: 'consentWrite',\n bit: SCOPE.consentWrite,\n label: 'Save consent',\n description: 'POST /v1/consent — record a user’s consent choices.'\n },\n {\n key: 'propertiesRead',\n bit: SCOPE.propertiesRead,\n label: 'Read properties',\n description: 'GET /v1/properties — read the properties stored for a user.'\n },\n {\n key: 'consentRead',\n bit: SCOPE.consentRead,\n label: 'Read consent',\n description: 'GET /v1/consent — read the consent stored for a user.'\n },\n {\n key: 'sessionRead',\n bit: SCOPE.sessionRead,\n label: 'Read session ids',\n description: 'GET /v1/session — read the anonymous and person ids for a user.'\n }\n]\n\n/**\n * Narrows an arbitrary string to a scope key a customer is allowed to grant.\n * @param value The candidate scope key.\n * @returns `true` when the value is one of the scopes in `WORKER_ACCESS_TOKEN_SCOPES`; platform-only scopes report `false`.\n */\nexport const isGrantableScope = (value: string): value is GrantableScope => {\n return WORKER_ACCESS_TOKEN_SCOPES.some((scope) => scope.key === value)\n}\n\n/**\n * Combines scope keys into the persisted bitmask; order and duplicates make no difference.\n * @param scopes The scope keys to grant.\n * @returns The scopes' bits OR-ed together, `0` for an empty list.\n */\nexport const maskFromScopes = (scopes: readonly WorkerAccessTokenScope[]): number => {\n return scopes.reduce((mask, scope) => mask | SCOPE[scope], 0)\n}\n","import type { AppEndpoint } from './endpoints'\nimport { validateAppEndpoint } from './endpoints'\nimport { ALL_SCOPE_MASK } from './scopes'\n\nexport type WorkerAccessTokensEnvEntry = { hashB64u: string; mask: number; app?: string; endpoints?: AppEndpoint[] }\n\nexport type ParsedWorkerAccessToken = { mask: number; app: string | null; endpoints: AppEndpoint[] | null }\n\nexport type ParsedWorkerAccessTokens = { tokens: Map<string, ParsedWorkerAccessToken>; error?: string }\n\ntype EncodedEndpoint = [number, string]\n\ntype EncodedEntry = { m: number; a?: string; e?: EncodedEndpoint[] }\n\nconst encodeEntry = (entry: WorkerAccessTokensEnvEntry): number | EncodedEntry => {\n const endpoints = entry.endpoints ?? []\n if (entry.app === undefined && endpoints.length === 0) {\n return entry.mask\n }\n\n return {\n m: entry.mask,\n ...(entry.app === undefined ? {} : { a: entry.app }),\n ...(endpoints.length === 0 ? {} : { e: endpoints.map((endpoint): EncodedEndpoint => [endpoint.methods, endpoint.path]) })\n }\n}\n\n/**\n * Encodes token hashes, their scope masks and their `/app/` endpoint grants as the `WORKER_ACCESS_TOKENS` env-var value; entry order does not change the output.\n * @param entries The token hashes, the scope mask each one grants, the app slug an install token belongs to, and the endpoints it may call.\n * @returns The versioned JSON string to store in the env var.\n */\nexport const serializeWorkerAccessTokensEnv = (entries: readonly WorkerAccessTokensEnvEntry[]): string => {\n const tokens: Record<string, number | EncodedEntry> = {}\n for (const entry of [...entries].sort((a, b) => a.hashB64u.localeCompare(b.hashB64u))) {\n tokens[entry.hashB64u] = encodeEntry(entry)\n }\n\n return JSON.stringify({ v: 2, t: tokens })\n}\n\nconst validMask = (mask: unknown): mask is number => {\n // Numeric bounds avoid 32-bit bitwise truncation authorizing high-bit masks.\n return typeof mask === 'number' && Number.isSafeInteger(mask) && mask >= 0 && mask <= ALL_SCOPE_MASK\n}\n\nconst validApp = (app: unknown): app is string | undefined => {\n return app === undefined || (typeof app === 'string' && app.length > 0 && app.length <= 30)\n}\n\nconst decodeEndpoints = (value: unknown): { endpoints: AppEndpoint[]; dropped: number } => {\n if (value === undefined) {\n return { endpoints: [], dropped: 0 }\n }\n\n if (!Array.isArray(value)) {\n return { endpoints: [], dropped: 1 }\n }\n\n const endpoints: AppEndpoint[] = []\n let dropped = 0\n for (const encoded of value) {\n if (!Array.isArray(encoded) || encoded.length !== 2 || typeof encoded[0] !== 'number' || typeof encoded[1] !== 'string') {\n dropped += 1\n continue\n }\n\n const result = validateAppEndpoint({ methods: encoded[0], path: encoded[1] })\n if (!result.ok) {\n dropped += 1\n continue\n }\n\n endpoints.push(result.value)\n }\n\n return { endpoints, dropped }\n}\n\nconst parseTokenEntry = (value: unknown): { entry: ParsedWorkerAccessToken | null; dropped: number } => {\n if (typeof value === 'number') {\n return { entry: validMask(value) && value > 0 ? { mask: value, app: null, endpoints: null } : null, dropped: 0 }\n }\n\n if (typeof value !== 'object' || value === null) {\n return { entry: null, dropped: 0 }\n }\n\n const entry = value as { m?: unknown; a?: unknown; e?: unknown }\n if (!validMask(entry.m) || !validApp(entry.a)) {\n return { entry: null, dropped: 0 }\n }\n\n const decoded = decodeEndpoints(entry.e)\n // A token that grants neither a scope nor a surviving endpoint authorizes nothing.\n if (entry.m === 0 && decoded.endpoints.length === 0) {\n return { entry: null, dropped: decoded.dropped }\n }\n\n return {\n entry: {\n mask: entry.m,\n app: typeof entry.a === 'string' ? entry.a : null,\n endpoints: decoded.endpoints.length === 0 ? null : decoded.endpoints\n },\n dropped: decoded.dropped\n }\n}\n\n/**\n * Decodes a `WORKER_ACCESS_TOKENS` env-var value; never throws — a malformed value yields no tokens, and invalid entries are skipped.\n * @param raw The raw env-var value; blank decodes to an empty map with no error.\n * @returns The token-hash to `{mask, app, endpoints}` map, with `error` set when any token entry or endpoint grant was rejected.\n */\nexport const parseWorkerAccessTokensEnv = (raw: string): ParsedWorkerAccessTokens => {\n if (raw.trim() === '') {\n return { tokens: new Map() }\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(raw)\n } catch {\n return { tokens: new Map(), error: 'WORKER_ACCESS_TOKENS is not valid JSON' }\n }\n\n if (typeof parsed !== 'object' || parsed === null || (parsed as { v?: unknown }).v !== 2) {\n return { tokens: new Map(), error: 'WORKER_ACCESS_TOKENS has an unsupported version' }\n }\n\n const table = (parsed as { t?: unknown }).t\n if (typeof table !== 'object' || table === null) {\n return { tokens: new Map(), error: 'WORKER_ACCESS_TOKENS is missing its token table' }\n }\n\n const tokens = new Map<string, ParsedWorkerAccessToken>()\n let rejected = 0\n for (const [hash, value] of Object.entries(table)) {\n const parsedEntry = parseTokenEntry(value)\n rejected += parsedEntry.dropped\n if (parsedEntry.entry === null) {\n rejected += 1\n continue\n }\n\n tokens.set(hash, parsedEntry.entry)\n }\n\n if (rejected > 0) {\n return { tokens, error: `WORKER_ACCESS_TOKENS dropped ${rejected} invalid entr${rejected === 1 ? 'y' : 'ies'}` }\n }\n\n return { tokens }\n}\n","// Web Crypto keeps token hashing identical in workerd and Node.\n/**\n * Hashes a worker access token for storage and lookup; the digest is unkeyed, so the same token always hashes to the same value.\n * @param raw The raw token string, `qwat_` prefix included.\n * @returns The token's SHA-256 digest, base64url-encoded without padding.\n */\nexport const hashWorkerAccessToken = async (raw: string): Promise<string> => {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))\n let binary = ''\n for (const byte of new Uint8Array(digest)) {\n binary += String.fromCharCode(byte)\n }\n\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n","import { readFile } from 'node:fs/promises'\n\nexport const readIfPresent = async (path: string): Promise<string | null> => {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null\n }\n\n // Only ENOENT is \"not written yet\": any other read failure must surface rather than silently reset the state or rotate the keys.\n throw error\n }\n}\n","import { randomBytes } from 'node:crypto'\nimport { writeFile } from 'node:fs/promises'\n\nimport { buildAppUiKeyEnv } from '@qinto/app-ui-token'\n\nimport type { DevPaths } from './paths'\nimport { readIfPresent } from './read-if-present'\n\nexport type DevKeys = {\n // The per-domain apps key master the site worker derives every app's internal key from.\n appsKeyMaster: string\n // The HS256 key the site worker validates iframe tokens with, and this server mints them with.\n appUiKeyId: string\n appUiKey: Uint8Array<ArrayBuffer>\n // The bearer the demo site and the console use against /v1/*.\n workerAccessToken: string\n // The app's own bearer, scoped to the capabilities its manifest declares.\n installToken: string\n}\n\ntype StoredKeys = {\n appsKeyMaster: string\n appUiKeyId: string\n appUiKey: string\n workerAccessToken: string\n installToken: string\n}\n\nconst keysPath = (paths: DevPaths): string => {\n return `${paths.root}/keys.json`\n}\n\nconst mint = (): StoredKeys => {\n return {\n appsKeyMaster: randomBytes(32).toString('base64'),\n appUiKeyId: randomBytes(4).toString('hex'),\n appUiKey: randomBytes(32).toString('base64'),\n workerAccessToken: `qwat_dev_${randomBytes(16).toString('hex')}`,\n installToken: `qwat_dev_install_${randomBytes(16).toString('hex')}`\n }\n}\n\nexport const loadDevKeys = async (paths: DevPaths): Promise<DevKeys> => {\n const existing = await readIfPresent(keysPath(paths))\n let stored: StoredKeys\n if (existing === null) {\n stored = mint()\n await writeFile(keysPath(paths), `${JSON.stringify(stored, null, 2)}\\n`, { mode: 0o600 })\n } else {\n stored = JSON.parse(existing) as StoredKeys\n }\n\n return {\n appsKeyMaster: stored.appsKeyMaster,\n appUiKeyId: stored.appUiKeyId,\n appUiKey: Uint8Array.from(Buffer.from(stored.appUiKey, 'base64')),\n workerAccessToken: stored.workerAccessToken,\n installToken: stored.installToken\n }\n}\n\nexport const devAppUiKeyEnv = (keys: DevKeys): string => {\n return buildAppUiKeyEnv({ [keys.appUiKeyId]: keys.appUiKey })\n}\n","import type { DeployableApp } from '@qinto/app-deploy'\nimport {\n APPS_CONTROL_MODULE,\n APPS_Q_MODULE,\n APPS_REGISTRY_MODULE,\n appServiceBindingName,\n buildAppsControlTargets,\n buildAppsQModule,\n buildAppsRegistry\n} from '@qinto/app-deploy'\nimport type { WorkerAccessTokensEnvEntry } from '@qinto/worker-access-token'\nimport { ALL_SCOPE_MASK, hashWorkerAccessToken, maskFromScopes, serializeWorkerAccessTokensEnv } from '@qinto/worker-access-token'\n\nimport type { ArtifactModule, WorkerArtifact } from '../artifacts'\nimport type { DevKeys } from '../keys'\nimport { devAppUiKeyEnv } from '../keys'\nimport type { DevState } from '../state'\nimport { APP_WORKER_NAME, SITE_WORKER_NAME } from './app-worker'\nimport type { DevBinding } from './resources'\n\ntype DurableObjectExport = { type: 'durable-object'; storage: 'sqlite' }\n\nexport type SiteWorkerComposition = {\n mainModule: string\n modules: ArtifactModule[]\n env: Record<string, DevBinding>\n exports: Record<string, DurableObjectExport>\n}\n\n// The id graph's three classes, bound by name and declared as SQLite namespaces of this worker.\nconst SITE_DURABLE_OBJECTS: Record<string, string> = {\n ANON_DO: 'AnonDO',\n GLOBAL_DO: 'GlobalDO',\n ALIAS_DO: 'AliasDO'\n}\n\ntype SiteWorkerInput = {\n artifact: WorkerArtifact\n apps: DeployableApp[]\n browserBundles: Map<string, string>\n state: DevState\n keys: DevKeys\n appUiOrigin: string | null\n rootDomain: string\n}\n\n// The site's own bearer plus one entry per installed app, whose mask is exactly the capabilities its\n// manifest declares — the same projection a deploy makes.\nconst tokensEnv = async (input: SiteWorkerInput): Promise<string> => {\n const entries: WorkerAccessTokensEnvEntry[] = [\n { hashB64u: await hashWorkerAccessToken(input.keys.workerAccessToken), mask: ALL_SCOPE_MASK }\n ]\n for (const app of input.apps) {\n entries.push({\n hashB64u: await hashWorkerAccessToken(input.keys.installToken),\n mask: maskFromScopes(app.manifest.capabilities.api),\n app: app.slug\n })\n }\n\n return serializeWorkerAccessTokensEnv(entries)\n}\n\nexport const composeSiteWorker = async (input: SiteWorkerInput): Promise<SiteWorkerComposition> => {\n const env: Record<string, DevBinding> = {\n WORKER_ACCESS_TOKENS: { type: 'text', value: await tokensEnv(input) },\n APPS_KEY_MASTER: { type: 'text', value: input.keys.appsKeyMaster },\n APP_UI_KEY: { type: 'text', value: devAppUiKeyEnv(input.keys) },\n BOT_PROTECTION: { type: 'text', value: JSON.stringify({ minBotScore: 2, countries: null }) },\n AUTO_CAPTURE: { type: 'text', value: JSON.stringify({ pageLoad: false }) },\n CONSENT_CONFIGURATION: { type: 'text', value: JSON.stringify({ enabled: input.state.consentEnabled }) },\n COOKIE_SAME_SITE: { type: 'text', value: 'none' },\n FALLBACK_COOKIE: { type: 'text', value: '' },\n SITE_STATUS: { type: 'text', value: 'active' },\n ROOT_DOMAIN: { type: 'text', value: input.rootDomain },\n QINTO_DOMAIN_ID: { type: 'text', value: input.state.domainId },\n DEPLOY_TARGET: { type: 'text', value: 'standard' },\n // Carries a scheme, which the ui-proxy then uses verbatim: locally the panel sits on a port,\n // with no per-slug subdomain to compose. Left unset when the app declares no panel.\n ...(input.appUiOrigin === null ? {} : { APP_UI_HOST: { type: 'text' as const, value: input.appUiOrigin } }),\n BROKER_RATE_LIMITER: { type: 'rate-limit', namespace: '2001', simple: { limit: 300, period: 60 } }\n }\n\n for (const app of input.apps) {\n env[appServiceBindingName(app.slug)] = { type: 'worker', workerName: APP_WORKER_NAME }\n }\n\n for (const [binding, className] of Object.entries(SITE_DURABLE_OBJECTS)) {\n env[binding] = { type: 'durable-object', workerName: SITE_WORKER_NAME, exportName: className }\n }\n\n return {\n mainModule: input.artifact.mainModule,\n modules: [\n ...input.artifact.modules,\n {\n name: APPS_CONTROL_MODULE,\n type: 'text',\n contents: buildAppsControlTargets(\n input.apps.map((app) => {\n return { slug: app.slug, workerName: APP_WORKER_NAME, versions: [{ version: app.version, versionId: app.versionId }] }\n })\n )\n },\n { name: APPS_REGISTRY_MODULE, type: 'text', contents: buildAppsRegistry(input.apps) },\n { name: APPS_Q_MODULE, type: 'text', contents: buildAppsQModule(input.apps, input.browserBundles) }\n ],\n env,\n exports: Object.fromEntries(\n Object.values(SITE_DURABLE_OBJECTS).map((className) => [className, { type: 'durable-object' as const, storage: 'sqlite' as const }])\n )\n }\n}\n","export const SPANS_MARKER = 'qinto:spans'\n\n// Cloudflare records at most 256 KB of log data per invocation, counting console output, exceptions\n// and its own request/header capture together, and drops the rest without saying so. This is the\n// spans record's allocation against that shared ceiling, not a cap.\nexport const MAX_SPANS_BYTES = 98_304\n\n// serializeAttachment refuses anything larger.\nexport const MAX_ATTACHMENT_BYTES = 16_384\n\nexport const APP_SPANS_HEADER = 'x-qinto-app-spans'\n\n// The encoded header value's allowance on an app worker's response.\nexport const MAX_APP_SPANS_BYTES = 8192\n\n// base64 spends 4 bytes per 3, so this is what the JSON must be budgeted to for the encoded header\n// to stay inside MAX_APP_SPANS_BYTES.\nexport const APP_SPANS_JSON_BUDGET = 6144\n\nexport type WireAttrValue = string | number | boolean\n\nexport type WireAttrs = Record<string, WireAttrValue>\n\nexport type WireSpanEvent = {\n t: number\n name: string\n level?: 'warn' | 'error'\n attrs?: WireAttrs\n}\n\nexport type WireSpan = {\n traceId: string\n spanId: string\n // May reference a span in another frame — renderers treat an unresolved parent as a root.\n parent?: string\n name: string\n // Workers clamp Date.now() between I/O, so start === end is legitimate for a CPU-only span.\n start: number\n end: number\n attrs?: WireAttrs\n events?: WireSpanEvent[]\n error?: string\n}\n\nexport type SpansRecord = {\n spans: WireSpan[]\n truncated?: number\n}\n\n/**\n * Renders a spans record as the single console argument an invocation logs it as.\n * @param record The record to render.\n * @returns One line the tail normalizers can read back with `parseSpansRecord`.\n */\nexport const formatSpansRecord = (record: SpansRecord): string => {\n return `${SPANS_MARKER} ${JSON.stringify(record)}`\n}\n\n// A trace may carry a console call as its argument array or as one already-formatted line, and a\n// formatted line is not JSON — an object passed as a second argument would arrive unrecoverable.\n// Emitting one pre-serialized string makes the record readable either way.\nconst loggedText = (message: unknown): string | undefined => {\n if (typeof message === 'string') {\n return message\n }\n\n const only = Array.isArray(message) && message.length === 1 ? message[0] : undefined\n\n return typeof only === 'string' ? only : undefined\n}\n\n/**\n * Reads back a spans record an invocation logged, from one trace log entry.\n * @param message The `message` of one trace log entry.\n * @returns The record, or `undefined` when the entry is an ordinary log line.\n */\nexport const parseSpansRecord = (message: unknown): SpansRecord | undefined => {\n const text = loggedText(message)\n if (text === undefined || !text.startsWith(`${SPANS_MARKER} `)) {\n return undefined\n }\n\n try {\n const parsed: unknown = JSON.parse(text.slice(SPANS_MARKER.length + 1))\n\n return Array.isArray((parsed as SpansRecord).spans) ? (parsed as SpansRecord) : undefined\n } catch {\n // The platform truncates past its log ceiling, which leaves the tail of the JSON missing.\n return undefined\n }\n}\n","import { isFiniteNumber, isPlainObject, parsedAttrs, SPAN_ID, TRACE_ID } from './validate'\nimport type { SpansRecord, WireSpan, WireSpanEvent } from './wire'\nimport { MAX_APP_SPANS_BYTES } from './wire'\n\nconst encoder = new TextEncoder()\n\nconst decoder = new TextDecoder()\n\nconst parsedEvent = (value: unknown): WireSpanEvent | null => {\n if (!isPlainObject(value)) {\n return null\n }\n\n if (!isFiniteNumber(value['t']) || typeof value['name'] !== 'string') {\n return null\n }\n\n const level = value['level']\n if (level !== undefined && level !== 'warn' && level !== 'error') {\n return null\n }\n\n const attrs = parsedAttrs(value['attrs'])\n if (attrs === null) {\n return null\n }\n\n return { t: value['t'], name: value['name'], ...(level === undefined ? {} : { level }), ...(attrs === undefined ? {} : { attrs }) }\n}\n\nconst parsedEvents = (value: unknown): WireSpanEvent[] | undefined | null => {\n if (value === undefined) {\n return undefined\n }\n\n if (!Array.isArray(value)) {\n return null\n }\n\n const events: WireSpanEvent[] = []\n for (const entry of value) {\n const event = parsedEvent(entry)\n if (event === null) {\n return null\n }\n\n events.push(event)\n }\n\n return events\n}\n\ntype SpanIds = Pick<WireSpan, 'traceId' | 'spanId' | 'parent'>\n\nconst parsedIds = (raw: Record<string, unknown>): SpanIds | null => {\n if (typeof raw['traceId'] !== 'string' || !TRACE_ID.test(raw['traceId'])) {\n return null\n }\n\n if (typeof raw['spanId'] !== 'string' || !SPAN_ID.test(raw['spanId'])) {\n return null\n }\n\n const ids = { traceId: raw['traceId'], spanId: raw['spanId'] }\n const parent = raw['parent']\n if (parent === undefined) {\n return ids\n }\n\n // A self-parent would leave the console's forest builder unable to root the span.\n if (typeof parent !== 'string' || !SPAN_ID.test(parent) || parent === raw['spanId']) {\n return null\n }\n\n return { ...ids, parent }\n}\n\ntype SpanBody = Pick<WireSpan, 'name' | 'start' | 'end' | 'error'>\n\nconst parsedBody = (raw: Record<string, unknown>): SpanBody | null => {\n if (typeof raw['name'] !== 'string' || !isFiniteNumber(raw['start']) || !isFiniteNumber(raw['end'])) {\n return null\n }\n\n const error = raw['error']\n if (error !== undefined && typeof error !== 'string') {\n return null\n }\n\n return { name: raw['name'], start: raw['start'], end: raw['end'], ...(error === undefined ? {} : { error }) }\n}\n\nconst parsedSpan = (value: unknown): WireSpan | null => {\n if (!isPlainObject(value)) {\n return null\n }\n\n const ids = parsedIds(value)\n const body = parsedBody(value)\n const attrs = parsedAttrs(value['attrs'])\n const events = parsedEvents(value['events'])\n if (ids === null || body === null || attrs === null || events === null) {\n return null\n }\n\n return { ...ids, ...body, ...(attrs === undefined ? {} : { attrs }), ...(events === undefined ? {} : { events }) }\n}\n\n/**\n * Renders a spans record as the `x-qinto-app-spans` header value an app worker answers with.\n * @param record The app invocation's finished record, already budgeted to `APP_SPANS_JSON_BUDGET`.\n * @returns The base64 header value `parseAppSpans` reads back — base64 because a header value is a `ByteString`, and a span name or log message carrying any character above U+00FF would make `Headers.set` throw.\n */\nexport const serializeAppSpans = (record: SpansRecord): string => {\n const bytes = encoder.encode(JSON.stringify(record))\n let binary = ''\n for (const byte of bytes) {\n binary += String.fromCharCode(byte)\n }\n\n return btoa(binary)\n}\n\n/**\n * Reads back a spans record from an `x-qinto-app-spans` header, refusing anything malformed.\n * @param header The header value, or `null` when absent.\n * @returns The validated record, including its `truncated` byte count, or `undefined` — an app bundle is third-party code, so one bad member rejects the whole header rather than admitting a partial trace.\n */\nexport const parseAppSpans = (header: string | null): SpansRecord | undefined => {\n if (header === null || header.length > MAX_APP_SPANS_BYTES) {\n return undefined\n }\n\n let parsed: unknown\n try {\n parsed = JSON.parse(decoder.decode(Uint8Array.from(atob(header), (character) => character.charCodeAt(0))))\n } catch {\n return undefined\n }\n\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return undefined\n }\n\n const raw = parsed as Record<string, unknown>\n if (!Array.isArray(raw['spans'])) {\n return undefined\n }\n\n const truncated = raw['truncated']\n if (truncated !== undefined && (typeof truncated !== 'number' || !Number.isFinite(truncated))) {\n return undefined\n }\n\n const spans: WireSpan[] = []\n for (const entry of raw['spans']) {\n const span = parsedSpan(entry)\n if (span === null) {\n return undefined\n }\n\n spans.push(span)\n }\n\n return { spans, ...(truncated === undefined ? {} : { truncated }) }\n}\n\nexport type AdoptionTarget = {\n traceId: string\n parent: string\n}\n\n/**\n * Rewrites foreign spans onto the adopting invocation's trace so they can be appended to its record.\n * @param spans The spans the app returned.\n * @param into The trace to adopt them into, and the span id an unresolved parent attaches to.\n * @returns The spans carrying `into.traceId`, with any parent the set does not contain re-pointed at `into.parent`, and any span claiming `into.parent`'s own id dropped — an app must not be able to write into another trace or displace the call span that invoked it.\n */\nexport const adoptSpans = (spans: WireSpan[], into: AdoptionTarget): WireSpan[] => {\n const ids = new Set(\n spans.map((span) => {\n return span.spanId\n })\n )\n\n return spans\n .filter((span) => {\n return span.spanId !== into.parent\n })\n .map((span) => {\n return {\n ...span,\n traceId: into.traceId,\n parent: span.parent !== undefined && ids.has(span.parent) ? span.parent : into.parent\n }\n })\n}\n","import type { SpansRecord, WireAttrs, WireSpan } from './wire'\n\nconst encoder = new TextEncoder()\n\nconst byteLength = (value: unknown): number => {\n return encoder.encode(JSON.stringify(value)).length\n}\n\n// UTF-8 needs at most three bytes per UTF-16 code unit — a four-byte sequence is encoded from a\n// surrogate pair, so two units — which proves a fit without allocating the encoded form. This runs\n// on every invocation's flush, and encoding dominated the measurement.\nconst fitsBudget = (text: string, max: number): boolean => {\n return text.length * 3 <= max || encoder.encode(text).length <= max\n}\n\n// Below this, cutting a string value further sheds noise, not bulk — move to the next tier instead.\nconst MIN_KEEP = 64\n\n// Halving the longest value converges in log steps and, unlike slicing to a byte allowance,\n// never overshoots on multi-byte characters: removing characters never adds encoded bytes.\nconst halveLongestString = (holders: WireAttrs[]): boolean => {\n let best: { holder: WireAttrs; key: string; length: number } | undefined\n for (const holder of holders) {\n for (const [key, value] of Object.entries(holder)) {\n if (typeof value === 'string' && value.length >= MIN_KEEP && (best === undefined || value.length > best.length)) {\n best = { holder, key, length: value.length }\n }\n }\n }\n\n if (best === undefined) {\n return false\n }\n\n best.holder[best.key] = (best.holder[best.key] as string).slice(0, Math.floor(best.length / 2))\n\n return true\n}\n\nconst attrHolders = (spans: WireSpan[]): WireAttrs[] => {\n const holders: WireAttrs[] = []\n for (const span of spans) {\n if (span.attrs !== undefined) {\n holders.push(span.attrs)\n }\n\n for (const event of span.events ?? []) {\n if (event.attrs !== undefined) {\n holders.push(event.attrs)\n }\n }\n }\n\n return holders\n}\n\nconst cloneSpan = (span: WireSpan): WireSpan => {\n return {\n ...span,\n ...(span.attrs === undefined ? {} : { attrs: { ...span.attrs } }),\n ...(span.events === undefined\n ? {}\n : { events: span.events.map((event) => ({ ...event, ...(event.attrs === undefined ? {} : { attrs: { ...event.attrs } }) })) })\n }\n}\n\nconst withoutPlainEvents = (span: WireSpan): WireSpan => {\n if (span.events === undefined) {\n return span\n }\n\n const { events, ...rest } = span\n const kept = events.filter((event) => {\n return event.name === 'exception'\n })\n\n return kept.length === 0 ? rest : { ...rest, events: kept }\n}\n\nconst skeleton = (span: WireSpan): WireSpan => {\n const { attrs, events, ...rest } = span\n\n return rest\n}\n\n// Non-root, non-errored spans go first, newest first — the roots and the failures are what a\n// truncated trace must still explain.\nconst removalOrder = (spans: WireSpan[]): WireSpan[] => {\n const ids = new Set(\n spans.map((span) => {\n return span.spanId\n })\n )\n const keeper = (span: WireSpan): boolean => {\n return span.error !== undefined || span.parent === undefined || !ids.has(span.parent)\n }\n const byNewest = (a: WireSpan, b: WireSpan): number => {\n return b.start - a.start\n }\n\n return [\n ...spans\n .filter((span) => {\n return !keeper(span)\n })\n .sort(byNewest),\n ...spans.filter(keeper).sort(byNewest)\n ]\n}\n\n/**\n * Trims a buffer of spans to its byte allowance: string attribute values are cut first, then plain span events, then all attributes, and finally whole spans — non-root, non-errored, newest first.\n * @param spans The invocation's finished spans.\n * @param max The allowance in UTF-8 bytes.\n * @returns The record unchanged when it fits, otherwise a smaller one guaranteed to fit, with `truncated` set to the bytes dropped.\n */\nexport const budgetSpans = (spans: WireSpan[], max: number): SpansRecord => {\n if (fitsBudget(JSON.stringify({ spans }), max)) {\n return { spans }\n }\n\n const full = byteLength({ spans })\n // Sized against the widest count the record can report, so the reservation never falls short.\n const fits = (list: WireSpan[]): boolean => {\n return fitsBudget(JSON.stringify({ spans: list, truncated: full }), max)\n }\n\n let working = spans.map(cloneSpan)\n while (!fits(working) && halveLongestString(attrHolders(working))) {\n // halveLongestString already advanced the state.\n }\n\n if (!fits(working)) {\n working = working.map(withoutPlainEvents)\n }\n\n if (!fits(working)) {\n working = working.map(skeleton)\n }\n\n for (const victim of removalOrder(working)) {\n if (fits(working)) {\n break\n }\n\n working = working.filter((span) => {\n return span !== victim\n })\n }\n\n return { spans: working, truncated: full - byteLength({ spans: working }) }\n}\n\nexport type BudgetedAttrs = {\n attrs: WireAttrs\n truncated?: number\n}\n\nconst dropLargestEntry = (attrs: WireAttrs): boolean => {\n let bestKey: string | undefined\n let bestSize = -1\n for (const [key, value] of Object.entries(attrs)) {\n const size = byteLength({ [key]: value })\n if (size > bestSize) {\n bestSize = size\n bestKey = key\n }\n }\n\n if (bestKey === undefined) {\n return false\n }\n\n delete attrs[bestKey]\n\n return true\n}\n\n/**\n * Trims an attribute set to its byte allowance, measured on the full serialized wrapper: string values are cut first, then whole entries, largest first.\n * @param attrs The attributes to budget.\n * @param max The allowance in UTF-8 bytes for the serialized result.\n * @returns The wrapper unchanged when it fits, otherwise a smaller one guaranteed to fit, with `truncated` set to the bytes dropped.\n */\nexport const budgetAttrs = (attrs: WireAttrs, max: number): BudgetedAttrs => {\n if (fitsBudget(JSON.stringify({ attrs }), max)) {\n return { attrs }\n }\n\n const full = byteLength({ attrs })\n const working = { ...attrs }\n const fits = (): boolean => {\n return fitsBudget(JSON.stringify({ attrs: working, truncated: full }), max)\n }\n\n while (!fits() && (halveLongestString([working]) || dropLargestEntry(working))) {\n // The shedding helpers already advanced the state.\n }\n\n return { attrs: working, truncated: full - byteLength({ attrs: working }) }\n}\n","import { AsyncLocalStorage } from 'node:async_hooks'\n\nimport type { TraceContext } from './propagation'\nimport type { WireSpan } from './wire'\n\n// `flushed` lives on the buffer, which every derived scope shares by reference — a `waitUntil`\n// continuation that inherits the async context can therefore never append to a buffer the\n// invocation already flushed.\nexport type TraceBuffer = {\n spans: WireSpan[]\n flushed: boolean\n}\n\nexport type TraceScope = {\n traceId: string\n buffer: TraceBuffer\n span: WireSpan | undefined\n}\n\n// The only module-level binding in this package. It stores nothing itself: a scope is reachable\n// only from the async-context frame `runInScope` creates, so it is collected with the invocation\n// rather than accumulating in the isolate across requests.\nconst scopes = new AsyncLocalStorage<TraceScope>()\n\nexport const runInScope = <T>(scope: TraceScope, run: () => T): T => {\n return scopes.run(scope, run)\n}\n\nexport const currentScope = (): TraceScope | undefined => {\n return scopes.getStore()\n}\n\nexport const currentSpan = (): WireSpan | undefined => {\n return scopes.getStore()?.span\n}\n\n/**\n * Reports the trace context an outbound call should carry, parenting the callee onto the span currently in scope.\n * @returns The context to serialize into the outbound header or RPC argument, or `undefined` outside an invocation.\n */\nexport const currentTraceContext = (): TraceContext | undefined => {\n const scope = scopes.getStore()\n if (scope === undefined) {\n return undefined\n }\n\n return { traceId: scope.traceId, ...(scope.span === undefined ? {} : { parent: scope.span.spanId }) }\n}\n","import type { SpansRecord } from '@qinto/tail-trace'\nimport { parseSpansRecord } from '@qinto/tail-trace'\n\nexport type DevLogEntry = { at: number; level: string; message: string; spans?: SpansRecord }\n\ntype LogSubscriber = (entry: DevLogEntry) => void\n\nexport type DevLogBus = {\n // Handed to Miniflare's structured-log hook: every worker console line arrives here, and the ones\n // carrying a spans record are parsed so the console can render the trace the site worker emitted.\n accept: (log: { timestamp: number; level: string; message: string }) => void\n recent: () => DevLogEntry[]\n subscribe: (subscriber: LogSubscriber) => () => void\n}\n\nexport const createLogBus = (capacity = 500): DevLogBus => {\n const entries: DevLogEntry[] = []\n const subscribers = new Set<LogSubscriber>()\n\n return {\n accept: (log) => {\n const spans = parseSpansRecord(log.message)\n const entry: DevLogEntry = {\n at: log.timestamp,\n level: log.level,\n message: log.message,\n ...(spans === undefined ? {} : { spans })\n }\n\n entries.push(entry)\n if (entries.length > capacity) {\n entries.shift()\n }\n\n for (const subscriber of subscribers) {\n subscriber(entry)\n }\n },\n recent: () => {\n return [...entries]\n },\n subscribe: (subscriber) => {\n subscribers.add(subscriber)\n return () => {\n subscribers.delete(subscriber)\n }\n }\n }\n}\n","import { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport type { Server, ServerResponse } from 'node:http'\nimport { createServer } from 'node:http'\nimport type { AddressInfo } from 'node:net'\nimport { join, normalize, resolve, sep } from 'node:path'\n\nexport type AppUiServerInput = { host: string; port: number; basePath: string; uiRoot: string }\n\nexport type AppUiServer = { origin: () => string; stop: () => Promise<void> }\n\nconst TYPES: Record<string, string> = {\n '.html': 'text/html; charset=utf-8',\n '.js': 'text/javascript; charset=utf-8',\n '.mjs': 'text/javascript; charset=utf-8',\n '.css': 'text/css; charset=utf-8',\n '.json': 'application/json; charset=utf-8',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.jpg': 'image/jpeg',\n '.jpeg': 'image/jpeg',\n '.gif': 'image/gif',\n '.webp': 'image/webp',\n '.ico': 'image/x-icon',\n '.woff': 'font/woff',\n '.woff2': 'font/woff2'\n}\n\nconst contentType = (path: string): string => {\n const dot = path.lastIndexOf('.')\n return (dot === -1 ? undefined : TYPES[path.slice(dot).toLowerCase()]) ?? 'application/octet-stream'\n}\n\nconst listening = (server: Server, host: string, port: number): Promise<void> => {\n return new Promise((resolve_, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n resolve_()\n })\n })\n}\n\nconst decoded = (path: string): string | null => {\n try {\n return decodeURIComponent(path)\n } catch {\n return null\n }\n}\n\n// `..` in the request path would otherwise reach any file the developer can read; normalize first,\n// then require the result to still sit under the built panel.\nconst resolveFile = (uiRoot: string, relative: string): string | null => {\n const root = resolve(uiRoot)\n const target = resolve(join(root, normalize(relative)))\n return target === root || target.startsWith(`${root}${sep}`) ? target : null\n}\n\n// A directory stands for its own index.html, which is how Astro's nested routes are served.\nconst locate = async (file: string): Promise<{ target: string; size: number } | null> => {\n const found = await stat(file).catch(() => {\n return null\n })\n if (found === null) {\n return null\n }\n\n const target = found.isDirectory() ? join(file, 'index.html') : file\n const stats = found.isDirectory()\n ? await stat(target).catch(() => {\n return null\n })\n : found\n\n return stats === null ? null : { target, size: stats.size }\n}\n\nexport const startAppUiServer = async (input: AppUiServerInput): Promise<AppUiServer> => {\n let bound = input.port\n\n const send = async (raw: string, response: ServerResponse): Promise<void> => {\n const path = decoded(raw)\n if (path === null) {\n response.writeHead(400, { 'content-type': 'text/plain' }).end('bad request')\n return\n }\n\n // Anything outside the panel's own base path is a request the published layout would not answer.\n if (!path.startsWith(input.basePath)) {\n response.writeHead(404, { 'content-type': 'text/plain' }).end('not found')\n return\n }\n\n const relative = path.slice(input.basePath.length)\n const file = resolveFile(input.uiRoot, relative === '' ? 'index.html' : relative)\n if (file === null) {\n response.writeHead(403, { 'content-type': 'text/plain' }).end('forbidden')\n return\n }\n\n const located = await locate(file)\n if (located === null) {\n response.writeHead(404, { 'content-type': 'text/plain' }).end('not found')\n return\n }\n\n // The panel is fetched cross-origin from the console, and its own calls are read-only here.\n response.writeHead(200, {\n 'content-type': contentType(located.target),\n 'content-length': located.size,\n 'cache-control': 'no-store',\n 'access-control-allow-origin': '*'\n })\n createReadStream(located.target).pipe(response)\n }\n\n const server = createServer((request, response) => {\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n response.writeHead(405, { allow: 'GET, HEAD' }).end()\n return\n }\n\n // Every await inside `send` handles its own failure, so there is no rejection to catch here.\n void send((request.url as string).split('?')[0] as string, response)\n })\n\n await listening(server, input.host, input.port)\n bound = (server.address() as AddressInfo).port\n\n return {\n origin: () => {\n return `http://${input.host}:${bound}`\n },\n stop: () => {\n return new Promise((resolve_) => {\n server.close(() => {\n resolve_()\n })\n })\n }\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { writeFile } from 'node:fs/promises'\n\nimport { MAX_INSTALLS_PER_APP } from '@qinto/app-envelope'\n\nimport type { DevPaths } from './paths'\nimport { resetDevRoot } from './paths'\nimport { readIfPresent } from './read-if-present'\n\nexport type DevInstall = {\n appInstallId: string\n ordinal: number\n label: string\n enabled: boolean\n variables: Record<string, string | boolean>\n}\n\nexport type DevGeo = { country: string; region: string; city: string; timezone: string }\n\nexport type DevState = {\n teamId: string\n domainId: string\n organizationId: string\n appId: string\n siteDomain: string\n installed: boolean\n enabled: boolean\n installs: DevInstall[]\n nextOrdinal: number\n // Per resource identifier, the local database a hyperdrive binding connects to. Never derived from\n // the manifest, whose origin names the deployment's database.\n hyperdrive: Record<string, string>\n geo: DevGeo\n botScore: number\n // Drives CONSENT_CONFIGURATION. Off by default, like a site whose manager has not turned consent\n // mode on: every connected app receives every event without a grant to check.\n consentEnabled: boolean\n}\n\nexport const DEV_SITE_DOMAIN = 'dev.localhost'\n\n// A hand-written app has no registered id, and the panel's asset paths are keyed by one, so it is\n// derived from the slug: stable across restarts, and distinct per app in one dev directory.\nexport const devAppId = (slug: string): string => {\n return `dev-${slug}`\n}\n\n// The dev root is keyed by the project directory, so a directory that now holds a different app\n// would otherwise inherit the previous one's installs, variables, secrets and stored data.\nexport const discardStateOfOtherApp = async (paths: DevPaths, slug: string): Promise<string | null> => {\n const stored = await readIfPresent(paths.state)\n if (stored === null) {\n return null\n }\n\n const previous = (JSON.parse(stored) as DevState).appId\n if (previous === devAppId(slug)) {\n return null\n }\n\n await resetDevRoot(paths)\n\n return previous.slice('dev-'.length)\n}\n\nexport type AddInstallResult = { state: DevState; install: DevInstall }\n\nexport const addDevInstall = (state: DevState, label: string): AddInstallResult => {\n if (state.installs.length >= MAX_INSTALLS_PER_APP) {\n throw new Error(`An app takes at most ${MAX_INSTALLS_PER_APP} installs on one site.`)\n }\n\n const install: DevInstall = {\n appInstallId: randomUUID(),\n ordinal: state.nextOrdinal,\n label,\n enabled: true,\n variables: {}\n }\n\n return { state: { ...state, installs: [...state.installs, install], nextOrdinal: state.nextOrdinal + 1 }, install }\n}\n\n// Installed with its first install from the first boot. A developer runs `qinto app dev` to exercise\n// their app, and an app that is merely present receives nothing — so finding the Install button is a\n// step with no decision in it. Uninstalling persists; only a fresh dev root seeds this.\nexport const seedDevState = (slug: string): DevState => {\n const seeded: DevState = {\n teamId: randomUUID(),\n domainId: randomUUID(),\n organizationId: randomUUID(),\n appId: devAppId(slug),\n siteDomain: DEV_SITE_DOMAIN,\n installed: true,\n enabled: true,\n installs: [],\n nextOrdinal: 1,\n hyperdrive: {},\n geo: { country: 'US', region: 'California', city: 'San Francisco', timezone: 'America/Los_Angeles' },\n botScore: 99,\n consentEnabled: false\n }\n\n return addDevInstall(seeded, 'Primary').state\n}\n\nexport const loadDevState = async (paths: DevPaths, slug: string): Promise<DevState> => {\n const stored = await readIfPresent(paths.state)\n\n return stored === null ? seedDevState(slug) : (JSON.parse(stored) as DevState)\n}\n\nexport const saveDevState = async (paths: DevPaths, state: DevState): Promise<void> => {\n await writeFile(paths.state, `${JSON.stringify(state, null, 2)}\\n`, { mode: 0o600 })\n}\n\nexport const loadDevSecrets = async (paths: DevPaths): Promise<Record<string, Record<string, string>>> => {\n const stored = await readIfPresent(paths.secrets)\n\n return stored === null ? {} : (JSON.parse(stored) as Record<string, Record<string, string>>)\n}\n\nexport const saveDevSecrets = async (paths: DevPaths, secrets: Record<string, Record<string, string>>): Promise<void> => {\n await writeFile(paths.secrets, `${JSON.stringify(secrets, null, 2)}\\n`, { mode: 0o600 })\n}\n\n// Kept out of DevState, which the console rewrites wholesale: an app value belongs to the app, not\n// to this site's install of it.\nexport type DevAppValues = Record<string, string>\n\nexport const loadDevAppValues = async (paths: DevPaths): Promise<DevAppValues> => {\n const stored = await readIfPresent(paths.appValues)\n\n return stored === null ? {} : (JSON.parse(stored) as DevAppValues)\n}\n\nexport const saveDevAppValues = async (paths: DevPaths, values: DevAppValues): Promise<void> => {\n await writeFile(paths.appValues, `${JSON.stringify(values, null, 2)}\\n`, { mode: 0o600 })\n}\n","export const endOfQuoted = (sql: string, start: number, quote: string): { end: number; closed: boolean } => {\n let index = start + 1\n while (index < sql.length) {\n if (sql[index] === quote && sql[index + 1] === quote) {\n index += 2\n continue\n }\n\n if (sql[index] === quote) {\n return { end: index + 1, closed: true }\n }\n\n index += 1\n }\n\n return { end: index, closed: false }\n}\n","import { endOfQuoted } from './sql-scan'\n\nconst LEDGER_TABLE = /\\b_qinto_migrations\\b/i\n\nconst TRANSACTION_CONTROL = /^(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE)\\b/i\n\nconst ADDITIVE_CREATE = /^CREATE\\s+(UNIQUE\\s+)?(TABLE|INDEX|VIEW)\\s+IF\\s+NOT\\s+EXISTS\\s+\\S/i\n\nconst ADDITIVE_TRIGGER = /^CREATE\\s+(TEMP\\s+|TEMPORARY\\s+)?TRIGGER\\s+IF\\s+NOT\\s+EXISTS\\s+\\S/i\n\nconst ADDITIVE_ALTER = /^ALTER\\s+TABLE\\s+\\S+\\s+ADD\\s+(COLUMN\\s+)?(?!CONSTRAINT\\b)\\S/i\n\nexport type D1Migration =\n | { id: string; phase: 'expand' | 'contract'; statements: string[] }\n | { id: string; phase: 'backfill'; handler: string }\n\nconst endOfLineComment = (sql: string, start: number): number => {\n let index = start\n while (index < sql.length && sql[index] !== '\\n') {\n index += 1\n }\n\n return index\n}\n\nconst endOfBlockComment = (sql: string, start: number): number => {\n let index = start + 2\n while (index < sql.length && !(sql[index] === '*' && sql[index + 1] === '/')) {\n index += 1\n }\n\n return index + 2\n}\n\ntype ScannedSql = { stripped: string; unterminatedLiteral: boolean }\n\nconst scan = (sql: string): ScannedSql => {\n let out = ''\n let unterminated = false\n let index = 0\n\n while (index < sql.length) {\n const char = sql[index]\n\n if (char === \"'\" || char === '\"') {\n const quoted = endOfQuoted(sql, index, char)\n out += sql.slice(index, quoted.end)\n unterminated = unterminated || !quoted.closed\n index = quoted.end\n continue\n }\n\n if (char === '-' && sql[index + 1] === '-') {\n index = endOfLineComment(sql, index)\n continue\n }\n\n if (char === '/' && sql[index + 1] === '*') {\n index = endOfBlockComment(sql, index)\n continue\n }\n\n out += char\n index += 1\n }\n\n return { stripped: out, unterminatedLiteral: unterminated }\n}\n\n/**\n * Removes SQL comments while preserving quoted strings and identifiers.\n * @param sql One complete D1 statement.\n * @returns The statement without line or block comments.\n */\nexport const stripSqlComments = (sql: string): string => {\n return scan(sql).stripped\n}\n\n/**\n * Validates one phased D1 migration against ledger, transaction, and expand-safety rules.\n * @param migration The immutable migration object.\n * @param position Its one-based declaration position for error reporting.\n * @returns A refusal reason, or `null` when the entry is valid.\n */\nexport const validateMigrationEntry = (migration: D1Migration, position: number): string | null => {\n if (migration.phase === 'backfill') {\n return null\n }\n\n for (const [statementIndex, raw] of migration.statements.entries()) {\n const scanned = scan(raw)\n const statement = scanned.stripped.trim()\n if (scanned.unterminatedLiteral) {\n return `Migration ${position} (${migration.id}) statement ${statementIndex + 1} contains an unterminated quoted string.`\n }\n\n if (statement === '') {\n return `Migration ${position} (${migration.id}) statement ${statementIndex + 1} is empty.`\n }\n\n if (LEDGER_TABLE.test(statement)) {\n return `Migration ${position} (${migration.id}) may not touch the _qinto_migrations table.`\n }\n\n if (TRANSACTION_CONTROL.test(statement)) {\n return `Migration ${position} (${migration.id}) may not contain explicit transaction control.`\n }\n\n if (\n migration.phase === 'expand' &&\n !ADDITIVE_CREATE.test(statement) &&\n !ADDITIVE_TRIGGER.test(statement) &&\n !ADDITIVE_ALTER.test(statement)\n ) {\n return `Migration ${position} (${migration.id}) must be additive: expand accepts CREATE … IF NOT EXISTS and ALTER TABLE … ADD COLUMN.`\n }\n }\n\n return null\n}\n\n/**\n * Validates an ordered D1 history and its stable ids.\n * @param migrations The resource's full declared history.\n * @returns The first refusal reason, or `null` when the history is valid.\n */\nexport const validateMigrations = (migrations: D1Migration[]): string | null => {\n const ids = new Set<string>()\n for (const [index, migration] of migrations.entries()) {\n if (ids.has(migration.id)) {\n return `Migration ${index + 1} repeats id ${migration.id}.`\n }\n\n ids.add(migration.id)\n const reason = validateMigrationEntry(migration, index + 1)\n if (reason !== null) {\n return reason\n }\n }\n\n return null\n}\n","import { createHash } from 'node:crypto'\n\nimport type { ControlMigration, ControlResponse } from '@qinto/app-envelope'\nimport type { AppManifestD1Migration } from '@qinto/app-manifest'\nimport { validateMigrations } from '@qinto/cloudflare/migrations'\n\nconst BACKFILL_LEDGER = '_qinto_dev_backfills'\nconst STATEMENT_LEDGER = '_qinto_migrations'\n\nexport type MigrationStatement = {\n bind: (...values: unknown[]) => MigrationStatement\n all: () => Promise<{ results: unknown[] }>\n first: <T>() => Promise<T | null>\n}\n\nexport type MigrationTarget = {\n prepare: (query: string) => MigrationStatement\n exec: (query: string) => Promise<unknown>\n}\n\nexport type DevMigrationPlan = {\n resource: string\n binding: string\n migrations: AppManifestD1Migration[]\n}\n\nexport type MigrationRunner = (migration: ControlMigration) => Promise<ControlResponse>\n\ntype LedgerRow = { id: string; checksum: string }\n\ntype BackfillRow = { checksum: string; checkpoint: string | null; completed: number }\ntype BackfillState = 'already_complete' | 'complete' | 'pending'\n\nconst digest = (migration: AppManifestD1Migration): string => {\n return createHash('sha256').update(JSON.stringify(migration)).digest('hex')\n}\n\nconst RESET = 'Run `qinto app dev --reset` to rebuild this local database.'\n\nconst statementRows = async (database: MigrationTarget): Promise<Map<string, string>> => {\n await database.exec(\n `CREATE TABLE IF NOT EXISTS ${STATEMENT_LEDGER} (id text primary key, checksum text not null, phase text not null, applied_at text not null)`\n )\n const stored = await database.prepare(`SELECT id, checksum FROM ${STATEMENT_LEDGER} ORDER BY applied_at, id`).all()\n\n return new Map((stored.results as LedgerRow[]).map((row) => [row.id, row.checksum]))\n}\n\nconst runBackfill = async (input: {\n database: MigrationTarget\n plan: DevMigrationPlan\n migration: Extract<AppManifestD1Migration, { phase: 'backfill' }>\n checksum: string\n run: MigrationRunner\n}): Promise<BackfillState> => {\n const { database, plan, migration, checksum, run } = input\n await database.exec(\n `CREATE TABLE IF NOT EXISTS ${BACKFILL_LEDGER} (id text primary key, checksum text not null, checkpoint text, completed integer not null)`\n )\n const stored = await database\n .prepare(`SELECT checksum, checkpoint, completed FROM ${BACKFILL_LEDGER} WHERE id = ?`)\n .bind(migration.id)\n .first<BackfillRow>()\n if (stored !== null && stored.checksum !== checksum) {\n throw new Error(`${plan.binding} migration ${migration.id} changed after it was applied. ${RESET}`)\n }\n\n if (stored?.completed === 1) {\n return 'already_complete'\n }\n\n const checkpoint = stored?.checkpoint === null || stored?.checkpoint === undefined ? null : JSON.parse(stored.checkpoint)\n const response = await run({\n resource: plan.resource,\n binding: plan.binding,\n id: migration.id,\n checksum,\n phase: 'backfill',\n handler: migration.handler,\n checkpoint\n })\n if (!response.ok || response.migration === undefined) {\n throw new Error(response.error?.message ?? `${plan.binding} migration ${migration.id} returned no result`)\n }\n\n if (response.migration.done) {\n await database.exec(\n `INSERT INTO ${BACKFILL_LEDGER} (id, checksum, checkpoint, completed) VALUES ('${migration.id}', '${checksum}', NULL, 1)\n ON CONFLICT(id) DO UPDATE SET checksum = excluded.checksum, checkpoint = NULL, completed = 1`\n )\n\n return 'complete'\n }\n\n const serialized = JSON.stringify(response.migration.checkpoint).replaceAll(\"'\", \"''\")\n await database.exec(\n `INSERT INTO ${BACKFILL_LEDGER} (id, checksum, checkpoint, completed) VALUES ('${migration.id}', '${checksum}', '${serialized}', 0)\n ON CONFLICT(id) DO UPDATE SET checksum = excluded.checksum, checkpoint = excluded.checkpoint, completed = 0`\n )\n\n return 'pending'\n}\n\nconst assertAppliedHistory = (plan: DevMigrationPlan, applied: Map<string, string>): void => {\n for (const [id, checksum] of applied) {\n const migration = plan.migrations.find((candidate) => candidate.id === id)\n if (migration === undefined || migration.phase === 'backfill') {\n throw new Error(`${plan.binding} has applied migration ${id} which the manifest no longer declares. ${RESET}`)\n }\n\n if (digest(migration) !== checksum) {\n throw new Error(`${plan.binding} migration ${id} changed after it was applied. ${RESET}`)\n }\n }\n}\n\nconst runStatementMigration = async (input: {\n plan: DevMigrationPlan\n migration: Exclude<AppManifestD1Migration, { phase: 'backfill' }>\n checksum: string\n run: MigrationRunner\n}): Promise<void> => {\n const { plan, migration, checksum, run } = input\n const response = await run({\n resource: plan.resource,\n binding: plan.binding,\n id: migration.id,\n checksum,\n phase: migration.phase,\n statements: migration.statements\n })\n if (!response.ok || response.migration?.done !== true) {\n throw new Error(response.error?.message ?? `${plan.binding} migration ${migration.id} returned no completion result`)\n }\n}\n\nexport const applyD1Migrations = async (database: MigrationTarget, plan: DevMigrationPlan, run: MigrationRunner): Promise<number> => {\n const reason = validateMigrations(plan.migrations)\n if (reason !== null) {\n throw new Error(`${plan.binding}: ${reason}`)\n }\n\n const applied = await statementRows(database)\n assertAppliedHistory(plan, applied)\n\n let completed = 0\n for (const migration of plan.migrations) {\n const checksum = digest(migration)\n if (migration.phase === 'backfill') {\n const state = await runBackfill({ database, plan, migration, checksum, run })\n if (state === 'complete') {\n completed += 1\n }\n\n if (state === 'pending') {\n return completed\n }\n\n continue\n }\n\n if (applied.has(migration.id)) {\n continue\n }\n\n await runStatementMigration({ plan, migration, checksum, run })\n\n applied.set(migration.id, checksum)\n completed += 1\n }\n\n return completed\n}\n","import type { ControlMigration, ControlResponse } from '@qinto/app-envelope'\nimport { CONTROL_ENVELOPE_VERSION, controlResponseSchema } from '@qinto/app-envelope'\nimport { Miniflare } from 'miniflare'\n\nimport type { ArtifactModule } from './artifacts'\nimport type { AppWorkerComposition } from './compose/app-worker'\nimport { APP_WORKER_NAME, SITE_WORKER_NAME } from './compose/app-worker'\nimport type { SiteWorkerComposition } from './compose/site-worker'\nimport type { DevMigrationPlan, MigrationTarget } from './migrations'\nimport { applyD1Migrations } from './migrations'\nimport type { DevGeo } from './state'\n\nexport type Stack = { site: SiteWorkerComposition; app: AppWorkerComposition }\n\ntype ScheduleInstall = { id: string; ord: number; label: string }\n\nexport type SupervisorOptions = {\n host: string\n port: number\n persistRoot: string\n compatibilityDate: string\n compatibilityFlags: string[]\n onLog: (log: { timestamp: number; level: string; message: string }) => void\n}\n\nexport type Supervisor = {\n update: (stack: Stack) => Promise<void>\n // The ledger keeps a recompose idempotent.\n migrate: (migrations: DevMigrationPlan[]) => Promise<void>\n // Fires one declared schedule now, for every enabled install — the hourly floor makes waiting for\n // the real window useless as a dev loop.\n runSchedule: (schedule: { id: string; cron: string }, installs: ScheduleInstall[]) => Promise<void>\n // Resolves to the address workerd actually bound, which is what a port of 0 has to be read back from.\n ready: () => Promise<URL>\n dispose: () => Promise<void>\n}\n\nconst moduleMap = (modules: ArtifactModule[]): Record<string, { type: 'esm' | 'text'; contents: string }> => {\n return Object.fromEntries(modules.map((module) => [module.name, { type: module.type, contents: module.contents }]))\n}\n\n// Miniflare fetches a `Request.cf` blob from Cloudflare on first use unless one is supplied, which\n// would both reach the network and make geo non-deterministic.\nexport const devCfBlob = (geo: DevGeo, botScore: number): Record<string, unknown> => {\n return {\n country: geo.country,\n region: geo.region,\n city: geo.city,\n timezone: geo.timezone,\n colo: 'DEV',\n botManagement: { score: botScore, verifiedBot: false, corporateProxy: false, staticResource: false }\n }\n}\n\ntype BuildOptionsInput = SupervisorOptions & { stack: Stack; cf: Record<string, unknown> }\n\nconst miniflareOptions = (input: BuildOptionsInput): ConstructorParameters<typeof Miniflare>[0] => {\n // Storage is in memory unless each worker's dev root is set, so a restart would wipe the visitor\n // graph and every app resource while the dev state still said the app was installed.\n const dev = { rootPath: input.persistRoot }\n\n return {\n host: input.host,\n port: input.port,\n cf: input.cf,\n handleStructuredLogs: input.onLog,\n workers: [\n {\n dev,\n config: {\n type: 'worker',\n name: SITE_WORKER_NAME,\n compatibilityDate: input.compatibilityDate,\n compatibilityFlags: input.compatibilityFlags,\n manifest: { mainModule: input.stack.site.mainModule, modules: moduleMap(input.stack.site.modules) },\n env: input.stack.site.env,\n exports: input.stack.site.exports\n }\n },\n {\n dev,\n config: {\n type: 'worker',\n name: APP_WORKER_NAME,\n compatibilityDate: input.compatibilityDate,\n compatibilityFlags: input.compatibilityFlags,\n manifest: { mainModule: input.stack.app.mainModule, modules: moduleMap(input.stack.app.modules) },\n env: input.stack.app.env,\n exports: input.stack.app.exports\n }\n }\n ]\n }\n}\n\nexport const startSupervisor = (options: SupervisorOptions, stack: Stack, cf: Record<string, unknown>): Supervisor => {\n const runtime = new Miniflare(miniflareOptions({ ...options, stack, cf }))\n let currentStack = stack\n\n // Resolved before any control work starts, so a missing binding is reported instead of surfacing\n // later as whatever the first envelope happens to fail on.\n const controlBindings = (kind: string): { app: { slug: string; version: string }; key: string } => {\n const contextBinding = currentStack.app.env['APP_CONTEXT']\n const keyBinding = currentStack.app.env['QINTO_INTERNAL_KEY']\n if (contextBinding?.type !== 'text' || keyBinding?.type !== 'text') {\n throw new Error(`The local app worker is missing its ${kind} control bindings.`)\n }\n\n return { app: JSON.parse(contextBinding.value) as { slug: string; version: string }, key: keyBinding.value }\n }\n\n const postControl = async (\n bindings: { app: { slug: string; version: string }; key: string },\n kind: string,\n payload: Record<string, unknown>\n ): Promise<ControlResponse> => {\n const site = await runtime.ready\n const appWorker = await runtime.getWorker(APP_WORKER_NAME)\n const response = await appWorker.fetch('https://app/__qinto/control', {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'x-qinto-app-key': bindings.key },\n body: JSON.stringify({\n v: CONTROL_ENVELOPE_VERSION,\n kind,\n site: { origin: site.origin },\n app: { slug: bindings.app.slug, version: bindings.app.version },\n ...payload\n })\n })\n const parsed = controlResponseSchema.safeParse(await response.json().catch(() => null))\n if (!response.ok || !parsed.success) {\n throw new Error(`Local app ${kind} control returned ${response.status}.`)\n }\n\n return parsed.data\n }\n\n return {\n update: async (next) => {\n await runtime.setOptions(miniflareOptions({ ...options, stack: next, cf }))\n currentStack = next\n },\n migrate: async (migrations) => {\n if (migrations.length === 0) {\n return\n }\n\n const bindings = controlBindings('migration')\n const run = async (migration: ControlMigration) => {\n return postControl(bindings, 'migration', { migration })\n }\n\n for (const plan of migrations) {\n const database = (await runtime.getD1Database(plan.binding, APP_WORKER_NAME)) as unknown as MigrationTarget\n await applyD1Migrations(database, plan, run)\n }\n },\n runSchedule: async (schedule, installs) => {\n if (installs.length === 0) {\n throw new Error('No enabled install to run this schedule for.')\n }\n\n const result = await postControl(controlBindings('schedule'), 'schedule', {\n schedule: { id: schedule.id, cron: schedule.cron, scheduledTime: Date.now(), installs }\n })\n if (!result.ok) {\n throw new Error(result.error?.message ?? `The ${schedule.id} handler failed.`)\n }\n },\n ready: () => {\n return runtime.ready\n },\n dispose: () => {\n return runtime.dispose()\n }\n }\n}\n","import { mkdtemp, readFile } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nimport { buildBundles, runUiBuild, validateServerHooks, validateUiAssets } from '@qinto/app-build'\nimport type { AppManifest } from '@qinto/app-manifest'\n\nimport type { WorkerArtifact } from './artifacts'\nimport { loadWorkerArtifact } from './artifacts'\nimport { APP_WORKER_NAME, composeAppWorker } from './compose/app-worker'\nimport type { InstallSecrets } from './compose/deployable'\nimport { devDeployableApp, isInstallActive } from './compose/deployable'\nimport type { InertResource } from './compose/resources'\nimport { composeSiteWorker } from './compose/site-worker'\nimport type { DevKeys } from './keys'\nimport { loadDevKeys } from './keys'\nimport type { DevLogBus } from './logs'\nimport { createLogBus } from './logs'\nimport type { DevPaths } from './paths'\nimport { devPaths, ensureDevRoot } from './paths'\nimport { startAppUiServer } from './server/app-ui'\nimport type { DevAppValues, DevState } from './state'\nimport {\n discardStateOfOtherApp,\n loadDevAppValues,\n loadDevSecrets,\n loadDevState,\n saveDevAppValues,\n saveDevSecrets,\n saveDevState\n} from './state'\nimport type { Stack, Supervisor } from './supervisor'\nimport { devCfBlob, startSupervisor } from './supervisor'\n\n// The version a local build stands in for. `qinto app publish` allocates a real one; here the loop\n// only needs a stable key for the registry, the bundle module name and the panel's asset path.\nexport const DEV_VERSION = '0.0.0-dev'\n\nexport type DevStackOptions = {\n dir: string\n artifactRoot: string\n host: string\n port: number\n uiPort: number\n // Where the app worker reaches the platform stand-in. The stack starts before the console, so the\n // port must be known up front — `--console-port 0` is refused for exactly this reason.\n consoleOrigin: string\n readManifest: () => Promise<AppManifest>\n}\n\n// The panel's own origin, deliberately not the console's, so the postMessage origin checks the\n// platform relies on are exercised locally rather than passing because everything is same-origin.\nexport type DevAppUi = { origin: string; basePath: string; iframeUrl: string }\n\nexport type DevStack = {\n origin: string\n appUi: DevAppUi | null\n paths: DevPaths\n keys: DevKeys\n logs: DevLogBus\n platformVersion: string\n discardedAppSlug: string | null\n state: () => DevState\n secrets: () => InstallSecrets\n appValues: () => DevAppValues\n manifest: () => AppManifest\n inert: () => InertResource[]\n apply: (next: { state: DevState; secrets: InstallSecrets; appValues: DevAppValues }) => Promise<void>\n // Fires one declared schedule now, for every enabled install of the app.\n runSchedule: (scheduleId: string) => Promise<void>\n rebuild: () => Promise<void>\n stop: () => Promise<void>\n}\n\ntype Built = { server: string; browser: string | null }\n\nconst buildApp = async (dir: string, manifest: AppManifest): Promise<Built> => {\n const outDir = await mkdtemp(join(tmpdir(), 'qinto-dev-build-'))\n const bundles = await buildBundles({ dir, manifest, outDir })\n // The same cross-check `app publish` runs: the registry advertises the manifest's hooks, so a\n // bundle that registers different ones would fail closed at dispatch instead of failing here.\n await validateServerHooks({ manifest, serverBundle: bundles.server })\n\n return {\n server: await readFile(bundles.server, 'utf8'),\n browser: bundles.browser === null ? null : await readFile(bundles.browser, 'utf8')\n }\n}\n\n// The published panel is fetched from `/<appId>/<version>/`, and every absolute asset Astro emits is\n// built against it — serving it anywhere else 404s the whole panel.\nconst uiBasePath = (appId: string): string => {\n return `/${appId}/${DEV_VERSION}/`\n}\n\nconst buildUi = async (dir: string, manifest: AppManifest, basePath: string): Promise<string | null> => {\n if (manifest.ui === undefined) {\n return null\n }\n\n await runUiBuild({ dir, ui: manifest.ui, basePath })\n const uiRoot = resolve(dir, manifest.ui.dir)\n await validateUiAssets({ uiRoot, basePath })\n return uiRoot\n}\n\ntype ComposeInput = {\n manifest: AppManifest\n built: Built\n state: DevState\n secrets: InstallSecrets\n appValues: DevAppValues\n consoleOrigin: string\n keys: DevKeys\n appUiOrigin: string | null\n artifacts: { main: WorkerArtifact; runtime: WorkerArtifact }\n}\n\nconst compose = async (input: ComposeInput): Promise<{ stack: Stack; inert: InertResource[] }> => {\n const runtimeModule = input.artifacts.runtime.modules.find((module) => module.name === input.artifacts.runtime.mainModule)\n if (runtimeModule === undefined) {\n throw new Error('The app-runtime artifact carries no main module.')\n }\n\n const app = await composeAppWorker({\n manifest: input.manifest,\n state: input.state,\n secrets: input.secrets,\n appValues: input.appValues,\n consoleOrigin: input.consoleOrigin,\n keys: input.keys,\n version: DEV_VERSION,\n serverBundle: input.built.server,\n runtimeModule,\n installToken: input.keys.installToken\n })\n\n const apps = input.state.installed\n ? [\n devDeployableApp({\n manifest: input.manifest,\n state: input.state,\n secrets: input.secrets,\n version: DEV_VERSION,\n workerName: APP_WORKER_NAME\n })\n ]\n : []\n const browserBundles = new Map<string, string>()\n if (input.built.browser !== null && apps.length > 0) {\n browserBundles.set(input.manifest.slug, input.built.browser)\n }\n\n const site = await composeSiteWorker({\n artifact: input.artifacts.main,\n apps,\n browserBundles,\n state: input.state,\n keys: input.keys,\n appUiOrigin: input.appUiOrigin,\n rootDomain: input.state.siteDomain\n })\n\n return { stack: { site, app }, inert: app.inert }\n}\n\nexport const startDevStack = async (options: DevStackOptions): Promise<DevStack> => {\n const paths = devPaths(options.dir)\n let manifest = await options.readManifest()\n const discardedAppSlug = await discardStateOfOtherApp(paths, manifest.slug)\n await ensureDevRoot(paths)\n\n const keys = await loadDevKeys(paths)\n const artifacts = {\n main: await loadWorkerArtifact(options.artifactRoot, 'main'),\n runtime: await loadWorkerArtifact(options.artifactRoot, 'app-runtime')\n }\n\n let state = await loadDevState(paths, manifest.slug)\n let secrets = await loadDevSecrets(paths)\n let appValues = await loadDevAppValues(paths)\n let built = await buildApp(options.dir, manifest)\n\n const basePath = uiBasePath(state.appId)\n const uiRoot = await buildUi(options.dir, manifest, basePath)\n const uiServer = uiRoot === null ? null : await startAppUiServer({ host: options.host, port: options.uiPort, basePath, uiRoot })\n const appUi: DevAppUi | null =\n uiServer === null ? null : { origin: uiServer.origin(), basePath, iframeUrl: `${uiServer.origin()}${basePath}index.html` }\n\n let composed = await compose({\n manifest,\n built,\n state,\n secrets,\n appValues,\n consoleOrigin: options.consoleOrigin,\n keys,\n appUiOrigin: appUi?.origin ?? null,\n artifacts\n })\n\n const logs = createLogBus()\n const supervisor: Supervisor = startSupervisor(\n {\n host: options.host,\n port: options.port,\n persistRoot: paths.persist,\n compatibilityDate: artifacts.main.compatibilityDate,\n compatibilityFlags: artifacts.main.compatibilityFlags,\n onLog: logs.accept\n },\n composed.stack,\n devCfBlob(state.geo, state.botScore)\n )\n // workerd is live from here, so a failed boot or a refused migration must take it down rather than\n // leave the runtime and its sockets behind.\n let origin: URL\n try {\n origin = await supervisor.ready()\n await supervisor.migrate(composed.stack.app.migrations)\n } catch (error) {\n await supervisor.dispose()\n await uiServer?.stop()\n throw error\n }\n\n const recompose = async (): Promise<void> => {\n composed = await compose({\n manifest,\n built,\n state,\n secrets,\n appValues,\n consoleOrigin: options.consoleOrigin,\n keys,\n appUiOrigin: appUi?.origin ?? null,\n artifacts\n })\n await supervisor.update(composed.stack)\n await supervisor.migrate(composed.stack.app.migrations)\n }\n\n // A change workerd refuses must leave nothing behind, or the next attempt would recompose the\n // rejected input again and the console could never be corrected.\n const settle = async (revert: () => void): Promise<void> => {\n try {\n await recompose()\n } catch (error) {\n revert()\n composed = await compose({\n manifest,\n built,\n state,\n secrets,\n appValues,\n consoleOrigin: options.consoleOrigin,\n keys,\n appUiOrigin: appUi?.origin ?? null,\n artifacts\n })\n await supervisor.update(composed.stack)\n throw error\n }\n }\n\n return {\n origin: origin.origin,\n appUi,\n paths,\n keys,\n logs,\n platformVersion: artifacts.main.version,\n discardedAppSlug,\n state: () => {\n return state\n },\n secrets: () => {\n return secrets\n },\n appValues: () => {\n return appValues\n },\n manifest: () => {\n return manifest\n },\n inert: () => {\n return composed.inert\n },\n // One write for all three: the state, its secrets and the app values are only persisted once\n // workerd has accepted them.\n apply: async (next) => {\n const previous = { state, secrets, appValues }\n state = next.state\n secrets = next.secrets\n appValues = next.appValues\n await settle(() => {\n state = previous.state\n secrets = previous.secrets\n appValues = previous.appValues\n })\n\n await saveDevState(paths, state)\n await saveDevSecrets(paths, secrets)\n await saveDevAppValues(paths, appValues)\n },\n runSchedule: async (scheduleId) => {\n const schedule = (manifest.server.schedules ?? []).find((candidate) => candidate.id === scheduleId)\n if (schedule === undefined) {\n throw new Error(`${manifest.slug} declares no schedule named ${scheduleId}.`)\n }\n\n if (!state.installed) {\n throw new Error(`${manifest.slug} is not installed on this site.`)\n }\n\n // The same predicate the platform dispatches on, so Run now cannot reach an install the\n // deployed sweep would drop.\n await supervisor.runSchedule(\n schedule,\n state.installs\n .filter((install) => isInstallActive(manifest, state, install, secrets))\n .map((install) => {\n return { id: install.appInstallId, ord: install.ordinal, label: install.label }\n })\n )\n },\n rebuild: async () => {\n const nextManifest = await options.readManifest()\n // The install, its variables, the keys, the persisted data and the panel's asset path all\n // belong to the slug this session booted on. Only a restart discards them for the new app.\n if (nextManifest.slug !== manifest.slug) {\n throw new Error('slug changed in the manifest. Restart `qinto app dev` to start the new app on its own local state.')\n }\n\n // The panel server was pointed at one directory when it started, so a moved `ui.dir` would\n // serve the previous build for the rest of the session.\n if (nextManifest.ui?.dir !== manifest.ui?.dir) {\n throw new Error('ui.dir changed in the manifest. Restart `qinto app dev` to serve the panel from its new directory.')\n }\n\n const nextBuilt = await buildApp(options.dir, nextManifest)\n await buildUi(options.dir, nextManifest, basePath)\n const previous = { manifest, built }\n manifest = nextManifest\n built = nextBuilt\n await settle(() => {\n manifest = previous.manifest\n built = previous.built\n })\n },\n stop: async () => {\n await supervisor.dispose()\n await uiServer?.stop()\n }\n }\n}\n","import type { AppManifest, AppManifestVariable } from '@qinto/app-manifest'\nimport { verifyAppUiWriteTicket } from '@qinto/app-ui-token'\n\nimport type { InstallSecrets } from '../compose/deployable'\nimport type { DevState } from '../state'\n\nexport type DevUiWriteInput = {\n ticket: string | null\n body: unknown\n slug: string\n appUiKeyId: string\n appUiKey: Uint8Array<ArrayBuffer>\n manifest: AppManifest\n state: DevState\n secrets: InstallSecrets\n}\n\nexport type DevUiWriteResult =\n | { ok: true; state: DevState; secrets: InstallSecrets }\n | { ok: false; status: number; error: string; message?: string }\n\ntype WriteBody = { appInstallId: string; values: Record<string, string | boolean> }\n\nconst parseBody = (body: unknown): WriteBody | null => {\n if (typeof body !== 'object' || body === null) {\n return null\n }\n\n const candidate = body as { appInstallId?: unknown; values?: unknown }\n if (typeof candidate.appInstallId !== 'string' || typeof candidate.values !== 'object' || candidate.values === null) {\n return null\n }\n\n return { appInstallId: candidate.appInstallId, values: candidate.values as Record<string, string | boolean> }\n}\n\nconst typeMismatch = (variable: AppManifestVariable, value: string | boolean): boolean => {\n return variable.type === 'toggle' ? typeof value !== 'boolean' : typeof value !== 'string'\n}\n\nexport const applyDevUiWrite = async (input: DevUiWriteInput): Promise<DevUiWriteResult> => {\n if (input.ticket === null) {\n return { ok: false, status: 401, error: 'unauthenticated' }\n }\n\n const verdict = await verifyAppUiWriteTicket({\n ticket: input.ticket,\n keys: { [input.appUiKeyId]: input.appUiKey },\n slug: input.slug,\n now: new Date()\n })\n if (!verdict.ok) {\n return { ok: false, status: 401, error: 'ticket_invalid' }\n }\n\n // The whole point of the local endpoint: without this gate, code writes fine under `qinto app dev`\n // and fails on deploy — the exact dev/prod divergence the rest of this stack exists to close.\n if (input.manifest.ui?.writesSettings !== true) {\n return { ok: false, status: 409, error: 'settings_not_declared', message: `${input.slug} does not declare ui.writesSettings.` }\n }\n\n const body = parseBody(input.body)\n if (body === null) {\n return { ok: false, status: 400, error: 'invalid_body' }\n }\n\n const install = input.state.installs.find((entry) => entry.appInstallId === body.appInstallId)\n if (install === undefined) {\n return { ok: false, status: 404, error: 'not_found' }\n }\n\n const variables = { ...install.variables }\n const secrets = { ...input.secrets[install.appInstallId] }\n for (const [name, value] of Object.entries(body.values)) {\n const variable = input.manifest.variables.find((candidate) => candidate.name === name)\n if (variable === undefined) {\n return { ok: false, status: 409, error: 'variable_invalid', message: `The app declares no variable named ${name}.` }\n }\n\n if (typeMismatch(variable, value)) {\n return { ok: false, status: 409, error: 'variable_invalid', message: `Variable ${name} has the wrong type.` }\n }\n\n if (variable.kind === 'secret') {\n secrets[name] = value as string\n } else {\n variables[name] = value\n }\n }\n\n return {\n ok: true,\n state: {\n ...input.state,\n installs: input.state.installs.map((entry) => {\n return entry.appInstallId === install.appInstallId ? { ...entry, variables } : entry\n })\n },\n secrets: { ...input.secrets, [install.appInstallId]: secrets }\n }\n}\n","import type { AppManifest } from '@qinto/app-manifest'\n\nimport type { InstallSecrets } from '../compose/deployable'\nimport type { DevAppValues, DevState } from '../state'\nimport { addDevInstall } from '../state'\n\nexport type ConsoleAction = { state: DevState; secrets: InstallSecrets; appValues: DevAppValues }\n\nexport type ApplyActionInput = {\n action: string\n fields: Record<string, string>\n manifest: AppManifest\n state: DevState\n secrets: InstallSecrets\n appValues: DevAppValues\n}\n\nconst withInstall = (\n state: DevState,\n appInstallId: string,\n change: (install: DevState['installs'][number]) => DevState['installs'][number]\n): DevState => {\n return {\n ...state,\n installs: state.installs.map((install) => {\n return install.appInstallId === appInstallId ? change(install) : install\n })\n }\n}\n\n// A checkbox posts its name only when ticked, so an absent field means false rather than unchanged.\nconst checked = (fields: Record<string, string>, name: string): boolean => {\n return fields[name] !== undefined\n}\n\nconst writeVariables = (input: ApplyActionInput, appInstallId: string): ConsoleAction => {\n const plain: Record<string, string | boolean> = {}\n const secret: Record<string, string> = { ...input.secrets[appInstallId] }\n\n for (const variable of input.manifest.variables) {\n const value = input.fields[`var_${variable.name}`]\n if (variable.kind === 'secret') {\n // Write-only, like the portal: an empty box leaves the stored secret alone.\n if (value !== undefined && value !== '') {\n secret[variable.name] = value\n }\n continue\n }\n\n if (variable.type === 'toggle') {\n plain[variable.name] = checked(input.fields, `var_${variable.name}`)\n continue\n }\n\n if (value !== undefined && value !== '') {\n plain[variable.name] = value\n }\n }\n\n return {\n appValues: input.appValues,\n state: withInstall(input.state, appInstallId, (install) => {\n return { ...install, variables: plain }\n }),\n secrets: { ...input.secrets, [appInstallId]: secret }\n }\n}\n\n// An app value has no unset, so a blank box leaves the stored one alone — for a plain variable as\n// much as for a secret.\nconst writeAppValues = (input: ApplyActionInput): ConsoleAction => {\n const appValues = { ...input.appValues }\n for (const variable of input.manifest.appVariables) {\n const value = input.fields[`appvar_${variable.name}`]\n if (value !== undefined && value !== '') {\n appValues[variable.name] = value\n }\n }\n\n return { state: input.state, secrets: input.secrets, appValues }\n}\n\nexport const applyConsoleAction = (input: ApplyActionInput): ConsoleAction => {\n const unchanged = { state: input.state, secrets: input.secrets, appValues: input.appValues }\n const appInstallId = input.fields['appInstallId'] ?? ''\n\n switch (input.action) {\n case 'install': {\n const seeded = input.state.installs.length === 0 ? addDevInstall(input.state, 'Primary') : { state: input.state }\n return { ...unchanged, state: { ...seeded.state, installed: true } }\n }\n case 'uninstall': {\n // The app values survive: they belong to the app, not to this site's install of it.\n return { state: { ...input.state, installed: false }, secrets: {}, appValues: input.appValues }\n }\n case 'app-enabled': {\n return { ...unchanged, state: { ...input.state, enabled: input.fields['enabled'] === 'true' } }\n }\n case 'install-add': {\n // The platform refuses a second install of a single-install app, so the local loop must too.\n if (input.manifest.install.multiple !== true) {\n throw new Error(`${input.manifest.slug} declares install.multiple false, so it takes one install.`)\n }\n\n return { ...unchanged, state: addDevInstall(input.state, input.fields['label'] ?? 'Install').state }\n }\n case 'install-remove': {\n // An installed app with no installs is a state the platform never holds; uninstall instead.\n if (input.state.installs.length <= 1) {\n throw new Error('The last install cannot be removed. Uninstall the app instead.')\n }\n\n const { [appInstallId]: removed, ...rest } = input.secrets\n return {\n state: { ...input.state, installs: input.state.installs.filter((install) => install.appInstallId !== appInstallId) },\n secrets: rest,\n appValues: input.appValues\n }\n }\n case 'hyperdrive': {\n // Both ride hidden or required inputs on the console's own form.\n const identifier = input.fields['identifier'] as string\n const url = input.fields['url'] as string\n const { [identifier]: cleared, ...rest } = input.state.hyperdrive\n return {\n ...unchanged,\n state: { ...input.state, hyperdrive: url === '' ? rest : { ...input.state.hyperdrive, [identifier]: url } }\n }\n }\n case 'install-label': {\n return {\n ...unchanged,\n state: withInstall(input.state, appInstallId, (install) => {\n return { ...install, label: input.fields['label'] ?? install.label }\n })\n }\n }\n case 'install-enabled': {\n return {\n ...unchanged,\n state: withInstall(input.state, appInstallId, (install) => {\n return { ...install, enabled: input.fields['enabled'] === 'true' }\n })\n }\n }\n case 'variables': {\n return writeVariables(input, appInstallId)\n }\n case 'app-variables': {\n return writeAppValues(input)\n }\n case 'consent': {\n return { ...unchanged, state: { ...input.state, consentEnabled: checked(input.fields, 'consentEnabled') } }\n }\n default: {\n return unchanged\n }\n }\n}\n","// lucide 1.24.0 path data (ISC), copied because this console renders HTML with no React, so the\n// lucide-react components the platform's sidebar draws cannot be imported here.\nconst ICONS = {\n activity:\n '<path d=\"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2\"/>',\n blocks:\n '<path d=\"M10 22V7a1 1 0 0 0-1-1H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5a1 1 0 0 0-1-1H2\"/><rect x=\"14\" y=\"2\" width=\"8\" height=\"8\" rx=\"1\"/>',\n bookOpen:\n '<path d=\"M12 7v14\"/><path d=\"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\"/>',\n building2:\n '<path d=\"M10 12h4\"/><path d=\"M10 8h4\"/><path d=\"M14 21v-3a2 2 0 0 0-4 0v3\"/><path d=\"M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2\"/><path d=\"M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16\"/>',\n chevronDown: '<path d=\"m6 9 6 6 6-6\"/>',\n chevronLeft: '<path d=\"m15 18-6-6 6-6\"/>',\n chevronRight: '<path d=\"m9 18 6-6-6-6\"/>',\n code: '<path d=\"m16 18 6-6-6-6\"/><path d=\"m8 6-6 6 6 6\"/>',\n globe: '<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20\"/><path d=\"M2 12h20\"/>',\n layers:\n '<path d=\"M12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83z\"/><path d=\"M2 12a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 12\"/><path d=\"M2 17a1 1 0 0 0 .58.91l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9A1 1 0 0 0 22 17\"/>',\n settings:\n '<path d=\"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z\"/><circle cx=\"12\" cy=\"12\" r=\"3\"/>'\n} as const\n\nexport type IconName = keyof typeof ICONS\n\nexport const icon = (name: IconName, size: number): string => {\n return `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${size}\" height=\"${size}\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\" aria-hidden=\"true\">${ICONS[name]}</svg>`\n}\n","// Tailwind's preflight, as the platform's pages get it from `@import \"tailwindcss\"`.\nconst RESET = `\n*, ::before, ::after { box-sizing: border-box; border: 0 solid; margin: 0; padding: 0 }\nhtml { font-family: var(--font-sans); line-height: 1.5; -webkit-text-size-adjust: 100% }\nh1, h2, h3 { font-size: inherit; font-weight: inherit }\nul, ol { list-style: none }\na { color: inherit; text-decoration: inherit }\ncode, pre { font-family: var(--font-mono); font-size: 1em }\ntable { border-collapse: collapse }\nsvg { display: block; vertical-align: middle }\niframe { display: block }\nbutton, input, select { font: inherit; color: inherit; background: transparent; letter-spacing: inherit }\nbutton:not(:disabled) { cursor: pointer }\n::placeholder { color: var(--muted-foreground) }`\n\n// `AppShell` + `Sidebar` + `SidebarNav`: the same widths, radii and colours their classes resolve to.\nconst SHELL = `\nbody { background: var(--color-cream-50); color: var(--color-gray-900) }\n.shell { display: flex; min-height: 100vh; background: var(--color-cream-50) }\naside { display: flex; width: 16rem; flex-shrink: 0; flex-direction: column; overflow-y: auto;\n border-right: 1px solid var(--line); background: var(--color-white) }\n.sidebar-head { display: flex; height: 73px; align-items: center; padding: 0 .75rem; border-bottom: 1px solid var(--line) }\n.sidebar-head.stacked { display: block; height: auto; padding: .75rem }\n.back { display: flex; align-items: center; gap: .25rem; margin-bottom: .5rem; font-size: .75rem; line-height: 1rem;\n color: var(--color-gray-500); transition: color .15s }\n.back:hover { color: var(--color-gray-700) }\n.switcher { display: flex; width: 100%; align-items: center; gap: .75rem; border: 1px solid var(--line);\n border-radius: var(--radius-xl); padding: .625rem .75rem; text-align: left; transition: background-color .15s }\n.switcher:hover { background: var(--color-cream-50) }\n.switcher-icon { display: flex; height: 2.25rem; width: 2.25rem; flex-shrink: 0; align-items: center; justify-content: center;\n border-radius: var(--radius-lg); background: var(--color-brand-50); color: var(--color-brand-600) }\n.switcher-text { min-width: 0; flex: 1 }\n.switcher-text strong { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;\n font-size: .875rem; line-height: 1.25rem; font-weight: 600; color: var(--color-gray-900) }\n.switcher-sub { display: flex; align-items: center; gap: .375rem; font-size: .75rem; line-height: 1rem; color: var(--color-gray-500) }\n.dot { height: .375rem; width: .375rem; flex-shrink: 0; border-radius: 9999px; background: var(--color-green-500) }\nnav { flex: 1; padding: .75rem }\nnav section + section { margin-top: 1rem }\nnav h2 { padding: 0 .75rem .25rem; font-size: 11px; line-height: 1rem; font-weight: 600; text-transform: uppercase;\n letter-spacing: .025em; color: var(--color-gray-500) }\n.nav-item { display: flex; align-items: center; gap: .625rem; border-radius: var(--radius-lg); padding: .5rem .75rem;\n font-size: .875rem; line-height: 1.25rem; font-weight: 500; color: var(--color-gray-700); transition: background-color .15s, color .15s }\n.nav-item:hover { background: var(--color-cream-100) }\n.nav-item.on, .nav-item[aria-current=\"page\"] { background: var(--color-brand-50); color: var(--color-brand-600) }\n.nav-item.muted { opacity: .6 }\n.nav-item + .nav-item, .nav-group + .nav-item, .nav-item + .nav-group, .nav-group + .nav-group { margin-top: .25rem }\n.nav-group > .nav-item { justify-content: space-between }\n.nav-group-label { display: flex; align-items: center; gap: .625rem }\n.nav-group svg:last-child { color: var(--color-gray-400) }\n.nav-children { margin: .25rem 0 0 1.75rem; padding-left: .5rem; border-left: 1px solid var(--line) }\n.nav-child { display: block; border-radius: var(--radius-lg); padding: .375rem .75rem; font-size: .875rem; line-height: 1.25rem;\n color: var(--color-gray-600); transition: background-color .15s, color .15s }\n.nav-child + .nav-child { margin-top: .25rem }\n.nav-child:hover { background: var(--color-cream-100) }\n.nav-child[aria-current=\"page\"] { background: var(--color-brand-50); font-weight: 500; color: var(--color-brand-600) }\n.sidebar-foot { border-top: 1px solid var(--line); padding: .75rem }\n.sidebar-foot > * + * { margin-top: .75rem }\n.stamp { display: flex; align-items: center; gap: .5rem; padding: 0 .75rem; font-size: .75rem; line-height: 1rem;\n color: var(--color-gray-500) }\n.stamp svg { color: var(--color-brand-500) }\n.content { display: flex; min-width: 0; flex: 1; flex-direction: column }\n.content > header { display: flex; height: 73px; align-items: center; gap: .75rem; padding: 0 1.5rem;\n border-bottom: 1px solid var(--line) }\nh1 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 1.125rem; line-height: 1.75rem;\n font-weight: 600; color: var(--color-gray-900) }\nmain { flex: 1; padding: 1.5rem }\n.page { width: 100% }\n.page.form { margin: 0 auto; max-width: 64rem }\n.narrow { max-width: 48rem }`\n\n// The page primitives the platform's routes compose, including the shadcn button and input variants\n// they use.\nconst CONTENT = `\n.stack > * + * { margin-top: 1.5rem }\n.rows > * + * { margin-top: 1rem }\n.lede { max-width: 42rem; font-size: .875rem; line-height: 1.25rem; color: var(--color-gray-600) }\n.card { border: 1px solid var(--line); border-radius: var(--radius-xl); background: var(--color-white); padding: 1.5rem }\n.card.dashed { border-style: dashed; border-color: var(--line-dashed); padding: 1rem }\n.card.danger { border-color: var(--color-red-200) }\n.card h2, .section-title { font-size: .875rem; line-height: 1.25rem; font-weight: 600; color: var(--color-gray-900) }\n.hint { margin-top: .25rem; font-size: .875rem; line-height: 1.25rem; color: var(--color-gray-500) }\n.table-card { overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius-xl); background: var(--color-white) }\n.table-scroll { overflow-x: auto }\ntable { width: 100%; font-size: .875rem; line-height: 1.25rem }\nthead tr { text-align: left }\nth { padding: .5rem 1rem .5rem 0; font-weight: 500; color: var(--color-gray-600) }\ntbody tr { border-top: 1px solid var(--line-soft) }\ntd { padding: .5rem 1rem .5rem 0; vertical-align: top; color: var(--color-gray-600) }\n.table-card thead tr { background: var(--color-cream-50) }\n.table-card th, .table-card td { padding: .75rem 1.25rem }\ntd.actions { text-align: right; white-space: nowrap }\ntd.actions form { display: inline-flex; vertical-align: middle }\ntd.actions > * + * { margin-left: .5rem }\n.empty-cell { padding: 2.5rem 1.25rem; text-align: center; color: var(--color-gray-500) }\n.badge { display: inline-block; border-radius: 9999px; background: var(--color-cream-100); padding: .125rem .5rem;\n font-size: .75rem; line-height: 1rem; font-weight: 500; color: var(--color-gray-600) }\n.badge.ok { background: var(--color-green-50); color: var(--color-green-700) }\n.badge.off { background: var(--color-cream-100); color: var(--color-gray-500) }\ncode { font-size: .75rem; line-height: 1rem; color: var(--color-gray-800) }\ncode.dim { color: var(--color-gray-500) }\ncode.sub { display: block; color: var(--color-gray-500) }\ncode.slug { display: block; margin-top: .75rem; overflow-wrap: break-word; border: 1px solid var(--line-dashed);\n border-radius: var(--radius-lg); background: var(--color-cream-50); padding: .5rem .75rem; font-size: .875rem }\n.installed-sites { margin-top: 1rem; border-top: 1px solid var(--line-soft); padding-top: 1rem; font-size: .875rem;\n line-height: 1.25rem }\n.installed-sites li { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .5rem }\n.installed-sites li + li { margin-top: .5rem }\ninput[readonly] { color: var(--color-gray-500) }\n.strong { font-weight: 500; color: var(--color-gray-800) }\na.link { font-weight: 500; color: var(--color-brand-600); transition: color .15s }\na.link:hover { color: var(--color-brand-700) }\nbutton, a.btn { display: inline-flex; flex-shrink: 0; align-items: center; justify-content: center; gap: .5rem; white-space: nowrap;\n height: 2rem; padding: .375rem 1rem; border-radius: var(--radius-md); font-size: .875rem; line-height: 1.25rem;\n font-weight: 500; background: var(--primary); color: var(--primary-foreground); transition: all .15s }\nbutton:hover, a.btn:hover { background: color-mix(in oklab, var(--primary) 90%, transparent) }\nbutton.outline, a.btn.outline { border: 1px solid var(--border); background: var(--background); color: var(--foreground);\n box-shadow: 0 1px 2px 0 rgb(0 0 0 / .05) }\nbutton.outline:hover, a.btn.outline:hover { background: var(--accent); color: var(--accent-foreground) }\nbutton.danger { background: var(--destructive); color: var(--primary-foreground) }\nbutton.danger:hover { background: color-mix(in oklab, var(--destructive) 90%, transparent) }\nbutton.sm, a.btn.sm { height: 1.75rem; gap: .375rem; padding: 0 .75rem }\ninput { height: 2.25rem; width: 100%; min-width: 0; border: 1px solid var(--input); border-radius: var(--radius-md);\n padding: .25rem .75rem; font-size: .875rem; line-height: 1.25rem; box-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);\n transition: color .15s, box-shadow .15s }\ninput:focus-visible { outline: none; border-color: var(--ring); box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent) }\ninput.narrow-field { width: 16rem }\ninput[type=\"checkbox\"] { height: 1rem; width: 1rem; margin-top: .125rem; box-shadow: none; accent-color: var(--color-brand-500) }\nlabel { display: flex; align-items: center; gap: .5rem; font-size: .875rem; line-height: 1; font-weight: 500;\n color: var(--color-gray-900) }\nlabel.check { align-items: flex-start; font-weight: 400; line-height: 1.25rem; color: var(--color-gray-700) }\n.field > * + * { margin-top: .375rem }\n.field-help { display: block; font-size: .75rem; line-height: 1rem; color: var(--color-gray-500) }\n.row { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem }\n.row.wide { gap: 1rem }\n.between { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: .75rem }\n.top { align-items: flex-start }\n.grid-2 { display: grid; gap: 1rem; grid-template-columns: repeat(2, minmax(0, 1fr)) }\n.capability-heading { font-size: .75rem; line-height: 1rem; font-weight: 500; text-transform: uppercase; letter-spacing: .025em;\n color: var(--color-gray-500) }\n.capability-list { margin-top: .25rem; padding-left: 1.25rem; list-style: disc; font-size: .875rem; line-height: 1.25rem;\n color: var(--color-gray-700) }\n.notice { border: 1px solid var(--color-amber-300); border-radius: var(--radius-lg); background: var(--color-amber-50);\n padding: .75rem 1rem; font-size: .875rem; line-height: 1.25rem; color: var(--color-amber-700) }\n.endpoint { border-top: 1px solid var(--line-soft); padding: .75rem 0 }\n.endpoint:first-child { border-top: 0 }\n.endpoint code { display: block; word-break: break-all }\n.endpoint-meta { margin-top: .25rem; display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; font-size: .75rem;\n line-height: 1rem; color: var(--color-gray-500) }\n.meta { font-size: .875rem; line-height: 1.25rem; color: var(--color-gray-600) }\n.dim-sm { font-size: .75rem; line-height: 1rem; color: var(--color-gray-500) }\n.check-label { font-weight: 500 }\n.mt-3 { margin-top: .75rem }\n.mt-4 { margin-top: 1rem }\n.panel { width: 100%; height: 480px; border: 1px solid var(--line); border-radius: var(--radius-xl); background: var(--color-white) }`\n\nexport const CONSOLE_STYLE = `${RESET}${SHELL}${CONTENT}`\n","// Copied from `projects/portal/ui/app/app.css` and the Tailwind palette it compiles against\n// (`tailwindcss/theme.css`). The console renders plain HTML, so the platform's utility classes are\n// written out as the variables they resolve to — one edit in the portal's token block is one edit here.\nconst PLATFORM_TOKENS = `\n --font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, sans-serif,\n 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';\n --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace;\n --radius: 0.625rem;\n --radius-sm: calc(var(--radius) - 4px);\n --radius-md: calc(var(--radius) - 2px);\n --radius-lg: var(--radius);\n --radius-xl: calc(var(--radius) + 4px);\n --background: oklch(1 0 0);\n --foreground: oklch(0.147 0.004 49.25);\n --primary: #f25c2b;\n --primary-foreground: #ffffff;\n --muted-foreground: oklch(0.553 0.013 58.071);\n --accent: oklch(0.97 0.001 106.424);\n --accent-foreground: oklch(0.216 0.006 56.043);\n --destructive: oklch(0.577 0.245 27.325);\n --border: oklch(0.923 0.003 48.717);\n --input: oklch(0.923 0.003 48.717);\n --ring: #f25c2b;\n --color-brand-50: #fff8f0;\n --color-brand-100: #fff1e0;\n --color-brand-200: #ffe0c2;\n --color-brand-300: #ffcda3;\n --color-brand-400: #ffb085;\n --color-brand-500: #f25c2b;\n --color-brand-600: #d94e22;\n --color-brand-700: #bf401a;\n --color-brand-800: #8c2f13;\n --color-brand-900: #5a1f0c;\n --color-cream-50: #fffdf9;\n --color-cream-100: #fff8f0;\n --color-cream-200: #fff1e0;\n --color-cream-300: #f5e6d3;\n --color-cream-400: #e8d5c4;\n --color-cream-500: #d4c0ae;\n --color-white: #fff;\n --color-gray-300: oklch(87.2% 0.01 258.338);\n --color-gray-400: oklch(70.7% 0.022 261.325);\n --color-gray-500: oklch(55.1% 0.027 264.364);\n --color-gray-600: oklch(44.6% 0.03 256.802);\n --color-gray-700: oklch(37.3% 0.034 259.733);\n --color-gray-800: oklch(27.8% 0.033 256.848);\n --color-gray-900: oklch(21% 0.034 264.665);\n --color-green-50: oklch(98.2% 0.018 155.826);\n --color-green-500: oklch(72.3% 0.219 149.579);\n --color-green-600: oklch(62.7% 0.194 149.214);\n --color-green-700: oklch(52.7% 0.154 150.069);\n --color-amber-50: oklch(98.7% 0.022 95.277);\n --color-amber-300: oklch(87.9% 0.169 91.605);\n --color-amber-700: oklch(55.5% 0.163 48.998);\n --color-red-200: oklch(88.5% 0.062 18.334);\n --color-red-500: oklch(63.7% 0.237 25.331);\n --color-red-700: oklch(50.5% 0.213 27.518);\n --line: color-mix(in oklab, var(--color-cream-400) 40%, transparent);\n --line-soft: color-mix(in oklab, var(--color-cream-400) 20%, transparent);\n --line-dashed: color-mix(in oklab, var(--color-cream-400) 60%, transparent);`\n\n// The `.dark` half of the platform's token block, applied with `.theme-developer` exactly as\n// `root.tsx` applies them: the developer area is dark on the platform, so it is dark here too.\nconst DARK_TOKENS = `\n --background: oklch(0.147 0.004 49.25);\n --foreground: oklch(0.985 0.001 106.423);\n --muted-foreground: oklch(0.709 0.01 56.259);\n --accent: oklch(0.268 0.007 34.298);\n --accent-foreground: oklch(0.985 0.001 106.423);\n --destructive: oklch(0.704 0.191 22.216);\n --border: oklch(1 0 0 / 10%);\n --input: oklch(1 0 0 / 15%);`\n\n// Verbatim from the portal's `.theme-developer` block: Tailwind v4 resolves every color utility\n// through these variables, so overriding them re-themes the shared shell with no dark variant.\nconst DEVELOPER_TOKENS = `\n --color-white: #1c1917;\n --color-cream-50: #121110;\n --color-cream-100: #262322;\n --color-cream-200: #302c2a;\n --color-cream-300: #3b3634;\n --color-cream-400: #6d635d;\n --color-cream-500: #7f746d;\n --color-gray-300: #57504c;\n --color-gray-400: #7b736e;\n --color-gray-500: #9a938d;\n --color-gray-600: #bab2ad;\n --color-gray-700: #d7d1cd;\n --color-gray-800: #ece8e6;\n --color-gray-900: #f8f6f5;\n --color-brand-50: #2b1610;\n --color-brand-100: #3a1d15;\n --color-brand-200: #5a2a18;\n --color-brand-300: #7d3a22;\n --color-brand-600: #ff7043;\n --color-brand-700: #ff8a63;\n --color-red-200: #7f1d1d;\n --color-red-500: #f87171;\n --color-green-600: #4ade80;\n --color-amber-50: #2e2210;\n --color-amber-300: #7c5a1d;\n --color-amber-700: #fbbf24;`\n\nexport const CONSOLE_TOKENS = `:root {${PLATFORM_TOKENS}\n}\n.dark {${DARK_TOKENS}\n}\n.theme-developer {${DEVELOPER_TOKENS}\n}`\n\nexport const themeClass = (path: string): string => {\n return path === '/developer' || path.startsWith('/developer/') ? 'dark theme-developer' : ''\n}\n","import type { IconName } from './console-icons'\nimport { icon } from './console-icons'\nimport { CONSOLE_STYLE } from './console-style'\nimport { CONSOLE_TOKENS, themeClass } from './console-theme'\n\ntype NavLink = { href: string; label: string }\n\ntype NavItem = NavLink & { icon: IconName; muted?: boolean; children?: NavLink[] }\n\nexport type NavSection = { label?: string; items: NavItem[] }\n\nexport type FooterLink = NavLink & { icon: IconName; external: boolean }\n\nexport type ShellHeader = { back: NavLink | null; icon: IconName; title: string; subtitle: string; dot: boolean }\n\nexport type ShellInput = {\n title: string\n path: string\n header: ShellHeader\n sections: NavSection[]\n footer: FooterLink[]\n platformVersion: string\n width: 'form' | 'full'\n body: string\n script?: string\n}\n\nexport const RELOAD_PATH = '/reload'\n\n// On every page, not just the panel's: a rebuild swaps the workers under the open tab, so whatever it\n// is showing is a render of the previous build until it reloads.\nconst RELOAD_SCRIPT = `new EventSource(${JSON.stringify(RELOAD_PATH)}).addEventListener('reload', () => { location.reload() })`\n\nexport const escapeHtml = (value: string): string => {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('\"', '"')\n}\n\nconst navChild = (child: NavLink, path: string): string => {\n const current = child.href === path ? ' aria-current=\"page\"' : ''\n return `<a class=\"nav-child\" href=\"${escapeHtml(child.href)}\"${current}>${escapeHtml(child.label)}</a>`\n}\n\nconst navItem = (item: NavItem, path: string): string => {\n const children = item.children ?? []\n const muted = item.muted === true ? ' muted' : ''\n // The platform's NavLink matches by prefix, so an item stays current on the pages below it.\n const open = path === item.href || path.startsWith(`${item.href}/`)\n if (children.length === 0) {\n const current = open ? ' aria-current=\"page\"' : ''\n return `<a class=\"nav-item${muted}\" href=\"${escapeHtml(item.href)}\"${current}>${icon(item.icon, 18)}${escapeHtml(item.label)}</a>`\n }\n\n // The parent highlights its whole area but is never the current page — that belongs to the child.\n return `<div class=\"nav-group\">\n <a class=\"nav-item${open ? ' on' : ''}${muted}\" href=\"${escapeHtml(item.href)}\" aria-expanded=\"${open}\">\n <span class=\"nav-group-label\">${icon(item.icon, 18)}${escapeHtml(item.label)}</span>${icon(open ? 'chevronDown' : 'chevronRight', 16)}\n </a>\n ${\n open\n ? `<div class=\"nav-children\">${children\n .map((child) => {\n return navChild(child, path)\n })\n .join('')}</div>`\n : ''\n }\n</div>`\n}\n\nconst navSection = (section: NavSection, path: string): string => {\n const label = section.label === undefined ? '' : `<h2>${escapeHtml(section.label)}</h2>`\n return `<section>${label}${section.items\n .map((item) => {\n return navItem(item, path)\n })\n .join('')}</section>`\n}\n\nconst sidebarHead = (header: ShellHeader): string => {\n const switcher = `<div class=\"switcher\">\n <span class=\"switcher-icon\">${icon(header.icon, 18)}</span>\n <span class=\"switcher-text\">\n <strong>${escapeHtml(header.title)}</strong>\n <span class=\"switcher-sub\">${header.dot ? '<span class=\"dot\"></span>' : ''}${escapeHtml(header.subtitle)}</span>\n </span>\n </div>`\n\n if (header.back === null) {\n return `<div class=\"sidebar-head\">${switcher}</div>`\n }\n\n return `<div class=\"sidebar-head stacked\">\n <a class=\"back\" href=\"${escapeHtml(header.back.href)}\">${icon('chevronLeft', 14)}${escapeHtml(header.back.label)}</a>\n ${switcher}\n</div>`\n}\n\nconst footerLink = (link: FooterLink): string => {\n const external = link.external ? ' target=\"_blank\" rel=\"noreferrer\"' : ''\n return `<a class=\"nav-item\" href=\"${escapeHtml(link.href)}\"${external}>${icon(link.icon, 18)}${escapeHtml(link.label)}</a>`\n}\n\nexport const consoleShell = (input: ShellInput): string => {\n const theme = themeClass(input.path)\n\n return `<!doctype html>\n<html lang=\"en\"${theme === '' ? '' : ` class=\"${theme}\"`}>\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${escapeHtml(input.title)} — Qinto</title>\n<style>${CONSOLE_TOKENS}${CONSOLE_STYLE}</style>\n</head>\n<body>\n<div class=\"shell\">\n <aside>\n ${sidebarHead(input.header)}\n <nav>${input.sections\n .map((section) => {\n return navSection(section, input.path)\n })\n .join('')}</nav>\n <div class=\"sidebar-foot\">\n ${input.footer.map(footerLink).join('')}\n <div class=\"stamp\">${icon('layers', 16)}local Qinto · platform ${escapeHtml(input.platformVersion)}</div>\n </div>\n </aside>\n <div class=\"content\">\n <header><h1>${escapeHtml(input.title)}</h1></header>\n <main><div class=\"page ${input.width}\">${input.body}</div></main>\n </div>\n</div>\n<script>${RELOAD_SCRIPT}</script>\n${input.script === undefined ? '' : `<script>${input.script}</script>`}\n</body>\n</html>\n`\n}\n","import type { AppManifestVariable } from '@qinto/app-manifest'\n\nimport { isInstallActive, missingRequiredVariables } from '../compose/deployable'\nimport type { DevInstall } from '../state'\nimport type { PageInput } from './console-pages'\nimport { escapeHtml } from './console-shell'\n\nconst fieldHelp = (variable: AppManifestVariable): string => {\n if (variable.helpText === undefined && variable.helpUrl === undefined) {\n return ''\n }\n\n const link =\n variable.helpUrl === undefined\n ? ''\n : ` <a class=\"link\" href=\"${escapeHtml(variable.helpUrl)}\" target=\"_blank\" rel=\"noreferrer\">Learn more</a>`\n return `<span class=\"field-help\">${escapeHtml(variable.helpText ?? '')}${link}</span>`\n}\n\nconst variableField = (variable: AppManifestVariable, install: DevInstall, input: PageInput): string => {\n const name = `var_${variable.name}`\n const id = `${install.appInstallId}-${variable.name}`\n const label = escapeHtml(`${variable.label}${variable.required === true ? ' *' : ''}`)\n\n if (variable.type === 'toggle') {\n return `<label class=\"check\" for=\"${id}\">\n <input id=\"${id}\" type=\"checkbox\" name=\"${name}\"${install.variables[variable.name] === true ? ' checked' : ''}>\n <span><span class=\"check-label\">${label}</span>${fieldHelp(variable)}</span>\n </label>`\n }\n\n if (variable.kind === 'secret') {\n const set = input.secrets[install.appInstallId]?.[variable.name] !== undefined\n return `<div class=\"field\">\n <div class=\"row\"><label for=\"${id}\">${label}</label><span class=\"badge ${set ? 'ok' : 'off'}\">${set ? 'Set' : 'Not set'}</span></div>\n <input id=\"${id}\" name=\"${name}\" type=\"password\" autocomplete=\"off\" placeholder=\"Enter a new value to replace\">\n ${fieldHelp(variable)}\n </div>`\n }\n\n const stored = install.variables[variable.name]\n return `<div class=\"field\">\n <label for=\"${id}\">${label}</label>\n <input id=\"${id}\" name=\"${name}\" type=\"${variable.type === 'password' ? 'password' : 'text'}\" value=\"${escapeHtml(\n typeof stored === 'string' ? stored : ''\n )}\">\n ${fieldHelp(variable)}\n </div>`\n}\n\nconst variablesForm = (input: PageInput, install: DevInstall): string => {\n if (input.manifest.variables.length === 0) {\n return ''\n }\n\n return `<form method=\"post\" action=\"/variables\" class=\"rows mt-4\">\n <input type=\"hidden\" name=\"appInstallId\" value=\"${install.appInstallId}\">\n ${input.manifest.variables\n .map((variable) => {\n return variableField(variable, install, input)\n })\n .join('')}\n <button class=\"sm\">Save variables</button>\n </form>`\n}\n\nconst missingNotice = (input: PageInput, install: DevInstall, active: boolean): string => {\n const missing = new Set(missingRequiredVariables(input.manifest, install, input.secrets))\n if (active || missing.size === 0) {\n return ''\n }\n\n const labels = input.manifest.variables\n .filter((variable) => {\n return missing.has(variable.name)\n })\n .map((variable) => variable.label)\n return `<p class=\"notice mt-3\">Missing required variables: ${escapeHtml(labels.join(', '))}</p>`\n}\n\nexport const installCard = (input: PageInput, install: DevInstall): string => {\n const active = isInstallActive(input.manifest, input.state, install, input.secrets)\n const removable = input.manifest.install.multiple && input.state.installs.length > 1\n\n return `<div class=\"card\">\n <div class=\"between\">\n <div class=\"row\">\n <form method=\"post\" action=\"/install-label\" class=\"row\">\n <input type=\"hidden\" name=\"appInstallId\" value=\"${install.appInstallId}\">\n <input class=\"narrow-field\" name=\"label\" value=\"${escapeHtml(install.label)}\" aria-label=\"Install label\">\n <button class=\"outline sm\">Rename</button>\n </form>\n <span class=\"badge ${active ? 'ok' : 'off'}\">${active ? 'Active' : 'Inactive'}</span>\n </div>\n <div class=\"row\">\n <form method=\"post\" action=\"/install-enabled\">\n <input type=\"hidden\" name=\"appInstallId\" value=\"${install.appInstallId}\">\n <input type=\"hidden\" name=\"enabled\" value=\"${install.enabled ? 'false' : 'true'}\">\n <button class=\"sm${install.enabled ? ' outline' : ''}\">${install.enabled ? 'Disable' : 'Enable'}</button>\n </form>\n ${\n removable\n ? `<form method=\"post\" action=\"/install-remove\">\n <input type=\"hidden\" name=\"appInstallId\" value=\"${install.appInstallId}\">\n <button class=\"danger sm\">Remove</button>\n </form>`\n : ''\n }\n </div>\n </div>\n ${missingNotice(input, install, active)}\n ${variablesForm(input, install)}\n</div>`\n}\n\nexport const addInstallCard = (input: PageInput): string => {\n if (!input.manifest.install.multiple) {\n return ''\n }\n\n return `<div class=\"card dashed\">\n <form method=\"post\" action=\"/install-add\" class=\"row\">\n <input class=\"narrow-field\" name=\"label\" placeholder=\"${escapeHtml(input.manifest.install.labelHint ?? 'Install label')}\"\n aria-label=\"New install label\">\n <button class=\"sm\">Add install</button>\n </form>\n</div>`\n}\n","// Mirrors `portal/ui/app/lib/tail-traces.ts` and `components/trace-dialog.tsx`.\nexport const LOGS_SCRIPT = `\nconst MAX_ROWS = 500\nconst rowsEl = document.getElementById('rows')\nconst statusEl = document.getElementById('status')\nconst dialogEl = document.getElementById('trace')\nconst rows = new Map()\nlet selectedSpan = null\nlet openTrace = null\n\nconst clock = (at) => new Date(at).toISOString().slice(11, 23)\n\nconst duration = (ms) => (ms < 1000 ? ms + 'ms' : (ms / 1000).toFixed(2) + 's')\n\n// Mirrors META_BLOCKS in portal/ui/app/lib/tail-traces.ts; the two consoles must group alike.\nconst META_BLOCKS = [\n { label: 'Init', keys: ['action.type', 'action.event', 'action.id', 'action.user_id', 'action.global_id', 'action.origin'], open: true },\n { label: 'Payload', keys: ['action.payload'], open: true },\n { label: 'Host data', keys: ['qinto.geo'], open: false },\n { label: 'Consent', keys: ['qinto.consent'], open: false },\n { label: 'Full user', keys: ['qinto.user'], open: false }\n]\n\nconst META_KEYS = new Set(META_BLOCKS.flatMap((block) => block.keys))\n\nconst metaSpan = (spans) => spans.filter((span) => span.attrs && span.attrs['qinto.user'] !== undefined).sort((a, b) => a.start - b.start)[0]\n\nconst spanLabel = (span) => {\n const type = span.attrs && span.attrs['action.type']\n if (typeof type !== 'string') { return span.name }\n const event = span.attrs && span.attrs['action.event']\n return typeof event === 'string' ? type + ' - ' + event : type\n}\n\nconst rootSpan = (spans) => {\n const ids = new Set(spans.map((span) => span.spanId))\n return spans.filter((span) => span.parent === undefined || !ids.has(span.parent)).sort((a, b) => a.start - b.start)[0]\n}\n\nconst summary = (row) => {\n const root = rootSpan(row.spans)\n return (root === undefined ? 'trace' : spanLabel(root)) + ' — ' + row.outcome\n}\n\nconst bounds = (spans) => {\n const t0 = Math.min(...spans.map((span) => span.start))\n return { t0, total: Math.max(...spans.map((span) => span.end)) - t0 }\n}\n\nconst forest = (spans) => {\n const nodes = new Map(spans.map((span) => [span.spanId, { span, children: [] }]))\n const roots = []\n for (const node of nodes.values()) {\n const parent = node.span.parent === undefined ? undefined : nodes.get(node.span.parent)\n if (parent === undefined) { roots.push(node) } else { parent.children.push(node) }\n }\n const byStart = (a, b) => a.span.start - b.span.start\n for (const node of nodes.values()) { node.children.sort(byStart) }\n return roots.sort(byStart)\n}\n\nconst flatten = (nodes, depth = 0, out = []) => {\n for (const node of nodes) {\n out.push({ span: node.span, depth })\n flatten(node.children, depth + 1, out)\n }\n return out\n}\n\nconst errored = (row) => row.spans.some((span) => span.error !== undefined)\n\nconst el = (tag, className, text) => {\n const node = document.createElement(tag)\n if (className !== undefined) { node.className = className }\n if (text !== undefined) { node.textContent = text }\n return node\n}\n\nconst renderRows = () => {\n const ordered = [...rows.values()].sort((a, b) => b.at - a.at).slice(0, MAX_ROWS)\n if (ordered.length === 0) {\n rowsEl.replaceChildren(el('li', 'waiting', 'Waiting for traffic on this site…'))\n return\n }\n rowsEl.replaceChildren(\n ...ordered.map((row) => {\n const parts = [summary(row), duration(bounds(row.spans).total)]\n if (row.spans.length > 1) { parts.push(row.spans.length + ' spans') }\n\n const button = el('button', 'trace-row')\n button.appendChild(el('span', 'at', clock(row.at)))\n button.appendChild(el('span', errored(row) ? 'label err' : 'label', parts.join(' · ')))\n for (const event of row.events) {\n button.appendChild(el('span', event.level === 'error' ? 'evt err' : event.level === 'warn' ? 'evt warn' : 'evt', '· ' + event.name))\n }\n button.addEventListener('click', () => { openDialog(row.traceId) })\n\n const item = el('li')\n item.appendChild(button)\n return item\n })\n )\n}\n\nconst kvLine = (key, value) => {\n const line = el('div', 'kv')\n line.appendChild(el('span', 'k', key))\n line.appendChild(el('span', undefined, ': ' + (typeof value === 'string' ? value : JSON.stringify(value))))\n return line\n}\n\nconst metaBlocks = (span, wrap) => {\n for (const block of META_BLOCKS) {\n const present = block.keys.filter((key) => (span.attrs || {})[key] !== undefined)\n if (present.length === 0) { continue }\n const details = el('details', 'meta')\n if (block.open) { details.open = true }\n details.appendChild(el('summary', 'section', block.label))\n for (const key of present) { details.appendChild(kvLine(key, span.attrs[key])) }\n wrap.appendChild(details)\n }\n}\n\nconst fields = (span) => {\n const values = {\n duration: duration(span.end - span.start),\n 'trace.span_id': span.spanId,\n ...(span.parent === undefined ? {} : { 'trace.parent_id': span.parent }),\n 'trace.trace_id': span.traceId,\n ...Object.fromEntries(Object.entries(span.attrs || {}).filter(([key]) => !META_KEYS.has(key)))\n }\n const wrap = el('div')\n const title = el('p', 'span-name', span.name)\n if (span.error !== undefined) { title.appendChild(el('span', 'err', ' — ' + span.error)) }\n wrap.appendChild(title)\n metaBlocks(span, wrap)\n wrap.appendChild(el('p', 'section', 'Fields'))\n for (const [key, value] of Object.entries(values)) {\n wrap.appendChild(kvLine(key, value))\n }\n if (Array.isArray(span.events) && span.events.length > 0) {\n wrap.appendChild(el('p', 'section', 'Span events'))\n for (const event of span.events) {\n const level = event.level === 'error' ? 'err' : event.level === 'warn' ? 'warn' : ''\n wrap.appendChild(el('p', 'evt ' + level, event.name + ' +' + duration(Math.max(0, event.t - span.start))))\n for (const [key, value] of Object.entries(event.attrs || {})) {\n wrap.appendChild(kvLine(key, value))\n }\n }\n }\n return wrap\n}\n\nconst renderDialog = () => {\n const row = rows.get(openTrace)\n if (row === undefined) { return }\n const scale = bounds(row.spans)\n const timeline = flatten(forest(row.spans))\n const selected = row.spans.find((span) => span.spanId === selectedSpan) || metaSpan(row.spans) || timeline[0].span\n\n const list = el('ul', 'timeline')\n for (const { span, depth } of timeline) {\n const left = scale.total === 0 ? 0 : ((span.start - scale.t0) / scale.total) * 100\n const width = scale.total === 0 ? 100 : ((span.end - span.start) / scale.total) * 100\n const button = el('button', 'span-row' + (span.spanId === selected.spanId ? ' on' : ''))\n const name = el('span', span.error === undefined ? 'span-label' : 'span-label err', span.name)\n name.style.paddingLeft = depth * 12 + 'px'\n button.appendChild(name)\n const track = el('span', 'track')\n const bar = el('span', span.error === undefined ? 'bar' : 'bar err')\n bar.style.left = left + '%'\n bar.style.width = width + '%'\n track.appendChild(bar)\n button.appendChild(track)\n button.appendChild(el('span', 'dur', duration(span.end - span.start)))\n button.addEventListener('click', () => { selectedSpan = span.spanId; renderDialog() })\n const item = el('li')\n item.appendChild(button)\n list.appendChild(item)\n }\n\n const head = el('div', 'dialog-head')\n head.appendChild(el('strong', undefined, summary(row) + ' · ' + duration(scale.total)))\n const close = el('button', 'outline sm', 'Close')\n close.addEventListener('click', () => { openTrace = null; dialogEl.close() })\n head.appendChild(close)\n\n const scaleRow = el('div', 'scale')\n scaleRow.appendChild(el('span', undefined, '0ms'))\n scaleRow.appendChild(el('span', undefined, duration(scale.total)))\n\n const left = el('div', 'timeline-pane')\n left.appendChild(scaleRow)\n left.appendChild(list)\n const right = el('div', 'fields-pane')\n right.appendChild(fields(selected))\n const body = el('div', 'dialog-body')\n body.appendChild(left)\n body.appendChild(right)\n\n dialogEl.replaceChildren(head, body)\n}\n\nconst openDialog = (traceId) => {\n openTrace = traceId\n selectedSpan = null\n renderDialog()\n dialogEl.showModal()\n}\n\nconst merge = (record) => {\n for (const span of record.spans) {\n const row = rows.get(span.traceId) || { traceId: span.traceId, at: Date.now(), spans: [], events: [], outcome: 'ok' }\n if (!row.spans.some((known) => known.spanId === span.spanId)) { row.spans.push(span) }\n for (const event of span.events || []) {\n if (event.level !== undefined) { row.events.push(event) }\n }\n if (span.error !== undefined) { row.outcome = 'error' }\n rows.set(span.traceId, row)\n }\n renderRows()\n if (openTrace !== null) { renderDialog() }\n}\n\nrenderRows()\n\nconst stream = new EventSource('/site/logs/stream')\nstream.addEventListener('open', () => { statusEl.textContent = 'Live'; statusEl.className = 'status ok' })\nstream.addEventListener('error', () => { statusEl.textContent = 'Reconnecting…'; statusEl.className = 'status off' })\nstream.addEventListener('spans', (event) => { merge(JSON.parse(event.data)) })\n`\n\n// The classes `tail-console.tsx`, `tail-trace-row.tsx` and `trace-dialog.tsx` resolve to, written out\n// for a page with no Tailwind build.\nexport const LOGS_STYLE = `\n<style>\n .status { font-size: .875rem; line-height: 1.25rem; color: var(--color-brand-700) }\n .status.ok { color: var(--color-green-700) } .status.off { color: var(--color-amber-700) }\n .console { border: 1px solid var(--color-cream-300); border-radius: var(--radius-lg); background: var(--color-white);\n font-family: var(--font-mono); font-size: .75rem; line-height: 1rem; max-height: 62vh; overflow: auto }\n .console li { border-bottom: 1px solid var(--color-cream-200) }\n .console li:last-child { border-bottom: 0 }\n .waiting { padding: 1rem; color: var(--color-brand-700) }\n .trace-row { display: block; width: 100%; height: auto; padding: .5rem; border-radius: 0; text-align: left;\n background: transparent; color: inherit; font-size: inherit; font-weight: 400 }\n .trace-row:hover { background: var(--color-cream-100) }\n .at { margin-right: .5rem; color: var(--color-brand-500) }\n .label { color: var(--color-brand-900) } .label.err, .err { color: var(--color-red-700) } .warn { color: var(--color-amber-700) }\n .evt { display: block; padding-left: 1rem; color: var(--color-brand-700) }\n /* The reset zeroes every margin, which is also the one the user agent centres a modal dialog with. */\n dialog { margin: auto; width: 72rem; max-width: calc(100% - 2rem); height: 80vh; overflow: hidden; padding: 1.5rem;\n border: 1px solid var(--line); border-radius: var(--radius-xl); background: var(--color-white); color: var(--color-brand-900);\n font-family: var(--font-mono); font-size: .75rem; line-height: 1rem; box-shadow: 0 10px 15px -3px rgb(0 0 0 / .1) }\n dialog[open] { display: flex; flex-direction: column }\n dialog::backdrop { background: rgb(0 0 0 / .5) }\n .dialog-head { display: flex; flex-shrink: 0; align-items: center; justify-content: space-between; gap: 1rem; padding-bottom: 1rem }\n .dialog-head strong { font-size: .875rem; line-height: 1.25rem; font-weight: 600 }\n .dialog-body { display: flex; min-height: 0; flex: 1; gap: 1rem }\n .timeline-pane { min-width: 0; flex: 1; overflow-y: auto; overflow-wrap: anywhere }\n .fields-pane { width: 24rem; flex-shrink: 0; overflow-y: auto; overflow-wrap: anywhere;\n border-left: 1px solid var(--color-cream-200); padding-left: 1rem }\n .scale { display: flex; justify-content: space-between; padding-bottom: .25rem; color: var(--color-brand-500) }\n .span-row { display: flex; width: 100%; height: auto; align-items: center; gap: .5rem; padding: .25rem; border-radius: .25rem;\n text-align: left; background: transparent; color: inherit; font-size: inherit; font-weight: 400 }\n /* A chromeless button still needs its own hover, or the shell's fills the row with solid brand orange. */\n .span-row:hover { background: var(--color-cream-100) }\n .span-row.on, .span-row.on:hover { background: var(--color-cream-100) }\n .span-label { width: 40%; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--color-brand-900) }\n .track { position: relative; height: .75rem; flex-grow: 1 }\n .bar { position: absolute; top: 0; height: .75rem; min-width: 2px; border-radius: var(--radius-sm); background: var(--color-brand-500) }\n .bar.err { background: var(--color-red-700) }\n .dur { flex-shrink: 0; color: var(--color-brand-500) }\n .span-name { font-weight: 600; margin-bottom: .5rem; color: var(--color-brand-900) }\n .section { margin: .5rem 0 .25rem; text-transform: uppercase; color: var(--color-brand-500) }\n .kv { color: var(--color-brand-700) } .kv .k { color: var(--color-brand-900) }\n .meta > summary { cursor: pointer; list-style: revert }\n</style>`\n","import type { AppManifest } from '@qinto/app-manifest'\n\nimport type { DevState } from '../state'\nimport type { FooterLink, NavSection, ShellHeader } from './console-shell'\n\nexport const DEVELOPER_APPS = '/developer/apps'\nexport const SITE_APPS = '/site/apps'\nexport const SITE_LOGS = '/site/logs'\nexport const SITE_SETTINGS_GENERAL = '/site/settings/general'\n\nexport type ConsoleChrome = { header: ShellHeader; sections: NavSection[]; footer: FooterLink[] }\n\nconst DOCS: FooterLink = { href: 'https://docs.qinto.io', label: 'Docs', icon: 'bookOpen', external: true }\n\nexport const consoleChrome = (input: { manifest: AppManifest; state: DevState; path: string }): ConsoleChrome => {\n if (input.path.startsWith('/developer')) {\n return {\n header: {\n back: { href: SITE_APPS, label: 'Back to site' },\n icon: 'building2',\n title: 'Local organization',\n subtitle: 'Organization',\n dot: false\n },\n sections: [{ items: [{ href: DEVELOPER_APPS, label: 'Apps', icon: 'blocks' }] }],\n footer: [DOCS]\n }\n }\n\n const sections: NavSection[] = [\n {\n label: 'Domain',\n items: [\n { href: SITE_LOGS, label: 'Analytics', icon: 'activity', children: [{ href: SITE_LOGS, label: 'Real time' }] },\n { href: SITE_APPS, label: 'Apps', icon: 'blocks' },\n {\n href: SITE_SETTINGS_GENERAL,\n label: 'Settings',\n icon: 'settings',\n children: [{ href: SITE_SETTINGS_GENERAL, label: 'General' }]\n }\n ]\n }\n ]\n\n // Mirrors `withDomainAppsSection`: the platform lists only the installed apps that ship a panel.\n if (input.state.installed && input.manifest.ui !== undefined) {\n sections.push({\n label: 'Apps',\n items: [\n {\n href: `${SITE_APPS}/${input.manifest.slug}/ui`,\n label: input.manifest.name,\n icon: 'blocks',\n muted: !input.state.enabled\n }\n ]\n })\n }\n\n return {\n header: { back: null, icon: 'globe', title: input.state.siteDomain, subtitle: 'Active', dot: true },\n sections,\n footer: [DOCS, { href: DEVELOPER_APPS, label: 'Developer', icon: 'code', external: false }]\n }\n}\n","import type { AppManifest } from '@qinto/app-manifest'\n\nimport type { InstallSecrets } from '../compose/deployable'\nimport { isInstallActive, missingRequiredVariables } from '../compose/deployable'\nimport type { InertResource } from '../compose/resources'\nimport type { DevAppUi } from '../stack'\nimport type { DevAppValues, DevState } from '../state'\nimport { LOGS_STYLE } from './console-logs'\nimport { DEVELOPER_APPS, SITE_APPS } from './console-nav'\nimport { escapeHtml } from './console-shell'\n\nexport type PageInput = {\n manifest: AppManifest\n state: DevState\n secrets: InstallSecrets\n appValues: DevAppValues\n inert: InertResource[]\n siteOrigin: string\n demoOrigin: string\n appUi: DevAppUi | null\n}\n\nconst FLOW_LABELS: Record<AppManifest['flows'][number], string> = {\n transform: 'Transform',\n destination: 'Destination'\n}\n\nexport const flowBadges = (manifest: AppManifest): string => {\n return manifest.flows\n .map((flow) => {\n return `<span class=\"badge\">${FLOW_LABELS[flow]}</span>`\n })\n .join(' ')\n}\n\nexport const activeInstalls = (input: PageInput): number => {\n return input.state.installs.filter((install) => {\n return isInstallActive(input.manifest, input.state, install, input.secrets)\n }).length\n}\n\nexport const developerAppsPage = (input: PageInput): string => {\n return `<div class=\"stack\">\n <p class=\"lede\">Apps run on the sites that install them. This organization builds one app locally — the project you are running.\n Its version is rebuilt from source, so there is nothing to publish here.</p>\n <div class=\"table-card\"><div class=\"table-scroll\">\n <table>\n <thead><tr><th>Name</th><th>Slug</th><th>Description</th><th>Flows</th><th>Version</th><th></th></tr></thead>\n <tbody>\n <tr>\n <td class=\"strong\">${escapeHtml(input.manifest.name)}</td>\n <td><code>${escapeHtml(input.manifest.slug)}</code></td>\n <td>${escapeHtml(input.manifest.description ?? '—')}</td>\n <td><div class=\"row\">${flowBadges(input.manifest)}</div></td>\n <td><code>0.0.0-dev</code></td>\n <td class=\"actions\"><a class=\"btn outline sm\" href=\"${DEVELOPER_APPS}/${escapeHtml(input.manifest.slug)}\">View</a></td>\n </tr>\n </tbody>\n </table>\n </div></div>\n</div>`\n}\n\nexport const siteAppsPage = (input: PageInput): string => {\n const name = escapeHtml(input.manifest.name)\n const row = input.state.installed\n ? `<tr>\n <td>\n <a class=\"link\" href=\"${SITE_APPS}/${escapeHtml(input.manifest.slug)}\">${name}</a>\n <code class=\"sub\">${escapeHtml(input.manifest.slug)}</code>\n </td>\n <td><div class=\"row\">${flowBadges(input.manifest)}</div></td>\n <td><code>0.0.0-dev</code></td>\n <td>${activeInstalls(input)} of ${input.state.installs.length} active</td>\n <td class=\"actions\">\n <form method=\"post\" action=\"/app-enabled\">\n <input type=\"hidden\" name=\"enabled\" value=\"${input.state.enabled ? 'false' : 'true'}\">\n <button class=\"sm${input.state.enabled ? ' outline' : ''}\">${input.state.enabled ? 'Disable' : 'Enable'}</button>\n </form>\n <a class=\"btn outline sm\" href=\"${SITE_APPS}/${escapeHtml(input.manifest.slug)}\">View</a>\n </td>\n </tr>`\n : `<tr>\n <td>\n <span class=\"strong\">${name}</span>\n <code class=\"sub\">${escapeHtml(input.manifest.slug)}</code>\n </td>\n <td><div class=\"row\">${flowBadges(input.manifest)}</div></td>\n <td><code>0.0.0-dev</code></td>\n <td>Not installed</td>\n <td class=\"actions\"><form method=\"post\" action=\"/install\"><button class=\"sm\">Install</button></form></td>\n </tr>`\n\n return `<div class=\"stack\">\n <p class=\"lede\">Apps run on this site's edge worker. On the platform they arrive with <code>qinto app publish</code>; here the app is\n built from source on every change.</p>\n <div class=\"table-card\"><div class=\"table-scroll\">\n <table>\n <thead><tr><th>App</th><th>Flows</th><th>Version</th><th>Installs</th><th></th></tr></thead>\n <tbody>${row}</tbody>\n </table>\n </div></div>\n</div>`\n}\n\n// An inactive install still traces the request, so the console looks healthy while the app is never\n// called — the one state where \"waiting for traffic\" is the wrong thing to read.\nconst inactiveNotice = (input: PageInput): string => {\n if (activeInstalls(input) > 0) {\n return ''\n }\n\n const appHref = `${SITE_APPS}/${escapeHtml(input.manifest.slug)}`\n if (!input.state.installed) {\n return `<p class=\"notice\">${escapeHtml(input.manifest.name)} is not installed on this site, so no trace will reach it.\n <a class=\"link\" href=\"${SITE_APPS}\">Install it</a> to see its hooks run.</p>`\n }\n\n const missing = input.state.installs.flatMap((install) => {\n return missingRequiredVariables(input.manifest, install, input.secrets)\n })\n if (missing.length === 0) {\n return `<p class=\"notice\">Every install of ${escapeHtml(input.manifest.name)} is disabled, so no trace will reach it.\n <a class=\"link\" href=\"${appHref}\">Enable one</a> to see its hooks run.</p>`\n }\n\n return `<p class=\"notice\">No install of ${escapeHtml(input.manifest.name)} is active, so its hooks never run and no app span appears\n below. Set its required variables — ${escapeHtml([...new Set(missing)].join(', '))} — on\n <a class=\"link\" href=\"${appHref}\">the app's page</a>.</p>`\n}\n\nexport const siteLogsPage = (input: PageInput): string => {\n return `${LOGS_STYLE}\n<div class=\"stack\">\n <p class=\"lede\">Every request this site worker serves, as OpenTelemetry traces — the same spans the platform streams from a deployed\n site. Your app's own <code>ctx.observability</code> lines arrive as span events. Fire something from the\n <a class=\"link\" href=\"${escapeHtml(input.demoOrigin)}\">demo site</a>.</p>\n ${inactiveNotice(input)}\n <p class=\"status\" id=\"status\">Connecting…</p>\n <ul class=\"console\" id=\"rows\"></ul>\n</div>\n<dialog id=\"trace\"></dialog>`\n}\n","import type { AppManifest } from '@qinto/app-manifest'\n\nimport { addInstallCard, installCard } from './console-install-card'\nimport type { PageInput } from './console-pages'\nimport { flowBadges } from './console-pages'\nimport { escapeHtml } from './console-shell'\n\n// The platform's own wording for what an app may call and read (`app-about-card.tsx`).\nconst API_CAPABILITY_LABELS: Record<AppManifest['capabilities']['api'][number], string> = {\n track: 'Send events on your behalf',\n identify: 'Identify visitors',\n alias: 'Link visitor identities',\n consentWrite: 'Update visitor consent',\n consentRead: 'Read visitor consent',\n propertiesRead: 'Read event properties',\n sessionRead: 'Read session data'\n}\n\nconst DATA_CAPABILITY_LABELS: Record<AppManifest['capabilities']['data'][number], string> = {\n pii: 'Personal information (name, email, phone)',\n customProperties: 'Custom event properties',\n consentState: 'Consent state',\n geo: 'Approximate location',\n eventContext: 'Page URL and referrer',\n sharedContext: 'Context shared with the other apps on this site'\n}\n\nconst AUTH_LABELS: Record<AppManifest['endpoints'][number]['auth'], string> = { public: 'No token', token: 'Edge token' }\n\nconst MODE_LABELS: Record<AppManifest['endpoints'][number]['mode'], string> = { webhook: 'Webhook', api: 'Request/response' }\n\nconst headerCard = (input: PageInput): string => {\n const description = input.manifest.description === undefined ? '' : `<p class=\"hint\">${escapeHtml(input.manifest.description)}</p>`\n\n return `<section class=\"card\">\n <div class=\"between top\">\n <div>\n <h2>${escapeHtml(input.manifest.name)}</h2>\n <code class=\"sub\">${escapeHtml(input.manifest.slug)}</code>\n ${description}\n </div>\n <form method=\"post\" action=\"/app-enabled\">\n <input type=\"hidden\" name=\"enabled\" value=\"${input.state.enabled ? 'false' : 'true'}\">\n <button class=\"sm${input.state.enabled ? ' outline' : ''}\">${input.state.enabled ? 'Disable app' : 'Enable app'}</button>\n </form>\n </div>\n <div class=\"row mt-3\">${flowBadges(input.manifest)}<span class=\"badge\">Consent: ${escapeHtml(input.manifest.consent.category)}</span></div>\n <div class=\"row mt-3 meta\">\n <span>Version <code>0.0.0-dev</code></span><span class=\"dim-sm\">rebuilt from source on every change</span>\n </div>\n</section>`\n}\n\nconst capabilityList = (heading: string, items: string[]): string => {\n const body =\n items.length === 0\n ? '<p class=\"hint\">None</p>'\n : `<ul class=\"capability-list\">${items\n .map((item) => {\n return `<li>${escapeHtml(item)}</li>`\n })\n .join('')}</ul>`\n return `<div><h3 class=\"capability-heading\">${heading}</h3>${body}</div>`\n}\n\nconst aboutCard = (input: PageInput): string => {\n return `<section class=\"card\">\n <h2>About this app</h2>\n <div class=\"row wide mt-3\">\n <a class=\"link\" href=\"${escapeHtml(input.manifest.legal.termsUrl)}\" target=\"_blank\" rel=\"noreferrer\">Terms of service</a>\n <a class=\"link\" href=\"${escapeHtml(input.manifest.legal.privacyUrl)}\" target=\"_blank\" rel=\"noreferrer\">Privacy policy</a>\n </div>\n <div class=\"grid-2 mt-4\">\n ${capabilityList(\n 'API access',\n input.manifest.capabilities.api.map((capability) => {\n return API_CAPABILITY_LABELS[capability]\n })\n )}\n ${capabilityList(\n 'Data access',\n input.manifest.capabilities.data.map((capability) => {\n return DATA_CAPABILITY_LABELS[capability]\n })\n )}\n </div>\n</section>`\n}\n\nconst endpointsCard = (input: PageInput): string => {\n if (input.manifest.endpoints.length === 0) {\n return ''\n }\n\n return `<section class=\"card\">\n <h2>Endpoints</h2>\n <p class=\"hint\">Give these URLs to the service that calls them — one URL serves every install.</p>\n <ul class=\"mt-4\">${input.manifest.endpoints\n .map((endpoint) => {\n return `<li class=\"endpoint\">\n <code>${escapeHtml(`${input.siteOrigin}/app/${input.manifest.slug}${endpoint.path}`)}</code>\n <div class=\"endpoint-meta\">\n <span class=\"badge\">${endpoint.methods.join(', ')}</span><span>${AUTH_LABELS[endpoint.auth]}</span><span>${\n MODE_LABELS[endpoint.mode]\n }</span>\n </div>\n </li>`\n })\n .join('')}</ul>\n</section>`\n}\n\n// The platform shows the same list, minus the button: a schedule runs at most once an hour, so\n// waiting for the real window is useless as a dev loop.\nconst schedulesCard = (input: PageInput): string => {\n const schedules = input.manifest.server.schedules ?? []\n if (schedules.length === 0) {\n return ''\n }\n\n return `<section class=\"card\">\n <h2>Schedules</h2>\n <p class=\"hint\">Runs on a timer, with no visitor. Each run reaches every enabled install.</p>\n <ul class=\"mt-4\">${schedules\n .map((schedule) => {\n return `<li class=\"endpoint\">\n <div class=\"endpoint-meta\">\n <code>${escapeHtml(schedule.id)}</code><span class=\"badge\">${escapeHtml(schedule.cron)}</span>\n </div>\n ${schedule.description === undefined ? '' : `<p class=\"hint\">${escapeHtml(schedule.description)}</p>`}\n <form method=\"post\" action=\"/schedule-run\">\n <input type=\"hidden\" name=\"scheduleId\" value=\"${escapeHtml(schedule.id)}\">\n <button>Run now</button>\n </form>\n </li>`\n })\n .join('')}</ul>\n</section>`\n}\n\n// No platform counterpart: a Hyperdrive origin names the deployed database, so the local loop asks\n// for a URL of its own rather than deriving one that would point at production.\nconst hyperdriveCard = (input: PageInput): string => {\n const declared = input.manifest.resources.filter((resource) => {\n return resource.type === 'hyperdrive'\n })\n if (declared.length === 0) {\n return ''\n }\n\n return `<section class=\"card\">\n <h2>Hyperdrive</h2>\n <p class=\"hint\">The origin in the manifest is the deployed database, so it is never used here. Give each one a local URL.</p>\n <div class=\"rows mt-4\">${declared\n .map((resource) => {\n return `<form method=\"post\" action=\"/hyperdrive\" class=\"field\">\n <input type=\"hidden\" name=\"identifier\" value=\"${escapeHtml(resource.identifier)}\">\n <label for=\"hyperdrive-${escapeHtml(resource.identifier)}\">${escapeHtml(resource.binding)}</label>\n <input id=\"hyperdrive-${escapeHtml(resource.identifier)}\" name=\"url\" value=\"${escapeHtml(\n input.state.hyperdrive[resource.identifier] ?? ''\n )}\" placeholder=\"postgres://user:password@localhost:5432/dev\">\n <button class=\"outline sm\">Save</button>\n </form>`\n })\n .join('')}</div>\n</section>`\n}\n\nconst inertCard = (input: PageInput): string => {\n if (input.inert.length === 0) {\n return ''\n }\n\n return `<section class=\"card\">\n <h2>Not available locally</h2>\n <div class=\"rows mt-3\">${input.inert\n .map((entry) => {\n return `<p class=\"notice\"><code>${escapeHtml(entry.binding)}</code> — ${escapeHtml(entry.reason)}</p>`\n })\n .join('')}</div>\n</section>`\n}\n\nconst uninstallCard = (input: PageInput): string => {\n return `<section class=\"card danger\">\n <h2>Uninstall this app</h2>\n <p class=\"hint\">Removes ${escapeHtml(input.manifest.name)} and all of its installs from ${escapeHtml(input.state.siteDomain)}.</p>\n <div class=\"mt-4\"><form method=\"post\" action=\"/uninstall\"><button class=\"danger\">Uninstall app</button></form></div>\n</section>`\n}\n\nexport const siteAppPage = (input: PageInput): string => {\n return `<div class=\"stack narrow\">\n${headerCard(input)}\n${aboutCard(input)}\n${endpointsCard(input)}\n${schedulesCard(input)}\n${hyperdriveCard(input)}\n${inertCard(input)}\n<section class=\"rows\">\n <h2 class=\"section-title\">Installs</h2>\n ${input.state.installs\n .map((install) => {\n return installCard(input, install)\n })\n .join('')}\n ${addInstallCard(input)}\n</section>\n${uninstallCard(input)}\n</div>`\n}\n","import type { AppManifestAppVariable } from '@qinto/app-manifest'\n\nimport { DEV_VERSION } from '../stack'\nimport { SITE_APPS } from './console-nav'\nimport type { PageInput } from './console-pages'\nimport { escapeHtml } from './console-shell'\n\nconst headerCard = (input: PageInput): string => {\n const description = input.manifest.description === undefined ? '' : `<p class=\"hint\">${escapeHtml(input.manifest.description)}</p>`\n\n return `<section class=\"card\">\n <h2>${escapeHtml(input.manifest.name)}</h2>\n ${description}\n <code class=\"slug\">${escapeHtml(input.manifest.slug)}</code>\n <p class=\"dim-sm mt-3\">The slug is permanent and identifies the app to the Qinto CLI.</p>\n</section>`\n}\n\nconst installCard = (input: PageInput): string => {\n const site = escapeHtml(input.state.siteDomain)\n if (!input.state.installed) {\n return `<section class=\"card\">\n <h2>Install on a site</h2>\n <p class=\"hint\">Installs version <code>${DEV_VERSION}</code> on <strong>${site}</strong>, the site this local Qinto seeds.</p>\n <div class=\"mt-4\"><form method=\"post\" action=\"/install\"><button>Install ${DEV_VERSION}</button></form></div>\n</section>`\n }\n\n return `<section class=\"card\">\n <h2>Install on a site</h2>\n <p class=\"hint\">Installs version <code>${DEV_VERSION}</code> on <strong>${site}</strong>, the site this local Qinto seeds.</p>\n <ul class=\"installed-sites\">\n <li>\n <span class=\"strong\">${site}</span>\n <span class=\"row\"><code class=\"dim\">${DEV_VERSION}</code><a class=\"link\" href=\"${SITE_APPS}/${escapeHtml(\n input.manifest.slug\n )}\">Manage</a></span>\n </li>\n </ul>\n</section>`\n}\n\nconst appVariableHelp = (variable: AppManifestAppVariable): string => {\n if (variable.helpText === undefined && variable.helpUrl === undefined) {\n return ''\n }\n\n const link =\n variable.helpUrl === undefined\n ? ''\n : ` <a class=\"link\" href=\"${escapeHtml(variable.helpUrl)}\" target=\"_blank\" rel=\"noreferrer\">Learn more</a>`\n return `<span class=\"field-help\">${escapeHtml(variable.helpText ?? '')}${link}</span>`\n}\n\nconst appVariableField = (variable: AppManifestAppVariable, input: PageInput): string => {\n const id = `appvar-${variable.name}`\n const name = `appvar_${variable.name}`\n const label = escapeHtml(`${variable.label}${variable.required === true ? ' *' : ''}`)\n const stored = input.appValues[variable.name]\n\n if (variable.kind === 'secret') {\n const set = stored !== undefined\n return `<div class=\"field\">\n <div class=\"row\"><label for=\"${id}\">${label}</label><span class=\"badge ${set ? 'ok' : 'off'}\">${set ? 'Set' : 'Not set'}</span></div>\n <input id=\"${id}\" name=\"${name}\" type=\"password\" autocomplete=\"off\" placeholder=\"Enter a new value to replace\">\n ${appVariableHelp(variable)}\n </div>`\n }\n\n return `<div class=\"field\">\n <label for=\"${id}\">${label}</label>\n <input id=\"${id}\" name=\"${name}\" type=\"${variable.type === 'password' ? 'password' : 'text'}\" value=\"${escapeHtml(stored ?? '')}\">\n ${appVariableHelp(variable)}\n </div>`\n}\n\nconst appVariablesCard = (input: PageInput): string => {\n if (input.manifest.appVariables.length === 0) {\n return ''\n }\n\n return `<section class=\"card\">\n <h2>App variables</h2>\n <p class=\"hint\">These values are the same for every site that installs this app. On the platform, changing one redeploys every site running it — about five minutes.</p>\n <form method=\"post\" action=\"/app-variables\" class=\"rows mt-4\">\n ${input.manifest.appVariables.map((variable) => appVariableField(variable, input)).join('\\n ')}\n <div><button>Save app variables</button></div>\n </form>\n</section>`\n}\n\n// The platform stores the name and description on the app row, so its form writes them. Here they are\n// read out of `qinto.app.jsonc`, which the watcher rebuilds from — writing them back would be undone\n// by the developer's next save.\nconst detailsCard = (input: PageInput): string => {\n return `<section class=\"card\">\n <h2>App details</h2>\n <div class=\"rows mt-4\">\n <div class=\"field\">\n <label for=\"app-name\">Name</label>\n <input id=\"app-name\" value=\"${escapeHtml(input.manifest.name)}\" readonly>\n </div>\n <div class=\"field\">\n <label for=\"app-description\">Description</label>\n <input id=\"app-description\" value=\"${escapeHtml(input.manifest.description ?? '')}\" placeholder=\"What the app does\" readonly>\n </div>\n <p class=\"dim-sm\">Both come from <code>qinto.app.jsonc</code>. Edit the file and this page reloads with the new values.</p>\n </div>\n</section>`\n}\n\nconst versionsCard = (): string => {\n return `<section class=\"card\">\n <h2>Versions</h2>\n <table class=\"mt-4\">\n <thead><tr><th>Version</th><th>Status</th><th>Built</th></tr></thead>\n <tbody>\n <tr>\n <td><code>${DEV_VERSION}</code></td>\n <td><span class=\"badge ok\">Ready</span></td>\n <td>from source, on every change</td>\n </tr>\n </tbody>\n </table>\n <p class=\"dim-sm mt-3\">On the platform <code>qinto app publish</code> allocates a real version; the local loop only ever runs this one.</p>\n</section>`\n}\n\nexport const developerAppPage = (input: PageInput): string => {\n return `<div class=\"stack narrow\">\n${headerCard(input)}\n${installCard(input)}\n${appVariablesCard(input)}\n${detailsCard(input)}\n${versionsCard()}\n</div>`\n}\n","import type { PageInput } from './console-pages'\n\nconst consentCard = (input: PageInput): string => {\n return `<section class=\"card\">\n <h2>Consent</h2>\n <p class=\"hint\">Do you ask visitors for consent on this site, with a cookie banner or a consent platform? If you do, turn consent mode on\n and Qinto sends each event only to the apps whose category that visitor allowed. Leave it off and every connected app receives every\n event.</p>\n <form method=\"post\" action=\"/consent\" class=\"mt-4\">\n <label class=\"check\" for=\"consentEnabled\">\n <input type=\"checkbox\" id=\"consentEnabled\" name=\"consentEnabled\"${input.state.consentEnabled ? ' checked' : ''}>\n <span>\n <span class=\"check-label\">Enable consent mode</span>\n <span class=\"field-help\">Only forward data to apps in the categories a visitor allowed.</span>\n </span>\n </label>\n <div class=\"mt-4\"><button class=\"sm\">Save</button></div>\n </form>\n</section>`\n}\n\nexport const siteSettingsGeneralPage = (input: PageInput): string => {\n return `<div class=\"stack\">\n <p class=\"lede\">Settings the platform stores against the domain. They ride the site worker's bindings, so saving one recomposes the\n local workerd stack the same way a redeploy carries them to the edge.</p>\n ${consentCard(input)}\n</div>`\n}\n","import type { DevAppUi } from '../stack'\nimport type { DevInstall, DevState } from '../state'\nimport { SITE_APPS } from './console-nav'\nimport type { PageInput } from './console-pages'\nimport { escapeHtml } from './console-shell'\n\nexport const opensPanel = (state: DevState, install: DevInstall): boolean => {\n // Deliberately looser than the platform, which frames a panel only for a fully active install: the\n // panel is the thing under development here, so a required variable nobody has filled in yet must\n // not hide it — what the panel does about one is the app's own business, inside the frame.\n return state.enabled && install.enabled\n}\n\nexport const panelFrame = (appUi: DevAppUi, install: DevInstall, title: string): string => {\n return `<iframe class=\"panel\" data-install=\"${install.appInstallId}\" src=\"${escapeHtml(appUi.iframeUrl)}\"\n title=\"${escapeHtml(title)}\" sandbox=\"allow-scripts allow-same-origin allow-forms\"></iframe>`\n}\n\nexport const panelPage = (input: PageInput, appUi: DevAppUi): string => {\n const name = escapeHtml(input.manifest.name)\n const appPath = `${SITE_APPS}/${escapeHtml(input.manifest.slug)}`\n const open = input.state.installs.filter((install) => {\n return opensPanel(input.state, install)\n })\n\n const panels =\n open.length === 0\n ? `<div class=\"card\"><p class=\"hint\">${\n input.state.enabled\n ? `Every install of ${name} is disabled, so there is no panel to open.`\n : `${name} is disabled on this site, so there is no panel to open.`\n } Enable one on the <a class=\"link\" href=\"${appPath}\">app's own page</a>.</p></div>`\n : open\n .map((install) => {\n // One panel needs no heading — the page is the app. Several do, or the developer cannot\n // tell which install each frame was opened for.\n const heading = open.length === 1 ? '' : `<h2 class=\"section-title\">${escapeHtml(install.label)}</h2>`\n return `<section class=\"rows\">${heading}\n ${panelFrame(appUi, install, `${input.manifest.name} — ${install.label}`)}\n </section>`\n })\n .join('')\n\n return `<div class=\"stack\">\n <p class=\"lede\">Served from <code>${escapeHtml(appUi.origin)}</code> — a different origin to this console, so the panel's\n <code>postMessage</code> checks are the ones a deployed panel makes.</p>\n ${panels}\n</div>`\n}\n\n// The parent half of the handshake, matching the platform's `AppUiFrame`: reply to `qinto:ready` with\n// the context and a token, mint a fresh one on `qinto:token`, and follow `qinto:resize`. Both origin\n// and source are checked, which is the whole reason the panel is served from its own port here.\nexport const PANEL_SCRIPT = (input: { iframeOrigin: string; tokenPath: string }): string => {\n return `\nconst ORIGIN = ${JSON.stringify(input.iframeOrigin)}\nconst TOKEN_PATH = ${JSON.stringify(input.tokenPath)}\nconst frames = [...document.querySelectorAll('iframe.panel')]\n\nconst send = async (frame) => {\n const response = await fetch(TOKEN_PATH + '?appInstallId=' + encodeURIComponent(frame.dataset.install), {\n headers: { accept: 'application/json' }\n })\n if (!response.ok) { return }\n const { context, token } = await response.json()\n frame.contentWindow.postMessage({ type: 'qinto:init', context, token }, ORIGIN)\n}\n\nwindow.addEventListener('message', (event) => {\n if (event.origin !== ORIGIN) { return }\n const frame = frames.find((candidate) => candidate.contentWindow !== null && candidate.contentWindow === event.source)\n if (frame === undefined) { return }\n\n const message = event.data\n if (message === null || typeof message !== 'object') { return }\n\n if (message.type === 'qinto:ready' || message.type === 'qinto:token') { void send(frame); return }\n if (message.type === 'qinto:resize' && typeof message.height === 'number') {\n frame.style.height = Math.max(120, Math.min(4000, Math.round(message.height))) + 'px'\n }\n})\n`\n}\n","import type { IncomingMessage, Server, ServerResponse } from 'node:http'\nimport { createServer } from 'node:http'\nimport type { AddressInfo } from 'node:net'\n\nimport { appUiWritePath } from '@qinto/app-envelope'\nimport { mintAppUiToken } from '@qinto/app-ui-token'\n\nimport type { DevStack } from '../stack'\nimport { DEV_VERSION } from '../stack'\nimport type { DevInstall } from '../state'\nimport { applyDevUiWrite } from './app-ui-write'\nimport { applyConsoleAction } from './console-actions'\nimport { siteAppPage } from './console-app-page'\nimport { developerAppPage } from './console-developer-app'\nimport { LOGS_SCRIPT } from './console-logs'\nimport { consoleChrome, DEVELOPER_APPS, SITE_APPS, SITE_LOGS, SITE_SETTINGS_GENERAL } from './console-nav'\nimport type { PageInput } from './console-pages'\nimport { developerAppsPage, siteAppsPage, siteLogsPage } from './console-pages'\nimport { siteSettingsGeneralPage } from './console-settings-page'\nimport { consoleShell, RELOAD_PATH } from './console-shell'\nimport { opensPanel, PANEL_SCRIPT, panelPage } from './console-ui-panel'\n\n// The console has one viewer and no auth; the platform's own token carries whoever is signed in.\nconst DEV_USER_ID = 'dev-user'\n\nexport type ConsoleServerInput = {\n host: string\n port: number\n stack: DevStack\n demoOrigin: () => string\n}\n\nexport type ConsoleServer = {\n origin: () => string\n reload: () => void\n stop: () => Promise<void>\n}\n\nconst MAX_BODY_BYTES = 64 * 1024\n\nconst listening = (server: Server, host: string, port: number): Promise<void> => {\n return new Promise((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n resolve()\n })\n })\n}\n\nconst readRawBody = async (request: IncomingMessage): Promise<string> => {\n const chunks: Buffer[] = []\n let size = 0\n for await (const chunk of request) {\n size += (chunk as Buffer).length\n if (size > MAX_BODY_BYTES) {\n throw new Error('The submitted form is too large.')\n }\n\n chunks.push(chunk as Buffer)\n }\n\n return Buffer.concat(chunks).toString('utf8')\n}\n\nconst readForm = async (request: IncomingMessage): Promise<Record<string, string>> => {\n return Object.fromEntries(new URLSearchParams(await readRawBody(request)))\n}\n\nconst LOOPBACK = new Set(['127.0.0.1', 'localhost', '[::1]'])\n\n// Binding to loopback stops nothing on its own: a page on any site can point its own hostname at\n// 127.0.0.1, and the browser then sends that hostname as Host with no Origin at all on a GET — so the\n// console's state and its live trace stream would be readable cross-site. Only the loopback spellings\n// a developer can type are answered, which is what makes the rebound hostname fail.\nconst loopbackAddress = (value: string | undefined, port: number): boolean => {\n const parsed = value === undefined ? null : URL.parse(value.includes('//') ? value : `http://${value}`)\n return parsed !== null && LOOPBACK.has(parsed.hostname) && parsed.port === String(port)\n}\n\ntype Page = { title: string; width: 'form' | 'full'; body: (input: PageInput) => string; script?: string }\n\nconst PAGES: Record<string, Page> = {\n [DEVELOPER_APPS]: { title: 'Apps', width: 'full', body: developerAppsPage },\n [SITE_APPS]: { title: 'Apps', width: 'full', body: siteAppsPage },\n [SITE_LOGS]: { title: 'Real time', width: 'full', body: siteLogsPage, script: LOGS_SCRIPT },\n [SITE_SETTINGS_GENERAL]: { title: 'Settings', width: 'form', body: siteSettingsGeneralPage }\n}\n\nconst installById = (context: PageInput, appInstallId: string): DevInstall | null => {\n const install = context.state.installs.find((candidate) => candidate.appInstallId === appInstallId)\n return install === undefined || !opensPanel(context.state, install) ? null : install\n}\n\n// `AppUiContext` and `AppUiInstall` from `@blotout/qinto-sdk-app/ui`, which the dev package does not\n// depend on: the panel a developer builds against that contract has to receive exactly this here.\ntype PanelInstall = {\n id: string\n label: string\n enabled: boolean\n variables: Record<string, string | boolean>\n}\n\ntype PanelContext = {\n teamId: string\n domainId: string\n siteOrigin: string\n appSlug: string\n appVersion: string\n appInstallId: string\n installs: PanelInstall[]\n theme: string\n}\n\n// Every live install, not only the one the panel was opened for: the platform sends them all so a\n// panel can render the configuration of an app the site installed more than once. Nothing about a\n// secret goes with them — `DevInstall.variables` holds the plain values and the secrets file, which\n// this never reads, holds the rest.\nconst panelInstalls = (context: PageInput): PanelInstall[] => {\n return context.state.installs.map((install) => {\n return { id: install.appInstallId, label: install.label, enabled: install.enabled, variables: install.variables }\n })\n}\n\nconst mintPanelSession = async (\n stack: DevStack,\n context: PageInput,\n appInstallId: string\n): Promise<{ context: PanelContext; token: string } | null> => {\n const install = installById(context, appInstallId)\n if (!context.state.installed || install === null || stack.appUi === null) {\n return null\n }\n\n const token = await mintAppUiToken({\n kid: stack.keys.appUiKeyId,\n key: stack.keys.appUiKey,\n now: new Date(),\n slug: context.manifest.slug,\n userId: DEV_USER_ID,\n domainId: context.state.domainId,\n appId: context.state.appId,\n appInstallId: install.appInstallId,\n appVersionId: DEV_VERSION,\n access: 'write'\n })\n\n return {\n token,\n context: {\n teamId: context.state.teamId,\n domainId: context.state.domainId,\n siteOrigin: stack.origin,\n appSlug: context.manifest.slug,\n appVersion: DEV_VERSION,\n appInstallId: install.appInstallId,\n installs: panelInstalls(context),\n theme: 'light'\n }\n }\n}\n\nconst pageFor = (path: string, installedPath: string, context: PageInput, tokenPath: string): Page | undefined => {\n if (path === `${DEVELOPER_APPS}/${context.manifest.slug}`) {\n return { title: 'App details', width: 'form', body: developerAppPage }\n }\n\n if (path === installedPath && context.state.installed) {\n return { title: 'App details', width: 'form', body: siteAppPage }\n }\n\n // The panel is reached from the Apps menu and nowhere else; an app with no `ui` block has no such\n // page at all.\n const appUi = context.appUi\n if (path === `${installedPath}/ui` && context.state.installed && appUi !== null) {\n return {\n title: context.manifest.name,\n width: 'full',\n body: (input) => {\n return panelPage(input, appUi)\n },\n script: PANEL_SCRIPT({ iframeOrigin: appUi.origin, tokenPath })\n }\n }\n\n return PAGES[path]\n}\n\nexport const startConsoleServer = async (input: ConsoleServerInput): Promise<ConsoleServer> => {\n let bound = input.port\n const origin = (): string => {\n return `http://${input.host}:${bound}`\n }\n\n const pageInput = (): PageInput => {\n return {\n manifest: input.stack.manifest(),\n state: input.stack.state(),\n secrets: input.stack.secrets(),\n appValues: input.stack.appValues(),\n inert: input.stack.inert(),\n appUi: input.stack.appUi,\n siteOrigin: input.stack.origin,\n demoOrigin: input.demoOrigin()\n }\n }\n\n const appPath = (): string => {\n return `${SITE_APPS}/${input.stack.manifest().slug}`\n }\n\n const render = (path: string): string | null => {\n const context = pageInput()\n const page = pageFor(path, appPath(), context, `${appPath()}/token`)\n if (page === undefined) {\n return null\n }\n\n return consoleShell({\n title: page.title,\n path,\n width: page.width,\n platformVersion: input.stack.platformVersion,\n ...consoleChrome({ manifest: context.manifest, state: context.state, path }),\n body: page.body(context),\n ...('script' in page && page.script !== undefined ? { script: page.script } : {})\n })\n }\n\n // An open stream is an unfinished response, and `server.close()` waits for every one of them — so\n // without this Ctrl-C hangs for as long as a console page is open in a tab.\n const streams = new Set<ServerResponse>()\n\n const stream = (response: ServerResponse, subscribe: (response: ServerResponse) => () => void): void => {\n response.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' })\n // Opens the stream at once, so the page reports itself live before any traffic arrives.\n response.write(': connected\\n\\n')\n streams.add(response)\n const unsubscribe = subscribe(response)\n response.on('close', () => {\n streams.delete(response)\n unsubscribe()\n })\n }\n\n const reloadStreams = new Set<ServerResponse>()\n\n const get = async (path: string, query: URLSearchParams, response: ServerResponse): Promise<void> => {\n if (path === '/') {\n response.writeHead(303, { location: SITE_APPS }).end()\n return\n }\n\n if (path === `${SITE_LOGS}/stream`) {\n stream(response, (open) => {\n return input.stack.logs.subscribe((entry) => {\n if (entry.spans !== undefined) {\n open.write(`event: spans\\ndata: ${JSON.stringify(entry.spans)}\\n\\n`)\n }\n })\n })\n return\n }\n\n if (path === RELOAD_PATH) {\n stream(response, (open) => {\n reloadStreams.add(open)\n return () => {\n reloadStreams.delete(open)\n }\n })\n return\n }\n\n if (path === `${appPath()}/token`) {\n const session = await mintPanelSession(input.stack, pageInput(), query.get('appInstallId') ?? '')\n if (session === null) {\n response.writeHead(409, { 'content-type': 'text/plain' }).end('no active install to open the panel for')\n return\n }\n\n response.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' }).end(JSON.stringify(session))\n return\n }\n\n const page = render(path)\n if (page === null) {\n response.writeHead(404, { 'content-type': 'text/plain' }).end('not found')\n return\n }\n\n response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })\n response.end(page)\n }\n\n const submit = async (request: IncomingMessage): Promise<string> => {\n const fields = await readForm(request)\n // `url` is optional only because IncomingMessage is shared with client responses.\n const action = (request.url as string).slice(1)\n // Running a schedule acts on the live worker instead of changing state, so it never reaches the\n // reducer.\n if (action === 'schedule-run') {\n await input.stack.runSchedule(fields['scheduleId'] ?? '')\n\n return action\n }\n\n const next = applyConsoleAction({\n action,\n fields,\n manifest: input.stack.manifest(),\n state: input.stack.state(),\n secrets: input.stack.secrets(),\n appValues: input.stack.appValues()\n })\n\n await input.stack.apply(next)\n\n return action\n }\n\n // Back to where the form lives: a domain setting belongs to the settings page, an app-scope value\n // to the developer page, and everything else to the app's own page once it is installed.\n const afterSubmit = (action: string): string => {\n if (action === 'consent') {\n return SITE_SETTINGS_GENERAL\n }\n\n if (action === 'app-variables') {\n return `${DEVELOPER_APPS}/${input.stack.manifest().slug}`\n }\n\n return input.stack.state().installed ? appPath() : SITE_APPS\n }\n\n const handlePanelWrite = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {\n const authorization = request.headers.authorization\n const raw = await readRawBody(request)\n let body: unknown\n try {\n body = JSON.parse(raw)\n } catch {\n body = null\n }\n\n const result = await applyDevUiWrite({\n ticket: authorization?.startsWith('Bearer ') === true ? authorization.slice('Bearer '.length) : null,\n body,\n slug: input.stack.manifest().slug,\n appUiKeyId: input.stack.keys.appUiKeyId,\n appUiKey: input.stack.keys.appUiKey,\n manifest: input.stack.manifest(),\n state: input.stack.state(),\n secrets: input.stack.secrets()\n })\n if (!result.ok) {\n const { status, ...payload } = result\n response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(payload))\n return\n }\n\n await input.stack.apply({ state: result.state, secrets: result.secrets, appValues: input.stack.appValues() })\n response.writeHead(202, { 'content-type': 'application/json' }).end(JSON.stringify({ accepted: true }))\n }\n\n const handle = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {\n if (!loopbackAddress(request.headers.host, bound)) {\n response.writeHead(403, { 'content-type': 'text/plain' }).end('this console answers loopback only')\n return\n }\n\n const url = new URL(request.url as string, origin())\n if (request.method === 'GET') {\n await get(url.pathname, url.searchParams, response)\n return\n }\n\n if (request.method !== 'POST') {\n response.writeHead(405, { allow: 'GET, POST' }).end()\n return\n }\n\n // Before the Origin check and before submit(): the caller is the app worker, not the console's\n // own page, so it carries no Origin and posts JSON rather than a form.\n if (url.pathname === appUiWritePath(input.stack.state().domainId, input.stack.manifest().slug)) {\n await handlePanelWrite(request, response)\n return\n }\n\n // A form post always carries Origin, so an absent one is not the console's own page.\n if (!loopbackAddress(request.headers.origin, bound)) {\n response.writeHead(403, { 'content-type': 'text/plain' }).end('cross-origin form posts are refused')\n return\n }\n\n response.writeHead(303, { location: afterSubmit(await submit(request)) }).end()\n }\n\n const server = createServer((request, response) => {\n void handle(request, response).catch((error: unknown) => {\n response.writeHead(500, { 'content-type': 'text/plain' }).end(error instanceof Error ? error.message : String(error))\n })\n })\n\n await listening(server, input.host, input.port)\n // A listening TCP server always reports an AddressInfo, and reading it back is what makes port 0 usable.\n bound = (server.address() as AddressInfo).port\n\n return {\n origin,\n reload: () => {\n for (const open of reloadStreams) {\n open.write('event: reload\\ndata: {}\\n\\n')\n }\n },\n stop: () => {\n return new Promise((resolve) => {\n for (const open of streams) {\n open.end()\n }\n\n server.close(() => {\n resolve()\n })\n })\n }\n }\n}\n","import { icon } from './console-icons'\nimport { CONSOLE_TOKENS } from './console-theme'\n\nexport type DemoPageInput = { siteOrigin: string; appName: string; slug: string; consentCategory: string }\n\nconst BRACELET = {\n id: '123123123',\n quantity: 1,\n value: 10.5,\n title: 'Summer Fun',\n category: 'bracelets',\n image: 'https://mysite.com/product/fun-main.jpg',\n url: 'https://mysite.com/summer-fun'\n}\nconst SHORTS = {\n id: '4423434343',\n quantity: 2,\n value: 5,\n title: 'Summer Shorts',\n category: 'shorts',\n image: 'https://mysite.com/product/shorts-main.jpg',\n url: 'https://mysite.com/summer-shorts'\n}\nconst CART = [BRACELET, SHORTS]\nconst CHECKOUT_URL = 'http://www.example.com/path/to/checkout'\n\n// Payload for payload what docs/standard-events.md documents; the two are read together and must not drift.\nexport const STANDARD_EVENTS: Record<string, Record<string, unknown>> = {\n PageView: {},\n ViewContent: { currency: 'USD', value: 10.5, contents: [BRACELET] },\n AddToCart: { currency: 'USD', value: 10.5, checkoutUrl: CHECKOUT_URL, contents: [BRACELET] },\n RemoveFromCart: { currency: 'USD', value: 10.5, checkoutUrl: CHECKOUT_URL, contents: [BRACELET] },\n InitiateCheckout: { currency: 'USD', value: 20.5, checkoutUrl: CHECKOUT_URL, contents: CART },\n AddShippingInfo: { currency: 'USD', value: 20.5, contents: CART },\n AddPaymentInfo: { currency: 'USD', value: 20.5, contents: CART },\n Purchase: {\n currency: 'USD',\n value: 20.5,\n orderId: '190315',\n discounts: [\n { code: 'OFF20', value: '20', type: 'PERCENTAGE' },\n { code: 'BONUS150', value: '150', type: 'FLAT' }\n ],\n contents: CART\n },\n Subscribe: { sourceId: 'Email', currency: 'USD', value: 49.99 },\n Search: { currency: 'USD', value: 10.5, search: 'summer', contents: [BRACELET] },\n Lead: { category: 'offers', name: 'Special Offer', currency: 'USD', value: 49.99 }\n}\n\n// The platform's primitives, spelled out as the variables they resolve to — the same reason\n// `console-style.ts` spells them out: this page is plain HTML, with no Tailwind to compile against.\nconst DEMO_STYLE = `\n*, ::before, ::after { box-sizing: border-box; border: 0 solid; margin: 0; padding: 0 }\nhtml { font-family: var(--font-sans); line-height: 1.5; -webkit-text-size-adjust: 100%; color-scheme: light }\nh1, h2 { font-size: inherit; font-weight: inherit }\ncode, pre { font-family: var(--font-mono); font-size: 1em }\nbutton, input, textarea { font: inherit; color: inherit; background: transparent; letter-spacing: inherit }\nbutton:not(:disabled) { cursor: pointer }\n::placeholder { color: var(--muted-foreground) }\n\nbody { background: var(--color-cream-50); color: var(--color-gray-900) }\nheader { display: flex; align-items: center; gap: .75rem; min-height: 73px; padding: .75rem 1.5rem;\n border-bottom: 1px solid var(--line); background: var(--color-white) }\n.mark { display: flex; height: 2.25rem; width: 2.25rem; flex-shrink: 0; align-items: center; justify-content: center;\n border-radius: var(--radius-lg); background: var(--color-brand-50); color: var(--color-brand-600) }\n.titles { min-width: 0; flex: 1 }\nh1 { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 1.125rem; line-height: 1.75rem;\n font-weight: 600; color: var(--color-gray-900) }\n.status { display: flex; align-items: center; gap: .375rem; font-size: .75rem; line-height: 1rem; color: var(--color-gray-500) }\n.dot { height: .375rem; width: .375rem; flex-shrink: 0; border-radius: 9999px; background: var(--color-gray-400) }\n.dot.on { background: var(--color-green-500) }\n.dot.off { background: var(--color-red-500) }\n.head-meta { display: flex; flex-shrink: 0; flex-wrap: wrap; align-items: center; justify-content: flex-end; gap: .5rem }\n.badge { border-radius: 9999px; background: var(--color-cream-100); padding: .125rem .5rem; font-size: .75rem;\n line-height: 1rem; font-weight: 500; color: var(--color-gray-600) }\n.head-meta code { font-size: .75rem; line-height: 1rem; color: var(--color-gray-500) }\n\nmain { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); align-items: start; gap: 1.5rem;\n margin: 0 auto; max-width: 80rem; padding: 1.5rem }\n.column > * + * { margin-top: 1.5rem }\nsection { border: 1px solid var(--line); border-radius: var(--radius-xl); background: var(--color-white); padding: 1.5rem }\nh2 { font-size: .875rem; line-height: 1.25rem; font-weight: 600; color: var(--color-gray-900) }\n.note { margin-top: .25rem; font-size: .875rem; line-height: 1.25rem; color: var(--color-gray-500) }\n.note code { color: var(--color-gray-700) }\n\n.actions { display: flex; flex-wrap: wrap; gap: .5rem; margin-top: 1rem }\nbutton { display: inline-flex; flex-shrink: 0; align-items: center; justify-content: center; white-space: nowrap;\n height: 2rem; padding: .375rem 1rem; border-radius: var(--radius-md); font-size: .875rem; line-height: 1.25rem;\n font-weight: 500; background: var(--primary); color: var(--primary-foreground); transition: all .15s }\nbutton:hover { background: color-mix(in oklab, var(--primary) 90%, transparent) }\nbutton.outline { border: 1px solid var(--border); background: var(--background); color: var(--foreground);\n box-shadow: 0 1px 2px 0 rgb(0 0 0 / .05) }\nbutton.outline:hover { background: var(--accent); color: var(--accent-foreground) }\n\n.fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 1rem; margin-top: 1rem }\n.field { margin-top: 1rem }\nlabel { display: block; font-size: .875rem; line-height: 1; font-weight: 500; color: var(--color-gray-900) }\ninput, textarea { display: block; width: 100%; margin-top: .375rem; border: 1px solid var(--input);\n border-radius: var(--radius-md); padding: .375rem .75rem; font-size: .875rem; line-height: 1.5rem;\n box-shadow: 0 1px 2px 0 rgb(0 0 0 / .05); transition: color .15s, box-shadow .15s }\ninput:focus-visible, textarea:focus-visible { outline: none; border-color: var(--ring);\n box-shadow: 0 0 0 3px color-mix(in oklab, var(--ring) 50%, transparent) }\ntextarea { font-family: var(--font-mono); font-size: .8125rem; min-height: 4.5rem; resize: vertical }\n\n.rows { margin-top: 1rem }\n.row { display: flex; align-items: baseline; gap: .75rem; border-top: 1px solid var(--line-soft); padding: .5rem 0;\n font-size: .875rem; line-height: 1.25rem; color: var(--color-gray-700) }\n.row:first-child { border-top: 0; padding-top: 0 }\n.k { min-width: 5rem; flex-shrink: 0; font-size: .75rem; line-height: 1rem; color: var(--color-gray-500) }\n.v { min-width: 0; word-break: break-word }\npre { margin-top: 1rem; max-height: 22rem; overflow: auto; border: 1px solid var(--line-dashed);\n border-radius: var(--radius-lg); background: var(--color-cream-50); padding: .75rem 1rem; font-size: .75rem;\n line-height: 1.5; color: var(--color-gray-700); white-space: pre-wrap; word-break: break-word }\n\n@media (max-width: 60rem) {\n header { flex-wrap: wrap }\n main, .fields { grid-template-columns: minmax(0, 1fr) }\n}`\n\n// The customer's page, cut down to what an app developer needs: fire each action the tag exposes,\n// feed it real identifiers and PII, watch the app's browser half activate, and see what came back.\n// It loads q.js from the local site worker exactly as a real site does, so the whole browser path is\n// the released one.\nexport const demoPage = (input: DemoPageInput): string => {\n return `<!doctype html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>${input.appName} — demo site</title>\n<style>${CONSOLE_TOKENS}${DEMO_STYLE}</style>\n</head>\n<body>\n<header>\n <span class=\"mark\">${icon('globe', 18)}</span>\n <div class=\"titles\">\n <h1>${input.appName} — demo site</h1>\n <p class=\"status\"><span class=\"dot\" id=\"status-dot\"></span><span id=\"status\">loading q.js</span></p>\n </div>\n <div class=\"head-meta\">\n <span class=\"badge\">consent · ${input.consentCategory}</span>\n <code>${input.siteOrigin}</code>\n </div>\n</header>\n<main>\n <div class=\"column\">\n <section>\n <h2>Session</h2>\n <div class=\"actions\">\n <button class=\"outline\" data-act=\"session\">Get session</button>\n <button class=\"outline\" data-act=\"alias\">Alias</button>\n </div>\n </section>\n <section>\n <h2>Identity</h2>\n <p class=\"note\">\n <code>email</code> and <code>phone</code> are validated and become ID-graph identifiers; the rest of these are PII traits.\n An app sees them only if its manifest declares the <code>pii</code> data capability.\n </p>\n <div class=\"fields\">\n <label>email <input id=\"t-email\" value=\"dev@example.com\"></label>\n <label>phone <input id=\"t-phone\" value=\"+14155550123\"></label>\n <label>firstName <input id=\"t-first\" value=\"Dev\"></label>\n <label>lastName <input id=\"t-last\" value=\"Tester\"></label>\n <label>city <input id=\"t-city\" value=\"San Francisco\"></label>\n <label>country <input id=\"t-country\" value=\"US\"></label>\n </div>\n <div class=\"actions\">\n <button data-act=\"identify\">Identify</button>\n <button class=\"outline\" data-act=\"identify-invalid\">Invalid email (dropped)</button>\n <button class=\"outline\" data-act=\"identify-unset\">Unset email</button>\n </div>\n </section>\n <section>\n <h2>Custom properties</h2>\n <p class=\"note\">Anything that is not a known PII key lands in custom properties, behind the <code>customProperties</code> capability.</p>\n <div class=\"field\"><textarea id=\"t-custom\" aria-label=\"Custom traits\">{ \"plan\": \"pro\", \"seats\": 12 }</textarea></div>\n <div class=\"actions\"><button data-act=\"identify-custom\">Identify with these</button></div>\n </section>\n <section>\n <h2>Consent</h2>\n <div class=\"actions\">\n <button data-act=\"grant\">Grant ${input.consentCategory}</button>\n <button class=\"outline\" data-act=\"deny\">Deny ${input.consentCategory}</button>\n <button class=\"outline\" data-act=\"getConsent\">Read consent back</button>\n </div>\n </section>\n <section>\n <h2>Events</h2>\n <p class=\"note\">\n A standard event loads its documented payload below — edit it, then <code>Track it</code> sends what you see.\n All of them reach your hooks; only <code>Purchase</code> carries the <code>value</code> and <code>orderId</code>\n that also record it as a conversion. See <code>docs/standard-events.md</code>.\n </p>\n <div class=\"actions\">\n${Object.keys(STANDARD_EVENTS)\n .map((event) => {\n return ` <button class=\"outline\" data-std=\"${event}\">${event}</button>`\n })\n .join('\\n')}\n </div>\n <div class=\"field\"><label>Event name <input id=\"event-name\" value=\"PageView\"></label></div>\n <div class=\"field\"><label>Properties <textarea id=\"event-props\">{}</textarea></label></div>\n <div class=\"actions\"><button data-act=\"custom\">Track it</button></div>\n </section>\n </div>\n <div class=\"column\">\n <section>\n <h2>App browser code</h2>\n <div class=\"rows\" id=\"apps\"><div class=\"row\"><span class=\"k\">waiting</span><span class=\"v\">for the tag to load</span></div></div>\n </section>\n <section>\n <h2>Log</h2>\n <pre id=\"log\"></pre>\n </section>\n </div>\n</main>\n<script>\n(() => {\n const SITE = ${JSON.stringify(input.siteOrigin)}\n const SLUG = ${JSON.stringify(input.slug)}\n const CATEGORY = ${JSON.stringify(input.consentCategory)}\n const STANDARD_EVENTS = ${JSON.stringify(STANDARD_EVENTS)}\n const logEl = document.getElementById('log')\n const appsEl = document.getElementById('apps')\n const statusEl = document.getElementById('status')\n const dotEl = document.getElementById('status-dot')\n\n const log = (label, detail) => {\n const at = new Date().toISOString().slice(11, 23)\n logEl.textContent = at + ' ' + label + (detail === undefined ? '' : ' ' + JSON.stringify(detail)) + '\\\\n' + logEl.textContent\n }\n\n const status = (text, state) => {\n statusEl.textContent = text\n dotEl.className = state === undefined ? 'dot' : 'dot ' + state\n }\n\n const row = (key, value) => {\n const el = document.createElement('div')\n el.className = 'row'\n el.innerHTML = '<span class=\"k\"></span><span class=\"v\"></span>'\n el.children[0].textContent = key\n el.children[1].textContent = value\n return el\n }\n\n // The buffering half of the snippet a customer pastes — keep it byte-equivalent to PROXY_STUB in\n // services/src/domains/snippet.ts. Two details are load-bearing: '_q: 1' is what marks the global\n // as ours, without which q.js's prelude reports a collision and never attaches config; and 'then',\n // 'ready' and 'config' must fall through to the buffer, or the tag reads a queueing function where\n // it expects them and skips its own boot.\n const buffer = { _q: 1, q: [] }\n window.qinto = new Proxy(buffer, {\n get: (_target, name) => {\n if (typeof name !== 'string' || ['then', 'ready', 'config'].includes(name) || name in buffer) {\n return buffer[name]\n }\n\n buffer[name] = (...args) => {\n const queued = new Promise((resolve, reject) => { buffer.q.push([name, args, resolve, reject]) })\n queued.catch(() => {})\n return queued\n }\n\n return buffer[name]\n }\n })\n\n const call = async (method, ...args) => {\n try {\n log(method + ' →', args.length === 1 ? args[0] : args)\n const result = await window.qinto[method](...args)\n log(method + ' ✓', result)\n } catch (error) {\n log(method + ' ✗', String(error && error.message ? error.message : error))\n }\n }\n\n const value = (id) => document.getElementById(id).value.trim()\n\n const json = (id) => {\n try {\n return JSON.parse(document.getElementById(id).value)\n } catch {\n log('that box is not valid JSON')\n return null\n }\n }\n\n const traits = () => {\n const all = {\n email: value('t-email'),\n phone: value('t-phone'),\n firstName: value('t-first'),\n lastName: value('t-last'),\n city: value('t-city'),\n country: value('t-country')\n }\n return Object.fromEntries(Object.entries(all).filter(([, trait]) => trait !== ''))\n }\n\n const ACTIONS = {\n session: () => call('getSession'),\n alias: () => call('alias', 'crm-' + Date.now()),\n identify: () => call('identify', traits()),\n // A malformed email is dropped rather than stored, so no identifier is minted for it.\n 'identify-invalid': () => call('identify', { email: 'not-an-email' }),\n // null unsets a trait, which is how a visitor's stored PII is cleared.\n 'identify-unset': () => call('identify', { email: null }),\n 'identify-custom': () => {\n const custom = json('t-custom')\n if (custom !== null) { call('identify', custom) }\n },\n grant: () => call('consent', { categories: { [CATEGORY]: true } }),\n deny: () => call('consent', { categories: { [CATEGORY]: false } }),\n getConsent: () => call('getConsent'),\n custom: () => {\n const props = json('event-props')\n if (props === null) { return }\n\n // eventId is an option in Qinto rather than a property, so the box can still mirror the\n // documented payload: whatever it carries is lifted into the options argument here.\n const { eventId, ...properties } = props\n const options = eventId === undefined ? [] : [{ eventId }]\n call('track', value('event-name'), properties, ...options)\n }\n }\n\n for (const button of document.querySelectorAll('button[data-act]')) {\n button.addEventListener('click', () => { ACTIONS[button.dataset.act]() })\n }\n\n const standardButtons = [...document.querySelectorAll('button[data-std]')]\n const loadStandard = (event) => {\n document.getElementById('event-name').value = event\n document.getElementById('event-props').value = JSON.stringify(STANDARD_EVENTS[event], null, 2)\n for (const button of standardButtons) {\n button.className = button.dataset.std === event ? '' : 'outline'\n }\n }\n\n for (const button of standardButtons) {\n button.addEventListener('click', () => { loadStandard(button.dataset.std) })\n }\n\n loadStandard('PageView')\n\n const renderApps = () => {\n const registered = (window.qinto._apps || []).map((entry) => entry[0])\n const installs = (window.qinto._appInstalls || {})[SLUG] || []\n appsEl.replaceChildren(\n row('bundled', registered.length === 0 ? 'no app code in q.js yet' : registered.join(', ')),\n row('installs', installs.length === 0 ? 'none active' : installs.map((i) => i.label + ' (#' + i.ord + ')').join(', '))\n )\n for (const install of installs) {\n appsEl.appendChild(row('#' + install.ord, JSON.stringify(install.variables)))\n }\n }\n\n const script = document.createElement('script')\n // The worker serves q.js with a five-minute cache; installing an app or changing a browser\n // variable rewrites it, so the dev page must never be handed the previous one.\n script.src = SITE + '/q.js?dev=' + Date.now()\n script.async = true\n script.addEventListener('error', () => {\n status('q.js failed to load', 'off')\n log('q.js failed to load from ' + SITE)\n })\n document.head.appendChild(script)\n\n // A tag that never attaches is otherwise silent: q.js loads, nothing else happens, and no action\n // ever reaches the worker — so nothing appears in the real-time logs and there is no error to find.\n let waited = 0\n const waitForTag = setInterval(() => {\n if (typeof window.qinto.ready?.then !== 'function') {\n waited += 100\n if (waited === 8000) {\n status('the tag never attached', 'off')\n log('q.js loaded but the tag never attached — nothing you click here will reach the worker.')\n log('This page may be older than the code you are editing. Restart qinto app dev.')\n }\n\n return\n }\n\n clearInterval(waitForTag)\n log('q.js loaded from ' + SITE)\n window.qinto.ready.then(\n () => {\n status('tag connected', 'on')\n log('connected')\n },\n (error) => {\n status('connect failed', 'off')\n log('connect failed', String(error))\n }\n )\n renderApps()\n }, 100)\n})()\n</script>\n</body>\n</html>\n`\n}\n","import type { Server } from 'node:http'\nimport { createServer } from 'node:http'\nimport type { AddressInfo } from 'node:net'\n\nimport { demoPage } from './demo-page'\n\nexport type DemoServerInput = {\n host: string\n port: number\n siteOrigin: string\n page: () => { appName: string; slug: string; consentCategory: string }\n}\n\nexport type DemoServer = {\n origin: () => string\n stop: () => Promise<void>\n}\n\n// A port conflict arrives as an `error` event, not a rejected listen, so without this it would land\n// as an uncaught exception well after the caller has moved on.\nconst listening = (server: Server, host: string, port: number): Promise<void> => {\n return new Promise((resolve, reject) => {\n server.once('error', reject)\n server.listen(port, host, () => {\n server.off('error', reject)\n resolve()\n })\n })\n}\n\nexport const startDemoServer = async (input: DemoServerInput): Promise<DemoServer> => {\n const server = createServer((request, response) => {\n if (request.method !== 'GET' && request.method !== 'HEAD') {\n response.writeHead(405, { allow: 'GET, HEAD' }).end()\n return\n }\n\n response.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })\n response.end(request.method === 'HEAD' ? undefined : demoPage({ siteOrigin: input.siteOrigin, ...input.page() }))\n })\n\n // Loopback only: the page is unauthenticated and carries the developer's own event payloads.\n await listening(server, input.host, input.port)\n // A listening TCP server always reports an AddressInfo, and reading it back is what makes port 0 usable.\n const bound = (server.address() as AddressInfo).port\n\n return {\n origin: () => {\n return `http://${input.host}:${bound}`\n },\n stop: () => {\n return new Promise((resolve) => {\n server.close(() => {\n resolve()\n })\n })\n }\n }\n}\n","import { watch } from 'node:fs'\nimport { sep } from 'node:path'\n\n// Never a source of a rebuild: dependency and VCS trees, and the caches the UI build writes as it\n// runs. A build that wrote into a watched directory would schedule the next one, forever.\nconst IGNORED_SEGMENTS = new Set(['node_modules', '.git', '.astro', '.wrangler', '.qinto'])\n\nconst posix = (value: string): string => {\n return value.split(sep).join('/')\n}\n\nexport const watched = (relative: string, ignore: readonly string[]): boolean => {\n const path = posix(relative)\n if (path.split('/').some((segment) => IGNORED_SEGMENTS.has(segment))) {\n return false\n }\n\n return !ignore.some((prefix) => {\n const normalized = posix(prefix)\n return path === normalized || path.startsWith(`${normalized}/`)\n })\n}\n\nexport type Rebuilder = { trigger: () => void; stop: () => void }\n\nexport type RebuilderInput = { quietMs: number; onChange: () => Promise<void> }\n\nexport const createRebuilder = (input: RebuilderInput): Rebuilder => {\n let timer: ReturnType<typeof setTimeout> | null = null\n let running = false\n let pending = false\n let stopped = false\n\n // A file saved while a rebuild is running is the common case, so the loop runs once more rather\n // than dropping the change or starting a second rebuild beside the first.\n const run = async (): Promise<void> => {\n running = true\n try {\n do {\n pending = false\n await input.onChange()\n } while (pending && !stopped)\n } finally {\n running = false\n }\n }\n\n const trigger = (): void => {\n if (stopped) {\n return\n }\n\n if (running) {\n pending = true\n return\n }\n\n if (timer !== null) {\n clearTimeout(timer)\n }\n\n timer = setTimeout(() => {\n timer = null\n void run()\n }, input.quietMs)\n }\n\n return {\n trigger,\n stop: () => {\n stopped = true\n if (timer !== null) {\n clearTimeout(timer)\n timer = null\n }\n }\n }\n}\n\nexport type WatcherInput = { dir: string; ignore: readonly string[]; quietMs: number; onChange: () => Promise<void> }\n\nexport type Watcher = { stop: () => void }\n\nexport const startWatcher = (input: WatcherInput): Watcher => {\n const rebuilder = createRebuilder({ quietMs: input.quietMs, onChange: input.onChange })\n const watcher = watch(input.dir, { recursive: true }, (_event, filename) => {\n // A rename can arrive with no name at all, and it is never worth guessing what moved.\n if (filename !== null && watched(filename.toString(), input.ignore)) {\n rebuilder.trigger()\n }\n })\n\n return {\n stop: () => {\n rebuilder.stop()\n watcher.close()\n }\n }\n}\n","import { existsSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nimport { CliError } from '../../../lib/errors'\n\n// Two layouts hold the released bundles: the published package, where the build copies them beside\n// the entry, and this repo, where they are the portal's committed artifacts.\nconst CANDIDATES = ['./worker-artifact', '../../../../../portal/services/worker-artifact']\n\nexport const resolveArtifactRoot = (): string => {\n for (const candidate of CANDIDATES) {\n const root = fileURLToPath(new URL(candidate, import.meta.url))\n if (existsSync(join(root, 'version.json'))) {\n return root\n }\n }\n\n throw new CliError('This build of the Qinto CLI ships no platform bundles, so `qinto app dev` cannot start.')\n}\n","import type { ConsoleServer, DevLogEntry, DevStack } from '@qinto/app-dev'\nimport {\n devPaths,\n missingRequiredVariables,\n resetDevRoot,\n startConsoleServer,\n startDemoServer,\n startDevStack,\n startWatcher\n} from '@qinto/app-dev'\n\nimport type { CommandInput, CommandSpec } from '../../command-spec'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliUsageError } from '../../lib/errors'\nimport { readAppManifestFile } from './common/manifest-file'\nimport { resolveArtifactRoot } from './dev/artifact-root'\n\nconst DEFAULT_WORKER_PORT = '4310'\nconst DEFAULT_DEMO_PORT = '4301'\nconst DEFAULT_CONSOLE_PORT = '4300'\nconst DEFAULT_UI_PORT = '4302'\n\ntype DevOptions = { workerPort: string; demoPort: string; consolePort: string; uiPort: string; reset?: boolean }\n\nconst parsePort = (flag: string, raw: string): number => {\n const port = Number(raw)\n if (!Number.isInteger(port) || port < 0 || port > 65535) {\n throw new CliUsageError(`Pass a port between 0 and 65535 to ${flag}.`)\n }\n\n return port\n}\n\n// An installed app whose required variables are unset receives nothing, and the traces still look\n// healthy — so the banner names what is blocking rather than only whether the app is installed.\nconst installLine = (stack: DevStack): string => {\n const state = stack.state()\n if (!state.installed) {\n return 'The app is not installed on the seeded site.'\n }\n\n const missing = [\n ...new Set(\n state.installs.flatMap((install) => {\n return missingRequiredVariables(stack.manifest(), install, stack.secrets())\n })\n )\n ]\n if (missing.length > 0) {\n return `The app is installed, but no install is active until you set ${missing.join(', ')} in the console.`\n }\n\n return 'The app is installed and active on the seeded site.'\n}\n\nconst banner = (stack: DevStack, origins: { console: string; demo: string }, deps: CliDeps): void => {\n const manifest = stack.manifest()\n if (stack.discardedAppSlug !== null) {\n deps.stderr(`\\n ! Local state belonged to app '${stack.discardedAppSlug}' — discarded for '${manifest.slug}'.\\n`)\n }\n\n deps.stdout(`\\n ${manifest.name} (${manifest.slug}) — local Qinto on platform ${stack.platformVersion}\\n\\n`)\n deps.stdout(` Console ${origins.console}\\n`)\n deps.stdout(` Demo site ${origins.demo}\\n`)\n deps.stdout(` Site worker ${stack.origin}\\n`)\n if (stack.appUi !== null) {\n deps.stdout(` App panel ${stack.appUi.origin}\\n`)\n }\n\n deps.stdout(` Dev state ${stack.paths.root}\\n`)\n deps.stdout(` Site token ${stack.keys.workerAccessToken}\\n\\n`)\n\n for (const resource of stack.inert()) {\n deps.stderr(` ! ${resource.binding} is not bound locally — ${resource.reason}\\n`)\n }\n\n deps.stdout(` ${installLine(stack)}\\n\\n`)\n deps.stdout(' Watching for changes — a saved file rebuilds the app and reloads the console.\\n\\n')\n}\n\nconst REBUILD_QUIET_MS = 120\n\nconst rebuildOnChange = (stack: DevStack, console_: ConsoleServer, deps: CliDeps): (() => Promise<void>) => {\n return async () => {\n deps.stdout(' rebuilding…\\n')\n try {\n await stack.rebuild()\n // Every open console page reloads, which is what brings a rebuilt panel into its iframe.\n console_.reload()\n deps.stdout(' rebuilt\\n')\n } catch (error) {\n deps.stderr(` ! rebuild failed: ${error instanceof Error ? error.message : String(error)}\\n`)\n }\n }\n}\n\n// A spans line already carries its own events; anything else is the worker writing to the console.\nconst printEntry = (entry: DevLogEntry, deps: CliDeps): void => {\n if (entry.spans === undefined) {\n deps.stdout(` ${entry.message}\\n`)\n return\n }\n\n for (const span of entry.spans.spans) {\n deps.stdout(` ${span.name} ${span.end - span.start}ms\\n`)\n for (const event of span.events ?? []) {\n deps.stdout(` · ${event.name}${event.attrs === undefined ? '' : ` ${JSON.stringify(event.attrs)}`}\\n`)\n }\n }\n}\n\nconst untilSignalled = (): Promise<void> => {\n return new Promise((resolve) => {\n const stop = (): void => {\n process.off('SIGINT', stop)\n process.off('SIGTERM', stop)\n resolve()\n }\n\n process.on('SIGINT', stop)\n process.on('SIGTERM', stop)\n })\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const dir = input.positionals.at(0) ?? '.'\n const options = input.options as DevOptions\n // Every port is parsed before anything happens: --reset deletes the project's persisted install,\n // variables and stored data, and a typo in a later flag must not take them with it.\n const ports = {\n worker: parsePort('--worker-port', options.workerPort),\n demo: parsePort('--demo-port', options.demoPort),\n console: parsePort('--console-port', options.consolePort),\n ui: parsePort('--ui-port', options.uiPort)\n }\n\n // The stack composes the app worker's platform binding before the console binds, so a chosen-at-\n // bind-time port would leave the app with no address to write settings back to.\n if (ports.console === 0) {\n throw new CliUsageError('--console-port must be a real port: the app worker is given the console address before it starts.')\n }\n\n if (options.reset === true) {\n await resetDevRoot(devPaths(dir))\n }\n\n const stack = await startDevStack({\n dir,\n artifactRoot: resolveArtifactRoot(),\n host: '127.0.0.1',\n port: ports.worker,\n uiPort: ports.ui,\n consoleOrigin: `http://127.0.0.1:${ports.console}`,\n readManifest: async () => {\n return (await readAppManifestFile(dir)).manifest\n }\n })\n\n // Past this point workerd is running, so every exit path has to take it down with it.\n try {\n const demo = await startDemoServer({\n host: '127.0.0.1',\n port: ports.demo,\n siteOrigin: stack.origin,\n page: () => {\n const manifest = stack.manifest()\n return { appName: manifest.name, slug: manifest.slug, consentCategory: manifest.consent.category }\n }\n })\n\n try {\n const console_ = await startConsoleServer({\n host: '127.0.0.1',\n port: ports.console,\n stack,\n demoOrigin: demo.origin\n })\n\n // The UI build writes into the directory it is watched from, so watching it would make every\n // rebuild schedule the next one.\n const uiDir = stack.manifest().ui?.dir\n const watcher = startWatcher({\n dir,\n ignore: uiDir === undefined ? [] : [uiDir],\n quietMs: REBUILD_QUIET_MS,\n onChange: rebuildOnChange(stack, console_, deps)\n })\n\n try {\n banner(stack, { console: console_.origin(), demo: demo.origin() }, deps)\n stack.logs.subscribe((entry) => {\n printEntry(entry, deps)\n })\n\n await untilSignalled()\n } finally {\n watcher.stop()\n await console_.stop()\n }\n } finally {\n await demo.stop()\n }\n } finally {\n await stack.stop()\n }\n}\n\nexport const appDevCommand: CommandSpec = {\n path: ['app', 'dev'],\n description: 'Run the app against a local Qinto: the released site worker and app runtime in workerd',\n positionals: [{ name: 'dir', description: 'App directory (defaults to the current one)', required: false }],\n options: [\n { flag: '--worker-port <port>', description: 'Port the local site worker listens on', type: 'string', default: DEFAULT_WORKER_PORT },\n { flag: '--console-port <port>', description: 'Port the local console is served from', type: 'string', default: DEFAULT_CONSOLE_PORT },\n { flag: '--demo-port <port>', description: 'Port the demo site is served from', type: 'string', default: DEFAULT_DEMO_PORT },\n { flag: '--ui-port <port>', description: 'Port the app’s UI panel is served from', type: 'string', default: DEFAULT_UI_PORT },\n { flag: '--reset', description: 'Discard this project’s local install, variables and stored data first', type: 'boolean' }\n ],\n result: { type: 'app-dev' },\n run\n}\n","type TableOptions = {\n indent?: number\n}\n\nexport const formatTable = (headers: readonly string[], rows: readonly (readonly string[])[], options: TableOptions = {}): string[] => {\n if (headers.length === 0) {\n throw new Error('A table must have at least one column.')\n }\n\n for (const row of rows) {\n if (row.length !== headers.length) {\n throw new Error(`Expected ${headers.length} table columns, received ${row.length}.`)\n }\n }\n\n const widths = headers.map((header, index) => Math.max(header.length, ...rows.map((row) => (row[index] as string).length)))\n const indent = ' '.repeat(options.indent ?? 0)\n const border = `${indent}+${widths.map((width) => '-'.repeat(width + 2)).join('+')}+`\n const renderRow = (row: readonly string[]): string => {\n const cells = row.map((cell, index) => cell.padEnd(widths[index] as number))\n return `${indent}| ${cells.join(' | ')} |`\n }\n\n const lines = [border, renderRow(headers), border, ...rows.map(renderRow)]\n if (rows.length > 0) {\n lines.push(border)\n }\n\n return lines\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { operations } from '../../generated/api'\nimport { apiJson } from '../../lib/api'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { listCallerOrganizations } from '../../lib/organizations'\nimport { formatTable } from '../../lib/table'\n\ntype AppsResponse = operations['listApps']['responses']['200']['content']['application/json']\n\ntype ListedApp = AppsResponse['apps'][number] & { organizationName: string }\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const origin = await resolveApiOrigin(deps, options)\n const organizations = await listCallerOrganizations(deps, origin)\n const apps: ListedApp[] = []\n for (const organization of organizations) {\n const response = await apiJson<AppsResponse>(deps, origin, `/developer/organizations/${organization.organizationId}/apps`)\n apps.push(...response.apps.map((app) => ({ ...app, organizationName: organization.name })))\n }\n\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ apps }, null, 2)}\\n`)\n return\n }\n\n if (apps.length === 0) {\n deps.stdout('No apps yet. Register one with `qinto app register`.\\n')\n return\n }\n\n for (const line of formatTable(\n ['Organization', 'Name', 'Slug', 'App ID'],\n apps.map((app) => [app.organizationName, app.name, app.slug, app.appId])\n )) {\n deps.stdout(`${line}\\n`)\n }\n}\n\nexport const appListCommand: CommandSpec = {\n path: ['app', 'list'],\n description: 'List your developer apps across organizations',\n positionals: [],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the apps as JSON', type: 'boolean' }],\n result: { type: 'app-list' },\n run\n}\n","import type { operations } from '../generated/api'\nimport { apiJson } from './api'\nimport type { CliDeps } from './deps'\nimport { CliError, CliUsageError } from './errors'\nimport type { CallerOrganization } from './organizations'\nimport { listCallerOrganizations } from './organizations'\n\ntype AppsResponse = operations['listApps']['responses']['200']['content']['application/json']\n\nexport type ResolvedApp = { app: AppsResponse['apps'][number]; organization: CallerOrganization }\n\nexport const resolveAppBySlug = async (input: {\n deps: CliDeps\n origin: string\n slug: string\n org?: string\n machine: boolean\n orgFlag?: boolean\n notFound: string\n}): Promise<ResolvedApp> => {\n const { deps, origin, slug, org, machine } = input\n const organizations = await listCallerOrganizations(deps, origin)\n const scope =\n org === undefined\n ? organizations\n : organizations.filter((organization) => organization.organizationId === org || organization.name === org)\n if (org !== undefined && scope.length === 0) {\n throw new CliUsageError(`Organization ${org} is not available to this credential.`)\n }\n\n const matches: ResolvedApp[] = []\n for (const organization of scope) {\n const response = await apiJson<AppsResponse>(deps, origin, `/developer/organizations/${organization.organizationId}/apps`)\n const app = response.apps.find((candidate) => candidate.slug === slug)\n if (app !== undefined) {\n matches.push({ app, organization })\n }\n }\n\n const only = matches.at(0)\n if (matches.length === 1 && only !== undefined) {\n return only\n }\n\n if (matches.length === 0) {\n throw new CliError(input.notFound)\n }\n\n if (machine) {\n throw new CliUsageError(`App '${slug}' exists in several organizations.${input.orgFlag === true ? ' Pass --org <organization>.' : ''}`)\n }\n\n const chosen = await deps.prompts.select(\n `Which organization's '${slug}' should be used?`,\n matches.map((match) => ({ name: match.organization.name, value: match.organization.organizationId }))\n )\n return matches.find((match) => match.organization.organizationId === chosen) as ResolvedApp\n}\n","import type { components } from '../generated/api'\nimport { apiJson } from './api'\nimport type { CliDeps } from './deps'\nimport { ApiResponseError, CliUsageError } from './errors'\n\nexport type Site = components['schemas']['Site']\n\nexport type Host = components['schemas']['Host']\n\nexport type DnsStatus = components['schemas']['SiteDns']\n\nexport type DnsState = 'verified' | 'pending' | 'not_required' | 'unavailable'\n\ntype ResolveSiteInput = {\n origin: string\n teamId: string\n reference?: string\n allowPrompt?: boolean\n}\n\ntype CheckDnsInput = {\n origin: string\n teamId: string\n domainId: string\n}\n\nexport const dnsState = (dns: DnsStatus): DnsState => {\n if (!dns.checked) {\n return 'unavailable'\n }\n\n if (!dns.required) {\n return 'not_required'\n }\n\n return dns.valid ? 'verified' : 'pending'\n}\n\nexport const listSites = async (deps: CliDeps, origin: string, teamId: string): Promise<Site[]> => {\n return (await apiJson<{ sites: Site[] }>(deps, origin, `/teams/${teamId}/domains`)).sites\n}\n\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i\n\nexport const resolveSite = async (deps: CliDeps, input: ResolveSiteInput): Promise<Site> => {\n const { origin, teamId, reference } = input\n const allowPrompt = input.allowPrompt ?? deps.interactive\n // An id resolves through the single-site endpoint: it needs only domain:read, while listing needs team:read.\n if (reference !== undefined && UUID_PATTERN.test(reference)) {\n try {\n return (await apiJson<{ site: Site }>(deps, origin, `/teams/${teamId}/domains/${reference}`)).site\n } catch (error) {\n if (error instanceof ApiResponseError && error.code === 'not_found') {\n throw new CliUsageError(`No authorized site matches ${reference} in team ${teamId}.`)\n }\n\n throw error\n }\n }\n\n const sites = await listSites(deps, origin, teamId)\n if (reference !== undefined) {\n const site = sites.find((candidate) => candidate.domainId === reference || candidate.domain === reference)\n if (site === undefined) {\n throw new CliUsageError(`No authorized site matches ${reference} in team ${teamId}.`)\n }\n\n return site\n }\n\n if (sites.length === 1) {\n return sites[0] as Site\n }\n\n if (!allowPrompt) {\n throw new CliUsageError('Pass a site ID or exact hostname when the team does not have exactly one authorized site.')\n }\n\n if (sites.length === 0) {\n throw new CliUsageError('This team has no authorized sites.')\n }\n\n const domainId = await deps.prompts.select(\n 'Choose a site',\n sites.map((site) => ({ name: `${site.domain} (${site.domainId})`, value: site.domainId }))\n )\n return sites.find((site) => site.domainId === domainId) as Site\n}\n\nexport const checkDns = async (deps: CliDeps, input: CheckDnsInput): Promise<DnsStatus> => {\n const { origin, teamId, domainId } = input\n return apiJson<DnsStatus>(deps, origin, `/teams/${teamId}/domains/${domainId}/dns/check`, { method: 'POST' })\n}\n\nexport const formatDnsRecords = (dns: DnsStatus): string[] => {\n if (dns.records.length === 0) {\n return []\n }\n\n return dns.records.map(\n (record) => `${record.type} ${record.name} → ${record.value}${record.note === undefined ? '' : ` (${record.note})`}`\n )\n}\n","import type { components } from '../generated/api'\nimport { apiJson } from './api'\nimport { loadActiveTeam, saveActiveTeam } from './credentials'\nimport type { CliDeps } from './deps'\nimport { CliUsageError } from './errors'\n\nexport type AuthorizedTeam = components['schemas']['Team']\n\nexport const listAuthorizedTeams = async (deps: CliDeps, origin: string): Promise<AuthorizedTeam[]> => {\n const response = await apiJson<{ teams: AuthorizedTeam[] }>(deps, origin, '/teams')\n return response.teams\n}\n\nexport const requireAuthorizedTeam = (teams: AuthorizedTeam[], teamId: string): AuthorizedTeam => {\n const team = teams.find((candidate) => candidate.teamId === teamId)\n if (team === undefined) {\n throw new CliUsageError(`Team ${teamId} is not authorized for this credential.`)\n }\n\n return team\n}\n\nexport const resolveCommandTeam = async (\n deps: CliDeps,\n origin: string,\n teams: AuthorizedTeam[],\n requestedTeamId?: string\n): Promise<AuthorizedTeam> => {\n if (requestedTeamId !== undefined) {\n return requireAuthorizedTeam(teams, requestedTeamId)\n }\n\n const activeTeamId = await loadActiveTeam(deps, origin)\n if (activeTeamId !== null) {\n const active = teams.find((team) => team.teamId === activeTeamId)\n if (active !== undefined) {\n return active\n }\n }\n\n if (teams.length === 1) {\n const team = teams[0] as AuthorizedTeam\n await saveActiveTeam(deps, origin, team.teamId)\n return team\n }\n\n throw new CliUsageError('No active team is selected. Run `qinto team active <teamId>` or pass `--team <teamId>`.')\n}\n","import type { CliDeps } from '../../../lib/deps'\nimport type { Site } from '../../../lib/domain-api'\nimport { listSites } from '../../../lib/domain-api'\nimport { CliUsageError } from '../../../lib/errors'\nimport type { AuthorizedTeam } from '../../../lib/teams'\nimport { listAuthorizedTeams, resolveCommandTeam } from '../../../lib/teams'\n\nexport type SiteTarget = { team: AuthorizedTeam; site: Site }\n\nexport const resolveSiteTarget = async (input: { deps: CliDeps; origin: string; site: string; team?: string }): Promise<SiteTarget> => {\n const { deps, origin } = input\n const teams = await listAuthorizedTeams(deps, origin)\n const team = await resolveCommandTeam(deps, origin, teams, input.team)\n const sites = await listSites(deps, origin, team.teamId)\n const site = sites.find((candidate) => candidate.domainId === input.site || candidate.domain === input.site)\n if (site === undefined) {\n if (sites.length === 0) {\n throw new CliUsageError(`Team ${team.teamId} has no authorized sites.`)\n }\n\n const known = sites.map((candidate) => `${candidate.domain} (${candidate.domainId})`).join(', ')\n throw new CliUsageError(`No site matches '${input.site}' in team ${team.teamId}. Sites: ${known}.`)\n }\n\n return { team, site }\n}\n","import { createHash } from 'node:crypto'\nimport { readFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport type { CliDeps } from '../../../lib/deps'\nimport { CliError } from '../../../lib/errors'\n\nexport type ArtifactDigest = { hash: string; size: number }\n\nexport const digestFile = async (absolute: string): Promise<ArtifactDigest> => {\n const bytes = await readFile(absolute)\n return { hash: createHash('sha256').update(bytes).digest('hex'), size: bytes.byteLength }\n}\n\nconst CONTENT_TYPES: Record<string, string> = {\n html: 'text/html',\n css: 'text/css',\n js: 'text/javascript',\n mjs: 'text/javascript',\n json: 'application/json',\n map: 'application/json',\n svg: 'image/svg+xml',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n ico: 'image/x-icon',\n txt: 'text/plain',\n woff: 'font/woff',\n woff2: 'font/woff2',\n wasm: 'application/wasm'\n}\n\nexport const contentTypeFor = (path: string): string => {\n const extension = path.slice(path.lastIndexOf('.') + 1).toLowerCase()\n return CONTENT_TYPES[extension] ?? 'application/octet-stream'\n}\n\nexport type UiUploadFile = { absolute: string; declaration: { path: string; hash: string; size: number; contentType: string } }\n\nexport const collectUiFiles = async (uiRoot: string, files: string[]): Promise<UiUploadFile[]> => {\n const collected: UiUploadFile[] = []\n for (const file of files) {\n const absolute = join(uiRoot, file)\n const digest = await digestFile(absolute)\n collected.push({ absolute, declaration: { path: file, ...digest, contentType: contentTypeFor(file) } })\n }\n\n return collected\n}\n\nexport type PresignedUpload = { key: string; url: string; headers: Record<string, string> }\n\nconst UPLOAD_CONCURRENCY = 4\n\nexport const uploadArtifacts = async (input: { deps: CliDeps; uploads: PresignedUpload[]; paths: string[] }): Promise<void> => {\n const queue = input.uploads.map((upload, index) => ({ upload, path: input.paths[index] as string }))\n const workers = Array.from({ length: Math.min(UPLOAD_CONCURRENCY, queue.length) }, async () => {\n for (let next = queue.shift(); next !== undefined; next = queue.shift()) {\n const bytes = await readFile(next.path)\n const response = await input.deps.fetch(next.upload.url, { method: 'PUT', headers: next.upload.headers, body: new Uint8Array(bytes) })\n if (!response.ok) {\n throw new CliError(`Uploading ${next.upload.key} failed with status ${response.status}.`)\n }\n }\n })\n await Promise.all(workers)\n}\n","import type { operations } from '../../../generated/api'\nimport { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport { ApiResponseError, CliUsageError } from '../../../lib/errors'\nimport type { SiteTarget } from '../common/site-target'\n\nexport type InstallOutcome = operations['installSiteApp']['responses']['200']['content']['application/json']\n\nexport type ConsentFlags = { acceptCapabilities: boolean; acknowledgeNecessary: boolean }\n\nconst CONSENT_REQUIREMENTS: Record<string, { flag: string; key: keyof ConsentFlags }> = {\n approval_required: { flag: '--accept-capabilities', key: 'acceptCapabilities' },\n acknowledgement_required: { flag: '--acknowledge-necessary', key: 'acknowledgeNecessary' }\n}\n\nconst API_REJECTION_PREFIX = 'The Qinto API rejected the request: '\n\nconst consentRetryKey = async (input: {\n deps: CliDeps\n machine: boolean\n error: unknown\n consent: ConsentFlags\n}): Promise<keyof ConsentFlags> => {\n const { error } = input\n if (!(error instanceof ApiResponseError)) {\n throw error\n }\n\n const requirement = CONSENT_REQUIREMENTS[error.code ?? '']\n if (requirement === undefined || input.consent[requirement.key]) {\n throw error\n }\n\n const reason = error.message.replace(API_REJECTION_PREFIX, '')\n if (input.machine) {\n throw new CliUsageError(`${reason} Pass ${requirement.flag} to proceed.`)\n }\n\n const confirmed = await input.deps.prompts.confirm(`${reason} Proceed?`, false)\n if (!confirmed) {\n throw new CliUsageError(`Install declined. Rerun with ${requirement.flag} to proceed.`)\n }\n\n return requirement.key\n}\n\nexport const installAppVersion = async (input: {\n deps: CliDeps\n origin: string\n machine: boolean\n target: SiteTarget\n slug: string\n appVersionId: string\n consent: ConsentFlags\n}): Promise<InstallOutcome> => {\n const { deps, origin, machine, target, slug, appVersionId } = input\n const consent = { ...input.consent }\n const path = `/teams/${target.team.teamId}/domains/${target.site.domainId}/apps/${slug}`\n for (;;) {\n try {\n return await apiJson<InstallOutcome>(deps, origin, path, {\n method: 'PUT',\n body: {\n appVersionId,\n ...(consent.acceptCapabilities ? { acceptCapabilities: true } : {}),\n ...(consent.acknowledgeNecessary ? { acknowledgeNecessary: true } : {})\n }\n })\n } catch (error) {\n consent[await consentRetryKey({ deps, machine, error, consent })] = true\n }\n }\n}\n","import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\n\nimport { lock } from 'proper-lockfile'\n\nimport { CliError } from '../../../lib/errors'\n\nexport type PublishRequest = { bump?: 'patch' | 'minor' | 'major'; version?: string }\n\ntype PublishPhase = 'init' | 'allocated' | 'uploaded' | 'installed'\n\nexport type PublishState = {\n publishId: string\n slug: string\n appId: string\n appVersionId?: string\n version?: string\n phase: PublishPhase\n request: PublishRequest\n site?: string\n domainAppId?: string\n}\n\nexport const withPublishLock = async <T>(dir: string, operation: () => Promise<T>): Promise<T> => {\n const target = join(dir, '.qinto', 'publish.lock')\n await mkdir(join(dir, '.qinto'), { recursive: true })\n await writeFile(target, '', { flag: 'a' })\n let release: () => Promise<void>\n try {\n release = await lock(target, { stale: 120_000, update: 10_000 })\n } catch {\n throw new CliError('A publish is already in progress here.')\n }\n\n try {\n return await operation()\n } finally {\n await release()\n }\n}\n\nexport const loadPublishState = async (dir: string): Promise<PublishState | null> => {\n let text: string\n try {\n text = await readFile(join(dir, '.qinto', 'publish.json'), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return null\n }\n\n throw error\n }\n\n try {\n return JSON.parse(text) as PublishState\n } catch {\n throw new CliError('.qinto/publish.json is corrupted. Pass --restart to discard it and start a fresh publish.')\n }\n}\n\nexport const savePublishState = async (dir: string, state: PublishState): Promise<void> => {\n await mkdir(join(dir, '.qinto'), { recursive: true })\n await writeFile(join(dir, '.qinto', 'publish.json'), `${JSON.stringify(state, null, 2)}\\n`)\n}\n\nexport const clearPublishState = async (dir: string): Promise<void> => {\n await rm(join(dir, '.qinto', 'publish.json'), { force: true })\n}\n","import { randomUUID } from 'node:crypto'\nimport { mkdtemp, rm } from 'node:fs/promises'\nimport { tmpdir } from 'node:os'\nimport { join, resolve } from 'node:path'\n\nimport { buildBundles, runUiBuild, validateServerHooks, validateUiAssets } from '@qinto/app-build'\nimport type { AppManifest } from '@qinto/app-manifest'\nimport { appManifestDigest } from '@qinto/app-manifest'\n\nimport type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { operations } from '../../generated/api'\nimport { apiJson } from '../../lib/api'\nimport { resolveAppBySlug } from '../../lib/apps'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { ApiResponseError, CliError, CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport { readAppManifestFile } from './common/manifest-file'\nimport type { SiteTarget } from './common/site-target'\nimport { resolveSiteTarget } from './common/site-target'\nimport type { ArtifactDigest, UiUploadFile } from './publish/artifacts'\nimport { collectUiFiles, digestFile, uploadArtifacts } from './publish/artifacts'\nimport type { InstallOutcome } from './publish/install'\nimport { installAppVersion } from './publish/install'\nimport type { PublishRequest, PublishState } from './publish/state'\nimport { clearPublishState, loadPublishState, savePublishState, withPublishLock } from './publish/state'\n\ntype CreateVersionResponse = operations['createAppVersion']['responses']['201']['content']['application/json']\n\ntype DeclareResponse = operations['declareAppArtifacts']['responses']['200']['content']['application/json']\n\ntype FinalizeResponse = operations['finalizeAppVersion']['responses']['200']['content']['application/json']\n\ntype AppVersion = CreateVersionResponse['version']\n\ntype PublishOptions = ApiTarget & {\n bump?: 'patch' | 'minor' | 'major'\n version?: string\n org?: string\n site?: string\n team?: string\n acceptCapabilities?: boolean\n acknowledgeNecessary?: boolean\n dryRun?: boolean\n restart?: boolean\n json?: boolean\n input?: boolean\n}\n\ntype Progress = (text: string) => void\n\ntype LocalBundle = ArtifactDigest & { absolute: string }\n\ntype LocalArtifacts = { server: LocalBundle; browser: LocalBundle | null; ui: UiUploadFile[] | null }\n\nconst DRY_RUN_BASE = '/dry-run/0.0.0/'\n\nconst resolveVersionRequest = (options: PublishOptions): PublishRequest => {\n if (options.bump !== undefined && options.version !== undefined) {\n throw new CliUsageError('Pass either --bump or --version, not both.')\n }\n\n if (options.version !== undefined) {\n if (!/^\\d+\\.\\d+\\.\\d+$/.test(options.version)) {\n throw new CliUsageError('Pass --version as x.y.z.')\n }\n\n return { version: options.version }\n }\n\n return { bump: options.bump ?? 'patch' }\n}\n\nconst progressPrinter = (deps: CliDeps, machine: boolean): Progress => {\n return (text) => {\n if (!machine) {\n deps.stderr(`${text}\\n`)\n }\n }\n}\n\nconst preparePublishState = async (input: {\n dir: string\n slug: string\n appId: string\n request: PublishRequest\n restart: boolean\n}): Promise<PublishState> => {\n if (input.restart) {\n await clearPublishState(input.dir)\n }\n\n const stored = input.restart ? null : await loadPublishState(input.dir)\n if (stored !== null) {\n const sameRequest = stored.request.bump === input.request.bump && stored.request.version === input.request.version\n if (stored.slug !== input.slug || stored.appId !== input.appId || !sameRequest) {\n throw new CliUsageError(\n 'An unfinished publish in this directory was started with different arguments. Rerun it with the same app and version request, or pass --restart to discard it.'\n )\n }\n\n return stored\n }\n\n const fresh: PublishState = { publishId: randomUUID(), slug: input.slug, appId: input.appId, phase: 'init', request: input.request }\n await savePublishState(input.dir, fresh)\n return fresh\n}\n\nconst buildLocalArtifacts = async (input: {\n dir: string\n manifest: AppManifest\n basePath: string\n outDir: string\n progress: Progress\n}): Promise<LocalArtifacts> => {\n const { dir, manifest, basePath, outDir, progress } = input\n progress('Building the server bundle…')\n const bundles = await buildBundles({ dir, manifest, outDir })\n await validateServerHooks({ manifest, serverBundle: bundles.server })\n const server = { absolute: bundles.server, ...(await digestFile(bundles.server)) }\n const browser = bundles.browser === null ? null : { absolute: bundles.browser, ...(await digestFile(bundles.browser)) }\n if (manifest.ui === undefined) {\n return { server, browser, ui: null }\n }\n\n progress('Building the UI panel…')\n await runUiBuild({ dir, ui: manifest.ui, basePath })\n const uiRoot = resolve(dir, manifest.ui.dir)\n const files = await validateUiAssets({ uiRoot, basePath })\n return { server, browser, ui: await collectUiFiles(uiRoot, files) }\n}\n\ntype DeclareInput = {\n deps: CliDeps\n origin: string\n versionPath: string\n publishId: string\n manifest: AppManifest\n artifacts: LocalArtifacts\n}\n\nconst declareAndUpload = async (input: DeclareInput): Promise<void> => {\n const { deps, origin, versionPath, publishId, manifest, artifacts } = input\n const body = {\n publishId,\n manifestDigest: await appManifestDigest(manifest),\n server: { hash: artifacts.server.hash, size: artifacts.server.size },\n ...(artifacts.browser === null ? {} : { browser: { hash: artifacts.browser.hash, size: artifacts.browser.size } }),\n ...(artifacts.ui === null ? {} : { uiFiles: artifacts.ui.map((file) => file.declaration) })\n }\n const declared = await apiJson<DeclareResponse>(deps, origin, `${versionPath}/artifacts`, { method: 'POST', body })\n const paths = [\n artifacts.server.absolute,\n ...(artifacts.browser === null ? [] : [artifacts.browser.absolute]),\n ...(artifacts.ui ?? []).map((file) => file.absolute)\n ]\n await uploadArtifacts({ deps, uploads: declared.uploads, paths })\n}\n\nconst finalizeVersion = async (input: DeclareInput & { progress: Progress }): Promise<AppVersion> => {\n const { deps, origin, versionPath, publishId } = input\n try {\n const response = await apiJson<FinalizeResponse>(deps, origin, `${versionPath}/finalize`, { method: 'POST', body: { publishId } })\n return response.version\n } catch (error) {\n if (error instanceof ApiResponseError && error.code === 'app_variables_unset') {\n // Saying the draft is held is the load-bearing half: without it a developer reaches for\n // `qinto app version cancel` and burns the version number on a value they can just set.\n throw new CliError(\n `${error.message} Set each one with \\`qinto app var set\\` or \\`qinto app secret set\\`, then re-run \\`qinto app publish\\` — this draft is still held, so it resumes on the same version.`\n )\n }\n\n if (!(error instanceof ApiResponseError) || error.code !== 'artifacts_stale') {\n throw error\n }\n\n input.progress('The declared artifacts went stale — redeclaring…')\n await declareAndUpload(input)\n const response = await apiJson<FinalizeResponse>(deps, origin, `${versionPath}/finalize`, { method: 'POST', body: { publishId } })\n return response.version\n }\n}\n\ntype InstallReport = { outcome: InstallOutcome; target: SiteTarget }\n\nconst reportSuccess = (input: {\n deps: CliDeps\n json: boolean\n slug: string\n version: AppVersion\n resumed?: boolean\n install?: InstallReport\n}): void => {\n if (input.json) {\n const install =\n input.install === undefined\n ? {}\n : {\n install: {\n domainAppId: input.install.outcome.domainAppId,\n action: input.install.outcome.action,\n site: { domainId: input.install.target.site.domainId, domain: input.install.target.site.domain },\n deployment: 'pending'\n }\n }\n input.deps.stdout(`${JSON.stringify({ status: 'published', slug: input.slug, version: input.version, ...install }, null, 2)}\\n`)\n return\n }\n\n if (input.resumed === true) {\n input.deps.stdout(`Version ${input.version.version} was already published from this directory.\\n`)\n } else {\n input.deps.stdout(`Published '${input.slug}'@${input.version.version}.\\nVersion ID: ${input.version.appVersionId}\\n`)\n }\n\n if (input.install !== undefined) {\n input.deps.stdout(\n `Install on ${input.install.target.site.domain}: ${input.install.outcome.action}. Deployment pending — the site deploys in the background.\\n`\n )\n } else if (input.resumed === true) {\n input.deps.stdout('Nothing left to do.\\n')\n }\n}\n\nconst finishPublish = async (input: {\n deps: CliDeps\n origin: string\n dir: string\n options: PublishOptions\n machine: boolean\n state: PublishState\n prior: PublishState\n version: AppVersion\n resumed: boolean\n progress: Progress\n}): Promise<void> => {\n const { deps, origin, dir, options, machine, state, prior, version, resumed, progress } = input\n const json = options.json === true\n if (options.site === undefined) {\n await clearPublishState(dir)\n reportSuccess({ deps, json, slug: state.slug, version, resumed })\n return\n }\n\n const target = await resolveSiteTarget({ deps, origin, site: options.site, team: options.team })\n const installedAppId = prior.phase === 'installed' && prior.site === target.site.domainId ? prior.domainAppId : undefined\n let outcome: InstallOutcome\n if (installedAppId === undefined) {\n progress(`Installing on ${target.site.domain}…`)\n outcome = await installAppVersion({\n deps,\n origin,\n machine,\n target,\n slug: state.slug,\n appVersionId: version.appVersionId,\n consent: {\n acceptCapabilities: options.acceptCapabilities === true,\n acknowledgeNecessary: options.acknowledgeNecessary === true\n }\n })\n await savePublishState(dir, { ...state, phase: 'installed', site: target.site.domainId, domainAppId: outcome.domainAppId })\n } else {\n outcome = { domainAppId: installedAppId, action: 'unchanged' }\n }\n\n await clearPublishState(dir)\n reportSuccess({ deps, json, slug: state.slug, version, resumed, install: { outcome, target } })\n}\n\nconst executePublish = async (input: {\n deps: CliDeps\n origin: string\n dir: string\n manifest: AppManifest\n request: PublishRequest\n options: PublishOptions\n machine: boolean\n}): Promise<void> => {\n const { deps, origin, dir, manifest, request, options, machine } = input\n const progress = progressPrinter(deps, machine)\n const resolved = await resolveAppBySlug({\n deps,\n origin,\n slug: manifest.slug,\n org: options.org,\n machine,\n orgFlag: true,\n notFound: `App '${manifest.slug}' is not registered. Run \\`qinto app register\\` first.`\n })\n const prior = await preparePublishState({\n dir,\n slug: manifest.slug,\n appId: resolved.app.appId,\n request,\n restart: options.restart === true\n })\n const publishId = prior.publishId\n const versionsPath = `/developer/organizations/${resolved.organization.organizationId}/apps/${resolved.app.appId}/versions`\n progress(`Allocating a version for '${manifest.slug}'…`)\n const created = await apiJson<CreateVersionResponse>(deps, origin, versionsPath, {\n method: 'POST',\n body: { publishId, manifest, ...request }\n })\n const state: PublishState = {\n publishId,\n slug: manifest.slug,\n appId: resolved.app.appId,\n appVersionId: created.version.appVersionId,\n version: created.version.version,\n phase: 'allocated',\n request\n }\n if (created.version.status === 'ready') {\n await finishPublish({ deps, origin, dir, options, machine, state, prior, version: created.version, resumed: true, progress })\n return\n }\n\n await savePublishState(dir, state)\n progress(`Allocated ${created.version.version} (draft).`)\n const versionPath = `${versionsPath}/${created.version.appVersionId}`\n const outDir = await mkdtemp(join(dir, '.qinto', 'build-'))\n try {\n const basePath = `/${resolved.app.appId}/${created.version.version}/`\n const artifacts = await buildLocalArtifacts({ dir, manifest, basePath, outDir, progress })\n progress(`Uploading ${1 + (artifacts.browser === null ? 0 : 1) + (artifacts.ui?.length ?? 0)} artifact(s)…`)\n await declareAndUpload({ deps, origin, versionPath, publishId, manifest, artifacts })\n await savePublishState(dir, { ...state, phase: 'uploaded' })\n progress('Finalizing…')\n const version = await finalizeVersion({ deps, origin, versionPath, publishId, manifest, artifacts, progress })\n await finishPublish({ deps, origin, dir, options, machine, state, prior, version, resumed: false, progress })\n } finally {\n await rm(outDir, { recursive: true, force: true })\n }\n}\n\nconst dryRunPublish = async (input: {\n deps: CliDeps\n dir: string\n manifest: AppManifest\n request: PublishRequest\n json: boolean\n machine: boolean\n}): Promise<void> => {\n const { deps, dir, manifest, request, json, machine } = input\n const outDir = await mkdtemp(join(tmpdir(), 'qinto-publish-'))\n try {\n const artifacts = await buildLocalArtifacts({ dir, manifest, basePath: DRY_RUN_BASE, outDir, progress: progressPrinter(deps, machine) })\n if (json) {\n const summary = {\n status: 'dry_run',\n slug: manifest.slug,\n request,\n server: { hash: artifacts.server.hash, size: artifacts.server.size },\n ...(artifacts.browser === null ? {} : { browser: { hash: artifacts.browser.hash, size: artifacts.browser.size } }),\n ...(artifacts.ui === null ? {} : { uiFiles: artifacts.ui.map((file) => file.declaration.path) })\n }\n deps.stdout(`${JSON.stringify(summary, null, 2)}\\n`)\n return\n }\n\n const parts = [`server bundle ${artifacts.server.size} bytes`]\n if (artifacts.browser !== null) {\n parts.push(`browser bundle ${artifacts.browser.size} bytes`)\n }\n\n if (artifacts.ui !== null) {\n parts.push(`${artifacts.ui.length} UI file(s)`)\n }\n\n const requested = request.version === undefined ? `bump ${request.bump}` : `version ${request.version}`\n deps.stdout('Dry run — nothing was allocated or uploaded.\\n')\n deps.stdout(`Would publish '${manifest.slug}' (${requested}): ${parts.join(', ')}.\\n`)\n } finally {\n await rm(outDir, { recursive: true, force: true })\n }\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as PublishOptions\n const machine = machineMode(options, deps)\n const dir = resolve(input.positionals.at(0) ?? '.')\n const request = resolveVersionRequest(options)\n const manifestFile = await readAppManifestFile(dir)\n if (options.dryRun === true) {\n await dryRunPublish({ deps, dir, manifest: manifestFile.manifest, request, json: options.json === true, machine })\n return\n }\n\n const origin = await resolveApiOrigin(deps, options)\n await withPublishLock(dir, async () => {\n await executePublish({ deps, origin, dir, manifest: manifestFile.manifest, request, options, machine })\n })\n}\n\nexport const appPublishCommand: CommandSpec = {\n path: ['app', 'publish'],\n description: 'Build an app and publish it as a new version',\n positionals: [{ name: 'dir', description: 'App directory holding qinto.app.jsonc (defaults to the current one)', required: false }],\n options: [\n ...API_TARGET_OPTIONS,\n {\n flag: '--bump <level>',\n description: 'Semver level to bump from the highest ready version (defaults to patch)',\n type: 'string',\n enum: ['patch', 'minor', 'major']\n },\n { flag: '--version <version>', description: 'Explicit x.y.z version to allocate instead of bumping', type: 'string' },\n { flag: '--org <organization>', description: 'Owning organization id or name (needed when the slug is ambiguous)', type: 'string' },\n { flag: '--site <site>', description: 'Install the published version on this site (domain or id) after finalizing', type: 'string' },\n { flag: '--team <teamId>', description: 'Use this authorized team when resolving --site', type: 'string' },\n { flag: '--accept-capabilities', description: 'Accept the additional capabilities a newer version requests', type: 'boolean' },\n { flag: '--acknowledge-necessary', description: 'Record that this app runs without visitor consent', type: 'boolean' },\n { flag: '--dry-run', description: 'Validate and build locally without allocating or uploading anything', type: 'boolean' },\n { flag: '--restart', description: 'Discard the resume state in this directory and start a fresh publish', type: 'boolean' },\n { flag: '--no-input', description: 'Disable all interactive prompts', type: 'boolean' },\n { flag: '--json', description: 'Print the published version as JSON', type: 'boolean' }\n ],\n result: { type: 'app-publish' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport { printRegisteredApp, registerOrganizationApp } from './common/register-app'\n\ntype RegisterOptions = ApiTarget & { slug?: string; name?: string; description?: string; org?: string; json?: boolean; input?: boolean }\n\nconst resolveField = async (input: { deps: CliDeps; value?: string; machine: boolean; flag: string; prompt: string }): Promise<string> => {\n if (input.value !== undefined && input.value !== '') {\n return input.value\n }\n\n if (input.machine) {\n throw new CliUsageError(`Pass ${input.flag}.`)\n }\n\n return input.deps.prompts.input(input.prompt)\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as RegisterOptions\n const machine = machineMode(options, deps)\n const origin = await resolveApiOrigin(deps, options)\n const slug = await resolveField({\n deps,\n value: options.slug,\n machine,\n flag: '--slug <slug>',\n prompt: 'App slug (3-30 lowercase letters, digits, hyphens)'\n })\n const name = await resolveField({ deps, value: options.name, machine, flag: '--name <name>', prompt: 'App name' })\n const registered = await registerOrganizationApp({\n deps,\n origin,\n machine,\n slug,\n name,\n description: options.description,\n org: options.org\n })\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ app: { ...registered.app, organizationName: registered.organization.name } }, null, 2)}\\n`)\n return\n }\n\n printRegisteredApp(deps, registered)\n}\n\nexport const appRegisterCommand: CommandSpec = {\n path: ['app', 'register'],\n description: 'Register a developer app under an organization',\n positionals: [],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--slug <slug>', description: 'Immutable app slug (3-30 lowercase letters, digits, hyphens)', type: 'string' },\n { flag: '--name <name>', description: 'App display name', type: 'string' },\n { flag: '--description <text>', description: 'Short summary of what the app does', type: 'string' },\n { flag: '--org <organization>', description: 'Owning organization id or name (prompted when ambiguous)', type: 'string' },\n { flag: '--no-input', description: 'Disable all interactive prompts', type: 'boolean' },\n { flag: '--json', description: 'Print the registered app as JSON', type: 'boolean' }\n ],\n result: { type: 'app-register' },\n run\n}\n","import type { operations } from '../../../generated/api'\nimport { apiJson } from '../../../lib/api'\nimport type { ResolvedApp } from '../../../lib/apps'\nimport { resolveAppBySlug } from '../../../lib/apps'\nimport type { CliDeps } from '../../../lib/deps'\nimport { CliError } from '../../../lib/errors'\n\ntype VariablesResponse = operations['listAppVariables']['responses']['200']['content']['application/json']\n\nexport type AppVariable = VariablesResponse['variables'][number]\n\nexport type VariableScope = { kind: 'plain' | 'secret'; noun: string; setCommand: string }\n\nexport const PLAIN_SCOPE: VariableScope = { kind: 'plain', noun: 'variable', setCommand: 'qinto app var set' }\n\nexport const SECRET_SCOPE: VariableScope = { kind: 'secret', noun: 'secret', setCommand: 'qinto app secret set' }\n\nconst variablesPath = (resolved: ResolvedApp): string => {\n return `/developer/organizations/${resolved.organization.organizationId}/apps/${resolved.app.appId}/variables`\n}\n\nexport const resolveVariableApp = async (input: {\n deps: CliDeps\n origin: string\n slug: string\n machine: boolean\n}): Promise<ResolvedApp> => {\n return resolveAppBySlug({ ...input, notFound: `App '${input.slug}' was not found in your organizations.` })\n}\n\nexport const fetchAppVariables = async (deps: CliDeps, origin: string, resolved: ResolvedApp): Promise<AppVariable[]> => {\n const response = await apiJson<VariablesResponse>(deps, origin, variablesPath(resolved))\n return response.variables\n}\n\nexport const writeAppVariable = async (input: {\n deps: CliDeps\n origin: string\n resolved: ResolvedApp\n name: string\n value: string\n scope: VariableScope\n}): Promise<AppVariable[]> => {\n const { deps, origin, resolved, name, value, scope } = input\n // The kind is checked before the write, so a name aimed at the wrong command never lands a value\n // in the other store — which the publish-time shape guard would then refuse to reconcile.\n const declared = (await fetchAppVariables(deps, origin, resolved)).find((variable) => variable.name === name)\n if (declared === undefined) {\n throw new CliError(\n `No version of '${resolved.app.slug}' declares an app ${scope.noun} named ${name}. Declare it under appVariables in qinto.app.jsonc first.`\n )\n }\n\n if (declared.kind !== scope.kind) {\n const other = scope.kind === 'secret' ? PLAIN_SCOPE : SECRET_SCOPE\n throw new CliError(`${name} is declared as a ${other.noun}; set it with \\`${other.setCommand}\\`.`)\n }\n\n const response = await apiJson<VariablesResponse>(deps, origin, variablesPath(resolved), {\n method: 'PATCH',\n body: { values: { [name]: value } }\n })\n return response.variables\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { machineMode } from '../../lib/machine-mode'\nimport { formatTable } from '../../lib/table'\nimport { fetchAppVariables, resolveVariableApp } from './common/app-variables'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const slug = input.positionals.at(0) as string\n const origin = await resolveApiOrigin(deps, options)\n const resolved = await resolveVariableApp({ deps, origin, slug, machine: machineMode(options, deps) })\n // Filtering to the secret kind is what makes \"this command cannot print a value\" structural: a\n // secret entry always carries a null value, so nothing here has one to print.\n const secrets = (await fetchAppVariables(deps, origin, resolved)).filter((variable) => variable.kind === 'secret')\n\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ secrets }, null, 2)}\\n`)\n return\n }\n\n if (secrets.length === 0) {\n deps.stdout(`No version of '${slug}' declares an app secret.\\n`)\n return\n }\n\n for (const line of formatTable(\n ['Name', 'Required', 'Status'],\n secrets.map((secret) => [secret.name, secret.required ? 'yes' : 'no', secret.set ? 'Set' : 'Not set'])\n )) {\n deps.stdout(`${line}\\n`)\n }\n}\n\nexport const appSecretListCommand: CommandSpec = {\n path: ['app', 'secret', 'list'],\n description: 'List an app’s app-scope secrets and whether each is set',\n positionals: [{ name: 'slug', description: 'Slug of the app to list', required: true }],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the secrets as JSON', type: 'boolean' }],\n result: { type: 'app-secret-list' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport { resolveVariableApp, SECRET_SCOPE, writeAppVariable } from './common/app-variables'\n\n// Never a positional: a secret passed on the command line lands in shell history and in a CI log.\nconst readSecret = async (deps: CliDeps, name: string): Promise<string> => {\n const raw = deps.interactive ? await deps.prompts.password(`Value for ${name}`) : await deps.readStdin()\n const value = raw.trim()\n if (value === '') {\n throw new CliUsageError(`No value for ${name}. Pipe it in (\\`echo -n \"$SECRET\" | qinto app secret set …\\`) or run this in a terminal.`)\n }\n\n return value\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const slug = input.positionals.at(0) as string\n const name = input.positionals.at(1) as string\n const origin = await resolveApiOrigin(deps, options)\n const resolved = await resolveVariableApp({ deps, origin, slug, machine: machineMode(options, deps) })\n const value = await readSecret(deps, name)\n const written = await writeAppVariable({ deps, origin, resolved, name, value, scope: SECRET_SCOPE })\n\n // Only the secret entries, whose value is always null, so no command in this pair can print one.\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ secrets: written.filter((variable) => variable.kind === 'secret') }, null, 2)}\\n`)\n return\n }\n\n deps.stdout(`Set ${name} for '${slug}'. Every site running this app picks it up within five minutes.\\n`)\n}\n\nexport const appSecretSetCommand: CommandSpec = {\n path: ['app', 'secret', 'set'],\n description: 'Set an app-scope secret the whole app shares',\n positionals: [\n { name: 'slug', description: 'Slug of the app the secret belongs to', required: true },\n { name: 'name', description: 'Secret name, as declared under appVariables in the manifest', required: true }\n ],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the resulting variables as JSON', type: 'boolean' }],\n result: { type: 'app-secret-set' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { operations } from '../../generated/api'\nimport { apiJson } from '../../lib/api'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { ApiResponseError, CliError } from '../../lib/errors'\nimport type { SiteTarget } from './common/site-target'\nimport { resolveSiteTarget } from './common/site-target'\n\ntype StatusResponse = operations['getSiteApp']['responses']['200']['content']['application/json']\n\ntype StatusApp = StatusResponse['app']\n\nconst installLine = (app: StatusApp, install: StatusResponse['installs'][number]): string => {\n const reasons: string[] = []\n if (!app.enabled) {\n reasons.push('the app is disabled')\n }\n\n if (!install.enabled) {\n reasons.push('this install is disabled')\n }\n\n if (install.missingRequired.length > 0) {\n reasons.push(`missing required: ${install.missingRequired.join(', ')}`)\n }\n\n return [install.active ? 'active' : 'inactive', ...reasons].join('; ')\n}\n\nconst endpointLine = (target: SiteTarget, app: StatusApp, endpoint: StatusResponse['endpoints'][number]): string => {\n return `${endpoint.methods.join(', ')} https://${target.site.domain}/app/${app.slug}${endpoint.path} — ${endpoint.auth}, ${endpoint.mode}`\n}\n\nconst grantLine = (grant: StatusResponse['grants'][number]): string => {\n return `${grant.status}: ${grant.callerAppSlug} → ${grant.providerAppSlug} (${grant.functions.join(', ')})`\n}\n\nconst printStatus = (deps: CliDeps, target: SiteTarget, status: StatusResponse): void => {\n const app = status.app\n deps.stdout(`${app.name} (${app.slug}) on ${target.site.domain}\\n`)\n deps.stdout(`Version: desired ${app.desiredVersion}, deployed ${app.deployedVersion ?? 'deployment pending'}\\n`)\n deps.stdout(`Enabled: ${app.enabled ? 'yes' : 'no'}\\n`)\n deps.stdout(`Flows: ${app.flows.join(', ')}\\n`)\n deps.stdout(`Consent category: ${app.consentCategory}\\n`)\n deps.stdout(`UI panel: ${app.ui ? 'yes' : 'no'}\\n`)\n deps.stdout(`API scopes: ${status.capabilities.api.length === 0 ? 'none' : status.capabilities.api.join(', ')}\\n`)\n deps.stdout(`Event data: ${status.capabilities.data.length === 0 ? 'none' : status.capabilities.data.join(', ')}\\n`)\n const captured = [\n ...status.capture.queryParams.map((name) => `${name} (query)`),\n ...status.capture.cookies.map((name) => `${name} (cookie)`)\n ]\n deps.stdout(`Captures: ${captured.length === 0 ? 'none' : captured.join(', ')}\\n`)\n if (status.endpoints.length === 0) {\n deps.stdout('Endpoints: none\\n')\n } else {\n deps.stdout('Endpoints:\\n')\n for (const endpoint of status.endpoints) {\n deps.stdout(` ${endpointLine(target, app, endpoint)}\\n`)\n }\n }\n\n deps.stdout('Installs:\\n')\n for (const install of status.installs) {\n deps.stdout(` #${install.ordinal} ${install.label} — ${installLine(app, install)}\\n`)\n }\n\n if (status.grants.length === 0) {\n deps.stdout('Grants: none\\n')\n return\n }\n\n deps.stdout(`Grants (${app.pendingGrantCount} pending):\\n`)\n for (const grant of status.grants) {\n deps.stdout(` ${grantLine(grant)}\\n`)\n }\n}\n\nconst fetchStatus = async (input: { deps: CliDeps; origin: string; target: SiteTarget; slug: string }): Promise<StatusResponse> => {\n const { deps, origin, target, slug } = input\n try {\n return await apiJson<StatusResponse>(deps, origin, `/teams/${target.team.teamId}/domains/${target.site.domainId}/apps/${slug}`)\n } catch (error) {\n if (error instanceof ApiResponseError && error.code === 'not_found') {\n throw new CliError(`App '${slug}' is not installed on ${target.site.domain}.`)\n }\n\n throw error\n }\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { site: string; team?: string; json?: boolean }\n const slug = input.positionals.at(0) as string\n const origin = await resolveApiOrigin(deps, options)\n const target = await resolveSiteTarget({ deps, origin, site: options.site, team: options.team })\n const status = await fetchStatus({ deps, origin, target, slug })\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ site: { domainId: target.site.domainId, domain: target.site.domain }, ...status }, null, 2)}\\n`)\n return\n }\n\n printStatus(deps, target, status)\n}\n\nexport const appStatusCommand: CommandSpec = {\n path: ['app', 'status'],\n description: 'Show an app’s desired vs deployed state on a site',\n positionals: [{ name: 'slug', description: 'Slug of the installed app', required: true }],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--site <site>', description: 'Site to inspect (domain or id)', type: 'string', required: true },\n { flag: '--team <teamId>', description: 'Use this authorized team when resolving --site', type: 'string' },\n { flag: '--json', description: 'Print the app status as JSON', type: 'boolean' }\n ],\n result: { type: 'app-status' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { machineMode } from '../../lib/machine-mode'\nimport { formatTable } from '../../lib/table'\nimport { fetchAppVariables, resolveVariableApp } from './common/app-variables'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const slug = input.positionals.at(0) as string\n const origin = await resolveApiOrigin(deps, options)\n const resolved = await resolveVariableApp({ deps, origin, slug, machine: machineMode(options, deps) })\n const variables = (await fetchAppVariables(deps, origin, resolved)).filter((variable) => variable.kind === 'plain')\n\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ variables }, null, 2)}\\n`)\n return\n }\n\n if (variables.length === 0) {\n deps.stdout(`No version of '${slug}' declares an app variable.\\n`)\n return\n }\n\n for (const line of formatTable(\n ['Name', 'Required', 'Value'],\n variables.map((variable) => [variable.name, variable.required ? 'yes' : 'no', variable.value ?? 'Not set'])\n )) {\n deps.stdout(`${line}\\n`)\n }\n}\n\nexport const appVarListCommand: CommandSpec = {\n path: ['app', 'var', 'list'],\n description: 'List an app’s app-scope variables and their values',\n positionals: [{ name: 'slug', description: 'Slug of the app to list', required: true }],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the variables as JSON', type: 'boolean' }],\n result: { type: 'app-var-list' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { machineMode } from '../../lib/machine-mode'\nimport { PLAIN_SCOPE, resolveVariableApp, writeAppVariable } from './common/app-variables'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const slug = input.positionals.at(0) as string\n const name = input.positionals.at(1) as string\n const value = input.positionals.at(2) as string\n const origin = await resolveApiOrigin(deps, options)\n const resolved = await resolveVariableApp({ deps, origin, slug, machine: machineMode(options, deps) })\n const written = await writeAppVariable({ deps, origin, resolved, name, value, scope: PLAIN_SCOPE })\n\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ variables: written.filter((variable) => variable.kind === 'plain') }, null, 2)}\\n`)\n return\n }\n\n deps.stdout(`Set ${name} for '${slug}'. Every site running this app picks it up within five minutes.\\n`)\n}\n\nexport const appVarSetCommand: CommandSpec = {\n path: ['app', 'var', 'set'],\n description: 'Set an app-scope variable the whole app shares',\n positionals: [\n { name: 'slug', description: 'Slug of the app the variable belongs to', required: true },\n { name: 'name', description: 'Variable name, as declared under appVariables in the manifest', required: true },\n { name: 'value', description: 'Value to store', required: true }\n ],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the resulting variables as JSON', type: 'boolean' }],\n result: { type: 'app-var-set' },\n run\n}\n","import { resolve } from 'node:path'\n\nimport type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { operations } from '../../generated/api'\nimport { apiJson } from '../../lib/api'\nimport type { ResolvedApp } from '../../lib/apps'\nimport { resolveAppBySlug } from '../../lib/apps'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { ApiResponseError, CliError, CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport { clearPublishState, loadPublishState } from './publish/state'\n\ntype VersionsResponse = operations['listAppVersions']['responses']['200']['content']['application/json']\n\ntype AppVersion = VersionsResponse['versions'][number]\n\nconst findVersion = async (input: { deps: CliDeps; origin: string; resolved: ResolvedApp; version: string }): Promise<AppVersion> => {\n const { deps, origin, resolved, version } = input\n const base = `/developer/organizations/${resolved.organization.organizationId}/apps/${resolved.app.appId}/versions`\n let cursor: VersionsResponse['nextCursor'] = null\n do {\n const query: string = cursor === null ? '' : `?cursorCreatedAt=${encodeURIComponent(cursor.createdAt)}&cursorId=${cursor.id}`\n const page: VersionsResponse = await apiJson<VersionsResponse>(deps, origin, `${base}${query}`)\n const match = page.versions.find((candidate) => candidate.version === version)\n if (match !== undefined) {\n return match\n }\n\n cursor = page.nextCursor\n } while (cursor !== null)\n\n throw new CliError(`Version ${version} was not found for '${resolved.app.slug}'.`)\n}\n\nconst mapCancelError = (error: unknown, version: string): never => {\n if (error instanceof ApiResponseError && error.code === 'not_draft') {\n throw new CliError(`Version ${version} is already ready and can never be cancelled.`)\n }\n\n if (error instanceof ApiResponseError && error.code === 'not_holder') {\n throw new CliError('Another publish holds this draft. Cancel it from that checkout, or pass --force as an organization owner.')\n }\n\n throw error\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { dir?: string; force?: boolean; json?: boolean }\n const slug = input.positionals.at(0) as string\n const version = input.positionals.at(1) as string\n const machine = machineMode(options, deps)\n const origin = await resolveApiOrigin(deps, options)\n const resolved = await resolveAppBySlug({ deps, origin, slug, machine, notFound: `App '${slug}' was not found in your organizations.` })\n const found = await findVersion({ deps, origin, resolved, version })\n if (found.status === 'ready') {\n throw new CliError(`Version ${version} is ready. A ready version is never cancelled; publish a new version instead.`)\n }\n\n const dir = resolve(options.dir ?? '.')\n const state = await loadPublishState(dir)\n const heldPublishId = state !== null && state.appVersionId === found.appVersionId ? state.publishId : null\n if (heldPublishId === null && options.force !== true) {\n throw new CliUsageError('This checkout does not hold this draft. Organization owners can pass --force to release it.')\n }\n\n const body = {\n ...(heldPublishId === null ? {} : { publishId: heldPublishId }),\n ...(options.force === true ? { force: true } : {})\n }\n const path = `/developer/organizations/${resolved.organization.organizationId}/apps/${resolved.app.appId}/versions/${found.appVersionId}`\n try {\n await apiJson(deps, origin, path, { method: 'DELETE', body })\n } catch (error) {\n mapCancelError(error, version)\n }\n\n if (heldPublishId !== null) {\n await clearPublishState(dir)\n }\n\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ cancelled: true, appVersionId: found.appVersionId, version }, null, 2)}\\n`)\n return\n }\n\n deps.stdout(`Cancelled draft ${slug}@${version}. Its version number is free again.\\n`)\n}\n\nexport const appVersionCancelCommand: CommandSpec = {\n path: ['app', 'version', 'cancel'],\n description: 'Release a draft version this checkout holds',\n positionals: [\n { name: 'slug', description: 'Slug of the app the draft belongs to', required: true },\n { name: 'version', description: 'Draft version number to release', required: true }\n ],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--dir <dir>', description: 'App directory holding the publish state (defaults to the current one)', type: 'string' },\n { flag: '--force', description: 'Force-release a wedged draft as an organization owner', type: 'boolean' },\n { flag: '--json', description: 'Print the cancellation as JSON', type: 'boolean' }\n ],\n result: { type: 'app-version-cancel' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { operations } from '../../generated/api'\nimport { apiJson } from '../../lib/api'\nimport { resolveAppBySlug } from '../../lib/apps'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport { formatTable } from '../../lib/table'\n\ntype VersionsResponse = operations['listAppVersions']['responses']['200']['content']['application/json']\n\nconst parseLimit = (value: string | undefined): number | undefined => {\n if (value === undefined) {\n return undefined\n }\n\n const parsed = Number.parseInt(value, 10)\n if (!Number.isInteger(parsed) || parsed < 1 || `${parsed}` !== value) {\n throw new CliUsageError('Pass a positive integer to --limit.')\n }\n\n return parsed\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { limit?: string; json?: boolean }\n const slug = input.positionals.at(0) as string\n const machine = machineMode(options, deps)\n const limit = parseLimit(options.limit)\n const origin = await resolveApiOrigin(deps, options)\n const resolved = await resolveAppBySlug({ deps, origin, slug, machine, notFound: `App '${slug}' was not found in your organizations.` })\n const path = `/developer/organizations/${resolved.organization.organizationId}/apps/${resolved.app.appId}/versions`\n const response = await apiJson<VersionsResponse>(deps, origin, limit === undefined ? path : `${path}?limit=${limit}`)\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ app: resolved.app, versions: response.versions, nextCursor: response.nextCursor }, null, 2)}\\n`)\n return\n }\n\n if (response.versions.length === 0) {\n deps.stdout(`No versions yet for '${slug}'. Publish one with \\`qinto app publish\\`.\\n`)\n return\n }\n\n for (const line of formatTable(\n ['Version', 'Status', 'Ready at', 'Created'],\n response.versions.map((version) => [\n version.version,\n version.status,\n version.status === 'ready' ? version.readyAt : '-',\n version.createdAt\n ])\n )) {\n deps.stdout(`${line}\\n`)\n }\n}\n\nexport const appVersionsCommand: CommandSpec = {\n path: ['app', 'versions'],\n description: 'List an app’s versions, drafts included',\n positionals: [{ name: 'slug', description: 'Slug of the app to list versions for', required: true }],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--limit <limit>', description: 'Page size, 1-200 (defaults to 50)', type: 'string' },\n { flag: '--json', description: 'Print the versions as JSON', type: 'boolean' }\n ],\n result: { type: 'app-versions' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../command-spec'\nimport type { CliDeps } from '../lib/deps'\nimport { CliError } from '../lib/errors'\nimport { buildManifest } from '../manifest'\nimport { COMMANDS } from '../registry'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const path = input.positionals\n const commands = path.length === 0 ? COMMANDS : COMMANDS.filter((command) => command.path.join(' ') === path.join(' '))\n if (commands.length === 0) {\n throw new CliError(`Unknown command: ${path.join(' ')}. Run \\`qinto describe\\` for the full list.`)\n }\n\n deps.stdout(`${JSON.stringify(buildManifest(commands), null, 2)}\\n`)\n}\n\nexport const describeCommand: CommandSpec = {\n path: ['describe'],\n description: 'Print a machine-readable description of the CLI commands',\n positionals: [{ name: 'command', description: 'Limit the output to one command path', required: false, variadic: true }],\n options: [],\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { checkDns, dnsState, formatDnsRecords, resolveSite } from '../../lib/domain-api'\nimport { machineMode } from '../../lib/machine-mode'\nimport { listAuthorizedTeams, resolveCommandTeam } from '../../lib/teams'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { team?: string; json?: boolean }\n const origin = await resolveApiOrigin(deps, options)\n const teams = await listAuthorizedTeams(deps, origin)\n const team = await resolveCommandTeam(deps, origin, teams, options.team)\n const site = await resolveSite(deps, {\n origin,\n teamId: team.teamId,\n reference: input.positionals.at(0),\n allowPrompt: !machineMode(options, deps)\n })\n const dns = await checkDns(deps, { origin, teamId: team.teamId, domainId: site.domainId })\n const result = { status: dnsState(dns), team, site, dns }\n if (options.json === true) {\n deps.stdout(`${JSON.stringify(result, null, 2)}\\n`)\n return\n }\n\n deps.stdout(`DNS for ${site.domain}: ${result.status}\\n`)\n for (const record of formatDnsRecords(dns)) {\n deps.stdout(` ${record}\\n`)\n }\n\n if (dns.message !== '') {\n deps.stdout(`${dns.message}\\n`)\n }\n}\n\nexport const domainDnsCommand: CommandSpec = {\n path: ['domain', 'dns'],\n description: 'Re-check DNS for an onboarded site',\n positionals: [{ name: 'site', description: 'Site UUID or exact hostname', required: false }],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--team <teamId>', description: 'Use this authorized team without changing the active team', type: 'string' },\n { flag: '--json', description: 'Print the DNS result as JSON', type: 'boolean' }\n ],\n result: { type: 'dns-check', statuses: ['verified', 'pending', 'not_required', 'unavailable'] },\n run\n}\n","// Generated from projects/portal/api/openapi.json by `pnpm generate:api` — do not edit.\nexport const JURISDICTIONS = ['eu', 'us'] as const\n\nexport const LOCATION_HINTS = ['wnam', 'enam', 'weur', 'eeur', 'apac', 'oc'] as const\n\nexport const DELIVERY_MODES = ['domain', 'development_url'] as const\n","// Mirrors the server's normalizeRootDomain so values match what it stores (punycode, lowercase, no www).\nexport const canonicalRootDomain = (raw: string): string | null => {\n const trimmed = raw.trim()\n const withScheme = /^[a-z][a-z0-9+.-]*:\\/\\//i.test(trimmed) ? trimmed : `http://${trimmed}`\n try {\n return new URL(withScheme).hostname.replace(/\\.$/, '').replace(/^www\\./, '')\n } catch {\n return null\n }\n}\n","import { targetFlags } from '../../../lib/config'\nimport { canonicalRootDomain } from './canonical'\n\nexport const resumeOnboardCommand = (input: {\n origin: string\n teamId: string\n machine: boolean\n siteId?: string\n rootDomain?: string\n hostId?: string\n needsZone?: boolean\n}): string => {\n const parts = ['qinto', 'domain', 'onboard']\n if (input.rootDomain !== undefined) {\n parts.push(canonicalRootDomain(input.rootDomain) ?? input.rootDomain)\n }\n\n if (input.siteId !== undefined) {\n parts.push('--site', input.siteId)\n }\n\n if (input.hostId !== undefined) {\n parts.push('--mode', 'self', '--host-id', input.hostId)\n }\n\n if (input.needsZone === true) {\n parts.push('--host-zone', '<zone>')\n }\n\n parts.push('--team', input.teamId)\n if (input.machine) {\n parts.push('--no-input', '--json')\n }\n\n parts.push(...targetFlags(input.origin))\n return parts.join(' ')\n}\n","import type { operations } from '../../../generated/api'\nimport type { JURISDICTIONS, LOCATION_HINTS } from '../../../generated/api-values'\nimport type { ApiTarget } from '../../../lib/config'\nimport type { CliDeps } from '../../../lib/deps'\nimport type { DnsStatus, Host, Site } from '../../../lib/domain-api'\nimport type { AuthorizedTeam } from '../../../lib/teams'\n\nexport const DELIVERY_FLAG_TO_WIRE = {\n domain: 'domain',\n 'development-url': 'development_url'\n} as const satisfies Record<string, Site['deliveryMode']>\n\nexport type OnboardOptions = ApiTarget & {\n team?: string\n mode?: 'managed' | 'self'\n name?: string\n subdomain?: string\n jurisdiction?: (typeof JURISDICTIONS)[number]\n locationHint?: (typeof LOCATION_HINTS)[number]\n delivery?: keyof typeof DELIVERY_FLAG_TO_WIRE\n site?: string\n shareDns?: string\n shareSubmissionId?: string\n input: boolean\n json?: boolean\n hostId?: string\n hostName?: string\n cloudflareAccountId?: string\n hostZone?: string\n workersForPlatforms?: boolean\n}\n\nexport type SiteInput = {\n rootDomain: string\n mode: 'managed' | 'self'\n name?: string\n subdomain?: string\n jurisdiction?: (typeof JURISDICTIONS)[number]\n locationHint?: (typeof LOCATION_HINTS)[number]\n}\n\nexport type HostSetup =\n | { status: 'ready'; hostId: string }\n | { status: 'host_setup_pending'; host: Host; zoneRequired: string[] | null; reason: string; resumeCommand: string }\n\nexport type CreatedHostResponse = operations['createHost']['responses']['201']['content']['application/json']\n\nexport type HostContext = {\n deps: CliDeps\n origin: string\n teamId: string\n rootDomain: string\n options: OnboardOptions\n machine: boolean\n}\n\nexport type PendingDnsResult = {\n dns: DnsStatus\n delivery: Site['deliveryMode'] | null\n shared: number\n}\n\nexport const ONBOARD_STATUSES = ['host_setup_pending', 'dns_pending', 'complete'] as const satisfies readonly OnboardResult['status'][]\n\nexport type OnboardResult =\n | {\n status: 'host_setup_pending'\n team: AuthorizedTeam\n host: Host\n zoneRequired: string[] | null\n reason: string\n resumeCommand: string\n }\n | {\n status: 'dns_pending'\n team: AuthorizedTeam\n site: Site\n dns: DnsStatus\n shared: number\n resumeCommand: string\n }\n | {\n status: 'complete'\n team: AuthorizedTeam\n site: Site\n dns: DnsStatus\n deployment: { deploymentId: string; version: string }\n snippet: { host: string; usingDevelopmentUrl: boolean; snippet: string }\n shared: number\n }\n","import { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport type { DnsStatus, Site } from '../../../lib/domain-api'\nimport type { AuthorizedTeam } from '../../../lib/teams'\nimport type { OnboardResult } from '../common/types'\n\nexport const completeOnboarding = async (input: {\n deps: CliDeps\n origin: string\n team: AuthorizedTeam\n site: Site\n dns: DnsStatus\n delivery: Site['deliveryMode']\n shared: number\n machine: boolean\n}): Promise<OnboardResult> => {\n const { deps, origin, team, site, dns, delivery, shared, machine } = input\n const progress = (text: string): void => {\n if (!machine) {\n deps.stderr(`${text}\\n`)\n }\n }\n\n progress(`Configuring delivery for ${site.domain}…`)\n await apiJson(deps, origin, `/teams/${team.teamId}/domains/${site.domainId}/delivery`, { method: 'PUT', body: { mode: delivery } })\n progress(`Deploying ${site.domain}… (this can take a few minutes)`)\n const deployment = await apiJson<{ deploymentId: string; version: string }>(\n deps,\n origin,\n `/teams/${team.teamId}/domains/${site.domainId}/deploy`,\n { method: 'POST', timeoutMs: 300_000 }\n )\n progress(`Fetching the install snippet for ${site.domain}…`)\n const snippet = await apiJson<{ host: string; usingDevelopmentUrl: boolean; snippet: string }>(\n deps,\n origin,\n `/teams/${team.teamId}/domains/${site.domainId}/snippet`\n )\n return { status: 'complete', team, site, dns, deployment, snippet, shared }\n}\n","import { CliUsageError } from '../../../lib/errors'\n\nexport const parseEmails = (raw: string): string[] | null => {\n const emails = [\n ...new Set(\n raw\n .split(',')\n .map((email) => email.trim().toLowerCase())\n .filter((email) => email !== '')\n )\n ]\n if (emails.length < 1 || emails.length > 10 || emails.some((email) => !/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email))) {\n return null\n }\n\n return emails\n}\n\nexport const validateEmails = (raw: string | undefined): string[] => {\n if (raw === undefined) {\n return []\n }\n\n const emails = parseEmails(raw)\n if (emails === null) {\n throw new CliUsageError('--share-dns must contain 1–10 comma-separated email addresses.')\n }\n\n return emails\n}\n","import { randomUUID } from 'node:crypto'\n\nimport { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport type { DnsStatus, Site } from '../../../lib/domain-api'\nimport { checkDns, dnsState, formatDnsRecords } from '../../../lib/domain-api'\nimport { CliUsageError } from '../../../lib/errors'\nimport type { AuthorizedTeam } from '../../../lib/teams'\nimport { parseEmails, validateEmails } from '../common/emails'\nimport type { OnboardOptions, PendingDnsResult } from '../common/types'\nimport { DELIVERY_FLAG_TO_WIRE } from '../common/types'\n\nconst shareDns = async (input: {\n deps: CliDeps\n origin: string\n teamId: string\n domainId: string\n emails: string[]\n submissionId?: string\n}): Promise<number> => {\n const { deps, origin, teamId, domainId, emails, submissionId } = input\n if (emails.length === 0) {\n return 0\n }\n\n const result = await apiJson<{ sent: number }>(deps, origin, `/teams/${teamId}/domains/${domainId}/dns/share`, {\n method: 'POST',\n body: { emails, submissionId: submissionId ?? randomUUID() }\n })\n return result.sent\n}\n\nconst printDnsStatus = (deps: CliDeps, site: Site, dns: DnsStatus): void => {\n deps.stdout(`DNS for ${site.domain}: ${dnsState(dns)}\\n`)\n for (const record of formatDnsRecords(dns)) {\n deps.stdout(` ${record}\\n`)\n }\n\n if (dns.message !== '') {\n deps.stdout(`${dns.message}\\n`)\n }\n}\n\nconst pendingDnsChoices = (site: Site): { name: string; value: string }[] => {\n const choices = [\n { name: 'Re-check DNS', value: 'recheck' },\n { name: 'Share DNS instructions by email', value: 'share' }\n ]\n if (site.developmentUrl !== null) {\n choices.push({ name: `Use development URL ${site.developmentUrl}`, value: 'development_url' })\n }\n\n choices.push({ name: 'Skip DNS for now and finish setup', value: 'skip' })\n return choices\n}\n\nconst shareFromPrompt = async (input: { deps: CliDeps; origin: string; teamId: string; domainId: string }): Promise<number> => {\n const { deps, origin, teamId, domainId } = input\n const emails = parseEmails(await deps.prompts.input('Recipient emails, comma-separated'))\n if (emails === null) {\n deps.stderr('Enter 1–10 comma-separated email addresses.\\n')\n return 0\n }\n\n const sent = await shareDns({ deps, origin, teamId, domainId, emails })\n deps.stderr(`Emailed DNS instructions to ${sent} recipient(s).\\n`)\n return sent\n}\n\nconst deliveryForDns = (dns: DnsStatus): 'domain' | null => {\n const state = dnsState(dns)\n if (state === 'verified' || state === 'not_required') {\n return 'domain'\n }\n\n return null\n}\n\nconst handlePendingDns = async (input: {\n deps: CliDeps\n origin: string\n team: AuthorizedTeam\n site: Site\n initialDns: DnsStatus\n options: OnboardOptions\n machine: boolean\n initiallyShared: number\n}): Promise<PendingDnsResult> => {\n const { deps, origin, team, site, initialDns, options, machine, initiallyShared } = input\n let dns = initialDns\n let shared = initiallyShared\n const requestedDelivery = options.delivery === undefined ? undefined : DELIVERY_FLAG_TO_WIRE[options.delivery]\n if (requestedDelivery === 'development_url') {\n if (site.developmentUrl === null) {\n throw new CliUsageError('This host does not provide a development URL.')\n }\n\n return { dns, delivery: 'development_url', shared }\n }\n\n if (requestedDelivery === 'domain') {\n return { dns, delivery: 'domain', shared }\n }\n\n while (!machine && (dnsState(dns) === 'pending' || dnsState(dns) === 'unavailable')) {\n const action = await deps.prompts.select('DNS is not verified yet', pendingDnsChoices(site))\n if (action === 'recheck') {\n dns = await checkDns(deps, { origin, teamId: team.teamId, domainId: site.domainId })\n printDnsStatus(deps, site, dns)\n continue\n }\n\n if (action === 'share') {\n shared += await shareFromPrompt({ deps, origin, teamId: team.teamId, domainId: site.domainId })\n continue\n }\n\n return { dns, delivery: action === 'development_url' ? 'development_url' : 'domain', shared }\n }\n\n return { dns, delivery: deliveryForDns(dns), shared }\n}\n\nexport const processDns = async (input: {\n deps: CliDeps\n origin: string\n team: AuthorizedTeam\n site: Site\n options: OnboardOptions\n machine: boolean\n}): Promise<PendingDnsResult> => {\n const { deps, origin, team, site, options, machine } = input\n const dns = await checkDns(deps, { origin, teamId: team.teamId, domainId: site.domainId })\n if (!machine) {\n printDnsStatus(deps, site, dns)\n }\n\n const shared = await shareDns({\n deps,\n origin,\n teamId: team.teamId,\n domainId: site.domainId,\n emails: validateEmails(options.shareDns),\n submissionId: options.shareSubmissionId\n })\n return handlePendingDns({ deps, origin, team, site, initialDns: dns, options, machine, initiallyShared: shared })\n}\n","import type { CliDeps } from '../../../lib/deps'\nimport { dnsState, formatDnsRecords } from '../../../lib/domain-api'\nimport type { OnboardResult } from '../common/types'\n\nconst hostPendingReason = (reason: string): string => {\n if (reason === 'zone_required') {\n return 'choose a Cloudflare zone for the host.'\n }\n\n if (reason === 'wfp_sync_failed') {\n return 'Workers for Platforms could not be synced.'\n }\n\n return `Workers for Platforms could not be synced (${reason}).`\n}\n\nconst printHostSetupPending = (deps: CliDeps, result: Extract<OnboardResult, { status: 'host_setup_pending' }>): void => {\n deps.stdout(`Host setup is pending for ${result.host.name}: ${hostPendingReason(result.reason)}\\n`)\n if (result.zoneRequired !== null && result.zoneRequired.length > 0) {\n deps.stdout('Pick one of these zones and pass --host-zone:\\n')\n for (const zone of result.zoneRequired) {\n deps.stdout(` ${zone}\\n`)\n }\n }\n\n deps.stdout(`Resume: ${result.resumeCommand}\\n`)\n}\n\nexport const printOnboardingResult = (deps: CliDeps, result: OnboardResult, json: boolean): void => {\n if (json) {\n deps.stdout(`${JSON.stringify(result, null, 2)}\\n`)\n return\n }\n\n if (result.status === 'host_setup_pending') {\n printHostSetupPending(deps, result)\n return\n }\n\n deps.stdout(`Site: ${result.site.domain}\\nDNS: ${dnsState(result.dns)}\\n`)\n for (const record of formatDnsRecords(result.dns)) {\n deps.stdout(` ${record}\\n`)\n }\n\n if (result.shared > 0) {\n deps.stdout(`Emailed DNS instructions to ${result.shared} recipient(s).\\n`)\n }\n\n if (result.status === 'dns_pending') {\n deps.stdout(`Resume: ${result.resumeCommand}\\n`)\n return\n }\n\n deps.stdout(`Deployment: ${result.deployment.deploymentId} (${result.deployment.version})\\n`)\n deps.stdout(`Install this snippet in your site's <head>:\\n${result.snippet.snippet}\\n`)\n if (result.snippet.usingDevelopmentUrl) {\n deps.stdout('The snippet serves from the development URL until DNS is verified.\\n')\n }\n}\n","import { JURISDICTIONS, LOCATION_HINTS } from '../../../generated/api-values'\nimport type { CliDeps } from '../../../lib/deps'\nimport { CliUsageError } from '../../../lib/errors'\nimport { validateEmails } from '../common/emails'\nimport type { OnboardOptions, SiteInput } from '../common/types'\n\nconst JURISDICTION_LABELS: Record<(typeof JURISDICTIONS)[number], string> = {\n eu: 'European Union',\n us: 'United States'\n}\n\nconst LOCATION_HINT_LABELS: Record<(typeof LOCATION_HINTS)[number], string> = {\n wnam: 'Western North America',\n enam: 'Eastern North America',\n weur: 'Western Europe',\n eeur: 'Eastern Europe',\n apac: 'Asia Pacific',\n oc: 'Oceania'\n}\n\nconst validateSiteInput = (rootDomain: string | undefined, options: OnboardOptions): void => {\n const selfHostSettings = [\n options.hostId,\n options.hostName,\n options.cloudflareAccountId,\n options.hostZone,\n options.workersForPlatforms === true ? 'workers-for-platforms' : undefined\n ]\n if (options.site !== undefined && rootDomain !== undefined) {\n throw new CliUsageError('Pass either a root domain or --site, not both.')\n }\n\n if (\n options.site !== undefined &&\n [options.mode, options.name, options.subdomain, options.jurisdiction, options.locationHint, ...selfHostSettings].some(\n (value) => value !== undefined\n )\n ) {\n throw new CliUsageError('--site cannot be combined with site creation or host settings.')\n }\n}\n\nconst validateSelfHostInput = (options: OnboardOptions, machine: boolean): void => {\n const hasSelfHostSettings = [\n options.hostId,\n options.hostName,\n options.cloudflareAccountId,\n options.hostZone,\n options.workersForPlatforms === true ? 'workers-for-platforms' : undefined\n ].some((value) => value !== undefined)\n\n if (hasSelfHostSettings && options.mode !== 'self') {\n throw new CliUsageError('Self-host options require --mode self.')\n }\n\n if (options.hostId !== undefined && (options.hostName !== undefined || options.cloudflareAccountId !== undefined)) {\n throw new CliUsageError('--host-id cannot be combined with new-host settings.')\n }\n\n if (options.hostId !== undefined && options.workersForPlatforms === true) {\n throw new CliUsageError('--workers-for-platforms is available only when creating a new host.')\n }\n\n if (\n machine &&\n options.mode === 'self' &&\n options.hostId === undefined &&\n (options.hostName === undefined || options.cloudflareAccountId === undefined)\n ) {\n throw new CliUsageError('Self-hosting requires --host-id, or both --host-name and --cloudflare-account-id.')\n }\n}\n\nconst validateDnsSharingInput = (options: OnboardOptions): void => {\n if (options.shareSubmissionId !== undefined && options.shareDns === undefined) {\n throw new CliUsageError('--share-submission-id requires --share-dns.')\n }\n\n if (\n options.shareSubmissionId !== undefined &&\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(options.shareSubmissionId)\n ) {\n throw new CliUsageError('--share-submission-id must be a UUID.')\n }\n\n validateEmails(options.shareDns)\n}\n\nexport const validateInputs = (rootDomain: string | undefined, options: OnboardOptions, machine: boolean): void => {\n validateSiteInput(rootDomain, options)\n validateSelfHostInput(options, machine)\n validateDnsSharingInput(options)\n\n if (machine && options.site === undefined && rootDomain === undefined) {\n throw new CliUsageError('Pass [rootDomain] or --site in non-interactive mode.')\n }\n}\n\nexport const collectSiteInput = async (\n deps: CliDeps,\n rootDomain: string | undefined,\n options: OnboardOptions,\n machine: boolean\n): Promise<SiteInput> => {\n const domain = rootDomain ?? (await deps.prompts.input('Customer root domain'))\n if (domain.trim() === '') {\n throw new CliUsageError('The customer root domain cannot be empty.')\n }\n\n const mode =\n options.mode ??\n (machine\n ? 'managed'\n : ((await deps.prompts.select('Hosting mode', [\n { name: 'Managed by Qinto', value: 'managed' },\n { name: 'Self-hosted on your Cloudflare account', value: 'self' }\n ])) as 'managed' | 'self'))\n let { name, subdomain, jurisdiction, locationHint } = options\n const hasAdvanced = name !== undefined || subdomain !== undefined || jurisdiction !== undefined || locationHint !== undefined\n if (!machine && (hasAdvanced || (await deps.prompts.confirm('Configure advanced site settings?', false)))) {\n name = name ?? (await deps.prompts.input('Site display name', domain))\n subdomain = subdomain ?? ((await deps.prompts.input('Site subdomain (leave blank for automatic)')) || undefined)\n jurisdiction =\n jurisdiction ??\n (((await deps.prompts.select('Data jurisdiction', [\n { name: 'Automatic', value: '' },\n ...JURISDICTIONS.map((value) => ({ name: JURISDICTION_LABELS[value], value }))\n ])) as OnboardOptions['jurisdiction'] | '') ||\n undefined)\n locationHint =\n locationHint ??\n (((await deps.prompts.select('Location hint', [\n { name: 'Automatic', value: '' },\n ...LOCATION_HINTS.map((value) => ({ name: LOCATION_HINT_LABELS[value], value }))\n ])) as OnboardOptions['locationHint'] | '') ||\n undefined)\n }\n\n return { rootDomain: domain, mode, name, subdomain, jurisdiction, locationHint }\n}\n","import { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport type { Host } from '../../../lib/domain-api'\nimport { CliUsageError } from '../../../lib/errors'\nimport { resumeOnboardCommand } from '../common/resume'\nimport type { CreatedHostResponse, HostContext, HostSetup } from '../common/types'\n\nconst setHostZone = async (input: {\n deps: HostContext['deps']\n origin: string\n teamId: string\n hostId: string\n zoneDomain: string\n}): Promise<CreatedHostResponse> => {\n const { deps, origin, teamId, hostId, zoneDomain } = input\n const response = await apiJson<{ host: Host; wfpSync: CreatedHostResponse['wfpSync'] }>(\n deps,\n origin,\n `/teams/${teamId}/hosts/${hostId}/zone`,\n { method: 'POST', body: { zoneDomain } }\n )\n return { ...response, zoneRequired: null }\n}\n\nconst selectHostZone = async (input: HostContext & { created: CreatedHostResponse }): Promise<string | undefined> => {\n const { deps, created, options, machine } = input\n if (created.host.zoneDomain !== null || created.zoneRequired === null) {\n return undefined\n }\n\n if (options.hostZone !== undefined || machine) {\n return options.hostZone\n }\n\n if (created.zoneRequired.length === 0) {\n return deps.prompts.input('Cloudflare zone domain')\n }\n\n return deps.prompts.select(\n 'Choose the Cloudflare zone for this host',\n created.zoneRequired.map((candidate) => ({ name: candidate, value: candidate }))\n )\n}\n\nconst configureHostZone = async (input: HostContext & { created: CreatedHostResponse }): Promise<CreatedHostResponse> => {\n const zone = await selectHostZone(input)\n if (zone === undefined) {\n return input.created\n }\n\n return setHostZone({\n deps: input.deps,\n origin: input.origin,\n teamId: input.teamId,\n hostId: input.created.host.hostId,\n zoneDomain: zone\n })\n}\n\nconst finishHostSetup = async (input: HostContext & { created: CreatedHostResponse }): Promise<HostSetup> => {\n const current = await configureHostZone(input)\n const reason =\n current.host.zoneDomain === null\n ? 'zone_required'\n : current.wfpSync?.pushed === false\n ? (current.wfpSync.reason ?? 'wfp_sync_failed')\n : null\n if (reason !== null) {\n return {\n status: 'host_setup_pending',\n host: current.host,\n zoneRequired: current.zoneRequired,\n reason,\n resumeCommand: resumeOnboardCommand({\n origin: input.origin,\n teamId: input.teamId,\n rootDomain: input.rootDomain,\n hostId: current.host.hostId,\n needsZone: current.host.zoneDomain === null,\n machine: input.machine\n })\n }\n }\n\n return { status: 'ready', hostId: current.host.hostId }\n}\n\nconst chooseHostId = async (input: HostContext, hosts: Host[]): Promise<string | undefined> => {\n if (input.options.hostId !== undefined || input.machine || hosts.length === 0) {\n return input.options.hostId\n }\n\n const selected = await input.deps.prompts.select('Choose a Cloudflare host', [\n ...hosts.map((host) => ({ name: `${host.name} (${host.accountId})`, value: host.hostId })),\n { name: 'Connect a new Cloudflare account', value: '__new__' }\n ])\n return selected === '__new__' ? undefined : selected\n}\n\nconst setupExistingHost = async (input: HostContext, hosts: Host[], hostId: string): Promise<HostSetup> => {\n const host = hosts.find((candidate) => candidate.hostId === hostId)\n if (host === undefined) {\n throw new CliUsageError(`Host ${hostId} is not available in team ${input.teamId}.`)\n }\n\n let outcome: CreatedHostResponse = { host, zoneRequired: host.zoneDomain === null ? [] : null, wfpSync: null }\n if (host.zoneDomain === null && input.options.hostZone !== undefined) {\n outcome = await setHostZone({\n deps: input.deps,\n origin: input.origin,\n teamId: input.teamId,\n hostId: host.hostId,\n zoneDomain: input.options.hostZone\n })\n } else if (host.wfp && host.zoneDomain !== null) {\n const synced = await apiJson<{ wfpSync: CreatedHostResponse['wfpSync'] }>(\n input.deps,\n input.origin,\n `/teams/${input.teamId}/hosts/${host.hostId}/wfp-sync`,\n { method: 'POST' }\n )\n outcome = { ...outcome, wfpSync: synced.wfpSync }\n }\n\n return finishHostSetup({ ...input, created: outcome })\n}\n\nconst promptUntilPresent = async (deps: CliDeps, read: () => Promise<string>, requirement: string): Promise<string> => {\n let value = await read()\n while (value.trim() === '') {\n deps.stderr(`${requirement}\\n`)\n value = await read()\n }\n\n return value\n}\n\nconst createSelfHost = async (input: HostContext): Promise<HostSetup> => {\n const { deps, origin, teamId, options, machine } = input\n const name =\n options.hostName ?? (await promptUntilPresent(deps, () => deps.prompts.input('Host display name'), 'A host display name is required.'))\n const accountId =\n options.cloudflareAccountId ??\n (await promptUntilPresent(deps, () => deps.prompts.input('Cloudflare account ID'), 'A Cloudflare account ID is required.'))\n const envToken = deps.env['QINTO_CLOUDFLARE_API_TOKEN']\n let apiToken = envToken === undefined || envToken === '' ? undefined : envToken\n if (apiToken === undefined) {\n if (machine) {\n throw new CliUsageError('Set QINTO_CLOUDFLARE_API_TOKEN when creating a self-host in non-interactive mode.')\n }\n\n apiToken = await promptUntilPresent(deps, () => deps.prompts.password('Cloudflare API token'), 'A Cloudflare API token is required.')\n }\n\n const created = await apiJson<CreatedHostResponse>(deps, origin, `/teams/${teamId}/hosts`, {\n method: 'POST',\n body: { name, accountId, apiToken, wfp: options.workersForPlatforms === true }\n })\n return finishHostSetup({ ...input, created })\n}\n\nexport const prepareSelfHost = async (input: HostContext): Promise<HostSetup> => {\n const hosts = (await apiJson<{ hosts: Host[] }>(input.deps, input.origin, `/teams/${input.teamId}/hosts`)).hosts\n const hostId = await chooseHostId(input, hosts)\n if (hostId !== undefined) {\n return setupExistingHost(input, hosts, hostId)\n }\n\n return createSelfHost(input)\n}\n","import { apiJson } from '../../../lib/api'\nimport type { CliDeps } from '../../../lib/deps'\nimport type { Site } from '../../../lib/domain-api'\nimport { listSites, resolveSite } from '../../../lib/domain-api'\nimport { ApiResponseError, CliUsageError } from '../../../lib/errors'\nimport { canonicalRootDomain } from '../common/canonical'\nimport { resumeOnboardCommand } from '../common/resume'\nimport type { HostSetup, OnboardOptions, SiteInput } from '../common/types'\nimport { prepareSelfHost } from './host'\nimport { collectSiteInput } from './settings'\n\nexport type SiteSetup = { status: 'ready'; site: Site } | Extract<HostSetup, { status: 'host_setup_pending' }>\n\nconst confirmSubdomainResume = async (input: {\n deps: CliDeps\n candidates: Site[]\n hostname: string\n machine: boolean\n}): Promise<Site | null> => {\n const { deps, candidates, hostname, machine } = input\n const match = candidates.find((site) => site.domain === hostname)\n if (match === undefined) {\n return null\n }\n\n if (machine) {\n throw new CliUsageError(`Site ${hostname} already exists. Pass --site ${match.domainId} to resume it.`)\n }\n\n const resume = await deps.prompts.confirm(`Resume onboarding for ${hostname} (site ${match.domainId})?`, true)\n if (!resume) {\n throw new CliUsageError(`Site ${hostname} already exists. Pass a different --subdomain, or --site ${match.domainId} to resume it.`)\n }\n\n return match\n}\n\nconst chooseResumableSite = async (input: {\n deps: CliDeps\n candidates: Site[]\n rootDomain: string\n machine: boolean\n}): Promise<Site | null> => {\n const { deps, candidates, rootDomain, machine } = input\n if (machine) {\n const ids = candidates.map((site) => site.domainId).join(', ')\n throw new CliUsageError(\n `Sites for ${rootDomain} already exist (${ids}). Pass --site <siteId> to resume one, or --subdomain to create a new site.`\n )\n }\n\n const selected = await deps.prompts.select(`${rootDomain} already has sites`, [\n ...candidates.map((site) => ({ name: `Resume site ${site.domain} (${site.domainId})`, value: site.domainId })),\n { name: 'Create a new site', value: '__new__' }\n ])\n if (selected === '__new__') {\n return null\n }\n\n return candidates.find((site) => site.domainId === selected) as Site\n}\n\nconst findResumableSite = async (input: {\n deps: CliDeps\n origin: string\n teamId: string\n siteInput: SiteInput\n machine: boolean\n}): Promise<Site | null> => {\n const { deps, origin, teamId, siteInput, machine } = input\n const canonical = canonicalRootDomain(siteInput.rootDomain)\n if (canonical === null) {\n return null\n }\n\n let sites: Site[]\n try {\n sites = await listSites(deps, origin, teamId)\n } catch (error) {\n // Listing needs team:read while creating needs only domain:write; a narrower credential skips duplicate detection instead of failing.\n if (error instanceof ApiResponseError && error.code === 'forbidden') {\n return null\n }\n\n throw error\n }\n\n const candidates = sites.filter((site) => site.rootDomain === canonical)\n if (candidates.length === 0) {\n return null\n }\n\n const subdomain = siteInput.subdomain?.trim().toLowerCase()\n if (subdomain !== undefined && subdomain !== '') {\n return confirmSubdomainResume({ deps, candidates, hostname: `${subdomain}.${canonical}`, machine })\n }\n\n return chooseResumableSite({ deps, candidates, rootDomain: canonical, machine })\n}\n\nexport const prepareSite = async (input: {\n deps: CliDeps\n origin: string\n teamId: string\n rootDomain: string | undefined\n options: OnboardOptions\n machine: boolean\n}): Promise<SiteSetup> => {\n const { deps, origin, teamId, rootDomain, options, machine } = input\n if (options.site !== undefined) {\n const site = await resolveSite(deps, { origin, teamId, reference: options.site })\n return { status: 'ready', site }\n }\n\n const siteInput = await collectSiteInput(deps, rootDomain, options, machine)\n const resumable = await findResumableSite({ deps, origin, teamId, siteInput, machine })\n if (resumable !== null) {\n return { status: 'ready', site: resumable }\n }\n\n let hostId: string | undefined\n if (siteInput.mode === 'self') {\n const host = await prepareSelfHost({ deps, origin, teamId, rootDomain: siteInput.rootDomain, options, machine })\n if (host.status === 'host_setup_pending') {\n return host\n }\n\n hostId = host.hostId\n }\n\n const response = await apiJson<{ site: Site }>(deps, origin, `/teams/${teamId}/domains`, {\n method: 'POST',\n body: { ...siteInput, hostId }\n })\n if (!machine) {\n const resume = resumeOnboardCommand({ origin, teamId, siteId: response.site.domainId, machine })\n deps.stderr(`Created site ${response.site.domain} (${response.site.domainId}). Resume anytime with: ${resume}\\n`)\n }\n\n return { status: 'ready', site: response.site }\n}\n","import { loadActiveTeam, saveActiveTeam } from '../../../lib/credentials'\nimport type { CliDeps } from '../../../lib/deps'\nimport { CliUsageError } from '../../../lib/errors'\nimport type { AuthorizedTeam } from '../../../lib/teams'\nimport { requireAuthorizedTeam, resolveCommandTeam } from '../../../lib/teams'\nimport type { OnboardOptions } from '../common/types'\n\nexport const chooseOnboardingTeam = async (input: {\n deps: CliDeps\n origin: string\n teams: AuthorizedTeam[]\n options: OnboardOptions\n machine: boolean\n}): Promise<AuthorizedTeam> => {\n const { deps, origin, teams, options, machine } = input\n if (options.team !== undefined || machine) {\n return resolveCommandTeam(deps, origin, teams, options.team)\n }\n\n if (teams.length === 0) {\n throw new CliUsageError('This credential has no authorized teams.')\n }\n\n const activeTeamId = await loadActiveTeam(deps, origin)\n const active = activeTeamId === null ? undefined : teams.find((team) => team.teamId === activeTeamId)\n if (active !== undefined && (await deps.prompts.confirm(`Use active team ${active.name ?? active.teamId} (${active.teamId})?`, true))) {\n return active\n }\n\n const teamId = await deps.prompts.select(\n 'Choose the team to onboard',\n teams.map((team) => ({ name: `${team.name ?? 'Untitled team'} (${team.teamId})`, value: team.teamId })),\n active?.teamId\n )\n const team = requireAuthorizedTeam(teams, teamId)\n await saveActiveTeam(deps, origin, team.teamId)\n return team\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport { JURISDICTIONS, LOCATION_HINTS } from '../../generated/api-values'\nimport { resolveApiOrigin } from '../../lib/config'\nimport type { CliDeps } from '../../lib/deps'\nimport { machineMode } from '../../lib/machine-mode'\nimport { listAuthorizedTeams } from '../../lib/teams'\nimport { resumeOnboardCommand } from './common/resume'\nimport type { OnboardOptions, OnboardResult } from './common/types'\nimport { DELIVERY_FLAG_TO_WIRE, ONBOARD_STATUSES } from './common/types'\nimport { completeOnboarding } from './onboarding/complete'\nimport { processDns } from './onboarding/dns'\nimport { printOnboardingResult } from './onboarding/result'\nimport { validateInputs } from './onboarding/settings'\nimport { prepareSite } from './onboarding/site'\nimport { chooseOnboardingTeam } from './onboarding/team'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as OnboardOptions\n const rootDomain = input.positionals.at(0)\n const machine = machineMode(options, deps)\n validateInputs(rootDomain, options, machine)\n const origin = await resolveApiOrigin(deps, options)\n const teams = await listAuthorizedTeams(deps, origin)\n const team = await chooseOnboardingTeam({ deps, origin, teams, options, machine })\n const siteSetup = await prepareSite({ deps, origin, teamId: team.teamId, rootDomain, options, machine })\n if (siteSetup.status === 'host_setup_pending') {\n printOnboardingResult(deps, { ...siteSetup, team }, options.json === true)\n return\n }\n\n const { site } = siteSetup\n try {\n const dns = await processDns({ deps, origin, team, site, options, machine })\n if (dns.delivery === null) {\n const result: OnboardResult = {\n status: 'dns_pending',\n team,\n site,\n dns: dns.dns,\n shared: dns.shared,\n resumeCommand: resumeOnboardCommand({ origin, teamId: team.teamId, siteId: site.domainId, machine })\n }\n printOnboardingResult(deps, result, options.json === true)\n return\n }\n\n const result = await completeOnboarding({\n deps,\n origin,\n team,\n site,\n dns: dns.dns,\n delivery: dns.delivery,\n shared: dns.shared,\n machine\n })\n printOnboardingResult(deps, result, options.json === true)\n } catch (error) {\n // The site already exists; without this pointer a retry of the original command creates a second one.\n const resume = resumeOnboardCommand({ origin, teamId: team.teamId, siteId: site.domainId, machine })\n const pointer = `Onboarding did not finish for site ${site.domainId}. Resume with: ${resume}`\n if (machine) {\n // Machine errors must stay one JSON document on stderr, so the pointer rides inside the error message.\n if (error instanceof Error) {\n error.message = `${error.message} ${pointer}`\n }\n\n throw error\n }\n\n deps.stderr(`${pointer}\\n`)\n throw error\n }\n}\n\nexport const domainOnboardCommand: CommandSpec = {\n path: ['domain', 'onboard'],\n description: 'Onboard a domain through DNS, deployment, and snippet installation',\n positionals: [{ name: 'rootDomain', description: 'Customer root domain to onboard', required: false }],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--team <teamId>', description: 'Use this authorized team without changing the active team', type: 'string' },\n { flag: '--mode <mode>', description: 'Choose managed or self-hosted infrastructure', type: 'string', enum: ['managed', 'self'] },\n { flag: '--name <name>', description: 'Site display name', type: 'string' },\n { flag: '--subdomain <subdomain>', description: 'Site subdomain', type: 'string' },\n { flag: '--jurisdiction <jurisdiction>', description: 'Choose the EU or US data jurisdiction', type: 'string', enum: JURISDICTIONS },\n {\n flag: '--location-hint <locationHint>',\n description: 'Place site state near a Cloudflare region',\n type: 'string',\n enum: LOCATION_HINTS\n },\n {\n flag: '--delivery <delivery>',\n description: 'Serve from the customer domain or a development URL',\n type: 'string',\n enum: Object.keys(DELIVERY_FLAG_TO_WIRE)\n },\n { flag: '--site <siteId>', description: 'Resume onboarding an existing site', type: 'string' },\n { flag: '--share-dns <emails>', description: 'Email DNS instructions to comma-separated recipients', type: 'string' },\n { flag: '--share-submission-id <submissionId>', description: 'UUID used to retry DNS sharing idempotently', type: 'string' },\n { flag: '--host-id <hostId>', description: 'Use an existing self-host', type: 'string' },\n { flag: '--host-name <name>', description: 'Display name for a new self-host', type: 'string' },\n { flag: '--cloudflare-account-id <accountId>', description: 'Cloudflare account ID for a new self-host', type: 'string' },\n { flag: '--host-zone <zone>', description: 'Cloudflare zone to use for the self-host', type: 'string' },\n { flag: '--workers-for-platforms', description: 'Enable Workers for Platforms on a new self-host', type: 'boolean' },\n { flag: '--no-input', description: 'Disable all interactive prompts', type: 'boolean' },\n { flag: '--json', description: 'Print a structured onboarding state as JSON', type: 'boolean' }\n ],\n environment: [\n { name: 'QINTO_API_TOKEN', description: 'Qinto bearer token used instead of stored OAuth credentials', secret: true },\n { name: 'QINTO_CLOUDFLARE_API_TOKEN', description: 'Cloudflare token used only when creating a self-host', secret: true }\n ],\n result: { type: 'domain-onboarding', statuses: ONBOARD_STATUSES },\n run\n}\n","import type { CommandInput, CommandSpec } from '../command-spec'\nimport type { QintoEnvironment } from '../lib/config'\nimport { API_ORIGINS, DEFAULT_ENVIRONMENT, ENVIRONMENTS, loadEnvironment, loginHint, saveEnvironment } from '../lib/config'\nimport { loadCredentials } from '../lib/credentials'\nimport type { CliDeps } from '../lib/deps'\nimport { CliUsageError } from '../lib/errors'\nimport { machineMode } from '../lib/machine-mode'\n\nconst printEnvironment = (deps: CliDeps, environment: QintoEnvironment, json: boolean): void => {\n if (json) {\n deps.stdout(`${JSON.stringify({ environment, apiOrigin: API_ORIGINS[environment] }, null, 2)}\\n`)\n return\n }\n\n deps.stdout(`${environment} (${API_ORIGINS[environment]})\\n`)\n}\n\nconst requestedEnvironment = (requested: string): QintoEnvironment => {\n const known = ENVIRONMENTS.find((name) => {\n return name === requested\n })\n if (known === undefined) {\n throw new CliUsageError(`Unknown environment: ${requested}. Choose ${ENVIRONMENTS.join(' or ')}.`)\n }\n\n return known\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as { json?: boolean }\n const json = options.json === true\n const current = (await loadEnvironment(deps)) ?? DEFAULT_ENVIRONMENT\n const requested = input.positionals.at(0)\n if (requested === undefined && machineMode(options, deps)) {\n printEnvironment(deps, current, json)\n return\n }\n\n const chosen = requestedEnvironment(\n requested ??\n (await deps.prompts.select(\n 'Choose the Qinto environment',\n ENVIRONMENTS.map((name) => ({ name: `${name} (${API_ORIGINS[name]})`, value: name })),\n current\n ))\n )\n\n await saveEnvironment(deps, chosen)\n printEnvironment(deps, chosen, json)\n const origin = API_ORIGINS[chosen]\n if (!json && (await loadCredentials(deps, origin)) === null) {\n deps.stderr(`You are not logged in to ${chosen}. Run \\`${loginHint(origin)}\\`.\\n`)\n }\n}\n\nexport const envCommand: CommandSpec = {\n path: ['env'],\n description: 'Show or set the Qinto environment every other command talks to',\n positionals: [{ name: 'name', description: `Environment to make current: ${ENVIRONMENTS.join(' or ')}`, required: false }],\n options: [{ flag: '--json', description: 'Print the current environment as JSON', type: 'boolean' }],\n result: { type: 'environment' },\n run\n}\n","import { createServer } from 'node:http'\nimport type { AddressInfo } from 'node:net'\n\nimport { CliError } from './errors'\n\nconst STYLE = [\n 'body{margin:0;box-sizing:border-box;min-height:100vh;display:grid;place-items:center;padding:40px 16px;',\n 'background:#fffdf9;color:#101828;font-family:ui-sans-serif,system-ui,-apple-system,\"Segoe UI\",Roboto,sans-serif}',\n '.mark{width:56px;height:56px;margin:0 auto 24px;display:grid;place-items:center;border-radius:16px;',\n 'background:#f25c2b;color:#fff;font-size:24px;font-weight:700;box-shadow:0 10px 20px -6px rgba(242,92,43,.45)}',\n 'main{width:100%;max-width:24rem}',\n '.card{padding:32px;text-align:center;border-radius:12px;background:#fff;',\n 'border:1px solid rgba(232,213,196,.6);box-shadow:0 1px 2px rgba(16,24,40,.05)}',\n 'h1{margin:0;font-size:20px;line-height:1.4;font-weight:700}',\n 'p{margin:8px 0 0;font-size:14px;line-height:1.5;color:#6a7282}'\n].join('')\n\nconst page = (title: string, detail: string): string => {\n return [\n '<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">',\n '<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"><title>Qinto CLI</title>',\n `<style>${STYLE}</style></head><body><main>`,\n '<div class=\"mark\">Q</div>',\n `<div class=\"card\"><h1>${title}</h1><p>${detail}</p></div>`,\n '</main></body></html>'\n ].join('')\n}\n\nexport type CallbackServer = { redirectUri: string; waitForCode: () => Promise<string>; close: () => void }\n\nexport const startCallbackServer = async (state: string, timeoutMs: number): Promise<CallbackServer> => {\n const { promise, resolve, reject } = Promise.withResolvers<string>()\n // The browser can answer before waitForCode attaches; without this handler that rejection counts as unhandled.\n promise.catch(() => {})\n const server = createServer()\n let timer: NodeJS.Timeout | undefined\n let closed = false\n\n const shutdown = (): void => {\n if (closed) {\n return\n }\n\n closed = true\n if (timer !== undefined) {\n clearTimeout(timer)\n }\n\n if (server.listening) {\n server.close()\n }\n }\n\n const succeed = (code: string): void => {\n resolve(code)\n shutdown()\n }\n\n const fail = (error: CliError): void => {\n reject(error)\n shutdown()\n }\n\n server.on('request', (req, res) => {\n const url = new URL(String(req.url), 'http://127.0.0.1')\n if (url.pathname !== '/callback') {\n res.writeHead(404).end()\n return\n }\n\n const finish = (status: number, title: string, detail: string): void => {\n res.writeHead(status, { 'content-type': 'text/html; charset=utf-8' }).end(page(title, detail))\n }\n\n if (url.searchParams.get('state') !== state) {\n finish(400, 'This login response does not match', 'Close this tab and run the login command again.')\n fail(new CliError('State mismatch in the login response. Run `qinto login` again.'))\n return\n }\n\n const error = url.searchParams.get('error')\n if (error !== null) {\n finish(200, 'Login was not completed', 'You can close this tab.')\n fail(new CliError(error === 'access_denied' ? 'Login was denied in the browser.' : `Authorization failed: ${error}`))\n return\n }\n\n const code = url.searchParams.get('code')\n if (code === null) {\n finish(400, 'This login response carried no code', 'Close this tab and run the login command again.')\n fail(new CliError('The login response carried no authorization code.'))\n return\n }\n\n finish(200, 'You are logged in to Qinto CLI', 'Return to your terminal.')\n succeed(code)\n })\n\n try {\n await new Promise<void>((listening, failed) => {\n const onError = (error: Error): void => {\n failed(error)\n }\n\n server.once('error', onError)\n server.listen(0, '127.0.0.1', () => {\n server.off('error', onError)\n listening()\n })\n })\n } catch (error) {\n shutdown()\n throw new CliError(`Could not start the browser login callback: ${(error as Error).message}`)\n }\n\n server.on('error', (error) => {\n fail(new CliError(`The browser login callback failed: ${error.message}`))\n })\n\n const { port } = server.address() as AddressInfo\n timer = setTimeout(() => {\n fail(new CliError(`Timed out after ${Math.round(timeoutMs / 1000)}s waiting for the browser login.`))\n }, timeoutMs)\n\n const waitForCode = (): Promise<string> => {\n return promise\n }\n\n const close = (): void => {\n fail(new CliError('Browser login callback closed.'))\n }\n\n return { redirectUri: `http://127.0.0.1:${port}/callback`, waitForCode, close }\n}\n","import { createHash, randomBytes } from 'node:crypto'\n\nexport type Pkce = { verifier: string; challenge: string; state: string }\n\nexport const challengeFor = (verifier: string): string => {\n return createHash('sha256').update(verifier).digest('base64url')\n}\n\nexport const createPkce = (): Pkce => {\n const verifier = randomBytes(32).toString('base64url')\n return { verifier, challenge: challengeFor(verifier), state: randomBytes(16).toString('base64url') }\n}\n","import type { CommandInput, CommandSpec } from '../command-spec'\nimport { API_TARGET_OPTIONS } from '../command-spec'\nimport { startCallbackServer } from '../lib/callback-server'\nimport type { ApiTarget } from '../lib/config'\nimport { resolveApiOrigin } from '../lib/config'\nimport type { StoredCredentials } from '../lib/credentials'\nimport { loadActiveTeam, saveActiveTeam, withCredentialsLock } from '../lib/credentials'\nimport type { CliDeps } from '../lib/deps'\nimport { CliError } from '../lib/errors'\nimport { buildAuthorizeUrl, failedRevocations, fetchDiscovery, maximalScopes, postToken, revokeToken } from '../lib/oauth'\nimport { createPkce } from '../lib/pkce'\nimport { request } from '../lib/request'\n\ntype LoginOptions = ApiTarget & { scopes?: string; team?: string; browser: boolean; timeout: string; reauthorize?: boolean }\n\ntype LoginIdentity = {\n user: { email: string } | null\n teams: { teamId: string; name: string | null; createdAt: string; scopes: string[] }[]\n}\n\nconst timeoutMsOf = (timeout: string): number => {\n const seconds = Number(timeout)\n if (!Number.isFinite(seconds) || seconds <= 0) {\n throw new CliError(`Invalid --timeout value: ${timeout}`)\n }\n\n return seconds * 1000\n}\n\nconst requestedScope = (scopes: string | undefined, scopesSupported: string[]): string => {\n if (scopes === undefined) {\n return maximalScopes(scopesSupported).join(' ')\n }\n\n return scopes\n .split(/[\\s,]+/)\n .filter((token) => token !== '')\n .join(' ')\n}\n\nconst loginIdentity = async (deps: CliDeps, origin: string, accessToken: string): Promise<LoginIdentity | null> => {\n try {\n const response = await request(deps, new URL('/me', origin), { headers: { authorization: `Bearer ${accessToken}` } })\n if (!response.ok) {\n return null\n }\n\n return (await response.json()) as LoginIdentity\n } catch {\n return null\n }\n}\n\nconst setLoginActiveTeam = async (\n deps: CliDeps,\n origin: string,\n identity: LoginIdentity | null,\n preferredTeamId?: string\n): Promise<string | null> => {\n if (identity === null || identity.teams.length === 0) {\n return null\n }\n\n const current = await loadActiveTeam(deps, origin)\n const validPreferred = preferredTeamId === undefined ? undefined : identity.teams.find((team) => team.teamId === preferredTeamId)\n const validCurrent = current === null ? undefined : identity.teams.find((team) => team.teamId === current)\n let team = validPreferred ?? validCurrent\n if (team === undefined && identity.teams.length === 1) {\n team = identity.teams[0]\n }\n\n if (team === undefined && deps.interactive) {\n const teamId = await deps.prompts.select(\n 'Choose the active team for CLI commands',\n identity.teams.map((candidate) => ({\n name: `${candidate.name ?? 'Untitled team'} (${candidate.teamId})`,\n value: candidate.teamId\n }))\n )\n team = identity.teams.find((candidate) => candidate.teamId === teamId)\n }\n\n if (team === undefined) {\n return null\n }\n\n await saveActiveTeam(deps, origin, team.teamId)\n return team.name ?? team.teamId\n}\n\nconst storeLogin = async (deps: CliDeps, origin: string, credentials: StoredCredentials): Promise<void> => {\n let persisted = false\n try {\n await withCredentialsLock(deps, async (transaction) => {\n const current = transaction.load(origin)\n const targets = [\n ...current.pendingRevocations,\n ...(current.login === null\n ? []\n : [{ token: current.login.refreshToken ?? current.login.accessToken, revocationEndpoint: current.login.revocationEndpoint }])\n ]\n await transaction.save(origin, { login: credentials, pendingRevocations: targets, activeTeamId: current.activeTeamId })\n persisted = true\n if (targets.length === 0) {\n return\n }\n\n const failures = await failedRevocations(deps, targets)\n const remaining = failures.map((failure) => failure.target)\n if (remaining.length > 0) {\n deps.stderr('Note: the previous session could not be revoked yet; the CLI retries on your next login or logout.\\n')\n }\n\n await transaction.save(origin, { login: credentials, pendingRevocations: remaining, activeTeamId: current.activeTeamId })\n })\n } catch (error) {\n if (persisted) {\n throw error\n }\n\n try {\n await revokeToken(deps, credentials.revocationEndpoint, credentials.refreshToken ?? credentials.accessToken)\n } catch (revocationError) {\n throw new CliError(\n `Could not save the new login (${(error as Error).message}) and could not revoke it (${(revocationError as Error).message}). Revoke Qinto CLI under User → Authorized apps in the Qinto platform.`\n )\n }\n\n throw error\n }\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as LoginOptions\n const origin = await resolveApiOrigin(deps, options)\n const timeoutMs = timeoutMsOf(options.timeout)\n const envToken = deps.env['QINTO_API_TOKEN']\n if (envToken !== undefined && envToken !== '') {\n deps.stderr('Note: QINTO_API_TOKEN is set and takes precedence over stored logins.\\n')\n }\n\n const discovery = await fetchDiscovery(deps, origin)\n const scope = requestedScope(options.scopes, discovery.scopesSupported)\n const pkce = createPkce()\n const server = await startCallbackServer(pkce.state, timeoutMs)\n let code: string\n try {\n const authorizeUrl = buildAuthorizeUrl({\n authorizationEndpoint: discovery.authorizationEndpoint,\n redirectUri: server.redirectUri,\n scope,\n state: pkce.state,\n challenge: pkce.challenge,\n team: options.team,\n reauthorize: options.reauthorize\n })\n\n deps.stderr(`Open this URL to log in:\\n\\n ${authorizeUrl}\\n\\n`)\n if (options.browser) {\n try {\n await deps.openBrowser(authorizeUrl)\n } catch {\n deps.stderr('Could not open a browser; use the URL above.\\n')\n }\n }\n\n code = await server.waitForCode()\n } finally {\n server.close()\n }\n\n const token = await postToken(deps, discovery.tokenEndpoint, {\n grant_type: 'authorization_code',\n code,\n redirect_uri: server.redirectUri,\n code_verifier: pkce.verifier\n })\n\n const credentials: StoredCredentials = {\n accessToken: token.accessToken,\n refreshToken: token.refreshToken,\n expiresAt: deps.now() + token.expiresIn * 1000,\n scope: token.scope,\n tokenEndpoint: discovery.tokenEndpoint,\n revocationEndpoint: discovery.revocationEndpoint\n }\n await storeLogin(deps, origin, credentials)\n\n const identity = await loginIdentity(deps, origin, token.accessToken)\n const activeTeam = await setLoginActiveTeam(deps, origin, identity, options.team)\n const account = identity?.user === null || identity?.user === undefined ? `Logged in to ${origin}` : `Logged in as ${identity.user.email}`\n deps.stdout(`${account}${activeTeam === null ? '.' : ` (active team ${activeTeam}).`}\\n`)\n}\n\nexport const loginCommand: CommandSpec = {\n path: ['login'],\n description: 'Log in to the Qinto platform through your browser',\n positionals: [],\n options: [\n ...API_TARGET_OPTIONS,\n { flag: '--scopes <scopes>', description: 'Request only these scopes instead of full access', type: 'string' },\n {\n flag: '--team <teamId>',\n description: 'Preselect this team during consent and prefer it as the active CLI team',\n type: 'string'\n },\n { flag: '--reauthorize', description: 'Always show consent instead of reusing prior authorization', type: 'boolean' },\n { flag: '--no-browser', description: 'Print the login URL instead of opening a browser', type: 'boolean' },\n { flag: '--timeout <seconds>', description: 'How long to wait for the browser login', type: 'string', default: '300' }\n ],\n run\n}\n","import type { CommandInput, CommandSpec } from '../command-spec'\nimport { API_TARGET_OPTIONS } from '../command-spec'\nimport type { ApiTarget } from '../lib/config'\nimport { resolveApiOrigin } from '../lib/config'\nimport { withCredentialsLock } from '../lib/credentials'\nimport type { CliDeps } from '../lib/deps'\nimport { CliError } from '../lib/errors'\nimport { failedRevocations } from '../lib/oauth'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget\n const origin = await resolveApiOrigin(deps, options)\n const envToken = deps.env['QINTO_API_TOKEN']\n if (envToken !== undefined && envToken !== '') {\n deps.stderr('Note: QINTO_API_TOKEN cannot be logged out; unset it in your shell.\\n')\n }\n\n const result = await withCredentialsLock(deps, async (transaction) => {\n const state = transaction.load(origin)\n const targets = [\n ...state.pendingRevocations,\n ...(state.login === null\n ? []\n : [{ token: state.login.refreshToken ?? state.login.accessToken, revocationEndpoint: state.login.revocationEndpoint }])\n ]\n if (targets.length === 0) {\n return 'empty' as const\n }\n\n const failures = await failedRevocations(deps, targets)\n if (failures.length > 0) {\n const first = failures[0] as (typeof failures)[number]\n throw new CliError(\n `Could not revoke the session on the server (${first.error.message}) Nothing was cleared — retry once the Qinto API is reachable, or revoke the app under User → Authorized apps in the Qinto platform.`\n )\n }\n\n await transaction.save(origin, { login: null, pendingRevocations: [], activeTeamId: state.activeTeamId })\n return state.login === null ? ('pending' as const) : ('login' as const)\n })\n\n if (result === 'empty') {\n deps.stdout(`Not logged in to ${origin}.\\n`)\n return\n }\n\n deps.stdout(result === 'pending' ? `Revoked the sessions left pending for ${origin}.\\n` : `Logged out of ${origin}.\\n`)\n}\n\nexport const logoutCommand: CommandSpec = {\n path: ['logout'],\n description: 'Revoke the current login and clear stored credentials',\n positionals: [],\n options: [...API_TARGET_OPTIONS],\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport { loadActiveTeam, saveActiveTeam } from '../../lib/credentials'\nimport type { CliDeps } from '../../lib/deps'\nimport { CliUsageError } from '../../lib/errors'\nimport { machineMode } from '../../lib/machine-mode'\nimport type { AuthorizedTeam } from '../../lib/teams'\nimport { listAuthorizedTeams, requireAuthorizedTeam } from '../../lib/teams'\n\ntype ActiveTeamOptions = ApiTarget & { json?: boolean }\n\nconst printActiveTeam = (deps: CliDeps, active: AuthorizedTeam | null, json: boolean): void => {\n if (json) {\n deps.stdout(`${JSON.stringify({ activeTeam: active }, null, 2)}\\n`)\n return\n }\n\n deps.stdout(active === null ? 'No active team is selected.\\n' : `${active.name ?? active.teamId} (${active.teamId})\\n`)\n}\n\nconst showCurrentTeam = async (deps: CliDeps, origin: string, teams: AuthorizedTeam[], json: boolean): Promise<void> => {\n const activeTeamId = await loadActiveTeam(deps, origin)\n const active = activeTeamId === null ? null : (teams.find((team) => team.teamId === activeTeamId) ?? null)\n printActiveTeam(deps, active, json)\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ActiveTeamOptions\n const origin = await resolveApiOrigin(deps, options)\n const teams = await listAuthorizedTeams(deps, origin)\n const requested = input.positionals.at(0)\n if (requested === undefined && machineMode(options, deps)) {\n await showCurrentTeam(deps, origin, teams, options.json === true)\n return\n }\n\n if (teams.length === 0) {\n throw new CliUsageError('This credential has no authorized teams.')\n }\n\n let teamId = requested\n if (teamId === undefined) {\n const activeTeamId = await loadActiveTeam(deps, origin)\n const active = activeTeamId === null ? undefined : teams.find((team) => team.teamId === activeTeamId)\n if (active !== undefined) {\n printActiveTeam(deps, active, false)\n if (!(await deps.prompts.confirm('Change the active team?', false))) {\n return\n }\n }\n\n teamId = await deps.prompts.select(\n 'Choose the active team',\n teams.map((team) => ({ name: `${team.name ?? 'Untitled team'} (${team.teamId})`, value: team.teamId })),\n active?.teamId\n )\n }\n\n const team = requireAuthorizedTeam(teams, teamId)\n await saveActiveTeam(deps, origin, team.teamId)\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ activeTeam: team }, null, 2)}\\n`)\n } else {\n deps.stdout(`Active team: ${team.name ?? team.teamId} (${team.teamId})\\n`)\n }\n}\n\nexport const activeTeamCommand: CommandSpec = {\n path: ['team', 'active'],\n description: 'Show or set the active team used by default',\n positionals: [{ name: 'teamId', description: 'Authorized team ID to make active', required: false }],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the active team as JSON', type: 'boolean' }],\n result: { type: 'active-team' },\n run\n}\n","import type { CommandInput, CommandSpec } from '../../command-spec'\nimport { API_TARGET_OPTIONS } from '../../command-spec'\nimport type { ApiTarget } from '../../lib/config'\nimport { resolveApiOrigin } from '../../lib/config'\nimport { loadActiveTeam } from '../../lib/credentials'\nimport type { CliDeps } from '../../lib/deps'\nimport { formatTable } from '../../lib/table'\nimport { listAuthorizedTeams } from '../../lib/teams'\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const origin = await resolveApiOrigin(deps, options)\n const [teams, activeTeamId] = await Promise.all([listAuthorizedTeams(deps, origin), loadActiveTeam(deps, origin)])\n const active = teams.some((team) => team.teamId === activeTeamId) ? activeTeamId : null\n if (options.json === true) {\n deps.stdout(\n `${JSON.stringify({ activeTeamId: active, teams: teams.map((team) => ({ ...team, active: team.teamId === active })) }, null, 2)}\\n`\n )\n return\n }\n\n for (const line of formatTable(\n ['Active', 'Team', 'ID', 'Scopes'],\n teams.map((team) => [team.teamId === active ? '*' : '', team.name ?? 'Untitled team', team.teamId, team.scopes.join(' ')])\n )) {\n deps.stdout(`${line}\\n`)\n }\n}\n\nexport const teamCommand: CommandSpec = {\n path: ['team'],\n description: 'List teams authorized for the current credential',\n positionals: [],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the teams as JSON', type: 'boolean' }],\n result: { type: 'team-list', activeTeamId: 'string|null' },\n run\n}\n","import { parseScopeToken } from '@qinto/oauth-grammar'\n\nimport type { CommandInput, CommandSpec } from '../command-spec'\nimport { API_TARGET_OPTIONS } from '../command-spec'\nimport type { operations } from '../generated/api'\nimport { apiRequest } from '../lib/api'\nimport type { ApiTarget } from '../lib/config'\nimport { loginHint, resolveApiOrigin } from '../lib/config'\nimport { loadActiveTeam } from '../lib/credentials'\nimport type { CliDeps } from '../lib/deps'\nimport { CliError } from '../lib/errors'\nimport { formatTable } from '../lib/table'\n\ntype MeResponse = operations['getMe']['responses']['200']['content']['application/json']\n\nconst scopeTable = (scopes: string[]): string[] => {\n const rows = scopes.map((token) => {\n const parsed = parseScopeToken(token)\n return parsed === null ? ([token, 'granted'] as const) : ([parsed.category, parsed.action] as const)\n })\n\n return formatTable(['Scope', 'Level / permission'], rows, { indent: 2 })\n}\n\nconst describeIdentity = (identity: MeResponse, activeTeamId: string | null): string[] => {\n const lines: string[] = []\n if (identity.user === null) {\n const kind = identity.tokenType === 'api_token' ? 'a team API token' : 'an OAuth token without the profile scope'\n lines.push(`Authenticated with ${kind} named '${identity.name}'.`)\n } else {\n lines.push(`Logged in as ${identity.user.email}.`)\n }\n\n if (identity.teams.length > 0) {\n lines.push(\n 'Teams:',\n ...identity.teams.map((team) => ` ${team.teamId === activeTeamId ? '*' : '-'} ${team.name ?? team.teamId} (${team.teamId})`)\n )\n }\n\n if (identity.organizations.length > 0) {\n lines.push('Organizations:', ...identity.organizations.map((organization) => ` - ${organization.name} (${organization.role})`))\n }\n\n lines.push('Scopes:', ...scopeTable(identity.scopes))\n return lines\n}\n\nconst run = async (input: CommandInput, deps: CliDeps): Promise<void> => {\n const options = input.options as ApiTarget & { json?: boolean }\n const origin = await resolveApiOrigin(deps, options)\n const response = await apiRequest(deps, origin, '/me')\n if (response.status === 401) {\n throw new CliError(`Your session is no longer valid. Run \\`${loginHint(origin)}\\` again.`)\n }\n\n if (!response.ok) {\n throw new CliError(`The Qinto API answered ${response.status}.`)\n }\n\n const identity = (await response.json()) as MeResponse\n const activeTeamId = await loadActiveTeam(deps, origin)\n if (options.json === true) {\n deps.stdout(`${JSON.stringify({ ...identity, activeTeamId }, null, 2)}\\n`)\n return\n }\n\n for (const line of describeIdentity(identity, activeTeamId)) {\n deps.stdout(`${line}\\n`)\n }\n}\n\nexport const whoamiCommand: CommandSpec = {\n path: ['whoami'],\n description: 'Show who you are logged in as, with your teams, organizations, and scopes',\n positionals: [],\n options: [...API_TARGET_OPTIONS, { flag: '--json', description: 'Print the identity as JSON', type: 'boolean' }],\n run\n}\n","import type { CommandSpec } from './command-spec'\nimport { appAddUiCommand } from './commands/app/add-ui'\nimport { appCreateCommand } from './commands/app/create'\nimport { appDevCommand } from './commands/app/dev'\nimport { appListCommand } from './commands/app/list'\nimport { appPublishCommand } from './commands/app/publish'\nimport { appRegisterCommand } from './commands/app/register'\nimport { appSecretListCommand } from './commands/app/secret-list'\nimport { appSecretSetCommand } from './commands/app/secret-set'\nimport { appStatusCommand } from './commands/app/status'\nimport { appVarListCommand } from './commands/app/var-list'\nimport { appVarSetCommand } from './commands/app/var-set'\nimport { appVersionCancelCommand } from './commands/app/version-cancel'\nimport { appVersionsCommand } from './commands/app/versions'\nimport { describeCommand } from './commands/describe'\nimport { domainDnsCommand } from './commands/domain/dns'\nimport { domainOnboardCommand } from './commands/domain/onboard'\nimport { envCommand } from './commands/env'\nimport { loginCommand } from './commands/login'\nimport { logoutCommand } from './commands/logout'\nimport { activeTeamCommand } from './commands/team/active'\nimport { teamCommand } from './commands/team/list'\nimport { whoamiCommand } from './commands/whoami'\n\nexport const COMMANDS: CommandSpec[] = [\n loginCommand,\n logoutCommand,\n whoamiCommand,\n envCommand,\n teamCommand,\n activeTeamCommand,\n domainOnboardCommand,\n domainDnsCommand,\n appCreateCommand,\n appRegisterCommand,\n appListCommand,\n appAddUiCommand,\n appDevCommand,\n appPublishCommand,\n appStatusCommand,\n appVersionsCommand,\n appVersionCancelCommand,\n appVarSetCommand,\n appVarListCommand,\n appSecretSetCommand,\n appSecretListCommand,\n describeCommand\n]\n","import { Command, CommanderError, Option } from 'commander'\n\nimport packageJson from '../package.json'\nimport type { CommandInput, CommandSpec, OptionSpec } from './command-spec'\nimport type { CliDeps } from './lib/deps'\nimport { CliUsageError } from './lib/errors'\nimport { flagName } from './manifest'\nimport { COMMANDS } from './registry'\n\nclass HandledError extends Error {\n readonly exitCode: 1 | 2 | 130\n\n constructor(message: string, exitCode: 1 | 2 | 130) {\n super(message)\n this.exitCode = exitCode\n }\n}\n\nconst toOption = (spec: OptionSpec): Option => {\n const option = new Option(spec.flag, spec.description)\n if (spec.required === true) {\n option.makeOptionMandatory()\n }\n\n if (spec.enum !== undefined) {\n option.choices(spec.enum)\n }\n\n if (spec.default !== undefined) {\n option.default(spec.default)\n }\n\n if (spec.env !== undefined) {\n option.env(spec.env)\n }\n\n return option\n}\n\nconst runAction = async (spec: CommandSpec, input: CommandInput, deps: CliDeps): Promise<void> => {\n try {\n await spec.run(input, deps)\n } catch (error) {\n if (error instanceof Error && error.name === 'ExitPromptError') {\n deps.stderr('Aborted.\\n')\n throw new HandledError('Aborted.', 130)\n }\n\n const message = error instanceof Error ? error.message : String(error)\n deps.stderr(input.options['json'] === true ? `${JSON.stringify({ error: message })}\\n` : `${message}\\n`)\n throw new HandledError(message, error instanceof CliUsageError ? 2 : 1)\n }\n}\n\nexport const buildProgram = (deps: CliDeps, commands: CommandSpec[] = COMMANDS, suppressUsageErrors = false): Command => {\n const program = new Command('qinto')\n program.description('The Qinto platform CLI')\n program.version(packageJson.version)\n const wire = (command: Command): void => {\n command.exitOverride()\n command.configureOutput({\n writeOut: (text) => {\n deps.stdout(text)\n },\n writeErr: (text) => {\n if (!suppressUsageErrors) {\n deps.stderr(text)\n }\n }\n })\n }\n\n wire(program)\n const nodes = new Map<string, Command>([['', program]])\n const nodeFor = (path: readonly string[]): Command => {\n const key = path.join(' ')\n const existing = nodes.get(key)\n if (existing !== undefined) {\n return existing\n }\n\n const parentPath = path.slice(0, -1)\n const parent = nodeFor(parentPath)\n const command = new Command(path.at(-1) as string)\n wire(command)\n parent.addCommand(command)\n nodes.set(key, command)\n return command\n }\n\n for (const spec of commands) {\n const command = nodeFor(spec.path)\n command.description(spec.description)\n for (const positional of spec.positionals) {\n const suffix = positional.variadic === true ? '...' : ''\n command.argument(positional.required ? `<${positional.name}${suffix}>` : `[${positional.name}${suffix}]`, positional.description)\n }\n\n for (const option of spec.options) {\n command.addOption(toOption(option))\n }\n\n command.action(async (...args) => {\n const positionals = args.slice(0, spec.positionals.length).flatMap((value) => {\n if (typeof value === 'string') {\n return [value]\n }\n\n return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : []\n })\n await runAction(spec, { options: command.opts(), positionals }, deps)\n })\n }\n\n return program\n}\n\nconst jsonUsageRequested = (argv: string[]): boolean => {\n const command = [...COMMANDS]\n .sort((left, right) => right.path.length - left.path.length)\n .find((spec) => spec.path.every((part, index) => argv.at(index) === part))\n if (command === undefined || !argv.includes('--json')) {\n return false\n }\n\n return command.options.some((option) => flagName(option.flag) === 'json')\n}\n\nexport const runProgram = async (deps: CliDeps, argv: string[]): Promise<number> => {\n const effectiveArgv = argv.length === 0 ? ['--help'] : argv\n const jsonUsage = jsonUsageRequested(effectiveArgv)\n try {\n await buildProgram(deps, COMMANDS, jsonUsage).parseAsync(effectiveArgv, { from: 'user' })\n return 0\n } catch (error) {\n if (error instanceof HandledError) {\n return error.exitCode\n }\n\n if (error instanceof CommanderError) {\n if (error.exitCode === 0) {\n return 0\n }\n\n if (jsonUsage) {\n deps.stderr(`${JSON.stringify({ error: error.message.replace(/^error: /, '') })}\\n`)\n }\n\n return 2\n }\n\n throw error\n }\n}\n","import { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nimport { confirm, input, password, select } from '@inquirer/prompts'\nimport open from 'open'\n\nimport type { CliDeps } from './lib/deps'\nimport { runProgram } from './program'\n\nconst deps: CliDeps = {\n fetch: globalThis.fetch,\n openBrowser: async (url) => {\n await open(url)\n },\n env: process.env,\n stdout: (text) => {\n process.stdout.write(text)\n },\n stderr: (text) => {\n process.stderr.write(text)\n },\n credentialsPath: join(homedir(), '.qinto', 'credentials.json'),\n settingsPath: join(homedir(), '.qinto', 'settings.json'),\n now: Date.now,\n interactive: process.stdin.isTTY === true && process.stderr.isTTY === true,\n readStdin: async () => {\n const chunks: Buffer[] = []\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer)\n }\n\n return Buffer.concat(chunks).toString('utf8')\n },\n prompts: {\n // Prompts render on stderr so a redirected stdout stays parseable and the UI stays visible.\n select: async (message, choices, initial) => {\n return select({ message, choices, default: initial }, { input: process.stdin, output: process.stderr })\n },\n input: async (message, initial) => {\n return input({ message, default: initial }, { input: process.stdin, output: process.stderr })\n },\n confirm: async (message, initial) => {\n return confirm({ message, default: initial }, { input: process.stdin, output: process.stderr })\n },\n password: async (message) => {\n return password({ message, mask: '*' }, { input: process.stdin, output: process.stderr })\n }\n }\n}\n\ntry {\n process.exitCode = await runProgram(deps, process.argv.slice(2))\n} catch (error) {\n process.stderr.write(`${error instanceof Error ? error.message : String(error)}\\n`)\n process.exitCode = 1\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;aACM,qBAAmB,IAAI,IAAI,CADZ,SAAS,KACa,CAAC;AAC5C,SAAS,GAAa,GAAO;CACzB,OAAO,GAAiB,IAAI,CAAK;AACrC;AACA,SAAgB,KAAwB;CACpC,IAAM,IAAM,QAAQ,IAAI;CAGxB,OAFK,IAEE,MAAM,KAAK,IAAI,IAAI,EACrB,YAAY,CAAC,CACb,MAAM,QAAQ,CAAC,CACf,OAAO,EAAY,CAAC,CAAC,IAJf,CAAC;AAKhB;AACA,IAAa,MAAW,GAAK,IAAc,CAAC,MAE5C,EAAI,SAAS,QAER,EAAY,SAAS,KAAK,KAAK,EAAI,S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