@manifest-network/manifest-agent-core 0.14.0 → 0.16.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/dist/close-lease.d.ts.map +1 -1
- package/dist/close-lease.js +15 -3
- package/dist/close-lease.js.map +1 -1
- package/dist/deploy-app.d.ts +2 -2
- package/dist/deploy-app.d.ts.map +1 -1
- package/dist/deploy-app.js +84 -37
- package/dist/deploy-app.js.map +1 -1
- package/dist/deploy-app.test-d.d.ts +1 -0
- package/dist/deploy-app.test-d.js +11 -0
- package/dist/deploy-app.test-d.js.map +1 -0
- package/dist/guarded-fetch.d.ts +2 -0
- package/dist/guarded-fetch.js +2 -0
- package/dist/index.d.ts +2 -3
- package/dist/index.js +1 -2
- package/dist/internals/cancellation.d.ts +57 -0
- package/dist/internals/cancellation.d.ts.map +1 -0
- package/dist/internals/cancellation.js +79 -0
- package/dist/internals/cancellation.js.map +1 -0
- package/dist/internals/inspect-image.js +1 -1
- package/dist/internals/inspect-image.js.map +1 -1
- package/dist/internals/render-intent-recap.d.ts +13 -11
- package/dist/internals/render-intent-recap.d.ts.map +1 -1
- package/dist/internals/render-intent-recap.js +5 -4
- package/dist/internals/render-intent-recap.js.map +1 -1
- package/dist/internals/spec-normalize.d.ts +34 -28
- package/dist/internals/spec-normalize.d.ts.map +1 -1
- package/dist/internals/spec-normalize.js +28 -22
- package/dist/internals/spec-normalize.js.map +1 -1
- package/dist/manage-domain.d.ts.map +1 -1
- package/dist/manage-domain.js +34 -8
- package/dist/manage-domain.js.map +1 -1
- package/dist/node_modules/@vitest/pretty-format/dist/index.js +888 -0
- package/dist/node_modules/@vitest/pretty-format/dist/index.js.map +1 -0
- package/dist/node_modules/@vitest/runner/dist/chunk-artifact.js +1500 -0
- package/dist/node_modules/@vitest/runner/dist/chunk-artifact.js.map +1 -0
- package/dist/node_modules/@vitest/runner/dist/index.js +1 -0
- package/dist/node_modules/@vitest/runner/dist/utils.js +1 -0
- package/dist/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +82 -0
- package/dist/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js.map +1 -0
- package/dist/node_modules/@vitest/utils/dist/display.js +558 -0
- package/dist/node_modules/@vitest/utils/dist/display.js.map +1 -0
- package/dist/node_modules/@vitest/utils/dist/helpers.js +68 -0
- package/dist/node_modules/@vitest/utils/dist/helpers.js.map +1 -0
- package/dist/node_modules/@vitest/utils/dist/source-map.js +95 -0
- package/dist/node_modules/@vitest/utils/dist/source-map.js.map +1 -0
- package/dist/node_modules/@vitest/utils/dist/timers.js +20 -0
- package/dist/node_modules/@vitest/utils/dist/timers.js.map +1 -0
- package/dist/node_modules/tinyrainbow/dist/index.js +86 -0
- package/dist/node_modules/tinyrainbow/dist/index.js.map +1 -0
- package/dist/node_modules/vite/dist/node/module-runner.js +22 -0
- package/dist/node_modules/vite/dist/node/module-runner.js.map +1 -0
- package/dist/node_modules/vitest/dist/index.js +6 -0
- package/dist/troubleshoot.d.ts.map +1 -1
- package/dist/troubleshoot.js +11 -1
- package/dist/troubleshoot.js.map +1 -1
- package/dist/types.d.ts +30 -51
- package/dist/types.d.ts.map +1 -1
- package/package.json +15 -7
- package/dist/internals/build-fred-input.d.ts +0 -46
- package/dist/internals/build-fred-input.d.ts.map +0 -1
- package/dist/internals/build-fred-input.js +0 -160
- package/dist/internals/build-fred-input.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"spec-normalize.js","names":[],"sources":["../../src/internals/spec-normalize.ts"],"sourcesContent":["import type {\n DeploySpec,\n ServiceDef,\n SingleServiceSpec,\n SpecSummary,\n StackSpec,\n} from '../types.js';\n\n/**\n * Spec normalization + summarization helpers. Exports `isStack`,\n * `firstImage`, `normalizeServices`, `summarizeSpec`, and `validateSpec`\n * (the latter surfaces pre-broadcast shape violations).\n *\n * Two spec shapes are supported (defined in `types.ts`; `size?` added in\n * ENG-275):\n * - **services-map (StackSpec)** — `{ services: { <name>: ServiceDef }, customDomain?, serviceName?, size? }`\n * - **legacy single-service (SingleServiceSpec)** — `{ image, port?, env?, customDomain?, size? }`\n *\n * `normalizeServices` collapses the two shapes into a single iterable form\n * so callers (Plan summary, manifest builder, etc.) walk one structure\n * regardless of which form the user passed.\n *\n * Validation: `validateSpec` throws a plain `TypeError` on shape violations\n * — agent-core has no workspace dep on `@manifest-network/manifest-mcp-core`\n * in PR 1/2 (per parent's REV 1), so `ManifestMCPError` isn't available\n * here. PR 3's high-level `deployApp` re-wraps `TypeError` into\n * `ManifestMCPError(INVALID_CONFIG)` at the public-API boundary.\n */\n\n/**\n * True when `spec` uses the services-map shape (StackSpec). Mirrors\n * `_spec.cjs#isStack`: `services` is a non-null, non-array object.\n */\nexport function isStackSpec(\n spec: DeploySpec | null | undefined,\n): spec is StackSpec {\n if (spec === null || spec === undefined || typeof spec !== 'object')\n return false;\n const services = (spec as { services?: unknown }).services;\n return (\n services !== null &&\n typeof services === 'object' &&\n !Array.isArray(services)\n );\n}\n\n/**\n * Return the canonical first image string for a spec. For legacy single-\n * service: `spec.image`. For stack: the first non-empty `image` in\n * `Object.values(spec.services)`. Returns `null` when neither shape\n * carries an image (or `spec` is malformed).\n */\nexport function firstImage(spec: DeploySpec | null | undefined): string | null {\n if (spec === null || spec === undefined || typeof spec !== 'object')\n return null;\n const single = spec as Partial<SingleServiceSpec>;\n if (typeof single.image === 'string' && single.image.length > 0) {\n return single.image;\n }\n if (isStackSpec(spec)) {\n for (const svc of Object.values(spec.services)) {\n if (svc !== null && typeof svc === 'object') {\n const image = (svc as Partial<ServiceDef>).image;\n if (typeof image === 'string' && image.length > 0) return image;\n }\n }\n }\n return null;\n}\n\n/**\n * Walk a spec as `[{name, raw}]` where:\n * - `name === null` for legacy single-service (only one entry, raw is the spec itself).\n * - `name === <key>` for each services-map entry; `raw` is the per-service ServiceDef.\n *\n * Stable iteration order matches `Object.entries` (insertion order in v8/modern engines).\n */\nexport interface NormalizedService {\n /** `null` for legacy single-service; the services-map key for stack leases. */\n name: string | null;\n /** The per-service object exactly as the spec stores it. No field projection. */\n raw: ServiceDef | SingleServiceSpec;\n}\n\nexport function normalizeServices(\n spec: DeploySpec | null | undefined,\n): NormalizedService[] {\n if (isStackSpec(spec)) {\n return Object.entries(spec.services).map(([name, raw]) => ({\n name,\n raw: (raw ?? {}) as ServiceDef,\n }));\n }\n return [\n {\n name: null,\n raw: (spec ?? {}) as SingleServiceSpec,\n },\n ];\n}\n\n/**\n * Produce the frozen `SpecSummary` shape for inclusion in the `Plan`\n * (camelCase fields: `serviceCount`, etc.).\n *\n * Port count rules:\n * - SingleServiceSpec `port: number` → +1 port.\n * - SingleServiceSpec `port: number[]` → +length ports.\n * - ServiceDef `ports: number[]` (per type) → +length ports.\n * - ServiceDef `ports` shaped as a Record (older codepath) → +key count.\n *\n * Env key uniqueness is computed across services (one `env_keys` set\n * spans the whole spec); `envCount` is the size of that set; `envKeys`\n * is sorted ascending.\n */\nexport function summarizeSpec(spec: DeploySpec): SpecSummary {\n const format: 'single' | 'stack' = isStackSpec(spec) ? 'stack' : 'single';\n const services = normalizeServices(spec);\n\n let portCount = 0;\n const envKeys = new Set<string>();\n const images: string[] = [];\n\n for (const { raw: svc } of services) {\n if (svc !== null && typeof svc === 'object') {\n const svcRecord = svc as unknown as Record<string, unknown>;\n const image = svcRecord.image;\n if (typeof image === 'string' && image.length > 0) images.push(image);\n\n const port = svcRecord.port;\n if (typeof port === 'number') portCount += 1;\n else if (Array.isArray(port)) portCount += port.length;\n\n const ports = svcRecord.ports;\n if (Array.isArray(ports)) {\n portCount += ports.length;\n } else if (ports !== null && typeof ports === 'object') {\n portCount += Object.keys(ports).length;\n }\n\n const env = svcRecord.env;\n if (env !== null && typeof env === 'object' && !Array.isArray(env)) {\n for (const k of Object.keys(env)) envKeys.add(k);\n }\n }\n }\n\n return {\n format,\n serviceCount: services.length,\n portCount,\n envCount: envKeys.size,\n envKeys: Array.from(envKeys).sort(),\n images,\n };\n}\n\n/**\n * Validate a `DeploySpec` shape pre-broadcast. Throws `TypeError` on the\n * first violation. The frozen type union (`SingleServiceSpec | StackSpec`)\n * already enforces most structural rules at compile time; this runtime\n * check defends against `unknown`-cast callers and `JSON.parse`-decoded\n * inputs.\n *\n * Rules (mirror fred's `deployApp.ts` input validation):\n * - `spec` must be a non-null object.\n * - Stack: `services` must have ≥1 entry; each entry's `image` must be a\n * non-empty string.\n * - Single: `image` must be a non-empty string.\n * - Mutually exclusive `image` AND `services` not allowed.\n *\n * The high-level `deployApp` in PR 3 layers domain checks on top\n * (`customDomain` shape, `serviceName` membership, etc.).\n */\nexport function validateSpec(spec: DeploySpec | null | undefined): void {\n if (spec === null || spec === undefined || typeof spec !== 'object') {\n throw new TypeError('validateSpec: spec must be a non-null object');\n }\n const record = spec as unknown as Record<string, unknown>;\n\n // Mutual-exclusion gate uses KEY presence (not value validity). This\n // closes the bypass where a caller supplies a malformed `image` value\n // (empty string, number, null) alongside a valid `services` map: the\n // value-based check would silently treat `image` as \"absent\" and accept\n // the spec, but the caller's intent was ambiguous (which shape did they\n // mean?). Rejecting on key-presence forces the caller to delete one key\n // before submission and removes the ambiguity.\n const hasImageKey = 'image' in record;\n const hasServicesKey = 'services' in record;\n if (hasImageKey && hasServicesKey) {\n throw new TypeError(\n 'validateSpec: spec has both `image` and `services` keys; these are mutually exclusive (regardless of value validity)',\n );\n }\n\n // Downstream value-validity check (after the mutual-exclusion gate has\n // ruled out the ambiguous case). An `image` key with a non-string or\n // empty-string value still fails here when `services` is absent.\n const hasImage = typeof record.image === 'string' && record.image.length > 0;\n const hasServices = isStackSpec(spec);\n if (!hasImage && !hasServices) {\n throw new TypeError(\n 'validateSpec: spec must declare either `image` (SingleServiceSpec) or `services` (StackSpec)',\n );\n }\n\n // Copilot review fix (PR #58 r3266786899): `customDomain` shape at\n // the boundary. The orchestrator's `buildFredDeployInput`\n // (`deploy-app.ts:701`) uses a `if (customDomain)` truthiness check,\n // which silently drops `''`, `null`, `false`, `0`, `NaN` from the\n // emitted `fredInput`. A user spec like `{ ..., customDomain: '' }`\n // passes validation today, fred receives `fredInput` WITHOUT the\n // domain, deploy proceeds — the user's requested domain silently\n // not claimed, no error signal.\n //\n // Boundary check: when `customDomain` is present, it must be a\n // non-empty string. `undefined` (key absent) is fine; that's the\n // \"no domain requested\" case. Fires before the stack-customDomain\n // serviceName check (r3249684707) so the user gets a clear\n // customDomain-shape error rather than a misleading\n // requires-serviceName one.\n // Copilot review fix (PR #58 r3267373001): reject whitespace-only\n // strings AND strings with surrounding whitespace (option (i) from\n // the team-lead's brief — strict; let the caller send a clean,\n // already-trimmed value rather than silently trim for them). The\n // prior `cd.length === 0` predicate accepted `' '`, `'\\t\\n'`,\n // and `' app.example.com '`; fred would either accept the\n // surrounding whitespace as part of the domain (correctness bug)\n // or trim-and-reject (worse UX than agent-core's clear error).\n if ('customDomain' in record) {\n const cd = record.customDomain;\n if (cd !== undefined) {\n const isCleanNonEmptyString =\n typeof cd === 'string' && cd.length > 0 && cd.trim() === cd;\n if (!isCleanNonEmptyString) {\n const got =\n typeof cd === 'string'\n ? cd.trim().length === 0\n ? `\"${cd}\"`\n : `\"${cd}\" (has surrounding whitespace)`\n : cd === null\n ? 'null'\n : typeof cd;\n throw new TypeError(\n `validateSpec: \\`customDomain\\` must be a non-empty trimmed string or absent (got ${got}).`,\n );\n }\n }\n }\n\n if (hasServices) {\n const entries = Object.entries(spec.services);\n if (entries.length === 0) {\n throw new TypeError(\n 'validateSpec: stack spec `services` must have at least one entry',\n );\n }\n for (const [name, svc] of entries) {\n if (svc === null || typeof svc !== 'object') {\n throw new TypeError(\n `validateSpec: stack service \"${name}\" must be a non-null object`,\n );\n }\n const image = (svc as Partial<ServiceDef>).image;\n if (typeof image !== 'string' || image.length === 0) {\n throw new TypeError(\n `validateSpec: stack service \"${name}\" must declare a non-empty \\`image\\` string`,\n );\n }\n }\n\n // Copilot review fix (PR #58 r3249684707): a stack spec with a\n // `customDomain` MUST declare which service receives the domain\n // via `serviceName`, and that value must be a key in `services`.\n // Without this guard, `customDomainServiceOf` in `deploy-app.ts`\n // returns `undefined`, planning proceeds with no target, renderers\n // misrepresent the claim, and fred rejects the set-domain tx\n // ONLY after `create-lease` commits — leaving the user with an\n // orphan lease + a failed domain claim. Catching this at\n // validate-time is fail-fast at the boundary.\n //\n // Single-service specs are unaffected: their `customDomain` is\n // claimed against the implicit single lease item — no\n // serviceName disambiguation needed.\n const stackDomain = (spec as Partial<StackSpec>).customDomain;\n if (typeof stackDomain === 'string' && stackDomain.length > 0) {\n const stackServiceName = (spec as Partial<StackSpec>).serviceName;\n if (\n typeof stackServiceName !== 'string' ||\n stackServiceName.length === 0\n ) {\n throw new TypeError(\n 'validateSpec: stack spec with `customDomain` requires `serviceName` identifying which service receives the domain.',\n );\n }\n // Copilot review fix (PR #58 r3250331968): use an own-key check.\n // The `in` operator walks the prototype chain, so `serviceName:\n // 'constructor'` (or `'toString'`, `'hasOwnProperty'`, etc.)\n // would falsely pass against a `services` map that doesn't\n // declare those names. Mirrors fred's own choice at\n // `packages/fred/src/tools/deployApp.ts:254` for cross-package\n // symmetry. `Object.keys().includes()` (not `Object.hasOwn`,\n // which is ES2022 and our `tsdown.config.ts` targets ES2020).\n if (!Object.keys(spec.services).includes(stackServiceName)) {\n throw new TypeError(\n `validateSpec: stack spec \\`serviceName\\` \"${stackServiceName}\" must be a key in \\`services\\` (got services: [${Object.keys(spec.services).join(', ')}]).`,\n );\n }\n }\n } else {\n // Single-service spec port requirement.\n //\n // Copilot review fix (PR #58 r3249097051): fred's image-mode rejects\n // portless inputs with `port is required when using image`\n // (`packages/fred/src/tools/deployApp.ts:202` +\n // `packages/fred/src/tools/buildManifestPreview.ts:181`). Without\n // an agent-core boundary check the orchestrator silently passed\n // `port: undefined` through `buildManifestPreviewInput` /\n // `buildFredDeployInput`, surfacing fred's error mid-orchestration\n // (after readiness check + plan render). Failing fast at validate\n // time produces a clearer message and avoids partial work.\n //\n // The escape hatch for genuinely internal-only services is the\n // stack spec — service-level `ports` is optional, so a stack with\n // `{ services: { mysvc: { image, env } } }` deploys without ports.\n //\n // Copilot review fix (PR #58 r3249294877): tighten the predicate to\n // a finite positive integer in the TCP port range. The prior\n // `typeof p === 'number'` check accepted `0`, `NaN`, `Infinity`,\n // negative numbers, non-integers, and out-of-range ports —\n // partially defeating the fail-fast intent. Fred catches `port: 0`\n // via `!input.port`, but the other shapes either flow through to a\n // less helpful error or get coerced silently. The shared predicate\n // `isValidPortNumber` (below) is the single source of truth.\n const port = (spec as Partial<SingleServiceSpec>).port;\n const hasValidPort =\n isValidPortNumber(port) ||\n (Array.isArray(port) && port.length > 0 && port.every(isValidPortNumber));\n if (!hasValidPort) {\n throw new TypeError(\n 'validateSpec: single-service specs require at least one port (port must be a finite positive integer in the TCP range (1-65535), or a non-empty array of such); got ' +\n `port=${JSON.stringify(port)}. For internal-only services, use a stack spec instead.`,\n );\n }\n }\n}\n\n/**\n * Predicate: `p` is a finite positive integer in the TCP port range\n * (1-65535). Used by `validateSpec` to gate single-service `port`\n * shapes against the broad `typeof === 'number'` bypass.\n *\n * Co-located in this module because it's exclusive to the port-\n * validation boundary; if a future caller needs the same check,\n * promote it to a shared utility then.\n */\nfunction isValidPortNumber(p: unknown): p is number {\n return typeof p === 'number' && Number.isInteger(p) && p > 0 && p <= 65535;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,YACd,MACmB;CACnB,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,OAAO,SAAS,UACzD,OAAO;CACT,MAAM,WAAY,KAAgC;CAClD,OACE,aAAa,QACb,OAAO,aAAa,YACpB,CAAC,MAAM,QAAQ,QAAQ;AAE3B;;;;;;;AAQA,SAAgB,WAAW,MAAoD;CAC7E,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,OAAO,SAAS,UACzD,OAAO;CACT,MAAM,SAAS;CACf,IAAI,OAAO,OAAO,UAAU,YAAY,OAAO,MAAM,SAAS,GAC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IAAI,UACR,gCAAgC,KAAK,4CACvC;EAEJ;EAeA,MAAM,cAAe,KAA4B;EACjD,IAAI,OAAO,gBAAgB,YAAY,YAAY,SAAS,GAAG;GAC7D,MAAM,mBAAoB,KAA4B;GACtD,IACE,OAAO,qBAAqB,YAC5B,iBAAiB,WAAW,GAE5B,MAAM,IAAI,UACR,oHACF;GAUF,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,EAAE,SAAS,gBAAgB,GACvD,MAAM,IAAI,UACR,6CAA6C,iBAAiB,kDAAkD,OAAO,KAAK,KAAK,QAAQ,EAAE,KAAK,IAAI,EAAE,IACxJ;EAEJ;CACF,OAAO;EAyBL,MAAM,OAAQ,KAAoC;EAIlD,IAAI,EAFF,kBAAkB,IAAI,KACrB,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,KAAK,KAAK,MAAM,iBAAiB,IAEvE,MAAM,IAAI,UACR,4KACU,KAAK,UAAU,IAAI,EAAE,wDACjC;CAEJ;AACF;;;;;;;;;;AAWA,SAAS,kBAAkB,GAAyB;CAClD,OAAO,OAAO,MAAM,YAAY,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,KAAK;AACvE"}
|
|
1
|
+
{"version":3,"file":"spec-normalize.js","names":[],"sources":["../../src/internals/spec-normalize.ts"],"sourcesContent":["import type { AppDeploySpec, ServiceConfig, SpecSummary } from '../types.js';\n\n/**\n * Spec normalization + summarization helpers. Exports `isStack`,\n * `firstImage`, `normalizeServices`, `summarizeSpec`, and `validateSpec`\n * (the latter surfaces pre-broadcast shape violations).\n *\n * The single canonical spec type (`AppDeploySpec`, ENG-310) covers two\n * shapes, discriminated by the presence of `services`:\n * - **stack** — `{ services: { <name>: ServiceConfig }, customDomain?, serviceName?, size, ... }`\n * - **single-service** — `{ image, port?, env?, customDomain?, size, ... }`\n *\n * `normalizeServices` collapses the two shapes into a single iterable form\n * so callers (Plan summary, manifest builder, etc.) walk one structure\n * regardless of which form the user passed.\n *\n * Validation: `validateSpec` stays a `void` `TypeError`-thrower on shape\n * violations. The high-level `deployApp` entry wrappers\n * (`deploy-app.ts`) map that `TypeError` to\n * `ManifestMCPError(INVALID_CONFIG)` at the public-API boundary, so this\n * helper does not depend on core's error type directly.\n */\n\n/**\n * True when `spec` uses the services-map (stack) shape. Discriminates on\n * the canonical `services` key being present and defined (ENG-310). The\n * non-null-object / non-array guard is retained as defense-in-depth so an\n * `unknown`-cast caller smuggling `services: null` / `[]` / `'str'` is NOT\n * mistaken for a stack (which would crash `Object.entries` downstream).\n */\nexport function isStackSpec(\n spec: unknown,\n): spec is AppDeploySpec & { services: Record<string, ServiceConfig> } {\n if (spec === null || spec === undefined || typeof spec !== 'object')\n return false;\n const record = spec as { services?: unknown };\n if (!('services' in record) || record.services === undefined) return false;\n const services = record.services;\n return (\n services !== null &&\n typeof services === 'object' &&\n !Array.isArray(services)\n );\n}\n\n/**\n * Return the canonical first image string for a spec. For legacy single-\n * service: `spec.image`. For stack: the first non-empty `image` in\n * `Object.values(spec.services)`. Returns `null` when neither shape\n * carries an image (or `spec` is malformed).\n */\nexport function firstImage(spec: unknown): string | null {\n if (spec === null || spec === undefined || typeof spec !== 'object')\n return null;\n const single = spec as Partial<AppDeploySpec>;\n if (typeof single.image === 'string' && single.image.length > 0) {\n return single.image;\n }\n if (isStackSpec(spec)) {\n for (const svc of Object.values(spec.services)) {\n if (svc !== null && typeof svc === 'object') {\n const image = (svc as Partial<ServiceConfig>).image;\n if (typeof image === 'string' && image.length > 0) return image;\n }\n }\n }\n return null;\n}\n\n/**\n * Walk a spec as `[{name, raw}]` where:\n * - `name === null` for legacy single-service (only one entry, raw is the spec itself).\n * - `name === <key>` for each services-map entry; `raw` is the per-service ServiceConfig.\n *\n * Stable iteration order matches `Object.entries` (insertion order in v8/modern engines).\n */\nexport interface NormalizedService {\n /** `null` for legacy single-service; the services-map key for stack leases. */\n name: string | null;\n /** The per-service object exactly as the spec stores it. No field projection. */\n raw: ServiceConfig | AppDeploySpec;\n}\n\nexport function normalizeServices(spec: unknown): NormalizedService[] {\n if (isStackSpec(spec)) {\n return Object.entries(spec.services).map(([name, raw]) => ({\n name,\n raw: (raw ?? {}) as ServiceConfig,\n }));\n }\n return [\n {\n name: null,\n raw: (spec ?? {}) as AppDeploySpec,\n },\n ];\n}\n\n/**\n * Produce the frozen `SpecSummary` shape for inclusion in the `Plan`\n * (camelCase fields: `serviceCount`, etc.).\n *\n * Port count rules:\n * - single-service `port: number` → +1 port.\n * - `ServiceConfig.ports` map (canonical `{ '<port>/<proto>': {} }`) →\n * +key count.\n * - A bare `port`/`ports` array smuggled in by an `unknown`-cast caller\n * is still counted defensively (+1 / +length) below.\n *\n * Env key uniqueness is computed across services (one `env_keys` set\n * spans the whole spec); `envCount` is the size of that set; `envKeys`\n * is sorted ascending.\n */\nexport function summarizeSpec(spec: unknown): SpecSummary {\n const format: 'single' | 'stack' = isStackSpec(spec) ? 'stack' : 'single';\n const services = normalizeServices(spec);\n\n let portCount = 0;\n const envKeys = new Set<string>();\n const images: string[] = [];\n\n for (const { raw: svc } of services) {\n if (svc !== null && typeof svc === 'object') {\n const svcRecord = svc as unknown as Record<string, unknown>;\n const image = svcRecord.image;\n if (typeof image === 'string' && image.length > 0) images.push(image);\n\n const port = svcRecord.port;\n if (typeof port === 'number') portCount += 1;\n else if (Array.isArray(port)) portCount += port.length;\n\n const ports = svcRecord.ports;\n if (Array.isArray(ports)) {\n portCount += ports.length;\n } else if (ports !== null && typeof ports === 'object') {\n portCount += Object.keys(ports).length;\n }\n\n const env = svcRecord.env;\n if (env !== null && typeof env === 'object' && !Array.isArray(env)) {\n for (const k of Object.keys(env)) envKeys.add(k);\n }\n }\n }\n\n return {\n format,\n serviceCount: services.length,\n portCount,\n envCount: envKeys.size,\n envKeys: Array.from(envKeys).sort(),\n images,\n };\n}\n\n/**\n * Validate an `AppDeploySpec` shape pre-broadcast. Throws `TypeError` on\n * the first violation. The canonical type already enforces most\n * structural rules at compile time; this runtime check defends against\n * `unknown`-cast callers and `JSON.parse`-decoded inputs (and the\n * image-XOR-services invariant the type cannot express).\n *\n * Rules (mirror fred's `deployApp.ts` input validation):\n * - `spec` must be a non-null object.\n * - Stack: `services` must have ≥1 entry; each entry's `image` must be a\n * non-empty string.\n * - Single: `image` must be a non-empty string.\n * - Mutually exclusive `image` AND `services` not allowed.\n *\n * The high-level `deployApp` in PR 3 layers domain checks on top\n * (`customDomain` shape, `serviceName` membership, etc.).\n */\nexport function validateSpec(spec: unknown): void {\n if (spec === null || spec === undefined || typeof spec !== 'object') {\n throw new TypeError('validateSpec: spec must be a non-null object');\n }\n const record = spec as unknown as Record<string, unknown>;\n\n // Mutual-exclusion gate uses KEY presence (not value validity). This\n // closes the bypass where a caller supplies a malformed `image` value\n // (empty string, number, null) alongside a valid `services` map: the\n // value-based check would silently treat `image` as \"absent\" and accept\n // the spec, but the caller's intent was ambiguous (which shape did they\n // mean?). Rejecting on key-presence forces the caller to delete one key\n // before submission and removes the ambiguity.\n const hasImageKey = 'image' in record;\n const hasServicesKey = 'services' in record;\n if (hasImageKey && hasServicesKey) {\n throw new TypeError(\n 'validateSpec: spec has both `image` and `services` keys; these are mutually exclusive (regardless of value validity)',\n );\n }\n\n // Downstream value-validity check (after the mutual-exclusion gate has\n // ruled out the ambiguous case). An `image` key with a non-string or\n // empty-string value still fails here when `services` is absent.\n const hasImage = typeof record.image === 'string' && record.image.length > 0;\n const hasServices = isStackSpec(spec);\n if (!hasImage && !hasServices) {\n throw new TypeError(\n 'validateSpec: spec must declare either `image` (single-service) or `services` (stack)',\n );\n }\n\n // Copilot review fix (PR #58 r3266786899): `customDomain` shape at\n // the boundary. Historically the orchestrator's `buildFredDeployInput`\n // mapper used an `if (customDomain)` truthiness check that silently\n // dropped `''`, `null`, `false`, `0`, `NaN` from the emitted\n // `fredInput`, so a spec like `{ ..., customDomain: '' }` deployed with\n // the domain silently not claimed. ENG-310 deleted that mapper: the\n // loss-free broadcast spread now forwards `customDomain` to fred\n // verbatim, so an empty/whitespace value would instead reach fred as a\n // claim for an invalid domain. Either way the fix is the same — reject\n // a malformed `customDomain` here, at the boundary, before it can do harm.\n //\n // Boundary check: when `customDomain` is present, it must be a\n // non-empty string. `undefined` (key absent) is fine; that's the\n // \"no domain requested\" case. Fires before the stack-customDomain\n // serviceName check (r3249684707) so the user gets a clear\n // customDomain-shape error rather than a misleading\n // requires-serviceName one.\n // Copilot review fix (PR #58 r3267373001): reject whitespace-only\n // strings AND strings with surrounding whitespace (option (i) from\n // the team-lead's brief — strict; let the caller send a clean,\n // already-trimmed value rather than silently trim for them). The\n // prior `cd.length === 0` predicate accepted `' '`, `'\\t\\n'`,\n // and `' app.example.com '`; fred would either accept the\n // surrounding whitespace as part of the domain (correctness bug)\n // or trim-and-reject (worse UX than agent-core's clear error).\n if ('customDomain' in record) {\n const cd = record.customDomain;\n if (cd !== undefined) {\n const isCleanNonEmptyString =\n typeof cd === 'string' && cd.length > 0 && cd.trim() === cd;\n if (!isCleanNonEmptyString) {\n const got =\n typeof cd === 'string'\n ? cd.trim().length === 0\n ? `\"${cd}\"`\n : `\"${cd}\" (has surrounding whitespace)`\n : cd === null\n ? 'null'\n : typeof cd;\n throw new TypeError(\n `validateSpec: \\`customDomain\\` must be a non-empty trimmed string or absent (got ${got}).`,\n );\n }\n }\n }\n\n if (hasServices) {\n const entries = Object.entries(spec.services);\n if (entries.length === 0) {\n throw new TypeError(\n 'validateSpec: stack spec `services` must have at least one entry',\n );\n }\n for (const [name, svc] of entries) {\n if (svc === null || typeof svc !== 'object') {\n throw new TypeError(\n `validateSpec: stack service \"${name}\" must be a non-null object`,\n );\n }\n const image = (svc as Partial<ServiceConfig>).image;\n if (typeof image !== 'string' || image.length === 0) {\n throw new TypeError(\n `validateSpec: stack service \"${name}\" must declare a non-empty \\`image\\` string`,\n );\n }\n }\n\n // Copilot review fix (PR #58 r3249684707): a stack spec with a\n // `customDomain` MUST declare which service receives the domain\n // via `serviceName`, and that value must be a key in `services`.\n // Without this guard, `customDomainServiceOf` in `deploy-app.ts`\n // returns `undefined`, planning proceeds with no target, renderers\n // misrepresent the claim, and fred rejects the set-domain tx\n // ONLY after `create-lease` commits — leaving the user with an\n // orphan lease + a failed domain claim. Catching this at\n // validate-time is fail-fast at the boundary.\n //\n // Single-service specs are unaffected: their `customDomain` is\n // claimed against the implicit single lease item — no\n // serviceName disambiguation needed.\n const stackDomain = (spec as Partial<AppDeploySpec>).customDomain;\n if (typeof stackDomain === 'string' && stackDomain.length > 0) {\n const stackServiceName = (spec as Partial<AppDeploySpec>).serviceName;\n if (\n typeof stackServiceName !== 'string' ||\n stackServiceName.length === 0\n ) {\n throw new TypeError(\n 'validateSpec: stack spec with `customDomain` requires `serviceName` identifying which service receives the domain.',\n );\n }\n // Copilot review fix (PR #58 r3250331968): use an own-key check.\n // The `in` operator walks the prototype chain, so `serviceName:\n // 'constructor'` (or `'toString'`, `'hasOwnProperty'`, etc.)\n // would falsely pass against a `services` map that doesn't\n // declare those names. Mirrors fred's own choice at\n // `packages/fred/src/tools/deployApp.ts:254` for cross-package\n // symmetry. `Object.keys().includes()` (not `Object.hasOwn`,\n // which is ES2022 and our `tsdown.config.ts` targets ES2020).\n if (!Object.keys(spec.services).includes(stackServiceName)) {\n throw new TypeError(\n `validateSpec: stack spec \\`serviceName\\` \"${stackServiceName}\" must be a key in \\`services\\` (got services: [${Object.keys(spec.services).join(', ')}]).`,\n );\n }\n }\n } else {\n // Single-service spec port requirement.\n //\n // Copilot review fix (PR #58 r3249097051): fred's image-mode rejects\n // portless inputs with `port is required when using image`\n // (`packages/fred/src/tools/deployApp.ts:202` +\n // `packages/fred/src/tools/buildManifestPreview.ts:181`). Without\n // an agent-core boundary check the orchestrator would pass\n // `port: undefined` straight through the loss-free broadcast spread\n // to fred, surfacing fred's error mid-orchestration (after readiness\n // check + plan render). Failing fast at validate time produces a\n // clearer message and avoids partial work.\n //\n // The escape hatch for genuinely internal-only services is the\n // stack spec — service-level `ports` is optional, so a stack with\n // `{ services: { mysvc: { image, env } } }` deploys without ports.\n //\n // Copilot review fix (PR #58 r3249294877): tighten the predicate to\n // a finite positive integer in the TCP port range. The prior\n // `typeof p === 'number'` check accepted `0`, `NaN`, `Infinity`,\n // negative numbers, non-integers, and out-of-range ports —\n // partially defeating the fail-fast intent. Fred catches `port: 0`\n // via `!input.port`, but the other shapes either flow through to a\n // less helpful error or get coerced silently. The shared predicate\n // `isValidPortNumber` (below) is the single source of truth.\n // Read as `unknown`: the canonical AppDeploySpec.port is `number`, but\n // this runtime guard also accepts a legacy `number[]` smuggled in by an\n // `unknown`-cast / JSON.parse caller (the array branch below) — typing it\n // `unknown` keeps `Array.isArray` from narrowing to `never` (ENG-310).\n const port: unknown = (spec as { port?: unknown }).port;\n const hasValidPort =\n isValidPortNumber(port) ||\n (Array.isArray(port) && port.length > 0 && port.every(isValidPortNumber));\n if (!hasValidPort) {\n throw new TypeError(\n 'validateSpec: single-service specs require at least one port (port must be a finite positive integer in the TCP range (1-65535), or a non-empty array of such); got ' +\n `port=${JSON.stringify(port)}. For internal-only services, use a stack spec instead.`,\n );\n }\n }\n}\n\n/**\n * Predicate: `p` is a finite positive integer in the TCP port range\n * (1-65535). Used by `validateSpec` to gate single-service `port`\n * shapes against the broad `typeof === 'number'` bypass.\n *\n * Co-located in this module because it's exclusive to the port-\n * validation boundary; if a future caller needs the same check,\n * promote it to a shared utility then.\n */\nfunction isValidPortNumber(p: unknown): p is number {\n return typeof p === 'number' && Number.isInteger(p) && p > 0 && p <= 65535;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,YACd,MACqE;CACrE,IAAI,SAAS,QAAQ,SAAS,KAAA,KAAa,OAAO,SAAS,UACzD,OAAO;CACT,MAAM,SAAS;CACf,IAAI,EAAE,cAAc,WAAW,OAAO,aAAa,KAAA,GAAW,OAAO;CACrE,MAAM,WAAW,OAAO;CACxB,OACE,aAAa,QACb,OAAO,aAAa,YACpB,CAAC,MAAM,QAAQ,QAAQ;AAE3B;;;;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Q,SAAS;GACjC,IAAI,QAAQ,QAAQ,OAAO,QAAQ,UACjC,MAAM,IAAI,UACR,gCAAgC,KAAK,4BACvC;GAEF,MAAM,QAAS,IAA+B;GAC9C,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAChD,MAAM,IAAI,UACR,gCAAgC,KAAK,4CACvC;EAEJ;EAeA,MAAM,cAAe,KAAgC;EACrD,IAAI,OAAO,gBAAgB,YAAY,YAAY,SAAS,GAAG;GAC7D,MAAM,mBAAoB,KAAgC;GAC1D,IACE,OAAO,qBAAqB,YAC5B,iBAAiB,WAAW,GAE5B,MAAM,IAAI,UACR,oHACF;GAUF,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,EAAE,SAAS,gBAAgB,GACvD,MAAM,IAAI,UACR,6CAA6C,iBAAiB,kDAAkD,OAAO,KAAK,KAAK,QAAQ,EAAE,KAAK,IAAI,EAAE,IACxJ;EAEJ;CACF,OAAO;EA6BL,MAAM,OAAiB,KAA4B;EAInD,IAAI,EAFF,kBAAkB,IAAI,KACrB,MAAM,QAAQ,IAAI,KAAK,KAAK,SAAS,KAAK,KAAK,MAAM,iBAAiB,IAEvE,MAAM,IAAI,UACR,4KACU,KAAK,UAAU,IAAI,EAAE,wDACjC;CAEJ;AACF;;;;;;;;;;AAWA,SAAS,kBAAkB,GAAyB;CAClD,OAAO,OAAO,MAAM,YAAY,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,KAAK;AACvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manage-domain.d.ts","names":[],"sources":["../src/manage-domain.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"manage-domain.d.ts","names":[],"sources":["../src/manage-domain.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAsHsB,YAAA,CACpB,IAAA,EAAM,gBAAA,EACN,SAAA,EAAW,qBAAA,EACX,IAAA,EAAM,mBAAA,GACL,OAAA,CAAQ,kBAAA"}
|
package/dist/manage-domain.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
+
import { makeCancellationScope } from "./internals/cancellation.js";
|
|
1
2
|
import { verifyAndRecover } from "./internals/verify-recover.js";
|
|
2
3
|
import { verifyDomainState } from "./internals/verify-domain-state.js";
|
|
3
|
-
import { ManifestMCPError, ManifestMCPErrorCode, setItemCustomDomain } from "@manifest-network/manifest-mcp-core";
|
|
4
|
+
import { ManifestMCPError, ManifestMCPErrorCode, noopLogger, parseFqdn, parseLeaseUuid, setItemCustomDomain } from "@manifest-network/manifest-mcp-core";
|
|
4
5
|
//#region src/manage-domain.ts
|
|
5
6
|
/**
|
|
6
7
|
* Public entry point: orchestrate setting, clearing, or looking up a
|
|
@@ -78,17 +79,33 @@ async function manageDomain(args, callbacks, opts) {
|
|
|
78
79
|
validateArgs(args);
|
|
79
80
|
if (args.action === "lookup") return await lookupDomain(args.fqdn, callbacks, opts);
|
|
80
81
|
const serviceName = args.serviceName;
|
|
81
|
-
const fqdn = args.action === "set" ? args.fqdn.trim() : "";
|
|
82
|
+
const fqdn = args.action === "set" ? args.fqdn.trim().toLowerCase() : "";
|
|
83
|
+
const cx = makeCancellationScope({
|
|
84
|
+
opts,
|
|
85
|
+
onProgress: callbacks.onProgress,
|
|
86
|
+
opLabel: "Domain update",
|
|
87
|
+
broadcasts: true
|
|
88
|
+
});
|
|
89
|
+
cx.throwIfCancelled();
|
|
82
90
|
const block = renderConfirmationBlock(args);
|
|
83
91
|
if (callbacks.onConfirm) {
|
|
84
|
-
if (await callbacks.onConfirm(block) !== "yes") throw new ManifestMCPError(ManifestMCPErrorCode.OPERATION_CANCELLED, `User declined to proceed with manage-domain ${args.action}.`);
|
|
92
|
+
if (await cx.race(callbacks.onConfirm(block)) !== "yes") throw new ManifestMCPError(ManifestMCPErrorCode.OPERATION_CANCELLED, `User declined to proceed with manage-domain ${args.action}.`);
|
|
85
93
|
}
|
|
86
94
|
callbacks.onProgress?.({ kind: "user_confirmed" });
|
|
87
|
-
const
|
|
95
|
+
const leaseUuid = parseLeaseUuid(args.leaseUuid);
|
|
96
|
+
cx.throwIfCancelled();
|
|
97
|
+
await setItemCustomDomain({
|
|
98
|
+
chain: opts.clientManager,
|
|
99
|
+
logger: noopLogger
|
|
100
|
+
}, args.action === "set" ? {
|
|
101
|
+
leaseUuid,
|
|
102
|
+
customDomain: parseFqdn(fqdn),
|
|
103
|
+
serviceName
|
|
104
|
+
} : {
|
|
105
|
+
leaseUuid,
|
|
88
106
|
clear: true,
|
|
89
|
-
|
|
90
|
-
};
|
|
91
|
-
await setItemCustomDomain(opts.clientManager, args.leaseUuid, fqdn, setOpts);
|
|
107
|
+
serviceName
|
|
108
|
+
});
|
|
92
109
|
const verifyResult = await verifyAndRecover({
|
|
93
110
|
verifier: async () => {
|
|
94
111
|
let result;
|
|
@@ -181,10 +198,19 @@ function renderConfirmationBlock(args) {
|
|
|
181
198
|
}
|
|
182
199
|
async function lookupDomain(fqdn, callbacks, opts) {
|
|
183
200
|
const customDomain = fqdn.trim();
|
|
201
|
+
const cx = makeCancellationScope({
|
|
202
|
+
opts,
|
|
203
|
+
onProgress: callbacks.onProgress,
|
|
204
|
+
opLabel: "Domain lookup",
|
|
205
|
+
broadcasts: false
|
|
206
|
+
});
|
|
207
|
+
cx.throwIfCancelled();
|
|
184
208
|
let result;
|
|
185
209
|
try {
|
|
186
|
-
|
|
210
|
+
const queryClient = await opts.clientManager.getQueryClient();
|
|
211
|
+
result = await cx.race(queryClient.liftedinit.billing.v1.leaseByCustomDomain({ customDomain }));
|
|
187
212
|
} catch (err) {
|
|
213
|
+
if (err instanceof ManifestMCPError && err.code === ManifestMCPErrorCode.OPERATION_CANCELLED) throw err;
|
|
188
214
|
if (isNotFoundError(err)) {
|
|
189
215
|
const notFoundResult = {
|
|
190
216
|
action: "lookup",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manage-domain.js","names":[],"sources":["../src/manage-domain.ts"],"sourcesContent":["/**\n * Public entry point: orchestrate setting, clearing, or looking up a\n * lease item's custom domain.\n *\n * Composition (mirrors `deploy-app.ts`'s shape):\n *\n * - `set` / `clear` render a confirmation block, optionally call\n * `onConfirm`, broadcast `setItemCustomDomain` against the agent's\n * bound chain client, then verify the post-broadcast on-chain state\n * via `verifyAndRecover` driving `verify-domain-state` over a direct\n * `billing.v1.lease({ leaseUuid })` single-lease query (tenant-\n * agnostic, no pagination edge cases). Branches are inline closures\n * bound to the per-action context; recovery options are intentionally\n * empty so the verifier surfaces failures via the simple-form\n * `onFailure({ reason })` adapter rather than the rich-form\n * `RecoveryOption[]` prompt (manage-domain has no recovery primitives\n * the orchestrator can dispatch; the user re-runs after a real fix).\n *\n * - `lookup` skips broadcast/verify and resolves the FQDN via the\n * `lease_by_custom_domain` chain query; returns `null` lease when\n * the FQDN isn't claimed.\n */\n\nimport {\n ManifestMCPError,\n ManifestMCPErrorCode,\n setItemCustomDomain,\n} from '@manifest-network/manifest-mcp-core';\nimport {\n type VerifyDomainOutcome,\n type VerifyDomainResult,\n verifyDomainState,\n} from './internals/verify-domain-state.js';\nimport {\n type VerificationSpec,\n verifyAndRecover,\n} from './internals/verify-recover.js';\nimport type {\n DeploymentPlanBlock,\n ManageDomainArgs,\n ManageDomainCallbacks,\n ManageDomainOptions,\n ManageDomainResult,\n} from './types.js';\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// RFC 1123 hostname: each label 1-63 chars, alphanumeric + hyphens, no leading/\n// trailing hyphen; total ≤253 chars; ≥2 labels (FQDN, not single-label host).\n// Rejects scheme prefixes ('http://'), whitespace, trailing dots, and raw\n// unicode (ASCII punycode `xn--...` is accepted — it matches the regex's\n// `[A-Za-z0-9-]` label character class, which is the standard wire form\n// for IDN labels).\n//\n// Client-side typo gate only. The chain's `MsgSetItemCustomDomain` keeper is\n// the authoritative validator (canonical lowercase, reserved-suffix rules,\n// FQDN format). This anchored regex catches the obvious-malformed-input\n// cases pre-broadcast so we don't waste a tx on `\"\"`, `\" \"`, `\"http://x.y\"`,\n// or `\"not a domain\"`. Anything that passes here still goes through the\n// chain's own validation.\nconst FQDN_RE =\n /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;\n\nconst SCHEME_PREFIX_RE = /^https?:\\/\\//i;\n\n/**\n * Cosmos SDK / gRPC NotFound message patterns. Match against\n * `Error.message` to distinguish chain-keeper NotFound (treated as\n * \"unclaimed FQDN\" → typed `null` result) from real failures (treated\n * as `QUERY_FAILED` throws). Anchored loose patterns to tolerate\n * different keeper / transport formatting (\"not found\", \"NotFound\",\n * \"no such record\", \"does not exist\").\n *\n * Per CLAUDE.md: use `String.prototype.match()` over `RegExp.test()`\n * to avoid the CI security hook's false-positive on shell-execution\n * tokens.\n */\nconst NOT_FOUND_RES: readonly RegExp[] = [\n /not.?found/i,\n /no.?such/i,\n /does.?not.?exist/i,\n];\n\n/**\n * Set / clear / look up a lease item's custom domain.\n *\n * @throws `ManifestMCPError(INVALID_CONFIG)` for args validation.\n * @throws `ManifestMCPError(OPERATION_CANCELLED)` when `onConfirm` returns\n * `'no'` (deliberate user cancellation — ENG-272).\n * @throws `ManifestMCPError` (typically `TX_FAILED`) propagated as-is\n * from the `setItemCustomDomain()` broadcast step in `set` / `clear`\n * paths. Broadcast errors do NOT invoke `onFailure` — that callback\n * is reserved for post-broadcast verification failures.\n * `setItemCustomDomain` already raises a structured `ManifestMCPError`\n * from the core package; wrapping it again at this layer would be\n * redundant. Callers wanting to react to broadcast errors should\n * catch them at the call site.\n * @throws `ManifestMCPError(TX_FAILED)` when post-broadcast verification\n * reaches a `not_found` / `mismatch` outcome (after `onFailure` has\n * been invoked so the caller can react).\n * @throws `ManifestMCPError(QUERY_FAILED)` when a chain query raises a\n * non-NotFound error (RPC / transport / decoding failure). Two paths\n * surface this:\n * - the `lookup` chain query (`lease_by_custom_domain`); the keeper's\n * `NotFound` on an unclaimed FQDN is surfaced as a typed\n * `{ lease: null }` result, not a throw.\n * - the post-broadcast verify chain query (`billing.v1.lease`) in\n * the `set` / `clear` paths (wrapped inside the verifier closure\n * so the failure flows through `onFailure({ reason })` before the\n * throw).\n * Structured `ManifestMCPError`s raised by the chain client are\n * re-thrown as-is (with `onFailure` invoked first).\n */\nexport async function manageDomain(\n args: ManageDomainArgs,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n validateArgs(args);\n\n if (args.action === 'lookup') {\n return await lookupDomain(args.fqdn, callbacks, opts);\n }\n\n const serviceName = args.serviceName;\n // Trim the FQDN silently for `set` (Copilot review PR #60, comment\n // 3276519081): align with the underlying `setItemCustomDomain`\n // primitive (which trims at `packages/core/src/tools/setItemCustomDomain.ts:78-81`)\n // and with `lookupDomain` (which already trims). `validateArgs`\n // continues to reject the empty / whitespace-only case via\n // `args.fqdn.trim() === ''`; this just normalizes the surviving\n // input.\n const fqdn = args.action === 'set' ? args.fqdn.trim() : '';\n\n // --- Confirmation block ---------------------------------------------\n const block = renderConfirmationBlock(args);\n if (callbacks.onConfirm) {\n const yesNo = await callbacks.onConfirm(block);\n if (yesNo !== 'yes') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.OPERATION_CANCELLED,\n `User declined to proceed with manage-domain ${args.action}.`,\n );\n }\n }\n callbacks.onProgress?.({ kind: 'user_confirmed' });\n\n // --- Broadcast ------------------------------------------------------\n const setOpts =\n args.action === 'set'\n ? serviceName\n ? { serviceName }\n : undefined\n : {\n clear: true as const,\n ...(serviceName ? { serviceName } : {}),\n };\n await setItemCustomDomain(opts.clientManager, args.leaseUuid, fqdn, setOpts);\n\n // --- Verify ---------------------------------------------------------\n // Direct single-lease query (Copilot review PR #60, comment 3275999569):\n // the previous `leasesByTenant` + page-1-only pagination would\n // false-`not_found` for tenants with >100 leases. `billing.v1.lease`\n // is the same query shape `troubleshoot.ts` already uses; it's\n // tenant-agnostic and bounded to a single lease.\n //\n // We wrap the single-lease result as `{ leases: [result.lease] }`\n // (or an empty array if the chain returns no match) so\n // `verifyDomainState` stays untouched — its `findLease` walks the\n // same shape, and a `not_found` outcome falls out naturally when the\n // wrapper array is empty.\n const spec: VerificationSpec<\n unknown,\n VerifyDomainOutcome,\n VerifyDomainResult\n > = {\n verifier: async () => {\n // Wrap the chain call in try/catch (Copilot review PR #60,\n // comment 3276419210): if `billing.v1.lease` rejects (RPC down,\n // transport, structured `ManifestMCPError`), the error would\n // otherwise propagate OUT of `verifyAndRecover` and bypass the\n // post-verify `onFailure({ reason })` callback below. Mirror\n // the disambiguation pattern from `lookupDomain` (commit aaa5cc5)\n // and `troubleshootDeployment` (commit f1a4737): invoke\n // `onFailure` first, then re-throw `ManifestMCPError` as-is or\n // wrap plain errors as `QUERY_FAILED`.\n let result: unknown;\n try {\n const queryClient = await opts.clientManager.getQueryClient();\n result = await queryClient.liftedinit.billing.v1.lease({\n leaseUuid: args.leaseUuid,\n });\n } catch (err) {\n const reason = `Failed to query lease ${args.leaseUuid} during ${args.action}-verify: ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const lease = (result as { lease?: unknown })?.lease;\n const leases = lease === null || lease === undefined ? [] : [lease];\n const decoded = verifyDomainState(\n { leases },\n {\n leaseUuid: args.leaseUuid,\n ...(serviceName ? { serviceName } : {}),\n expected: fqdn,\n },\n );\n return { outcome: decoded.outcome, diagnostic: decoded };\n },\n successValues: ['match'],\n branches: {\n mismatch: {\n branchId: 'domain_verification_mismatch',\n journalActionTags: ['domain-verification-mismatch'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n args.action === 'set'\n ? `Chain shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected \"${fqdn}\".`\n : `Chain still shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected cleared.`,\n }),\n buildRecoveryOptions: () => [],\n },\n not_found: {\n branchId: 'domain_not_found',\n journalActionTags: ['domain-verification-not-found'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n d.reason ??\n `Lease ${args.leaseUuid} not found when verifying domain state.`,\n }),\n buildRecoveryOptions: () => [],\n },\n },\n };\n\n const verifyResult = await verifyAndRecover(spec, undefined);\n const verified = verifyResult.result === 'success';\n const finalCustomDomain = deriveFinalCustomDomain(\n verifyResult.diagnostic,\n args.action,\n );\n\n if (!verified) {\n const reason =\n verifyResult.failure?.reason ??\n `manage-domain ${args.action} verification failed.`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.TX_FAILED, reason);\n }\n\n const result: ManageDomainResult = {\n action: args.action,\n leaseUuid: args.leaseUuid,\n verified,\n finalCustomDomain,\n };\n callbacks.onComplete?.(result);\n return result;\n}\n\n// --- Helpers --------------------------------------------------------\n\nfunction validateArgs(args: ManageDomainArgs): void {\n if (\n args.action !== 'set' &&\n args.action !== 'clear' &&\n args.action !== 'lookup'\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain: unknown action \"${(args as { action?: string }).action}\".`,\n );\n }\n if (args.action === 'lookup') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain lookup: fqdn must be a non-empty string.',\n );\n }\n return;\n }\n if (typeof args.leaseUuid !== 'string' || !args.leaseUuid.match(UUID_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain ${args.action}: leaseUuid must be a UUID; got \"${args.leaseUuid}\".`,\n );\n }\n if (args.action === 'set') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain set: fqdn must be a non-empty string.',\n );\n }\n // Trim silently (Copilot review PR #60, comment 3276519081):\n // align with `setItemCustomDomain` (which trims at\n // `packages/core/src/tools/setItemCustomDomain.ts:78-81`) and with\n // `lookupDomain` (which already trims). Validation gates below\n // run against the trimmed candidate; the broadcast and confirm\n // block (rendered in the caller) also use the trimmed form.\n const candidate = args.fqdn.trim();\n if (candidate.match(SCHEME_PREFIX_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn must be a bare hostname (no scheme); got \"${args.fqdn}\".`,\n );\n }\n if (!candidate.match(FQDN_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn \"${args.fqdn}\" is not a valid RFC 1123 hostname (≤253 chars, ≥2 dot-separated labels of 1-63 alphanumeric/hyphen chars; no leading/trailing hyphens).`,\n );\n }\n }\n}\n\nfunction renderConfirmationBlock(\n args: Exclude<ManageDomainArgs, { action: 'lookup' }>,\n): DeploymentPlanBlock {\n const lines: string[] = [];\n if (args.action === 'set') {\n lines.push(`Set custom domain on lease ${args.leaseUuid}:`);\n // Display the trimmed FQDN — matches the value that will be\n // broadcast (per the silent-trim semantics aligned with\n // setItemCustomDomain) so users don't see whitespace in the\n // confirm prompt that won't appear on-chain.\n lines.push(` FQDN: ${args.fqdn.trim()}`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n } else {\n lines.push(`Clear custom domain on lease ${args.leaseUuid}:`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n }\n return { text: lines.join('\\n') };\n}\n\nasync function lookupDomain(\n fqdn: string,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n const customDomain = fqdn.trim();\n let result: unknown;\n try {\n // Pull `getQueryClient()` INSIDE the try (Copilot review PR #60,\n // comment 3276719558). `getQueryClient()` can throw\n // `INVALID_CONFIG` (neither rpcUrl nor restUrl set) or\n // `RPC_CONNECTION_FAILED` (connect failure). Catching here routes\n // those init-time failures through the same `onFailure` +\n // QUERY_FAILED / structured-passthrough normalization the chain-\n // query failure mode already gets. The set/clear verifier closure\n // (in `manageDomain` body above) already wraps `getQueryClient()`\n // since commit d9793c1; this brings `lookupDomain` to parity.\n const queryClient = await opts.clientManager.getQueryClient();\n result = await queryClient.liftedinit.billing.v1.leaseByCustomDomain({\n customDomain,\n });\n } catch (err) {\n // Narrowed disambiguation (Copilot review PR #60): the chain keeper\n // raises a NotFound-shaped error when the FQDN is unclaimed (cosmjs/\n // grpc surfaces this as a plain `Error` whose message matches\n // `/not.?found|no.?such|does.?not.?exist/i`). Only that case is\n // collapsed to the typed `{ lease: null }` result. Every other\n // failure mode (RPC transport, decoding, structured\n // `ManifestMCPError`, etc.) flows through `onFailure({ reason })`\n // then a typed throw — matching the lease-package's\n // `lease_by_custom_domain` handler (packages/lease/src/index.ts:442)\n // and `getBalance`'s `catchNotFound` pattern (packages/core/src/\n // tools/getBalance.ts:4). The bare `catch` was masking real failures.\n if (isNotFoundError(err)) {\n const notFoundResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: null,\n };\n callbacks.onComplete?.(notFoundResult);\n return notFoundResult;\n }\n const reason = `lease_by_custom_domain lookup failed for \"${customDomain}\": ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const uuid = readLeaseUuid((result as { lease?: unknown })?.lease);\n const lookupResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: uuid ? { leaseUuid: uuid } : null,\n };\n // Symmetric `onComplete` fire (Copilot review PR #60, comment\n // 3288656598). Pre-fix, the lookup path returned without invoking\n // `onComplete` — asymmetric vs the set/clear paths in this same\n // function and vs `closeLease` / `troubleshootDeployment`. Was\n // documented as \"intentional\" in PR_DESCRIPTION.md Risks #1 but\n // was really an oversight rationalized post-hoc. Now consistent.\n callbacks.onComplete?.(lookupResult);\n return lookupResult;\n}\n\nfunction isNotFoundError(err: unknown): boolean {\n // Pass-through guard for structured failures: a `ManifestMCPError` is\n // always a real, intentional error — never silently re-classified as\n // \"FQDN unclaimed\" even if its message happens to contain \"not found\".\n if (err instanceof ManifestMCPError) return false;\n if (!(err instanceof Error)) return false;\n const msg = err.message;\n return NOT_FOUND_RES.some((re) => msg.match(re) !== null);\n}\n\nfunction readLeaseUuid(lease: unknown): string | undefined {\n if (lease === null || typeof lease !== 'object') return undefined;\n const r = lease as {\n uuid?: unknown;\n lease_uuid?: unknown;\n leaseUuid?: unknown;\n };\n const u = r.uuid ?? r.lease_uuid ?? r.leaseUuid;\n return typeof u === 'string' && u.length > 0 ? u : undefined;\n}\n\nfunction deriveFinalCustomDomain(\n diagnostic: VerifyDomainResult,\n action: 'set' | 'clear',\n): string | null {\n if (action === 'clear') return null;\n const actual = diagnostic.actual ?? '';\n return actual.length > 0 ? actual : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,UACJ;AAeF,MAAM,UACJ;AAEF,MAAM,mBAAmB;;;;;;;;;;;;;AAczB,MAAM,gBAAmC;CACvC;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,aACpB,MACA,WACA,MAC6B;CAC7B,aAAa,IAAI;CAEjB,IAAI,KAAK,WAAW,UAClB,OAAO,MAAM,aAAa,KAAK,MAAM,WAAW,IAAI;CAGtD,MAAM,cAAc,KAAK;CAQzB,MAAM,OAAO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6C,aAAa,KACvE,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;EAEjD,IAAI,UAAU,WACZ,MAAM,UAAU,UAAU,EAAE,OAAO,CAAC;EAEtC,IAAI,eAAe,kBACjB,MAAM;EAER,MAAM,IAAI,iBAAiB,qBAAqB,cAAc,MAAM;CACtE;CACA,MAAM,OAAO,cAAe,QAAgC,KAAK;CACjE,MAAM,eAAmC;EACvC,QAAQ;EACR,MAAM;EACN,OAAO,OAAO,EAAE,WAAW,KAAK,IAAI;CACtC;CAOA,UAAU,aAAa,YAAY;CACnC,OAAO;AACT;AAEA,SAAS,gBAAgB,KAAuB;CAI9C,IAAI,eAAe,kBAAkB,OAAO;CAC5C,IAAI,EAAE,eAAe,QAAQ,OAAO;CACpC,MAAM,MAAM,IAAI;CAChB,OAAO,cAAc,MAAM,OAAO,IAAI,MAAM,EAAE,MAAM,IAAI;AAC1D;AAEA,SAAS,cAAc,OAAoC;CACzD,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO,KAAA;CACxD,MAAM,IAAI;CAKV,MAAM,IAAI,EAAE,QAAQ,EAAE,cAAc,EAAE;CACtC,OAAO,OAAO,MAAM,YAAY,EAAE,SAAS,IAAI,IAAI,KAAA;AACrD;AAEA,SAAS,wBACP,YACA,QACe;CACf,IAAI,WAAW,SAAS,OAAO;CAC/B,MAAM,SAAS,WAAW,UAAU;CACpC,OAAO,OAAO,SAAS,IAAI,SAAS;AACtC"}
|
|
1
|
+
{"version":3,"file":"manage-domain.js","names":[],"sources":["../src/manage-domain.ts"],"sourcesContent":["/**\n * Public entry point: orchestrate setting, clearing, or looking up a\n * lease item's custom domain.\n *\n * Composition (mirrors `deploy-app.ts`'s shape):\n *\n * - `set` / `clear` render a confirmation block, optionally call\n * `onConfirm`, broadcast `setItemCustomDomain` against the agent's\n * bound chain client, then verify the post-broadcast on-chain state\n * via `verifyAndRecover` driving `verify-domain-state` over a direct\n * `billing.v1.lease({ leaseUuid })` single-lease query (tenant-\n * agnostic, no pagination edge cases). Branches are inline closures\n * bound to the per-action context; recovery options are intentionally\n * empty so the verifier surfaces failures via the simple-form\n * `onFailure({ reason })` adapter rather than the rich-form\n * `RecoveryOption[]` prompt (manage-domain has no recovery primitives\n * the orchestrator can dispatch; the user re-runs after a real fix).\n *\n * - `lookup` skips broadcast/verify and resolves the FQDN via the\n * `lease_by_custom_domain` chain query; returns `null` lease when\n * the FQDN isn't claimed.\n */\n\nimport {\n ManifestMCPError,\n ManifestMCPErrorCode,\n noopLogger,\n parseFqdn,\n parseLeaseUuid,\n setItemCustomDomain,\n} from '@manifest-network/manifest-mcp-core';\nimport { makeCancellationScope } from './internals/cancellation.js';\nimport {\n type VerifyDomainOutcome,\n type VerifyDomainResult,\n verifyDomainState,\n} from './internals/verify-domain-state.js';\nimport {\n type VerificationSpec,\n verifyAndRecover,\n} from './internals/verify-recover.js';\nimport type {\n DeploymentPlanBlock,\n ManageDomainArgs,\n ManageDomainCallbacks,\n ManageDomainOptions,\n ManageDomainResult,\n} from './types.js';\n\nconst UUID_RE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n// RFC 1123 hostname: each label 1-63 chars, alphanumeric + hyphens, no leading/\n// trailing hyphen; total ≤253 chars; ≥2 labels (FQDN, not single-label host).\n// Rejects scheme prefixes ('http://'), whitespace, trailing dots, and raw\n// unicode (ASCII punycode `xn--...` is accepted — it matches the regex's\n// `[A-Za-z0-9-]` label character class, which is the standard wire form\n// for IDN labels).\n//\n// Client-side typo gate only. The chain's `MsgSetItemCustomDomain` keeper is\n// the authoritative validator (canonical lowercase, reserved-suffix rules,\n// FQDN format). This anchored regex catches the obvious-malformed-input\n// cases pre-broadcast so we don't waste a tx on `\"\"`, `\" \"`, `\"http://x.y\"`,\n// or `\"not a domain\"`. Anything that passes here still goes through the\n// chain's own validation.\nconst FQDN_RE =\n /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\\.)+[A-Za-z](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$/;\n\nconst SCHEME_PREFIX_RE = /^https?:\\/\\//i;\n\n/**\n * Cosmos SDK / gRPC NotFound message patterns. Match against\n * `Error.message` to distinguish chain-keeper NotFound (treated as\n * \"unclaimed FQDN\" → typed `null` result) from real failures (treated\n * as `QUERY_FAILED` throws). Anchored loose patterns to tolerate\n * different keeper / transport formatting (\"not found\", \"NotFound\",\n * \"no such record\", \"does not exist\").\n *\n * Per CLAUDE.md: use `String.prototype.match()` over `RegExp.test()`\n * to avoid the CI security hook's false-positive on shell-execution\n * tokens.\n */\nconst NOT_FOUND_RES: readonly RegExp[] = [\n /not.?found/i,\n /no.?such/i,\n /does.?not.?exist/i,\n];\n\n/**\n * Set / clear / look up a lease item's custom domain.\n *\n * @throws `ManifestMCPError(INVALID_CONFIG)` for args validation.\n * @throws `ManifestMCPError(OPERATION_CANCELLED)` when `onConfirm` returns\n * `'no'` (deliberate user cancellation — ENG-272).\n * @throws `ManifestMCPError` (typically `TX_FAILED`) propagated as-is\n * from the `setItemCustomDomain()` broadcast step in `set` / `clear`\n * paths. Broadcast errors do NOT invoke `onFailure` — that callback\n * is reserved for post-broadcast verification failures.\n * `setItemCustomDomain` already raises a structured `ManifestMCPError`\n * from the core package; wrapping it again at this layer would be\n * redundant. Callers wanting to react to broadcast errors should\n * catch them at the call site.\n * @throws `ManifestMCPError(TX_FAILED)` when post-broadcast verification\n * reaches a `not_found` / `mismatch` outcome (after `onFailure` has\n * been invoked so the caller can react).\n * @throws `ManifestMCPError(QUERY_FAILED)` when a chain query raises a\n * non-NotFound error (RPC / transport / decoding failure). Two paths\n * surface this:\n * - the `lookup` chain query (`lease_by_custom_domain`); the keeper's\n * `NotFound` on an unclaimed FQDN is surfaced as a typed\n * `{ lease: null }` result, not a throw.\n * - the post-broadcast verify chain query (`billing.v1.lease`) in\n * the `set` / `clear` paths (wrapped inside the verifier closure\n * so the failure flows through `onFailure({ reason })` before the\n * throw).\n * Structured `ManifestMCPError`s raised by the chain client are\n * re-thrown as-is (with `onFailure` invoked first).\n */\nexport async function manageDomain(\n args: ManageDomainArgs,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n validateArgs(args);\n\n if (args.action === 'lookup') {\n return await lookupDomain(args.fqdn, callbacks, opts);\n }\n\n const serviceName = args.serviceName;\n // Normalize the FQDN once for `set`: trim surrounding whitespace\n // (Copilot review PR #60, comment 3276519081) AND lowercase (RFC 4343),\n // matching what `parseFqdn` does to the broadcast value below. Both the\n // broadcast (`parseFqdn(fqdn)`) and the post-broadcast verification\n // (`expected: fqdn`) must compare the SAME normalized value — otherwise a\n // mixed-case input broadcasts lowercased but verifies against the raw\n // casing, producing a spurious mismatch (code-review PR #102).\n // `validateArgs` still rejects the empty / whitespace-only case via\n // `args.fqdn.trim() === ''`.\n const fqdn = args.action === 'set' ? args.fqdn.trim().toLowerCase() : '';\n\n // Cancellation seam (ENG-374, shared via internals/cancellation.ts). Race ONLY\n // the pre-broadcast `onConfirm`; the post-broadcast verifier routes into\n // recovery (D4.6) and is never cancelled.\n const cx = makeCancellationScope({\n opts,\n onProgress: callbacks.onProgress,\n opLabel: 'Domain update',\n broadcasts: true,\n });\n cx.throwIfCancelled();\n\n // --- Confirmation block ---------------------------------------------\n const block = renderConfirmationBlock(args);\n if (callbacks.onConfirm) {\n const yesNo = await cx.race(callbacks.onConfirm(block));\n if (yesNo !== 'yes') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.OPERATION_CANCELLED,\n `User declined to proceed with manage-domain ${args.action}.`,\n );\n }\n }\n callbacks.onProgress?.({ kind: 'user_confirmed' });\n\n // --- Broadcast ------------------------------------------------------\n // txCtx has no signer (ManageDomainOptions carries no walletProvider); the\n // sender resolves from ctx.chain (the CosmosClientManager wallet). See OI-SENDER.\n // The raw MCP `leaseUuid`/`fqdn` strings are unbranded → parse at the boundary.\n const leaseUuid = parseLeaseUuid(args.leaseUuid);\n cx.throwIfCancelled();\n await setItemCustomDomain(\n { chain: opts.clientManager, logger: noopLogger },\n args.action === 'set'\n ? { leaseUuid, customDomain: parseFqdn(fqdn), serviceName }\n : { leaseUuid, clear: true, serviceName },\n );\n\n // --- Verify ---------------------------------------------------------\n // Direct single-lease query (Copilot review PR #60, comment 3275999569):\n // the previous `leasesByTenant` + page-1-only pagination would\n // false-`not_found` for tenants with >100 leases. `billing.v1.lease`\n // is the same query shape `troubleshoot.ts` already uses; it's\n // tenant-agnostic and bounded to a single lease.\n //\n // We wrap the single-lease result as `{ leases: [result.lease] }`\n // (or an empty array if the chain returns no match) so\n // `verifyDomainState` stays untouched — its `findLease` walks the\n // same shape, and a `not_found` outcome falls out naturally when the\n // wrapper array is empty.\n const spec: VerificationSpec<\n unknown,\n VerifyDomainOutcome,\n VerifyDomainResult\n > = {\n verifier: async () => {\n // Wrap the chain call in try/catch (Copilot review PR #60,\n // comment 3276419210): if `billing.v1.lease` rejects (RPC down,\n // transport, structured `ManifestMCPError`), the error would\n // otherwise propagate OUT of `verifyAndRecover` and bypass the\n // post-verify `onFailure({ reason })` callback below. Mirror\n // the disambiguation pattern from `lookupDomain` (commit aaa5cc5)\n // and `troubleshootDeployment` (commit f1a4737): invoke\n // `onFailure` first, then re-throw `ManifestMCPError` as-is or\n // wrap plain errors as `QUERY_FAILED`.\n let result: unknown;\n try {\n const queryClient = await opts.clientManager.getQueryClient();\n result = await queryClient.liftedinit.billing.v1.lease({\n leaseUuid: args.leaseUuid,\n });\n } catch (err) {\n const reason = `Failed to query lease ${args.leaseUuid} during ${args.action}-verify: ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const lease = (result as { lease?: unknown })?.lease;\n const leases = lease === null || lease === undefined ? [] : [lease];\n const decoded = verifyDomainState(\n { leases },\n {\n leaseUuid: args.leaseUuid,\n ...(serviceName ? { serviceName } : {}),\n expected: fqdn,\n },\n );\n return { outcome: decoded.outcome, diagnostic: decoded };\n },\n successValues: ['match'],\n branches: {\n mismatch: {\n branchId: 'domain_verification_mismatch',\n journalActionTags: ['domain-verification-mismatch'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n args.action === 'set'\n ? `Chain shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected \"${fqdn}\".`\n : `Chain still shows custom_domain=\"${d.actual ?? ''}\" for lease ${args.leaseUuid}; expected cleared.`,\n }),\n buildRecoveryOptions: () => [],\n },\n not_found: {\n branchId: 'domain_not_found',\n journalActionTags: ['domain-verification-not-found'],\n buildFailureEnvelope: (d) => ({\n outcome: 'failed',\n reason:\n d.reason ??\n `Lease ${args.leaseUuid} not found when verifying domain state.`,\n }),\n buildRecoveryOptions: () => [],\n },\n },\n };\n\n const verifyResult = await verifyAndRecover(spec, undefined);\n const verified = verifyResult.result === 'success';\n const finalCustomDomain = deriveFinalCustomDomain(\n verifyResult.diagnostic,\n args.action,\n );\n\n if (!verified) {\n const reason =\n verifyResult.failure?.reason ??\n `manage-domain ${args.action} verification failed.`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.TX_FAILED, reason);\n }\n\n const result: ManageDomainResult = {\n action: args.action,\n leaseUuid: args.leaseUuid,\n verified,\n finalCustomDomain,\n };\n callbacks.onComplete?.(result);\n return result;\n}\n\n// --- Helpers --------------------------------------------------------\n\nfunction validateArgs(args: ManageDomainArgs): void {\n if (\n args.action !== 'set' &&\n args.action !== 'clear' &&\n args.action !== 'lookup'\n ) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain: unknown action \"${(args as { action?: string }).action}\".`,\n );\n }\n if (args.action === 'lookup') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain lookup: fqdn must be a non-empty string.',\n );\n }\n return;\n }\n if (typeof args.leaseUuid !== 'string' || !args.leaseUuid.match(UUID_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain ${args.action}: leaseUuid must be a UUID; got \"${args.leaseUuid}\".`,\n );\n }\n if (args.action === 'set') {\n if (typeof args.fqdn !== 'string' || args.fqdn.trim() === '') {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n 'manageDomain set: fqdn must be a non-empty string.',\n );\n }\n // Validate against the trimmed candidate (Copilot review PR #60,\n // comment 3276519081): surrounding whitespace is silently stripped\n // (like `lookupDomain`) rather than rejected. Note `setItemCustomDomain`\n // does NOT re-trim — it takes an already-normalized branded `Fqdn`\n // (parse-once at the boundary) — so the normalization lives here and at\n // the `fqdn` assignment above, not in the primitive.\n const candidate = args.fqdn.trim();\n if (candidate.match(SCHEME_PREFIX_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn must be a bare hostname (no scheme); got \"${args.fqdn}\".`,\n );\n }\n if (!candidate.match(FQDN_RE)) {\n throw new ManifestMCPError(\n ManifestMCPErrorCode.INVALID_CONFIG,\n `manageDomain set: fqdn \"${args.fqdn}\" is not a valid RFC 1123 hostname (≤253 chars, ≥2 dot-separated labels of 1-63 alphanumeric/hyphen chars; no leading/trailing hyphens).`,\n );\n }\n }\n}\n\nfunction renderConfirmationBlock(\n args: Exclude<ManageDomainArgs, { action: 'lookup' }>,\n): DeploymentPlanBlock {\n const lines: string[] = [];\n if (args.action === 'set') {\n lines.push(`Set custom domain on lease ${args.leaseUuid}:`);\n // Display the trimmed FQDN — matches the value that will be\n // broadcast (per the silent-trim semantics aligned with\n // setItemCustomDomain) so users don't see whitespace in the\n // confirm prompt that won't appear on-chain.\n lines.push(` FQDN: ${args.fqdn.trim()}`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n } else {\n lines.push(`Clear custom domain on lease ${args.leaseUuid}:`);\n if (args.serviceName) {\n lines.push(` Service: ${args.serviceName}`);\n }\n lines.push('');\n lines.push('Proceed?');\n }\n return { text: lines.join('\\n') };\n}\n\nasync function lookupDomain(\n fqdn: string,\n callbacks: ManageDomainCallbacks,\n opts: ManageDomainOptions,\n): Promise<ManageDomainResult> {\n const customDomain = fqdn.trim();\n // Cancellation seam (ENG-374): read-only flow races the single query for\n // withReadSignal parity. Manifestjs queries take no AbortSignal, so on abort\n // we stop awaiting (the RPC is not actually cancelled).\n const cx = makeCancellationScope({\n opts,\n onProgress: callbacks.onProgress,\n opLabel: 'Domain lookup',\n broadcasts: false,\n });\n cx.throwIfCancelled();\n let result: unknown;\n try {\n // Pull `getQueryClient()` INSIDE the try (Copilot review PR #60,\n // comment 3276719558). `getQueryClient()` can throw\n // `INVALID_CONFIG` (neither rpcUrl nor restUrl set) or\n // `RPC_CONNECTION_FAILED` (connect failure). Catching here routes\n // those init-time failures through the same `onFailure` +\n // QUERY_FAILED / structured-passthrough normalization the chain-\n // query failure mode already gets. The set/clear verifier closure\n // (in `manageDomain` body above) already wraps `getQueryClient()`\n // since commit d9793c1; this brings `lookupDomain` to parity.\n const queryClient = await opts.clientManager.getQueryClient();\n result = await cx.race(\n queryClient.liftedinit.billing.v1.leaseByCustomDomain({\n customDomain,\n }),\n );\n } catch (err) {\n // Cancellation short-circuit (ENG-374): an aborted read is neither a\n // \"not found\" nor a query failure — re-throw BEFORE the not-found /\n // onFailure handling so it never invokes `onFailure`.\n if (\n err instanceof ManifestMCPError &&\n err.code === ManifestMCPErrorCode.OPERATION_CANCELLED\n ) {\n throw err;\n }\n // Narrowed disambiguation (Copilot review PR #60): the chain keeper\n // raises a NotFound-shaped error when the FQDN is unclaimed (cosmjs/\n // grpc surfaces this as a plain `Error` whose message matches\n // `/not.?found|no.?such|does.?not.?exist/i`). Only that case is\n // collapsed to the typed `{ lease: null }` result. Every other\n // failure mode (RPC transport, decoding, structured\n // `ManifestMCPError`, etc.) flows through `onFailure({ reason })`\n // then a typed throw — matching the lease-package's\n // `lease_by_custom_domain` handler (packages/lease/src/index.ts:442)\n // and `getBalance`'s `catchNotFound` pattern (packages/core/src/\n // tools/getBalance.ts:4). The bare `catch` was masking real failures.\n if (isNotFoundError(err)) {\n const notFoundResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: null,\n };\n callbacks.onComplete?.(notFoundResult);\n return notFoundResult;\n }\n const reason = `lease_by_custom_domain lookup failed for \"${customDomain}\": ${\n err instanceof Error ? err.message : String(err)\n }`;\n if (callbacks.onFailure) {\n await callbacks.onFailure({ reason });\n }\n if (err instanceof ManifestMCPError) {\n throw err;\n }\n throw new ManifestMCPError(ManifestMCPErrorCode.QUERY_FAILED, reason);\n }\n const uuid = readLeaseUuid((result as { lease?: unknown })?.lease);\n const lookupResult: ManageDomainResult = {\n action: 'lookup',\n fqdn: customDomain,\n lease: uuid ? { leaseUuid: uuid } : null,\n };\n // Symmetric `onComplete` fire (Copilot review PR #60, comment\n // 3288656598). Pre-fix, the lookup path returned without invoking\n // `onComplete` — asymmetric vs the set/clear paths in this same\n // function and vs `closeLease` / `troubleshootDeployment`. Was\n // documented as \"intentional\" in PR_DESCRIPTION.md Risks #1 but\n // was really an oversight rationalized post-hoc. Now consistent.\n callbacks.onComplete?.(lookupResult);\n return lookupResult;\n}\n\nfunction isNotFoundError(err: unknown): boolean {\n // Pass-through guard for structured failures: a `ManifestMCPError` is\n // always a real, intentional error — never silently re-classified as\n // \"FQDN unclaimed\" even if its message happens to contain \"not found\".\n if (err instanceof ManifestMCPError) return false;\n if (!(err instanceof Error)) return false;\n const msg = err.message;\n return NOT_FOUND_RES.some((re) => msg.match(re) !== null);\n}\n\nfunction readLeaseUuid(lease: unknown): string | undefined {\n if (lease === null || typeof lease !== 'object') return undefined;\n const r = lease as {\n uuid?: unknown;\n lease_uuid?: unknown;\n leaseUuid?: unknown;\n };\n const u = r.uuid ?? r.lease_uuid ?? r.leaseUuid;\n return typeof u === 'string' && u.length > 0 ? u : undefined;\n}\n\nfunction deriveFinalCustomDomain(\n diagnostic: VerifyDomainResult,\n action: 'set' | 'clear',\n): string | null {\n if (action === 'clear') return null;\n const actual = diagnostic.actual ?? '';\n return actual.length > 0 ? actual : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,UACJ;AAeF,MAAM,UACJ;AAEF,MAAM,mBAAmB;;;;;;;;;;;;;AAczB,MAAM,gBAAmC;CACvC;CACA;CACA;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,eAAsB,aACpB,MACA,WACA,MAC6B;CAC7B,aAAa,IAAI;CAEjB,IAAI,KAAK,WAAW,UAClB,OAAO,MAAM,aAAa,KAAK,MAAM,WAAW,IAAI;CAGtD,MAAM,cAAc,KAAK;CAUzB,MAAM,OAAO,KAAK,WAAW,QAAQ,KAAK,KAAK,KAAK,EAAE,YAAY,IAAI;CAKtE,MAAM,KAAK,sBAAsB;EAC/B;EACA,YAAY,UAAU;EACtB,SAAS;EACT,YAAY;CACd,CAAC;CACD,GAAG,iBAAiB;CAGpB,MAAM,QAAQ,wBAAwB,IAAI;CAC1C,IAAI,UAAU;MAER,MADgB,GAAG,KAAK,UAAU,UAAU,KAAK,CAAC,MACxC,OACZ,MAAM,IAAI,iBACR,qBAAqB,qBACrB,+CAA+C,KAAK,OAAO,EAC7D;CAAA;CAGJ,UAAU,aAAa,EAAE,MAAM,iBAAiB,CAAC;CAMjD,MAAM,YAAY,eAAe,KAAK,SAAS;CAC/C,GAAG,iBAAiB;CACpB,MAAM,oBACJ;EAAE,OAAO,KAAK;EAAe,QAAQ;CAAW,GAChD,KAAK,WAAW,QACZ;EAAE;EAAW,cAAc,UAAU,IAAI;EAAG;CAAY,IAC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