@modainteract/moda-interact-shared 5.0.0 → 5.2.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/security/credentials/errors.ts","../src/security/credentials/aad.ts","../src/security/credentials/keyring.ts","../src/security/credentials/command-hmac-key.ts","../src/security/credentials/aead.ts"],"sourcesContent":["/** A stable, secret-free error vocabulary shared by credential-security operations. */\nexport type CredentialSecurityErrorCode =\n | \"INVALID_KEYRING\"\n | \"KEY_UNAVAILABLE\"\n | \"INVALID_CREDENTIAL\"\n | \"INVALID_COMMAND_HMAC_KEY\";\n\nconst MESSAGES: Readonly<Record<CredentialSecurityErrorCode, string>> = {\n INVALID_KEYRING: \"Invalid credential keyring configuration\",\n KEY_UNAVAILABLE: \"Credential encryption key is unavailable\",\n INVALID_CREDENTIAL: \"Invalid encrypted credential\",\n INVALID_COMMAND_HMAC_KEY: \"Invalid command authentication key\",\n};\n\nexport class CredentialSecurityError extends Error {\n readonly code: CredentialSecurityErrorCode;\n\n constructor(code: CredentialSecurityErrorCode) {\n super(MESSAGES[code]);\n this.name = \"CredentialSecurityError\";\n this.code = code;\n }\n}\n","import { canonicalJson } from \"../../commerce/canonical-json.js\";\nimport {\n CommerceEnvironmentSchema,\n type CommerceEnvironment,\n} from \"../../commerce/model/index.js\";\nimport { CredentialSecurityError } from \"./errors.js\";\n\nconst KEY_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\nconst PURPOSES = new Set([\"MERCHANT_KNOWLEDGE\", \"REFERENCE_TAXONOMY\"]);\nconst FORBIDDEN_ID_CHARACTERS = /[\\r\\n\\0]/;\nconst INVALID_UNICODE = /\\p{Surrogate}/u;\nconst RESERVED_KEY_IDS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\ntype EmbeddingPurpose = \"MERCHANT_KNOWLEDGE\" | \"REFERENCE_TAXONOMY\";\n\nexport type CommerceEmbeddingCredentialAadInput = Readonly<{\n environment: CommerceEnvironment;\n purpose: EmbeddingPurpose;\n provider: string;\n keyId: string;\n}>;\n\nexport type WooRestReadGrantAadInput = Readonly<{\n shopId: string;\n installationId: string;\n authorizationAttemptId: string;\n credentialVersionSnapshot: number;\n}>;\n\nfunction invalidAad(): never {\n // The message/code are constant: never interpolate merchant identifiers or secrets.\n throw new CredentialSecurityError(\"INVALID_CREDENTIAL\");\n}\n\nfunction isBoundedIdentifier(value: unknown, limit: number): value is string {\n return typeof value === \"string\" &&\n value.length >= 1 && value.length <= limit &&\n value.trim().length > 0 &&\n !FORBIDDEN_ID_CHARACTERS.test(value) &&\n !INVALID_UNICODE.test(value);\n}\n\n/** Preserve the existing embedding canonical-JSON AAD bytes across writer/readers. */\nexport function createCommerceEmbeddingCredentialAad(\n input: CommerceEmbeddingCredentialAadInput,\n): string {\n if (\n input === null || typeof input !== \"object\" ||\n !CommerceEnvironmentSchema.safeParse(input.environment).success ||\n !PURPOSES.has(input.purpose) ||\n !isBoundedIdentifier(input.provider, 128) ||\n typeof input.keyId !== \"string\" ||\n !KEY_ID_PATTERN.test(input.keyId) ||\n RESERVED_KEY_IDS.has(input.keyId)\n ) {\n return invalidAad();\n }\n\n return canonicalJson({\n credentialType: \"EMBEDDING\",\n environment: input.environment,\n purpose: input.purpose,\n provider: input.provider,\n keyId: input.keyId,\n });\n}\n\n/** Preserve the existing Woo API/Background JSON-array AAD bytes exactly. */\nexport function createWooRestReadGrantAad(input: WooRestReadGrantAadInput): string {\n if (\n input === null || typeof input !== \"object\" ||\n !isBoundedIdentifier(input.shopId, 128) ||\n !isBoundedIdentifier(input.installationId, 128) ||\n !isBoundedIdentifier(input.authorizationAttemptId, 128) ||\n !Number.isSafeInteger(input.credentialVersionSnapshot) ||\n input.credentialVersionSnapshot < 1\n ) {\n return invalidAad();\n }\n\n return JSON.stringify([\n \"moda-woo-rest-read-v1\",\n input.shopId,\n input.installationId,\n input.authorizationAttemptId,\n input.credentialVersionSnapshot,\n ]);\n}\n","import { Buffer } from \"node:buffer\";\nimport { CredentialSecurityError } from \"./errors.js\";\n\nconst KEY_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\nconst STANDARD_BASE64_KEY_PATTERN = /^[A-Za-z0-9+/]{43}=$/;\nconst RESERVED_KEY_IDS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\nconst MAX_CONFIG_BYTES = 4096;\nconst MAX_KEYS = 16;\nconst KEY_BYTES = 32;\n\nexport interface CredentialKeyring {\n readonly keyIds: readonly string[];\n hasKey(keyId: string): boolean;\n}\n\n// The keyring descriptor never contains key material. In particular, consumers cannot\n// obtain a reference to any retained secret through keyIds, hasKey, or object inspection.\nconst privateKeys = new WeakMap<CredentialKeyring, ReadonlyMap<string, Uint8Array>>();\n\nfunction invalidKeyring(): never {\n throw new CredentialSecurityError(\"INVALID_KEYRING\");\n}\n\n/**\n * Read a JSON string token, returning the decoded contents and the next offset.\n * JSON.parse validates escapes (including Unicode escapes) and rejects malformed text.\n * Only decoded property names are compared, preventing escaped duplicate aliases.\n */\nfunction readJsonString(raw: string, start: number): [string, number] {\n if (raw[start] !== '\"') invalidKeyring();\n let cursor = start + 1;\n while (cursor < raw.length) {\n const character = raw[cursor];\n if (character === \"\\\\\") {\n cursor += 2;\n continue;\n }\n if (character === '\"') {\n const decoded: unknown = JSON.parse(raw.slice(start, cursor + 1));\n if (typeof decoded !== \"string\") invalidKeyring();\n return [decoded, cursor + 1];\n }\n cursor += 1;\n }\n return invalidKeyring();\n}\n\n/**\n * A small strict JSON-object scanner: the only supported format is a top-level\n * object mapping JSON string IDs to JSON string key values. Using JSON.parse(raw)\n * alone would silently discard duplicate property names, which we must reject.\n */\nfunction parseUniqueStringObject(raw: string): Map<string, string> {\n // Validate the complete JSON grammar, including escape sequences and trailing data.\n let decoded: unknown;\n try {\n decoded = JSON.parse(raw);\n } catch {\n return invalidKeyring();\n }\n if (decoded === null || typeof decoded !== \"object\" || Array.isArray(decoded)) {\n return invalidKeyring();\n }\n\n let index = 0;\n const skipWhitespace = (): void => {\n while (index < raw.length && /[ \\t\\r\\n]/.test(raw[index]!)) index += 1;\n };\n\n const entries = new Map<string, string>();\n skipWhitespace();\n if (raw[index++] !== \"{\") return invalidKeyring();\n skipWhitespace();\n if (raw[index] === \"}\") return invalidKeyring();\n\n while (index < raw.length) {\n const [key, afterKey] = readJsonString(raw, index);\n if (entries.has(key)) return invalidKeyring();\n if (!KEY_ID_PATTERN.test(key) || RESERVED_KEY_IDS.has(key)) return invalidKeyring();\n index = afterKey;\n skipWhitespace();\n if (raw[index++] !== \":\") return invalidKeyring();\n skipWhitespace();\n const [value, afterValue] = readJsonString(raw, index);\n entries.set(key, value);\n if (entries.size > MAX_KEYS) return invalidKeyring();\n index = afterValue;\n skipWhitespace();\n const separator = raw[index++];\n if (separator === \"}\") break;\n if (separator !== \",\") return invalidKeyring();\n skipWhitespace();\n }\n skipWhitespace();\n if (index !== raw.length || entries.size === 0) return invalidKeyring();\n return entries;\n}\n\n/** Validate and retain canonical 32-byte AES key material without exposing the bytes. */\nexport function parseCredentialKeyring(raw: string | undefined): CredentialKeyring {\n if (typeof raw !== \"string\" || raw.trim().length === 0 || Buffer.byteLength(raw, \"utf8\") > MAX_CONFIG_BYTES) {\n return invalidKeyring();\n }\n\n let entries: Map<string, string>;\n try {\n entries = parseUniqueStringObject(raw);\n } catch {\n // No native JSON parsing error or untrusted data may escape this boundary.\n return invalidKeyring();\n }\n\n const keys = new Map<string, Uint8Array>();\n for (const [keyId, encoded] of entries) {\n if (!STANDARD_BASE64_KEY_PATTERN.test(encoded)) return invalidKeyring();\n const bytes = Buffer.from(encoded, \"base64\");\n if (bytes.length !== KEY_BYTES || bytes.toString(\"base64\") !== encoded) {\n return invalidKeyring();\n }\n keys.set(keyId, Uint8Array.from(bytes));\n }\n\n const keyIds = Object.freeze([...keys.keys()].sort());\n const descriptor: CredentialKeyring = Object.freeze({\n keyIds,\n hasKey: (keyId: string): boolean => typeof keyId === \"string\" && keys.has(keyId),\n });\n privateKeys.set(descriptor, keys);\n return descriptor;\n}\n\n/** An explicit writer selection; never select the first key or trim an input. */\nexport function resolveActiveCredentialKey(\n keyring: CredentialKeyring,\n activeKeyId: string | undefined,\n): string {\n const keys = privateKeys.get(keyring);\n if (\n !keys ||\n typeof activeKeyId !== \"string\" ||\n !KEY_ID_PATTERN.test(activeKeyId) ||\n RESERVED_KEY_IDS.has(activeKeyId) ||\n !keys.has(activeKeyId)\n ) {\n throw new CredentialSecurityError(\"KEY_UNAVAILABLE\");\n }\n return activeKeyId;\n}\n\n/**\n * Package-internal helper for SHARED-002. Never re-export from the public Node\n * entrypoint. Return a defensive copy so an AEAD consumer cannot mutate the\n * retained key material (including after an encryption failure).\n */\nexport function getCredentialKeyBytes(keyring: CredentialKeyring, keyId: string): Uint8Array {\n const bytes = privateKeys.get(keyring)?.get(keyId);\n if (!bytes) throw new CredentialSecurityError(\"KEY_UNAVAILABLE\");\n return Uint8Array.from(bytes);\n}\n","import { Buffer } from \"node:buffer\";\nimport { timingSafeEqual } from \"node:crypto\";\nimport { CredentialSecurityError } from \"./errors.js\";\nimport { getCredentialKeyBytes, type CredentialKeyring } from \"./keyring.js\";\n\nconst CANONICAL_BASE64_32_BYTE_KEY = /^[A-Za-z0-9+/]{43}=$/;\n\nfunction invalidCommandHmacKey(): never {\n throw new CredentialSecurityError(\"INVALID_COMMAND_HMAC_KEY\");\n}\n\n/**\n * Decode the Commerce connection-command HMAC secret, without accessing service\n * configuration or exposing AES key bytes. The caller supplies the configured\n * value and the canonical AES keyring explicitly.\n */\nexport function parseCommerceConnectionCommandHmacKey(\n raw: string | undefined,\n aesKeyring: CredentialKeyring,\n): Uint8Array {\n if (typeof raw !== \"string\" || !CANONICAL_BASE64_32_BYTE_KEY.test(raw)) {\n return invalidCommandHmacKey();\n }\n\n const decoded = Buffer.from(raw, \"base64\");\n if (decoded.length !== 32 || decoded.toString(\"base64\") !== raw) {\n return invalidCommandHmacKey();\n }\n\n // Examine *every* AES key, rather than returning on the first match. A\n // failed or forged keyring must never bypass the separation requirement.\n let reusesEncryptionKey = false;\n try {\n for (const keyId of aesKeyring.keyIds) {\n const aesBytes = getCredentialKeyBytes(aesKeyring, keyId);\n try {\n reusesEncryptionKey = timingSafeEqual(decoded, aesBytes) || reusesEncryptionKey;\n } finally {\n aesBytes.fill(0); // Only wipes the defensive copy, not the keyring.\n }\n }\n // The parser creates a nonempty keyring; reject invalid caller-supplied\n // substitutes rather than treating them as an empty, trusted keyring.\n if (aesKeyring.keyIds.length === 0) return invalidCommandHmacKey();\n } catch {\n return invalidCommandHmacKey();\n }\n\n if (reusesEncryptionKey) return invalidCommandHmacKey();\n return Uint8Array.from(decoded);\n}\n","import { Buffer } from \"node:buffer\";\nimport { createCipheriv, createDecipheriv, randomBytes } from \"node:crypto\";\nimport { TextDecoder } from \"node:util\";\nimport { CredentialSecurityError } from \"./errors.js\";\nimport {\n getCredentialKeyBytes,\n resolveActiveCredentialKey,\n type CredentialKeyring,\n} from \"./keyring.js\";\n\nconst NONCE_BYTES = 12;\nconst AUTH_TAG_BYTES = 16;\nconst MAX_CREDENTIAL_BYTES = 8192;\nconst MAX_AAD_BYTES = 4096;\nconst KEY_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\nconst RESERVED_KEY_IDS = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\n\n/** Crypto envelope only; persistence and AAD construction belong to the caller. */\nexport type CredentialEnvelope = Readonly<{\n keyId: string;\n nonce: Uint8Array;\n ciphertext: Uint8Array;\n authTag: Uint8Array;\n}>;\n\nfunction invalidCredential(): never {\n throw new CredentialSecurityError(\"INVALID_CREDENTIAL\");\n}\n\n/** Reject UTF-16 strings that Node would otherwise encode with replacement bytes. */\nfunction isValidUnicode(value: string): boolean {\n for (let index = 0; index < value.length; index += 1) {\n const unit = value.charCodeAt(index);\n if (unit >= 0xd800 && unit <= 0xdbff) {\n if (index + 1 === value.length) return false;\n const next = value.charCodeAt(index + 1);\n if (next < 0xdc00 || next > 0xdfff) return false;\n index += 1;\n } else if (unit >= 0xdc00 && unit <= 0xdfff) {\n return false;\n }\n }\n return true;\n}\n\nfunction aadBytes(value: unknown): Buffer {\n let bytes: Buffer;\n if (typeof value === \"string\") {\n if (!isValidUnicode(value)) return invalidCredential();\n bytes = Buffer.from(value, \"utf8\");\n } else if (value instanceof Uint8Array) {\n // Copy the exact view, not its possibly larger underlying ArrayBuffer.\n bytes = Buffer.from(value);\n } else {\n return invalidCredential();\n }\n if (bytes.length < 1 || bytes.length > MAX_AAD_BYTES) return invalidCredential();\n return bytes;\n}\n\nfunction validEnvelope(value: unknown): value is CredentialEnvelope {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const candidate = value as Partial<CredentialEnvelope>;\n return (\n typeof candidate.keyId === \"string\" &&\n KEY_ID_PATTERN.test(candidate.keyId) &&\n !RESERVED_KEY_IDS.has(candidate.keyId) &&\n candidate.nonce instanceof Uint8Array &&\n candidate.nonce.byteLength === NONCE_BYTES &&\n candidate.ciphertext instanceof Uint8Array &&\n candidate.ciphertext.byteLength >= 1 &&\n candidate.ciphertext.byteLength <= MAX_CREDENTIAL_BYTES &&\n candidate.authTag instanceof Uint8Array &&\n candidate.authTag.byteLength === AUTH_TAG_BYTES\n );\n}\n\n/** Keep native crypto and UTF-8 decoding exceptions out of the public error contract. */\nfunction protectCredentialOperation<T>(operation: () => T): T {\n try {\n return operation();\n } catch (error) {\n if (error instanceof CredentialSecurityError) throw error;\n return invalidCredential();\n }\n}\n\n/** Encrypt a UTF-8 credential with caller-provided, mandatory authenticated data. */\nexport function encryptCredential(input: {\n keyring: CredentialKeyring;\n activeKeyId: string;\n plaintext: string;\n aad: string | Uint8Array;\n}): CredentialEnvelope {\n return protectCredentialOperation(() => {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return invalidCredential();\n const { keyring, activeKeyId, plaintext, aad } = input;\n if (typeof plaintext !== \"string\" || !isValidUnicode(plaintext)) return invalidCredential();\n const plaintextBytes = Buffer.from(plaintext, \"utf8\");\n if (plaintextBytes.length < 1 || plaintextBytes.length > MAX_CREDENTIAL_BYTES) {\n plaintextBytes.fill(0);\n return invalidCredential();\n }\n let key: Uint8Array | undefined;\n try {\n const authenticatedData = aadBytes(aad);\n const keyId = resolveActiveCredentialKey(keyring, activeKeyId);\n key = getCredentialKeyBytes(keyring, keyId);\n const nonce = randomBytes(NONCE_BYTES);\n const cipher = createCipheriv(\"aes-256-gcm\", key, nonce, { authTagLength: AUTH_TAG_BYTES });\n cipher.setAAD(authenticatedData);\n const ciphertext = Buffer.concat([cipher.update(plaintextBytes), cipher.final()]);\n return Object.freeze({\n keyId,\n nonce: Uint8Array.from(nonce),\n ciphertext: Uint8Array.from(ciphertext),\n authTag: Uint8Array.from(cipher.getAuthTag()),\n });\n } finally {\n key?.fill(0);\n plaintextBytes.fill(0);\n }\n });\n}\n\n/** Decrypt only authenticated UTF-8 text; never return unauthenticated bytes. */\nexport function decryptCredential(input: {\n keyring: CredentialKeyring;\n envelope: CredentialEnvelope;\n aad: string | Uint8Array;\n}): string {\n return protectCredentialOperation(() => {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return invalidCredential();\n const { keyring, envelope, aad } = input;\n if (!validEnvelope(envelope)) return invalidCredential();\n const authenticatedData = aadBytes(aad);\n const key = getCredentialKeyBytes(keyring, envelope.keyId);\n let plaintextBytes: Buffer | undefined;\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", key, Buffer.from(envelope.nonce), {\n authTagLength: AUTH_TAG_BYTES,\n });\n decipher.setAAD(authenticatedData);\n decipher.setAuthTag(Buffer.from(envelope.authTag));\n plaintextBytes = Buffer.concat([\n decipher.update(Buffer.from(envelope.ciphertext)),\n decipher.final(),\n ]);\n // ignoreBOM preserves a leading U+FEFF so decrypt(encrypt(text)) is exact.\n return new TextDecoder(\"utf-8\", { fatal: true, ignoreBOM: true }).decode(plaintextBytes);\n } finally {\n plaintextBytes?.fill(0);\n key.fill(0);\n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,QACjF,eAAe;AAAA,MACjB,CAAC;AACD,eAAS,OAAO,iBAAiB;AACjC,eAAS,WAAWA,QAAO,KAAK,SAAS,OAAO,CAAC;AACjD,uBAAiBA,QAAO,OAAO;AAAA,QAC7B,SAAS,OAAOA,QAAO,KAAK,SAAS,UAAU,CAAC;AAAA,QAChD,SAAS,MAAM;AAAA,MACjB,CAAC;AAED,aAAO,IAAI,YAAY,SAAS,EAAE,OAAO,MAAM,WAAW,KAAK,CAAC,EAAE,OAAO,cAAc;AAAA,IACzF,UAAE;AACA,sBAAgB,KAAK,CAAC;AACtB,UAAI,KAAK,CAAC;AAAA,IACZ;AAAA,EACF,CAAC;AACH;","names":["KEY_ID_PATTERN","RESERVED_KEY_IDS","Buffer","Buffer","Buffer","KEY_ID_PATTERN","RESERVED_KEY_IDS","Buffer"]}
@@ -1,6 +1,8 @@
1
- import { a as CommerceConversationGrant, e as CommerceBuiltInToolDescriptor, P as PublishedToolDescriptor, G as GrantedTool, b as CommerceManifest, S as SubsetSchema, f as CommerceToolDefinition, d as CommerceFinalResponse, D as Digest, C as CommerceTurnIdentity, g as CommerceBuiltInToolGrant } from '../response-DUOmPh9C.js';
2
- export { h as CommerceAlternativeSchema, i as CommerceAnswerPresentationSelection, j as CommerceAnswerPresentationSelectionSchema, k as CommerceAssertionSchema, l as CommerceBasketSchema, m as CommerceBuiltInToolDescriptorSchema, n as CommerceBuiltInToolGrantSchema, o as CommerceBuiltInToolNameSchema, p as CommerceCategoryCandidate, q as CommerceCategoryCandidateSchema, r as CommerceCategoryResolution, s as CommerceCategoryResolutionSchema, t as CommerceConversationGrantSchema, u as CommerceDefinitionCompiler, v as CommerceDiscountCombinationFacts, w as CommerceDiscountCombinationFactsSchema, x as CommerceDiscountConditionFacts, y as CommerceDiscountConditionFactsSchema, z as CommerceDiscountDetails, A as CommerceDiscountDetailsSchema, B as CommerceErrorCodeSchema, E as CommerceEvidence, F as CommerceEvidenceSchema, H as CommerceExecuteAssertionSchema, I as CommerceExecutionSchema, J as CommerceFinalResponseSchema, K as CommerceManifestSchema, L as CommerceOfferSchema, M as CommerceOptionalLookupUnavailable, N as CommerceOptionalLookupUnavailableSchema, O as CommerceProductRecommendationSelection, Q as CommerceProductRecommendationSelectionSchema, R as CommerceProductSaleEvidence, U as CommerceProductSaleEvidenceSchema, V as CommerceProductSchema, W as CommerceProposalSchema, X as CommerceReleaseIdentitySchema, Y as CommerceResolveAssertionSchema, Z as CommerceResponseContract, _ as CommerceResponseContractSchema, $ as CommerceResponseDisposition, a0 as CommerceResponseDispositionSchema, a1 as CommerceShippingInformation, a2 as CommerceShippingInformationInput, a3 as CommerceShippingInformationInputSchema, a4 as CommerceShippingInformationSchema, a5 as CommerceToolDefinitionSchema, a6 as CommerceToolDraftDefinition, a7 as CommerceToolDraftDefinitionSchema, a8 as CommerceToolIdentitySchema, a9 as CommerceToolInputs, aa as CommerceToolOutputs, c as CommerceToolResult, ab as CommerceToolResultSchema, ac as CommerceToolRevisionIdentitySchema, ad as CommerceTurnIdentitySchema, ae as DetailsSchemaSchema, af as EMPTY_RESPONSE_CONTRACT, ag as ExternalHttpExecution, ah as ExternalHttpExecutionSchema, ai as GrantedToolSchema, aj as GrantedToolsSchema, ak as InputSchemaSchema, al as Json, am as MONEY_PATTERN, an as POLICY_OPERATIONS, ao as POLICY_OPERATION_DESCRIPTORS, ap as PublishedGrantedTool, aq as PublishedGrantedToolSchema, ar as PublishedToolDescriptorSchema, as as ReferralReasonSchema, at as ResponseTemplateSchema, T as ToolDescriptor, au as ToolDescriptorSchema, av as ToolNameSchema, aw as canonicalJson, ax as commerceToolResultSchema, ay as compileSubset, az as definitionToMcpDescriptor, aA as finalResponseSchema, aB as finalResponseToolSchema, aC as isBuiltInTool, aD as jsonBytes, aE as mapToolArguments, aF as matchesSubset, aG as productBelongsToDomain, aH as responseContractCanonicalJson, aI as safeName, aJ as safePath, aK as toolHashInput, aL as validateDefinitionForPublication, aM as validateDefinitionVersion, aN as validateSubset, aO as verifyResponseContract } from '../response-DUOmPh9C.js';
1
+ import { a as CommerceConversationGrant, e as CommerceBuiltInToolDescriptor, P as PublishedToolDescriptor, G as GrantedTool, b as CommerceManifest, S as SubsetSchema, f as CommerceToolDefinition, d as CommerceFinalResponse, D as Digest, C as CommerceTurnIdentity, g as CommerceBuiltInToolGrant } from '../response-k0hO3yus.js';
2
+ export { h as CommerceAlternativeSchema, i as CommerceAnswerPresentationSelection, j as CommerceAnswerPresentationSelectionSchema, k as CommerceAssertionSchema, l as CommerceBasketSchema, m as CommerceBuiltInToolDescriptorSchema, n as CommerceBuiltInToolGrantSchema, o as CommerceBuiltInToolNameSchema, p as CommerceCategoryCandidate, q as CommerceCategoryCandidateSchema, r as CommerceCategoryResolution, s as CommerceCategoryResolutionSchema, t as CommerceConversationGrantSchema, u as CommerceDefinitionCompiler, v as CommerceDiscountCombinationFacts, w as CommerceDiscountCombinationFactsSchema, x as CommerceDiscountConditionFacts, y as CommerceDiscountConditionFactsSchema, z as CommerceDiscountDetails, A as CommerceDiscountDetailsSchema, B as CommerceErrorCodeSchema, E as CommerceEvidence, F as CommerceEvidenceSchema, H as CommerceExecuteAssertionSchema, I as CommerceExecutionSchema, J as CommerceFinalResponseSchema, K as CommerceManifestSchema, L as CommerceOfferSchema, M as CommerceOptionalLookupUnavailable, N as CommerceOptionalLookupUnavailableSchema, O as CommerceProductRecommendationSelection, Q as CommerceProductRecommendationSelectionSchema, R as CommerceProductSaleEvidence, U as CommerceProductSaleEvidenceSchema, V as CommerceProductSchema, W as CommerceProposalSchema, X as CommerceReleaseIdentitySchema, Y as CommerceResolveAssertionSchema, Z as CommerceResponseContract, _ as CommerceResponseContractSchema, $ as CommerceResponseDisposition, a0 as CommerceResponseDispositionSchema, a1 as CommerceShippingInformation, a2 as CommerceShippingInformationInput, a3 as CommerceShippingInformationInputSchema, a4 as CommerceShippingInformationSchema, a5 as CommerceToolDefinitionSchema, a6 as CommerceToolDraftDefinition, a7 as CommerceToolDraftDefinitionSchema, a8 as CommerceToolIdentitySchema, a9 as CommerceToolInputs, aa as CommerceToolOutputs, c as CommerceToolResult, ab as CommerceToolResultSchema, ac as CommerceToolRevisionIdentitySchema, ad as CommerceTurnIdentitySchema, ae as DetailsSchemaSchema, af as EMPTY_RESPONSE_CONTRACT, ag as ExternalHttpExecution, ah as ExternalHttpExecutionSchema, ai as GrantedToolSchema, aj as GrantedToolsSchema, ak as InputSchemaSchema, al as Json, am as MONEY_PATTERN, an as POLICY_OPERATIONS, ao as POLICY_OPERATION_DESCRIPTORS, ap as PublishedGrantedTool, aq as PublishedGrantedToolSchema, ar as PublishedToolDescriptorSchema, as as ReferralReasonSchema, at as ResponseTemplateSchema, T as ToolDescriptor, au as ToolDescriptorSchema, av as ToolNameSchema, aw as canonicalJson, ax as commerceToolResultSchema, ay as compileSubset, az as definitionToMcpDescriptor, aA as finalResponseSchema, aB as finalResponseToolSchema, aC as isBuiltInTool, aD as jsonBytes, aE as mapToolArguments, aF as matchesSubset, aG as productBelongsToDomain, aH as responseContractCanonicalJson, aI as safeName, aJ as safePath, aK as toolHashInput, aL as validateDefinitionForPublication, aM as validateDefinitionVersion, aN as validateSubset, aO as verifyResponseContract } from '../response-k0hO3yus.js';
3
+ import * as zod from 'zod';
3
4
  import { z } from 'zod';
5
+ import * as zod_v4_core from 'zod/v4/core';
4
6
 
5
7
  declare const ContractVersionSchema: z.ZodLiteral<"commerce.v1">;
6
8
  declare const IdSchema: z.ZodString;
@@ -13,6 +15,169 @@ declare const LanguageSchema: z.ZodString;
13
15
  declare const distinct: <T>(values: T[]) => boolean;
14
16
  declare const boundedJson: (bytes: number) => z.ZodUnknown;
15
17
 
18
+ /**
19
+ * Canonical Shared mapping for the two published discount capabilities.
20
+ * Consumers reuse these validators instead of maintaining local copies.
21
+ * `operationVersion` is independent of immutable published tool definition
22
+ * versions selected by Commerce during publication.
23
+ */
24
+ declare const DISCOUNT_POLICY_OPERATION_DESCRIPTORS: readonly [Readonly<{
25
+ toolName: "commerce_get_discount_options";
26
+ displayName: "Get Discount Options";
27
+ operation: "discounts.getOptions";
28
+ operationVersion: "1.0.0";
29
+ description: "Read the configured discount mode and available offers.";
30
+ inputValidator: zod.ZodObject<{
31
+ limit: zod.ZodDefault<zod.ZodNumber>;
32
+ cursor: zod.ZodDefault<zod.ZodNullable<zod.ZodString>>;
33
+ }, zod_v4_core.$strict>;
34
+ outputValidator: zod.ZodUnion<readonly [zod.ZodObject<{
35
+ outcome: zod.ZodEnum<{
36
+ UNAVAILABLE: "UNAVAILABLE";
37
+ }>;
38
+ reasonCode: zod.ZodEnum<{
39
+ TEMPORARY_UNAVAILABLE: "TEMPORARY_UNAVAILABLE";
40
+ }>;
41
+ }, zod_v4_core.$strict>, zod.ZodObject<{
42
+ mode: zod.ZodEnum<{
43
+ NONE: "NONE";
44
+ FIXED: "FIXED";
45
+ AI_BEST_APPLICABLE: "AI_BEST_APPLICABLE";
46
+ }>;
47
+ offers: zod.ZodArray<zod.ZodObject<{
48
+ offerId: zod.ZodString;
49
+ title: zod.ZodString;
50
+ method: zod.ZodEnum<{
51
+ AUTOMATIC: "AUTOMATIC";
52
+ CODE: "CODE";
53
+ }>;
54
+ code: zod.ZodNullable<zod.ZodString>;
55
+ startsAt: zod.ZodNullable<zod.ZodString>;
56
+ endsAt: zod.ZodNullable<zod.ZodString>;
57
+ support: zod.ZodEnum<{
58
+ SUPPORTED: "SUPPORTED";
59
+ UNSUPPORTED: "UNSUPPORTED";
60
+ UNKNOWN: "UNKNOWN";
61
+ }>;
62
+ reasonCodes: zod.ZodArray<zod.ZodString>;
63
+ }, zod_v4_core.$strict>>;
64
+ truncated: zod.ZodBoolean;
65
+ cursor: zod.ZodOptional<zod.ZodNullable<zod.ZodString>>;
66
+ }, zod_v4_core.$strict>]>;
67
+ }>, Readonly<{
68
+ toolName: "commerce_get_discount_details";
69
+ displayName: "Get Discount Details";
70
+ operation: "discounts.getDetails";
71
+ operationVersion: "1.0.0";
72
+ description: "Read details and condition facts for a permitted discount.";
73
+ inputValidator: zod.ZodObject<{
74
+ offerId: zod.ZodString;
75
+ }, zod_v4_core.$strict>;
76
+ outputValidator: zod.ZodUnion<readonly [zod.ZodObject<{
77
+ outcome: zod.ZodEnum<{
78
+ UNAVAILABLE: "UNAVAILABLE";
79
+ }>;
80
+ reasonCode: zod.ZodEnum<{
81
+ TEMPORARY_UNAVAILABLE: "TEMPORARY_UNAVAILABLE";
82
+ }>;
83
+ }, zod_v4_core.$strict>, zod.ZodObject<{
84
+ details: zod.ZodNullable<zod.ZodObject<{
85
+ offer: zod.ZodObject<{
86
+ offerId: zod.ZodString;
87
+ title: zod.ZodString;
88
+ method: zod.ZodEnum<{
89
+ AUTOMATIC: "AUTOMATIC";
90
+ CODE: "CODE";
91
+ }>;
92
+ code: zod.ZodNullable<zod.ZodString>;
93
+ startsAt: zod.ZodNullable<zod.ZodString>;
94
+ endsAt: zod.ZodNullable<zod.ZodString>;
95
+ support: zod.ZodEnum<{
96
+ SUPPORTED: "SUPPORTED";
97
+ UNSUPPORTED: "UNSUPPORTED";
98
+ UNKNOWN: "UNKNOWN";
99
+ }>;
100
+ reasonCodes: zod.ZodArray<zod.ZodString>;
101
+ }, zod_v4_core.$strict>;
102
+ facts: zod.ZodObject<{
103
+ provider: zod.ZodEnum<{
104
+ SHOPIFY: "SHOPIFY";
105
+ WOOCOMMERCE: "WOOCOMMERCE";
106
+ }>;
107
+ completeness: zod.ZodEnum<{
108
+ UNKNOWN: "UNKNOWN";
109
+ COMPLETE: "COMPLETE";
110
+ PARTIAL: "PARTIAL";
111
+ }>;
112
+ observedAt: zod.ZodString;
113
+ providerStatus: zod.ZodString;
114
+ unavailableAt: zod.ZodNullable<zod.ZodString>;
115
+ discountKind: zod.ZodEnum<{
116
+ UNKNOWN: "UNKNOWN";
117
+ PERCENTAGE: "PERCENTAGE";
118
+ FIXED_AMOUNT: "FIXED_AMOUNT";
119
+ FREE_SHIPPING: "FREE_SHIPPING";
120
+ BUY_X_GET_Y: "BUY_X_GET_Y";
121
+ OTHER: "OTHER";
122
+ }>;
123
+ discountValue: zod.ZodNullable<zod.ZodString>;
124
+ discountCurrency: zod.ZodNullable<zod.ZodString>;
125
+ targeting: zod.ZodObject<{
126
+ kind: zod.ZodEnum<{
127
+ UNKNOWN: "UNKNOWN";
128
+ ALL: "ALL";
129
+ PRODUCTS: "PRODUCTS";
130
+ VARIANTS: "VARIANTS";
131
+ CATEGORIES: "CATEGORIES";
132
+ COLLECTIONS: "COLLECTIONS";
133
+ MIXED: "MIXED";
134
+ }>;
135
+ includedProductIds: zod.ZodArray<zod.ZodString>;
136
+ includedVariantIds: zod.ZodArray<zod.ZodString>;
137
+ includedCategoryIds: zod.ZodArray<zod.ZodString>;
138
+ includedCollectionIds: zod.ZodArray<zod.ZodString>;
139
+ excludedProductIds: zod.ZodArray<zod.ZodString>;
140
+ excludedVariantIds: zod.ZodArray<zod.ZodString>;
141
+ excludedCategoryIds: zod.ZodArray<zod.ZodString>;
142
+ excludedCollectionIds: zod.ZodArray<zod.ZodString>;
143
+ }, zod_v4_core.$strict>;
144
+ minimumSubtotal: zod.ZodNullable<zod.ZodString>;
145
+ maximumSubtotal: zod.ZodNullable<zod.ZodString>;
146
+ subtotalRequirementCurrency: zod.ZodNullable<zod.ZodString>;
147
+ minimumQuantity: zod.ZodNullable<zod.ZodNumber>;
148
+ usageLimit: zod.ZodNullable<zod.ZodNumber>;
149
+ usageCount: zod.ZodNullable<zod.ZodNumber>;
150
+ perCustomerLimit: zod.ZodNullable<zod.ZodNumber>;
151
+ customerScope: zod.ZodEnum<{
152
+ UNKNOWN: "UNKNOWN";
153
+ ALL: "ALL";
154
+ RESTRICTED: "RESTRICTED";
155
+ }>;
156
+ excludesSaleItems: zod.ZodNullable<zod.ZodBoolean>;
157
+ individualUse: zod.ZodNullable<zod.ZodBoolean>;
158
+ combination: zod.ZodObject<{
159
+ discountClasses: zod.ZodNullable<zod.ZodArray<zod.ZodEnum<{
160
+ ORDER: "ORDER";
161
+ PRODUCT: "PRODUCT";
162
+ SHIPPING: "SHIPPING";
163
+ }>>>;
164
+ shopifyPlus: zod.ZodNullable<zod.ZodBoolean>;
165
+ combinesWith: zod.ZodNullable<zod.ZodObject<{
166
+ orderDiscounts: zod.ZodNullable<zod.ZodBoolean>;
167
+ productDiscounts: zod.ZodNullable<zod.ZodBoolean>;
168
+ shippingDiscounts: zod.ZodNullable<zod.ZodBoolean>;
169
+ }, zod_v4_core.$strict>>;
170
+ discountTags: zod.ZodNullable<zod.ZodArray<zod.ZodString>>;
171
+ allowedSameLineProductTags: zod.ZodNullable<zod.ZodArray<zod.ZodString>>;
172
+ }, zod_v4_core.$strict>;
173
+ unrepresentedConditions: zod.ZodArray<zod.ZodString>;
174
+ }, zod_v4_core.$strict>;
175
+ providerDiscountId: zod.ZodNullable<zod.ZodString>;
176
+ }, zod_v4_core.$strict>>;
177
+ }, zod_v4_core.$strict>]>;
178
+ }>];
179
+ type DiscountPolicyOperationDescriptor = (typeof DISCOUNT_POLICY_OPERATION_DESCRIPTORS)[number];
180
+
16
181
  type FeatureFacts = {
17
182
  id: string;
18
183
  active: boolean;
@@ -471,4 +636,4 @@ declare const commerceDiscountBuiltInDescriptors: readonly CommerceBuiltInToolDe
471
636
  declare function isTrustedCommerceBuiltInDescriptor(value: CommerceBuiltInToolDescriptor): boolean;
472
637
  declare function isTrustedCommerceBuiltInGrant(value: CommerceBuiltInToolGrant): boolean;
473
638
 
474
- export { type CodeResponseProcessorInput, type CodeResponseProcessorResult, CommerceBuiltInToolDescriptor, CommerceBuiltInToolGrant, CommerceConversationGrant, CommerceFinalResponse, CommerceManifest, type CommerceOutreachToolContext, CommerceOutreachToolContextSchema, CommerceToolDefinition, CommerceTurnIdentity, type ConnectionCommand, ConnectionCommandSchema, ConnectionIssueSchema, type ConnectionResult, ConnectionResultSchema, type ConnectionRevisionView, ConnectionRevisionViewSchema, type ConnectionView, ConnectionViewSchema, ContractVersionSchema, type CredentialStatus, CredentialStatusSchema, CurrencySchema, DateSchema, Digest, type ExternalHttpResultData, ExternalHttpResultDataSchema, ExternalPathSchema, ExternalQueryMappingSchema, ExternalQueryMappingsSchema, ExternalQueryValueSchema, type ExternalResponseFormat, ExternalResponseFormatSchema, type FeatureFacts, type FieldProjection, FieldProjectionSchema, GrantedTool, HashSchema, IdSchema, type InitialOutreachCheckoutOfferSet, InitialOutreachCheckoutOfferSetSchema, LanguageSchema, MAX_STORE_CATEGORY_PROMPT_CONDITIONS, MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS, MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS, MoneySchema, PublishedToolDescriptor, type ResponseFilter, ResponseFilterSchema, type ResponseProcessing, ResponseProcessingSchema, type RevisionInput, RevisionInputSchema, STORE_CATEGORY_PROMPT_RUNTIME_VERSION, SemverSchema, type StoreCategoryPromptConditionKey, StoreCategoryPromptConditionKeySchema, type StoreCategoryPromptContext, StoreCategoryPromptContextSchema, type StoreCategoryPromptRenderResult, type StoreCategoryPromptTemplateIssue, type StoreCategoryPromptTemplateValidation, SubsetSchema, type TransformResponse, TransformResponseSchema, type TransformSample, TransformSampleSchema, type VisualResponseProcessing, VisualResponseProcessingSchema, type VisualResponseProcessorInput, type VisualResponseProcessorResult, boundedJson, commerceDiscountBuiltInDescriptors, createStoreCategoryPromptConditionBlock, createStoreCategoryPromptContext, currentlyGrantedTools, deduplicateTools, distinct, exampleDefinition, exampleFinal, exampleGrant, exampleManifest, exampleTool, exampleTurn, isTrustedCommerceBuiltInDescriptor, isTrustedCommerceBuiltInGrant, manifestMatchesGrant, parseCommerceManifest, renderStoreCategoryPromptTemplate, selectCapabilities, validateStoreCategoryPromptTemplate };
639
+ export { type CodeResponseProcessorInput, type CodeResponseProcessorResult, CommerceBuiltInToolDescriptor, CommerceBuiltInToolGrant, CommerceConversationGrant, CommerceFinalResponse, CommerceManifest, type CommerceOutreachToolContext, CommerceOutreachToolContextSchema, CommerceToolDefinition, CommerceTurnIdentity, type ConnectionCommand, ConnectionCommandSchema, ConnectionIssueSchema, type ConnectionResult, ConnectionResultSchema, type ConnectionRevisionView, ConnectionRevisionViewSchema, type ConnectionView, ConnectionViewSchema, ContractVersionSchema, type CredentialStatus, CredentialStatusSchema, CurrencySchema, DISCOUNT_POLICY_OPERATION_DESCRIPTORS, DateSchema, Digest, type DiscountPolicyOperationDescriptor, type ExternalHttpResultData, ExternalHttpResultDataSchema, ExternalPathSchema, ExternalQueryMappingSchema, ExternalQueryMappingsSchema, ExternalQueryValueSchema, type ExternalResponseFormat, ExternalResponseFormatSchema, type FeatureFacts, type FieldProjection, FieldProjectionSchema, GrantedTool, HashSchema, IdSchema, type InitialOutreachCheckoutOfferSet, InitialOutreachCheckoutOfferSetSchema, LanguageSchema, MAX_STORE_CATEGORY_PROMPT_CONDITIONS, MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS, MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS, MoneySchema, PublishedToolDescriptor, type ResponseFilter, ResponseFilterSchema, type ResponseProcessing, ResponseProcessingSchema, type RevisionInput, RevisionInputSchema, STORE_CATEGORY_PROMPT_RUNTIME_VERSION, SemverSchema, type StoreCategoryPromptConditionKey, StoreCategoryPromptConditionKeySchema, type StoreCategoryPromptContext, StoreCategoryPromptContextSchema, type StoreCategoryPromptRenderResult, type StoreCategoryPromptTemplateIssue, type StoreCategoryPromptTemplateValidation, SubsetSchema, type TransformResponse, TransformResponseSchema, type TransformSample, TransformSampleSchema, type VisualResponseProcessing, VisualResponseProcessingSchema, type VisualResponseProcessorInput, type VisualResponseProcessorResult, boundedJson, commerceDiscountBuiltInDescriptors, createStoreCategoryPromptConditionBlock, createStoreCategoryPromptContext, currentlyGrantedTools, deduplicateTools, distinct, exampleDefinition, exampleFinal, exampleGrant, exampleManifest, exampleTool, exampleTurn, isTrustedCommerceBuiltInDescriptor, isTrustedCommerceBuiltInGrant, manifestMatchesGrant, parseCommerceManifest, renderStoreCategoryPromptTemplate, selectCapabilities, validateStoreCategoryPromptTemplate };
@@ -4,7 +4,7 @@ import {
4
4
  manifestMatchesGrant,
5
5
  parseCommerceManifest,
6
6
  selectCapabilities
7
- } from "../chunk-H7NE3H5R.js";
7
+ } from "../chunk-C2PCRWOW.js";
8
8
  import {
9
9
  CommerceAlternativeSchema,
10
10
  CommerceAnswerPresentationSelectionSchema,
@@ -98,7 +98,7 @@ import {
98
98
  validateDefinitionVersion,
99
99
  validateSubset,
100
100
  verifyResponseContract
101
- } from "../chunk-NA76IPIW.js";
101
+ } from "../chunk-6OBYUIQ3.js";
102
102
  import {
103
103
  ContractVersionSchema,
104
104
  CurrencySchema,
@@ -118,6 +118,28 @@ import {
118
118
  } from "../chunk-AUS3WQIW.js";
119
119
  import "../chunk-4KSODB2R.js";
120
120
 
121
+ // src/commerce/discount-capability-contracts.ts
122
+ var DISCOUNT_POLICY_OPERATION_DESCRIPTORS = Object.freeze([
123
+ Object.freeze({
124
+ toolName: "commerce_get_discount_options",
125
+ displayName: "Get Discount Options",
126
+ operation: "discounts.getOptions",
127
+ operationVersion: "1.0.0",
128
+ description: "Read the configured discount mode and available offers.",
129
+ inputValidator: CommerceToolInputs.commerce_get_discount_options,
130
+ outputValidator: CommerceToolOutputs.commerce_get_discount_options
131
+ }),
132
+ Object.freeze({
133
+ toolName: "commerce_get_discount_details",
134
+ displayName: "Get Discount Details",
135
+ operation: "discounts.getDetails",
136
+ operationVersion: "1.0.0",
137
+ description: "Read details and condition facts for a permitted discount.",
138
+ inputValidator: CommerceToolInputs.commerce_get_discount_details,
139
+ outputValidator: CommerceToolOutputs.commerce_get_discount_details
140
+ })
141
+ ]);
142
+
121
143
  // src/commerce/store-category-prompt.ts
122
144
  import { z } from "zod";
123
145
  var STORE_CATEGORY_PROMPT_RUNTIME_VERSION = "store-category-prompt.v1";
@@ -659,6 +681,7 @@ export {
659
681
  ContractVersionSchema,
660
682
  CredentialStatusSchema,
661
683
  CurrencySchema,
684
+ DISCOUNT_POLICY_OPERATION_DESCRIPTORS,
662
685
  DateSchema,
663
686
  DetailsSchemaSchema,
664
687
  EMPTY_RESPONSE_CONTRACT,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commerce/store-category-prompt.ts","../../src/commerce/outreach-context.ts","../../src/commerce/outreach-checkout-offer-set.ts","../../src/commerce/fixtures.ts"],"sourcesContent":["import { z } from \"zod\";\n\nexport const STORE_CATEGORY_PROMPT_RUNTIME_VERSION = \"store-category-prompt.v1\" as const;\nexport const MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_CONDITIONS = 256;\nconst MAX_CONTROL_TAGS = 512;\nconst MAX_CONTROL_DEPTH = 8;\nconst MAX_EXPRESSION_CHARS = 1_024;\n\nconst forbiddenConditionKeys = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\nconst conditionKeyPattern = /^[a-z][a-z0-9_]{0,127}$/;\n\nexport const StoreCategoryPromptConditionKeySchema = z\n .string()\n .regex(conditionKeyPattern)\n .refine((value) => !forbiddenConditionKeys.has(value));\n\nexport type StoreCategoryPromptConditionKey = z.infer<typeof StoreCategoryPromptConditionKeySchema>;\n\nexport const StoreCategoryPromptContextSchema = z.strictObject({\n mappings: z\n .record(StoreCategoryPromptConditionKeySchema, z.boolean())\n .refine((value) => Object.keys(value).length <= MAX_STORE_CATEGORY_PROMPT_CONDITIONS),\n});\n\nexport type StoreCategoryPromptContext = z.infer<typeof StoreCategoryPromptContextSchema>;\n\nexport type StoreCategoryPromptTemplateIssue = {\n path: \"/promptText\";\n code:\n | \"invalid_prompt_source\"\n | \"unsupported_template_construct\"\n | \"invalid_template_structure\"\n | \"invalid_template_expression\"\n | \"invalid_mapping_condition\"\n | \"unknown_mapping_condition\"\n | \"template_too_complex\"\n | \"rendered_prompt_too_large\";\n message: string;\n};\n\nexport type StoreCategoryPromptTemplateValidation = {\n valid: boolean;\n issues: StoreCategoryPromptTemplateIssue[];\n referencedConditionKeys: string[];\n};\n\nexport type StoreCategoryPromptRenderResult =\n | { ok: true; promptText: string; referencedConditionKeys: string[] }\n | { ok: false; issues: StoreCategoryPromptTemplateIssue[] };\n\ntype ExpressionNode =\n | { kind: \"condition\"; key: string }\n | { kind: \"not\"; operand: ExpressionNode }\n | { kind: \"and\"; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"or\"; left: ExpressionNode; right: ExpressionNode };\n\ntype TemplateNode =\n | { kind: \"text\"; text: string }\n | {\n kind: \"if\";\n branches: Array<{ expression: ExpressionNode; body: TemplateNode[] }>;\n elseBody: TemplateNode[] | null;\n };\n\ntype TemplateToken =\n | { kind: \"text\"; text: string }\n | { kind: \"control\"; source: string }\n | { kind: \"unsupported\"; source: string; marker: \"interpolation\" | \"comment\" };\n\ntype CompileResult = {\n issues: StoreCategoryPromptTemplateIssue[];\n nodes: TemplateNode[];\n referencedConditionKeys: string[];\n};\n\nfunction issue(code: StoreCategoryPromptTemplateIssue[\"code\"], message: string): StoreCategoryPromptTemplateIssue {\n return { path: \"/promptText\", code, message };\n}\n\nfunction boundedIssues(issues: StoreCategoryPromptTemplateIssue[]): StoreCategoryPromptTemplateIssue[] {\n return issues.slice(0, 32).map((entry) => ({\n path: entry.path,\n code: entry.code,\n message: entry.message.slice(0, 512),\n }));\n}\n\nfunction sourceLength(value: string): number {\n return Array.from(value).length;\n}\n\nfunction findNextMarker(source: string, start: number): { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null {\n let best: { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null = null;\n for (const marker of [\"{%\", \"{{\", \"{#\"] as const) {\n const index = source.indexOf(marker, start);\n if (index >= 0 && (!best || index < best.index)) best = { index, marker };\n }\n return best;\n}\n\nfunction tokenizeTemplate(source: string, issues: StoreCategoryPromptTemplateIssue[]): TemplateToken[] {\n const tokens: TemplateToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const next = findNextMarker(source, cursor);\n if (!next) {\n tokens.push({ kind: \"text\", text: source.slice(cursor) });\n break;\n }\n if (next.index > cursor) tokens.push({ kind: \"text\", text: source.slice(cursor, next.index) });\n const closeMarker = next.marker === \"{%\" ? \"%}\" : next.marker === \"{{\" ? \"}}\" : \"#}\";\n const close = source.indexOf(closeMarker, next.index + 2);\n if (close < 0) {\n issues.push(issue(\"invalid_template_structure\", `Unclosed ${next.marker} template construct.`));\n tokens.push({ kind: \"text\", text: source.slice(next.index) });\n break;\n }\n const raw = source.slice(next.index + 2, close).trim();\n if (next.marker === \"{%\") tokens.push({ kind: \"control\", source: raw });\n else tokens.push({ kind: \"unsupported\", source: raw, marker: next.marker === \"{{\" ? \"interpolation\" : \"comment\" });\n cursor = close + 2;\n }\n if (source.length === 0) tokens.push({ kind: \"text\", text: \"\" });\n return tokens;\n}\n\ntype ExprToken = { kind: \"word\"; value: string } | { kind: \"dot\" } | { kind: \"lparen\" } | { kind: \"rparen\" };\n\nfunction lexExpression(source: string, issues: StoreCategoryPromptTemplateIssue[]): ExprToken[] | null {\n if (sourceLength(source) > MAX_EXPRESSION_CHARS) {\n issues.push(issue(\"template_too_complex\", `Conditional expressions must not exceed ${MAX_EXPRESSION_CHARS} characters.`));\n return null;\n }\n const tokens: ExprToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const char = source[cursor];\n if (/\\s/.test(char)) {\n cursor += 1;\n continue;\n }\n if (char === \".\") {\n tokens.push({ kind: \"dot\" });\n cursor += 1;\n continue;\n }\n if (char === \"(\") {\n tokens.push({ kind: \"lparen\" });\n cursor += 1;\n continue;\n }\n if (char === \")\") {\n tokens.push({ kind: \"rparen\" });\n cursor += 1;\n continue;\n }\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(cursor));\n if (!match) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions may only use mappings.<conditionKey>, not, and, or, and parentheses.\"));\n return null;\n }\n tokens.push({ kind: \"word\", value: match[0] });\n cursor += match[0].length;\n }\n return tokens;\n}\n\nfunction parseExpression(source: string, issues: StoreCategoryPromptTemplateIssue[], referenced: string[]): ExpressionNode | null {\n const tokens = lexExpression(source, issues);\n if (!tokens || tokens.length === 0) {\n if (tokens?.length === 0) issues.push(issue(\"invalid_template_expression\", \"A conditional expression is required.\"));\n return null;\n }\n let index = 0;\n const peekWord = (word: string) => {\n const token = tokens[index];\n return token?.kind === \"word\" && token.value === word;\n };\n\n const parsePrimary = (): ExpressionNode | null => {\n const token = tokens[index];\n if (token?.kind === \"lparen\") {\n index += 1;\n const inner = parseOr();\n if (tokens[index]?.kind !== \"rparen\") {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression parentheses are unbalanced.\"));\n return null;\n }\n index += 1;\n return inner;\n }\n if (!peekWord(\"mappings\")) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions must reference mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n if (tokens[index]?.kind !== \"dot\") {\n issues.push(issue(\"invalid_template_expression\", \"Mapping conditions must use mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n const keyToken = tokens[index];\n if (keyToken?.kind !== \"word\") {\n issues.push(issue(\"invalid_mapping_condition\", \"A valid mapping condition key is required after mappings.\"));\n return null;\n }\n index += 1;\n if (!StoreCategoryPromptConditionKeySchema.safeParse(keyToken.value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${keyToken.value}.`));\n return null;\n }\n if (!referenced.includes(keyToken.value)) referenced.push(keyToken.value);\n return { kind: \"condition\", key: keyToken.value };\n };\n\n const parseNot = (): ExpressionNode | null => {\n if (peekWord(\"not\")) {\n index += 1;\n const operand = parseNot();\n return operand ? { kind: \"not\", operand } : null;\n }\n return parsePrimary();\n };\n\n const parseAnd = (): ExpressionNode | null => {\n let left = parseNot();\n while (left && peekWord(\"and\")) {\n index += 1;\n const right = parseNot();\n if (!right) return null;\n left = { kind: \"and\", left, right };\n }\n return left;\n };\n\n const parseOr = (): ExpressionNode | null => {\n let left = parseAnd();\n while (left && peekWord(\"or\")) {\n index += 1;\n const right = parseAnd();\n if (!right) return null;\n left = { kind: \"or\", left, right };\n }\n return left;\n };\n\n const expression = parseOr();\n if (expression && index !== tokens.length) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression contains unsupported syntax.\"));\n return null;\n }\n return expression;\n}\n\nfunction compileStoreCategoryPromptTemplate(source: string): CompileResult {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const referencedConditionKeys: string[] = [];\n const nodes: TemplateNode[] = [];\n\n if (source.trim().length === 0) issues.push(issue(\"invalid_prompt_source\", \"Prompt template must not be blank.\"));\n if (sourceLength(source) > MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS) {\n issues.push(issue(\"invalid_prompt_source\", `Prompt template must not exceed ${MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS.toLocaleString()} characters.`));\n }\n\n const tokens = tokenizeTemplate(source, issues);\n type Frame = {\n node: Extract<TemplateNode, { kind: \"if\" }>;\n parentBody: TemplateNode[];\n currentBody: TemplateNode[];\n sawElse: boolean;\n };\n const stack: Frame[] = [];\n let currentBody = nodes;\n let controlCount = 0;\n\n for (const token of tokens) {\n if (token.kind === \"text\") {\n if (token.text) currentBody.push({ kind: \"text\", text: token.text });\n continue;\n }\n if (token.kind === \"unsupported\") {\n issues.push(issue(\n \"unsupported_template_construct\",\n token.marker === \"interpolation\"\n ? \"Variable interpolation is not supported in Store Category prompt templates.\"\n : \"Template comments are not supported in Store Category prompt templates.\",\n ));\n continue;\n }\n\n controlCount += 1;\n if (controlCount > MAX_CONTROL_TAGS) {\n issues.push(issue(\"template_too_complex\", `Prompt template must not contain more than ${MAX_CONTROL_TAGS} control tags.`));\n break;\n }\n\n const ifMatch = /^if\\s+([\\s\\S]+)$/.exec(token.source);\n if (ifMatch) {\n if (stack.length >= MAX_CONTROL_DEPTH) {\n issues.push(issue(\"template_too_complex\", `Conditional nesting must not exceed ${MAX_CONTROL_DEPTH} levels.`));\n continue;\n }\n const expression = parseExpression(ifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n const node: Extract<TemplateNode, { kind: \"if\" }> = {\n kind: \"if\",\n branches: [{ expression, body: branchBody }],\n elseBody: null,\n };\n currentBody.push(node);\n const frame: Frame = { node, parentBody: currentBody, currentBody: branchBody, sawElse: false };\n stack.push(frame);\n currentBody = branchBody;\n continue;\n }\n\n const elifMatch = /^elif\\s+([\\s\\S]+)$/.exec(token.source);\n if (elifMatch) {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"elif must appear inside an if block and before else.\"));\n continue;\n }\n const expression = parseExpression(elifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n frame.node.branches.push({ expression, body: branchBody });\n frame.currentBody = branchBody;\n currentBody = branchBody;\n continue;\n }\n\n if (token.source === \"else\") {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"else must appear once inside an if block.\"));\n continue;\n }\n const elseBody: TemplateNode[] = [];\n frame.node.elseBody = elseBody;\n frame.currentBody = elseBody;\n frame.sawElse = true;\n currentBody = elseBody;\n continue;\n }\n\n if (token.source === \"endif\") {\n const frame = stack.pop();\n if (!frame) {\n issues.push(issue(\"invalid_template_structure\", \"endif does not have a matching if block.\"));\n continue;\n }\n currentBody = frame.parentBody;\n continue;\n }\n\n issues.push(issue(\n \"unsupported_template_construct\",\n \"Only if, elif, else, and endif control tags are supported in Store Category prompt templates.\",\n ));\n }\n\n if (stack.length) issues.push(issue(\"invalid_template_structure\", \"Every if block must end with endif.\"));\n return { issues: boundedIssues(issues), nodes, referencedConditionKeys };\n}\n\nfunction validateAvailableConditionKeys(values: readonly string[], issues: StoreCategoryPromptTemplateIssue[]): Set<string> {\n if (values.length > MAX_STORE_CATEGORY_PROMPT_CONDITIONS) {\n issues.push(issue(\"template_too_complex\", `At most ${MAX_STORE_CATEGORY_PROMPT_CONDITIONS} mapping conditions are supported.`));\n }\n const keys = new Set<string>();\n for (const value of values.slice(0, MAX_STORE_CATEGORY_PROMPT_CONDITIONS + 1)) {\n if (!StoreCategoryPromptConditionKeySchema.safeParse(value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${value}.`));\n continue;\n }\n if (keys.has(value)) {\n issues.push(issue(\"invalid_mapping_condition\", `Duplicate mapping condition key: ${value}.`));\n continue;\n }\n keys.add(value);\n }\n return keys;\n}\n\nexport function validateStoreCategoryPromptTemplate(input: {\n source: string;\n availableConditionKeys: readonly string[];\n}): StoreCategoryPromptTemplateValidation {\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n const issues = [...compiled.issues];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n for (const key of compiled.referencedConditionKeys) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Prompt template references unavailable mapping condition: mappings.${key}.`));\n }\n const bounded = boundedIssues(issues);\n return { valid: bounded.length === 0, issues: bounded, referencedConditionKeys: compiled.referencedConditionKeys };\n}\n\n\nexport function createStoreCategoryPromptConditionBlock(conditionKey: string): string {\n const parsed = StoreCategoryPromptConditionKeySchema.safeParse(conditionKey);\n if (!parsed.success) throw new TypeError(`Invalid mapping condition key: ${conditionKey}.`);\n return `{% if mappings.${conditionKey} %}\\n\\n{% endif %}`;\n}\n\nexport function createStoreCategoryPromptContext(input: {\n availableConditionKeys: readonly string[];\n selectedConditionKeys: readonly string[];\n}): StoreCategoryPromptContext {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n const selected = validateAvailableConditionKeys(input.selectedConditionKeys, issues);\n for (const key of selected) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Selected mapping condition is unavailable: ${key}.`));\n }\n if (issues.length) throw new TypeError(issues[0].message);\n const mappings = Object.create(null) as Record<string, boolean>;\n for (const key of available) mappings[key] = selected.has(key);\n return { mappings };\n}\n\nfunction evaluateExpression(expression: ExpressionNode, mappings: Record<string, boolean>): boolean {\n switch (expression.kind) {\n case \"condition\":\n return mappings[expression.key] === true;\n case \"not\":\n return !evaluateExpression(expression.operand, mappings);\n case \"and\":\n return evaluateExpression(expression.left, mappings) && evaluateExpression(expression.right, mappings);\n case \"or\":\n return evaluateExpression(expression.left, mappings) || evaluateExpression(expression.right, mappings);\n }\n}\n\nfunction renderNodes(nodes: TemplateNode[], mappings: Record<string, boolean>, append: (text: string) => boolean): boolean {\n for (const node of nodes) {\n if (node.kind === \"text\") {\n if (!append(node.text)) return false;\n continue;\n }\n let renderedBranch = false;\n for (const branch of node.branches) {\n if (evaluateExpression(branch.expression, mappings)) {\n if (!renderNodes(branch.body, mappings, append)) return false;\n renderedBranch = true;\n break;\n }\n }\n if (!renderedBranch && node.elseBody && !renderNodes(node.elseBody, mappings, append)) return false;\n }\n return true;\n}\n\nexport function renderStoreCategoryPromptTemplate(input: {\n source: string;\n context: StoreCategoryPromptContext;\n}): StoreCategoryPromptRenderResult {\n const contextResult = StoreCategoryPromptContextSchema.safeParse(input.context);\n if (!contextResult.success) {\n return { ok: false, issues: [issue(\"invalid_mapping_condition\", \"Store Category prompt context contains invalid mapping conditions.\")] };\n }\n const availableConditionKeys = Object.keys(contextResult.data.mappings);\n const validation = validateStoreCategoryPromptTemplate({ source: input.source, availableConditionKeys });\n if (!validation.valid) return { ok: false, issues: validation.issues };\n\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n let output = \"\";\n let outputChars = 0;\n const append = (text: string) => {\n outputChars += sourceLength(text);\n if (outputChars > MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS) return false;\n output += text;\n return true;\n };\n const rendered = renderNodes(compiled.nodes, contextResult.data.mappings, append);\n if (!rendered) {\n return {\n ok: false,\n issues: [issue(\"rendered_prompt_too_large\", `Rendered prompt must not exceed ${MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS.toLocaleString()} characters.`)],\n };\n }\n return { ok: true, promptText: output, referencedConditionKeys: validation.referencedConditionKeys };\n}\n","import { z } from \"zod\";\n\nexport const CommerceOutreachToolContextSchema = z.strictObject({\n purpose: z.literal(\"INITIAL_RECOVERY_OUTREACH\"),\n});\n\nexport type CommerceOutreachToolContext =\n z.infer<typeof CommerceOutreachToolContextSchema>;\n","import { z } from \"zod\";\n\n/** Ordered source-backed checkout offers confirmed in one initial outreach send. */\nexport const InitialOutreachCheckoutOfferSetSchema = z.strictObject({\n schemaVersion: z.literal(\"moda.outreach.checkout-offers.v1\"),\n offers: z.array(z.strictObject({\n offerId: z.string().min(1).max(191),\n providerDiscountId: z.string().min(1).max(191).nullable(),\n method: z.enum([\"CODE\", \"AUTOMATIC\"]),\n code: z.string().min(1).max(128).nullable(),\n })).min(1).max(3),\n});\nexport type InitialOutreachCheckoutOfferSet = z.infer<\n typeof InitialOutreachCheckoutOfferSetSchema\n>;\n","/** Synthetic examples; no provider identity, schema artifact or publication claim. */\nimport type {\n CommerceManifest,\n CommerceConversationGrant,\n CommerceTurnIdentity,\n} from \"./schemas\";\nimport {\n EMPTY_RESPONSE_CONTRACT,\n type CommerceFinalResponse,\n} from \"./response\";\nimport type { Digest } from \"./canonical-json\";\nimport { responseContractCanonicalJson } from \"./canonical-json\";\nimport type { PublishedToolDescriptor, CommerceToolDefinition } from \"./definitions\";\nexport const exampleTool: PublishedToolDescriptor = {\n toolId: \"tool-fixture\",\n toolRevisionId: \"revision-fixture\",\n name: \"never_seeded_catalogue_facts\",\n definitionVersion: \"1.0.0\",\n description: \"Read synthetic catalogue facts.\",\n inputSchema: {\n type: \"object\",\n properties: { handle: { type: \"string\", minLength: 1, maxLength: 255 } },\n required: [\"handle\"],\n additionalProperties: false,\n },\n};\nexport const exampleDefinition: CommerceToolDefinition = {\n name: exampleTool.name,\n definitionVersion: \"1.0.0\",\n description: exampleTool.description,\n inputSchema: exampleTool.inputSchema,\n execution: {\n kind: \"SHOPIFY_STOREFRONT_QUERY\",\n executorVersion: \"1.0.0\",\n apiVersion: \"2026-07\",\n schemaHash: \"a\".repeat(64),\n document:\n \"query ProductDetails($handle: String!) { product(handle: $handle) { title description } }\",\n operationName: \"ProductDetails\",\n variables: { handle: { input: \"handle\" } },\n resultPath: \"product\",\n },\n responseTemplate: {\n kind: \"text\",\n text: \"{{result.values.title}}: {{result.values.description}}\",\n unavailable: \"Product details could not be verified.\",\n },\n};\nexport const exampleTurn: CommerceTurnIdentity = {\n contractVersion: \"commerce.v1\",\n shopId: \"shop-fixture\",\n checkoutRecoveryId: \"recovery-fixture\",\n conversationId: \"conversation-fixture\",\n inboundVersion: 1,\n};\nexport function exampleManifest(\n digest: Digest,\n withTool = false,\n): CommerceManifest {\n const capabilities = withTool\n ? [{\n capabilityId: \"capability-fixture\",\n key: \"feature_product_read\",\n featureId: \"feature-fixture\",\n position: 0,\n toolDescriptor: structuredClone(exampleTool),\n }]\n : [];\n return {\n contractVersion: \"commerce.v1\",\n releaseId: \"release-fixture\",\n runnerCompatibility: \"^1.0.0\",\n capabilities,\n featureBehaviours: withTool\n ? [{ featureId: \"feature-fixture\", behaviourPrompt: \"Synthetic Feature behavior.\" }]\n : [],\n selectedCapabilityKeys: capabilities.map((capability) => capability.key),\n builtInTools: [],\n grantedTools: withTool\n ? [\n {\n toolId: exampleTool.toolId,\n toolRevisionId: exampleTool.toolRevisionId,\n toolName: exampleTool.name,\n definitionVersion: \"1.0.0\",\n capabilityKeys: [\"feature_product_read\"],\n },\n ]\n : [],\n responseContract: structuredClone(EMPTY_RESPONSE_CONTRACT),\n responseContractHash: digest(\n responseContractCanonicalJson(EMPTY_RESPONSE_CONTRACT),\n ),\n };\n}\nexport function exampleGrant(\n manifest: CommerceManifest,\n): CommerceConversationGrant {\n return {\n id: \"grant-fixture\",\n shopId: exampleTurn.shopId,\n conversationId: exampleTurn.conversationId,\n initialInboundVersion: 1,\n releaseId: manifest.releaseId,\n selectedCapabilityKeys: [...manifest.selectedCapabilityKeys],\n grantedTools: structuredClone(manifest.grantedTools),\n runnerVersion: \"1.0.0\",\n createdAt: \"2026-09-20T00:00:00.000Z\",\n expiresAt: null,\n };\n}\nexport const exampleFinal: CommerceFinalResponse = {\n answerKind: \"REFER_TO_STORE\",\n replyText:\n \"I cannot verify that information. Please contact the store directly.\",\n referralReason: \"INSUFFICIENT_TOOLS\",\n detectedLanguageTag: null,\n detectedLanguageConfidence: null,\n evidenceIds: [],\n details: {},\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS;AAEX,IAAM,wCAAwC;AAC9C,IAAM,yCAAyC;AAC/C,IAAM,2CAA2C;AACjD,IAAM,uCAAuC;AACpD,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAC1B,IAAM,uBAAuB;AAE7B,IAAM,yBAAyB,oBAAI,IAAI,CAAC,aAAa,aAAa,aAAa,CAAC;AAChF,IAAM,sBAAsB;AAErB,IAAM,wCAAwC,EAClD,OAAO,EACP,MAAM,mBAAmB,EACzB,OAAO,CAAC,UAAU,CAAC,uBAAuB,IAAI,KAAK,CAAC;AAIhD,IAAM,mCAAmC,EAAE,aAAa;AAAA,EAC7D,UAAU,EACP,OAAO,uCAAuC,EAAE,QAAQ,CAAC,EACzD,OAAO,CAAC,UAAU,OAAO,KAAK,KAAK,EAAE,UAAU,oCAAoC;AACxF,CAAC;AAqDD,SAAS,MAAM,MAAgD,SAAmD;AAChH,SAAO,EAAE,MAAM,eAAe,MAAM,QAAQ;AAC9C;AAEA,SAAS,cAAc,QAAgF;AACrG,SAAO,OAAO,MAAM,GAAG,EAAE,EAAE,IAAI,CAAC,WAAW;AAAA,IACzC,MAAM,MAAM;AAAA,IACZ,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM,QAAQ,MAAM,GAAG,GAAG;AAAA,EACrC,EAAE;AACJ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AAA,IACvD;AAAA,EACF;AACF;AACO,SAAS,aACd,UAC2B;AAC3B,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,QAAQ,YAAY;AAAA,IACpB,gBAAgB,YAAY;AAAA,IAC5B,uBAAuB;AAAA,IACvB,WAAW,SAAS;AAAA,IACpB,wBAAwB,CAAC,GAAG,SAAS,sBAAsB;AAAA,IAC3D,cAAc,gBAAgB,SAAS,YAAY;AAAA,IACnD,eAAe;AAAA,IACf,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AACF;AACO,IAAM,eAAsC;AAAA,EACjD,YAAY;AAAA,EACZ,WACE;AAAA,EACF,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,4BAA4B;AAAA,EAC5B,aAAa,CAAC;AAAA,EACd,SAAS,CAAC;AACZ;","names":["z","z"]}
1
+ {"version":3,"sources":["../../src/commerce/discount-capability-contracts.ts","../../src/commerce/store-category-prompt.ts","../../src/commerce/outreach-context.ts","../../src/commerce/outreach-checkout-offer-set.ts","../../src/commerce/fixtures.ts"],"sourcesContent":["import { CommerceToolInputs, CommerceToolOutputs } from \"./schemas.js\";\n\n/**\n * Canonical Shared mapping for the two published discount capabilities.\n * Consumers reuse these validators instead of maintaining local copies.\n * `operationVersion` is independent of immutable published tool definition\n * versions selected by Commerce during publication.\n */\nexport const DISCOUNT_POLICY_OPERATION_DESCRIPTORS = Object.freeze([\n Object.freeze({\n toolName: \"commerce_get_discount_options\",\n displayName: \"Get Discount Options\",\n operation: \"discounts.getOptions\",\n operationVersion: \"1.0.0\",\n description: \"Read the configured discount mode and available offers.\",\n inputValidator: CommerceToolInputs.commerce_get_discount_options,\n outputValidator: CommerceToolOutputs.commerce_get_discount_options,\n }),\n Object.freeze({\n toolName: \"commerce_get_discount_details\",\n displayName: \"Get Discount Details\",\n operation: \"discounts.getDetails\",\n operationVersion: \"1.0.0\",\n description: \"Read details and condition facts for a permitted discount.\",\n inputValidator: CommerceToolInputs.commerce_get_discount_details,\n outputValidator: CommerceToolOutputs.commerce_get_discount_details,\n }),\n] as const);\n\nexport type DiscountPolicyOperationDescriptor =\n (typeof DISCOUNT_POLICY_OPERATION_DESCRIPTORS)[number];\n","import { z } from \"zod\";\n\nexport const STORE_CATEGORY_PROMPT_RUNTIME_VERSION = \"store-category-prompt.v1\" as const;\nexport const MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_CONDITIONS = 256;\nconst MAX_CONTROL_TAGS = 512;\nconst MAX_CONTROL_DEPTH = 8;\nconst MAX_EXPRESSION_CHARS = 1_024;\n\nconst forbiddenConditionKeys = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\nconst conditionKeyPattern = /^[a-z][a-z0-9_]{0,127}$/;\n\nexport const StoreCategoryPromptConditionKeySchema = z\n .string()\n .regex(conditionKeyPattern)\n .refine((value) => !forbiddenConditionKeys.has(value));\n\nexport type StoreCategoryPromptConditionKey = z.infer<typeof StoreCategoryPromptConditionKeySchema>;\n\nexport const StoreCategoryPromptContextSchema = z.strictObject({\n mappings: z\n .record(StoreCategoryPromptConditionKeySchema, z.boolean())\n .refine((value) => Object.keys(value).length <= MAX_STORE_CATEGORY_PROMPT_CONDITIONS),\n});\n\nexport type StoreCategoryPromptContext = z.infer<typeof StoreCategoryPromptContextSchema>;\n\nexport type StoreCategoryPromptTemplateIssue = {\n path: \"/promptText\";\n code:\n | \"invalid_prompt_source\"\n | \"unsupported_template_construct\"\n | \"invalid_template_structure\"\n | \"invalid_template_expression\"\n | \"invalid_mapping_condition\"\n | \"unknown_mapping_condition\"\n | \"template_too_complex\"\n | \"rendered_prompt_too_large\";\n message: string;\n};\n\nexport type StoreCategoryPromptTemplateValidation = {\n valid: boolean;\n issues: StoreCategoryPromptTemplateIssue[];\n referencedConditionKeys: string[];\n};\n\nexport type StoreCategoryPromptRenderResult =\n | { ok: true; promptText: string; referencedConditionKeys: string[] }\n | { ok: false; issues: StoreCategoryPromptTemplateIssue[] };\n\ntype ExpressionNode =\n | { kind: \"condition\"; key: string }\n | { kind: \"not\"; operand: ExpressionNode }\n | { kind: \"and\"; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"or\"; left: ExpressionNode; right: ExpressionNode };\n\ntype TemplateNode =\n | { kind: \"text\"; text: string }\n | {\n kind: \"if\";\n branches: Array<{ expression: ExpressionNode; body: TemplateNode[] }>;\n elseBody: TemplateNode[] | null;\n };\n\ntype TemplateToken =\n | { kind: \"text\"; text: string }\n | { kind: \"control\"; source: string }\n | { kind: \"unsupported\"; source: string; marker: \"interpolation\" | \"comment\" };\n\ntype CompileResult = {\n issues: StoreCategoryPromptTemplateIssue[];\n nodes: TemplateNode[];\n referencedConditionKeys: string[];\n};\n\nfunction issue(code: StoreCategoryPromptTemplateIssue[\"code\"], message: string): StoreCategoryPromptTemplateIssue {\n return { path: \"/promptText\", code, message };\n}\n\nfunction boundedIssues(issues: StoreCategoryPromptTemplateIssue[]): StoreCategoryPromptTemplateIssue[] {\n return issues.slice(0, 32).map((entry) => ({\n path: entry.path,\n code: entry.code,\n message: entry.message.slice(0, 512),\n }));\n}\n\nfunction sourceLength(value: string): number {\n return Array.from(value).length;\n}\n\nfunction findNextMarker(source: string, start: number): { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null {\n let best: { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null = null;\n for (const marker of [\"{%\", \"{{\", \"{#\"] as const) {\n const index = source.indexOf(marker, start);\n if (index >= 0 && (!best || index < best.index)) best = { index, marker };\n }\n return best;\n}\n\nfunction tokenizeTemplate(source: string, issues: StoreCategoryPromptTemplateIssue[]): TemplateToken[] {\n const tokens: TemplateToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const next = findNextMarker(source, cursor);\n if (!next) {\n tokens.push({ kind: \"text\", text: source.slice(cursor) });\n break;\n }\n if (next.index > cursor) tokens.push({ kind: \"text\", text: source.slice(cursor, next.index) });\n const closeMarker = next.marker === \"{%\" ? \"%}\" : next.marker === \"{{\" ? \"}}\" : \"#}\";\n const close = source.indexOf(closeMarker, next.index + 2);\n if (close < 0) {\n issues.push(issue(\"invalid_template_structure\", `Unclosed ${next.marker} template construct.`));\n tokens.push({ kind: \"text\", text: source.slice(next.index) });\n break;\n }\n const raw = source.slice(next.index + 2, close).trim();\n if (next.marker === \"{%\") tokens.push({ kind: \"control\", source: raw });\n else tokens.push({ kind: \"unsupported\", source: raw, marker: next.marker === \"{{\" ? \"interpolation\" : \"comment\" });\n cursor = close + 2;\n }\n if (source.length === 0) tokens.push({ kind: \"text\", text: \"\" });\n return tokens;\n}\n\ntype ExprToken = { kind: \"word\"; value: string } | { kind: \"dot\" } | { kind: \"lparen\" } | { kind: \"rparen\" };\n\nfunction lexExpression(source: string, issues: StoreCategoryPromptTemplateIssue[]): ExprToken[] | null {\n if (sourceLength(source) > MAX_EXPRESSION_CHARS) {\n issues.push(issue(\"template_too_complex\", `Conditional expressions must not exceed ${MAX_EXPRESSION_CHARS} characters.`));\n return null;\n }\n const tokens: ExprToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const char = source[cursor];\n if (/\\s/.test(char)) {\n cursor += 1;\n continue;\n }\n if (char === \".\") {\n tokens.push({ kind: \"dot\" });\n cursor += 1;\n continue;\n }\n if (char === \"(\") {\n tokens.push({ kind: \"lparen\" });\n cursor += 1;\n continue;\n }\n if (char === \")\") {\n tokens.push({ kind: \"rparen\" });\n cursor += 1;\n continue;\n }\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(cursor));\n if (!match) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions may only use mappings.<conditionKey>, not, and, or, and parentheses.\"));\n return null;\n }\n tokens.push({ kind: \"word\", value: match[0] });\n cursor += match[0].length;\n }\n return tokens;\n}\n\nfunction parseExpression(source: string, issues: StoreCategoryPromptTemplateIssue[], referenced: string[]): ExpressionNode | null {\n const tokens = lexExpression(source, issues);\n if (!tokens || tokens.length === 0) {\n if (tokens?.length === 0) issues.push(issue(\"invalid_template_expression\", \"A conditional expression is required.\"));\n return null;\n }\n let index = 0;\n const peekWord = (word: string) => {\n const token = tokens[index];\n return token?.kind === \"word\" && token.value === word;\n };\n\n const parsePrimary = (): ExpressionNode | null => {\n const token = tokens[index];\n if (token?.kind === \"lparen\") {\n index += 1;\n const inner = parseOr();\n if (tokens[index]?.kind !== \"rparen\") {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression parentheses are unbalanced.\"));\n return null;\n }\n index += 1;\n return inner;\n }\n if (!peekWord(\"mappings\")) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions must reference mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n if (tokens[index]?.kind !== \"dot\") {\n issues.push(issue(\"invalid_template_expression\", \"Mapping conditions must use mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n const keyToken = tokens[index];\n if (keyToken?.kind !== \"word\") {\n issues.push(issue(\"invalid_mapping_condition\", \"A valid mapping condition key is required after mappings.\"));\n return null;\n }\n index += 1;\n if (!StoreCategoryPromptConditionKeySchema.safeParse(keyToken.value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${keyToken.value}.`));\n return null;\n }\n if (!referenced.includes(keyToken.value)) referenced.push(keyToken.value);\n return { kind: \"condition\", key: keyToken.value };\n };\n\n const parseNot = (): ExpressionNode | null => {\n if (peekWord(\"not\")) {\n index += 1;\n const operand = parseNot();\n return operand ? { kind: \"not\", operand } : null;\n }\n return parsePrimary();\n };\n\n const parseAnd = (): ExpressionNode | null => {\n let left = parseNot();\n while (left && peekWord(\"and\")) {\n index += 1;\n const right = parseNot();\n if (!right) return null;\n left = { kind: \"and\", left, right };\n }\n return left;\n };\n\n const parseOr = (): ExpressionNode | null => {\n let left = parseAnd();\n while (left && peekWord(\"or\")) {\n index += 1;\n const right = parseAnd();\n if (!right) return null;\n left = { kind: \"or\", left, right };\n }\n return left;\n };\n\n const expression = parseOr();\n if (expression && index !== tokens.length) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression contains unsupported syntax.\"));\n return null;\n }\n return expression;\n}\n\nfunction compileStoreCategoryPromptTemplate(source: string): CompileResult {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const referencedConditionKeys: string[] = [];\n const nodes: TemplateNode[] = [];\n\n if (source.trim().length === 0) issues.push(issue(\"invalid_prompt_source\", \"Prompt template must not be blank.\"));\n if (sourceLength(source) > MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS) {\n issues.push(issue(\"invalid_prompt_source\", `Prompt template must not exceed ${MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS.toLocaleString()} characters.`));\n }\n\n const tokens = tokenizeTemplate(source, issues);\n type Frame = {\n node: Extract<TemplateNode, { kind: \"if\" }>;\n parentBody: TemplateNode[];\n currentBody: TemplateNode[];\n sawElse: boolean;\n };\n const stack: Frame[] = [];\n let currentBody = nodes;\n let controlCount = 0;\n\n for (const token of tokens) {\n if (token.kind === \"text\") {\n if (token.text) currentBody.push({ kind: \"text\", text: token.text });\n continue;\n }\n if (token.kind === \"unsupported\") {\n issues.push(issue(\n \"unsupported_template_construct\",\n token.marker === \"interpolation\"\n ? \"Variable interpolation is not supported in Store Category prompt templates.\"\n : \"Template comments are not supported in Store Category prompt templates.\",\n ));\n continue;\n }\n\n controlCount += 1;\n if (controlCount > MAX_CONTROL_TAGS) {\n issues.push(issue(\"template_too_complex\", `Prompt template must not contain more than ${MAX_CONTROL_TAGS} control tags.`));\n break;\n }\n\n const ifMatch = /^if\\s+([\\s\\S]+)$/.exec(token.source);\n if (ifMatch) {\n if (stack.length >= MAX_CONTROL_DEPTH) {\n issues.push(issue(\"template_too_complex\", `Conditional nesting must not exceed ${MAX_CONTROL_DEPTH} levels.`));\n continue;\n }\n const expression = parseExpression(ifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n const node: Extract<TemplateNode, { kind: \"if\" }> = {\n kind: \"if\",\n branches: [{ expression, body: branchBody }],\n elseBody: null,\n };\n currentBody.push(node);\n const frame: Frame = { node, parentBody: currentBody, currentBody: branchBody, sawElse: false };\n stack.push(frame);\n currentBody = branchBody;\n continue;\n }\n\n const elifMatch = /^elif\\s+([\\s\\S]+)$/.exec(token.source);\n if (elifMatch) {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"elif must appear inside an if block and before else.\"));\n continue;\n }\n const expression = parseExpression(elifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n frame.node.branches.push({ expression, body: branchBody });\n frame.currentBody = branchBody;\n currentBody = branchBody;\n continue;\n }\n\n if (token.source === \"else\") {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"else must appear once inside an if block.\"));\n continue;\n }\n const elseBody: TemplateNode[] = [];\n frame.node.elseBody = elseBody;\n frame.currentBody = elseBody;\n frame.sawElse = true;\n currentBody = elseBody;\n continue;\n }\n\n if (token.source === \"endif\") {\n const frame = stack.pop();\n if (!frame) {\n issues.push(issue(\"invalid_template_structure\", \"endif does not have a matching if block.\"));\n continue;\n }\n currentBody = frame.parentBody;\n continue;\n }\n\n issues.push(issue(\n \"unsupported_template_construct\",\n \"Only if, elif, else, and endif control tags are supported in Store Category prompt templates.\",\n ));\n }\n\n if (stack.length) issues.push(issue(\"invalid_template_structure\", \"Every if block must end with endif.\"));\n return { issues: boundedIssues(issues), nodes, referencedConditionKeys };\n}\n\nfunction validateAvailableConditionKeys(values: readonly string[], issues: StoreCategoryPromptTemplateIssue[]): Set<string> {\n if (values.length > MAX_STORE_CATEGORY_PROMPT_CONDITIONS) {\n issues.push(issue(\"template_too_complex\", `At most ${MAX_STORE_CATEGORY_PROMPT_CONDITIONS} mapping conditions are supported.`));\n }\n const keys = new Set<string>();\n for (const value of values.slice(0, MAX_STORE_CATEGORY_PROMPT_CONDITIONS + 1)) {\n if (!StoreCategoryPromptConditionKeySchema.safeParse(value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${value}.`));\n continue;\n }\n if (keys.has(value)) {\n issues.push(issue(\"invalid_mapping_condition\", `Duplicate mapping condition key: ${value}.`));\n continue;\n }\n keys.add(value);\n }\n return keys;\n}\n\nexport function validateStoreCategoryPromptTemplate(input: {\n source: string;\n availableConditionKeys: readonly string[];\n}): StoreCategoryPromptTemplateValidation {\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n const issues = [...compiled.issues];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n for (const key of compiled.referencedConditionKeys) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Prompt template references unavailable mapping condition: mappings.${key}.`));\n }\n const bounded = boundedIssues(issues);\n return { valid: bounded.length === 0, issues: bounded, referencedConditionKeys: compiled.referencedConditionKeys };\n}\n\n\nexport function createStoreCategoryPromptConditionBlock(conditionKey: string): string {\n const parsed = StoreCategoryPromptConditionKeySchema.safeParse(conditionKey);\n if (!parsed.success) throw new TypeError(`Invalid mapping condition key: ${conditionKey}.`);\n return `{% if mappings.${conditionKey} %}\\n\\n{% endif %}`;\n}\n\nexport function createStoreCategoryPromptContext(input: {\n availableConditionKeys: readonly string[];\n selectedConditionKeys: readonly string[];\n}): StoreCategoryPromptContext {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n const selected = validateAvailableConditionKeys(input.selectedConditionKeys, issues);\n for (const key of selected) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Selected mapping condition is unavailable: ${key}.`));\n }\n if (issues.length) throw new TypeError(issues[0].message);\n const mappings = Object.create(null) as Record<string, boolean>;\n for (const key of available) mappings[key] = selected.has(key);\n return { mappings };\n}\n\nfunction evaluateExpression(expression: ExpressionNode, mappings: Record<string, boolean>): boolean {\n switch (expression.kind) {\n case \"condition\":\n return mappings[expression.key] === true;\n case \"not\":\n return !evaluateExpression(expression.operand, mappings);\n case \"and\":\n return evaluateExpression(expression.left, mappings) && evaluateExpression(expression.right, mappings);\n case \"or\":\n return evaluateExpression(expression.left, mappings) || evaluateExpression(expression.right, mappings);\n }\n}\n\nfunction renderNodes(nodes: TemplateNode[], mappings: Record<string, boolean>, append: (text: string) => boolean): boolean {\n for (const node of nodes) {\n if (node.kind === \"text\") {\n if (!append(node.text)) return false;\n continue;\n }\n let renderedBranch = false;\n for (const branch of node.branches) {\n if (evaluateExpression(branch.expression, mappings)) {\n if (!renderNodes(branch.body, mappings, append)) return false;\n renderedBranch = true;\n break;\n }\n }\n if (!renderedBranch && node.elseBody && !renderNodes(node.elseBody, mappings, append)) return false;\n }\n return true;\n}\n\nexport function renderStoreCategoryPromptTemplate(input: {\n source: string;\n context: StoreCategoryPromptContext;\n}): StoreCategoryPromptRenderResult {\n const contextResult = StoreCategoryPromptContextSchema.safeParse(input.context);\n if (!contextResult.success) {\n return { ok: false, issues: [issue(\"invalid_mapping_condition\", \"Store Category prompt context contains invalid mapping conditions.\")] };\n }\n const availableConditionKeys = Object.keys(contextResult.data.mappings);\n const validation = validateStoreCategoryPromptTemplate({ source: input.source, availableConditionKeys });\n if (!validation.valid) return { ok: false, issues: validation.issues };\n\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n let output = \"\";\n let outputChars = 0;\n const append = (text: string) => {\n outputChars += sourceLength(text);\n if (outputChars > MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS) return false;\n output += text;\n return true;\n };\n const rendered = renderNodes(compiled.nodes, contextResult.data.mappings, append);\n if (!rendered) {\n return {\n ok: false,\n issues: [issue(\"rendered_prompt_too_large\", `Rendered prompt must not exceed ${MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS.toLocaleString()} characters.`)],\n };\n }\n return { ok: true, promptText: output, referencedConditionKeys: validation.referencedConditionKeys };\n}\n","import { z } from \"zod\";\n\nexport const CommerceOutreachToolContextSchema = z.strictObject({\n purpose: z.literal(\"INITIAL_RECOVERY_OUTREACH\"),\n});\n\nexport type CommerceOutreachToolContext =\n z.infer<typeof CommerceOutreachToolContextSchema>;\n","import { z } from \"zod\";\n\n/** Ordered source-backed checkout offers confirmed in one initial outreach send. */\nexport const InitialOutreachCheckoutOfferSetSchema = z.strictObject({\n schemaVersion: z.literal(\"moda.outreach.checkout-offers.v1\"),\n offers: z.array(z.strictObject({\n offerId: z.string().min(1).max(191),\n providerDiscountId: z.string().min(1).max(191).nullable(),\n method: z.enum([\"CODE\", \"AUTOMATIC\"]),\n code: z.string().min(1).max(128).nullable(),\n })).min(1).max(3),\n});\nexport type InitialOutreachCheckoutOfferSet = z.infer<\n typeof InitialOutreachCheckoutOfferSetSchema\n>;\n","/** Synthetic examples; no provider identity, schema artifact or publication claim. */\nimport type {\n CommerceManifest,\n CommerceConversationGrant,\n CommerceTurnIdentity,\n} from \"./schemas\";\nimport {\n EMPTY_RESPONSE_CONTRACT,\n type CommerceFinalResponse,\n} from \"./response\";\nimport type { Digest } from \"./canonical-json\";\nimport { responseContractCanonicalJson } from \"./canonical-json\";\nimport type { PublishedToolDescriptor, CommerceToolDefinition } from \"./definitions\";\nexport const exampleTool: PublishedToolDescriptor = {\n toolId: \"tool-fixture\",\n toolRevisionId: \"revision-fixture\",\n name: \"never_seeded_catalogue_facts\",\n definitionVersion: \"1.0.0\",\n description: \"Read synthetic catalogue facts.\",\n inputSchema: {\n type: \"object\",\n properties: { handle: { type: \"string\", minLength: 1, maxLength: 255 } },\n required: [\"handle\"],\n additionalProperties: false,\n },\n};\nexport const exampleDefinition: CommerceToolDefinition = {\n name: exampleTool.name,\n definitionVersion: \"1.0.0\",\n description: exampleTool.description,\n inputSchema: exampleTool.inputSchema,\n execution: {\n kind: \"SHOPIFY_STOREFRONT_QUERY\",\n executorVersion: \"1.0.0\",\n apiVersion: \"2026-07\",\n schemaHash: \"a\".repeat(64),\n document:\n \"query ProductDetails($handle: String!) { product(handle: $handle) { title description } }\",\n operationName: \"ProductDetails\",\n variables: { handle: { input: \"handle\" } },\n resultPath: \"product\",\n },\n responseTemplate: {\n kind: \"text\",\n text: \"{{result.values.title}}: {{result.values.description}}\",\n unavailable: \"Product details could not be verified.\",\n },\n};\nexport const exampleTurn: CommerceTurnIdentity = {\n contractVersion: \"commerce.v1\",\n shopId: \"shop-fixture\",\n checkoutRecoveryId: \"recovery-fixture\",\n conversationId: \"conversation-fixture\",\n inboundVersion: 1,\n};\nexport function exampleManifest(\n digest: Digest,\n withTool = false,\n): CommerceManifest {\n const capabilities = withTool\n ? [{\n capabilityId: \"capability-fixture\",\n key: \"feature_product_read\",\n featureId: \"feature-fixture\",\n position: 0,\n toolDescriptor: structuredClone(exampleTool),\n }]\n : [];\n return {\n contractVersion: \"commerce.v1\",\n releaseId: \"release-fixture\",\n runnerCompatibility: \"^1.0.0\",\n capabilities,\n featureBehaviours: withTool\n ? [{ featureId: \"feature-fixture\", behaviourPrompt: \"Synthetic Feature behavior.\" }]\n : [],\n selectedCapabilityKeys: capabilities.map((capability) => capability.key),\n builtInTools: [],\n grantedTools: withTool\n ? [\n {\n toolId: exampleTool.toolId,\n toolRevisionId: exampleTool.toolRevisionId,\n toolName: exampleTool.name,\n definitionVersion: \"1.0.0\",\n capabilityKeys: [\"feature_product_read\"],\n },\n ]\n : [],\n responseContract: structuredClone(EMPTY_RESPONSE_CONTRACT),\n responseContractHash: digest(\n responseContractCanonicalJson(EMPTY_RESPONSE_CONTRACT),\n ),\n };\n}\nexport function exampleGrant(\n manifest: CommerceManifest,\n): CommerceConversationGrant {\n return {\n id: \"grant-fixture\",\n shopId: exampleTurn.shopId,\n conversationId: exampleTurn.conversationId,\n initialInboundVersion: 1,\n releaseId: manifest.releaseId,\n selectedCapabilityKeys: [...manifest.selectedCapabilityKeys],\n grantedTools: structuredClone(manifest.grantedTools),\n runnerVersion: \"1.0.0\",\n createdAt: \"2026-09-20T00:00:00.000Z\",\n expiresAt: null,\n };\n}\nexport const exampleFinal: CommerceFinalResponse = {\n answerKind: \"REFER_TO_STORE\",\n replyText:\n \"I cannot verify that information. Please contact the store directly.\",\n referralReason: \"INSUFFICIENT_TOOLS\",\n detectedLanguageTag: null,\n detectedLanguageConfidence: null,\n evidenceIds: [],\n details: {},\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,wCAAwC,OAAO,OAAO;AAAA,EACjE,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,aAAa;AAAA,IACb,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,gBAAgB,mBAAmB;AAAA,IACnC,iBAAiB,oBAAoB;AAAA,EACvC,CAAC;AAAA,EACD,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,aAAa;AAAA,IACb,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,gBAAgB,mBAAmB;AAAA,IACnC,iBAAiB,oBAAoB;AAAA,EACvC,CAAC;AACH,CAAU;;;AC3BV,SAAS,SAAS;AAEX,IAAM,wCAAwC;AAC9C,IAAM,yCAAyC;AAC/C,IAAM,2CAA2C;AACjD,IAAM,uCAAuC;AACpD,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAC1B,IAAM,uBAAuB;AAE7B,IAAM,yBAAyB,oBAAI,IAAI,CAAC,aAAa,aAAa,aAAa,CAAC;AAChF,IAAM,sBAAsB;AAErB,IAAM,wCAAwC,EAClD,OAAO,EACP,MAAM,mBAAmB,EACzB,OAAO,CAAC,UAAU,CAAC,uBAAuB,IAAI,KAAK,CAAC;AAIhD,IAAM,mCAAmC,EAAE,aAAa;AAAA,EAC7D,UAAU,EACP,OAAO,uCAAuC,EAAE,QAAQ,CAAC,EACzD,OA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ACL,wBAAwB,aAAa,IAAI,CAAC,eAAe,WAAW,GAAG;AAAA,IACvE,cAAc,CAAC;AAAA,IACf,cAAc,WACV;AAAA,MACE;AAAA,QACE,QAAQ,YAAY;AAAA,QACpB,gBAAgB,YAAY;AAAA,QAC5B,UAAU,YAAY;AAAA,QACtB,mBAAmB;AAAA,QACnB,gBAAgB,CAAC,sBAAsB;AAAA,MACzC;AAAA,IACF,IACA,CAAC;AAAA,IACL,kBAAkB,gBAAgB,uBAAuB;AAAA,IACzD,sBAAsB;AAAA,MACpB,8BAA8B,uBAAuB;AAAA,IACvD;AAAA,EACF;AACF;AACO,SAAS,aACd,UAC2B;AAC3B,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,QAAQ,YAAY;AAAA,IACpB,gBAAgB,YAAY;AAAA,IAC5B,uBAAuB;AAAA,IACvB,WAAW,SAAS;AAAA,IACpB,wBAAwB,CAAC,GAAG,SAAS,sBAAsB;AAAA,IAC3D,cAAc,gBAAgB,SAAS,YAAY;AAAA,IACnD,eAAe;AAAA,IACf,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AACF;AACO,IAAM,eAAsC;AAAA,EACjD,YAAY;AAAA,EACZ,WACE;AAAA,EACF,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,4BAA4B;AAAA,EAC5B,aAAa,CAAC;AAAA,EACd,SAAS,CAAC;AACZ;","names":["z","z"]}
@@ -1,6 +1,6 @@
1
- import { R as RunnerTransportCode, C as CommerceModelInvoker, M as ModelStep } from '../../types-COI4ckJc.js';
1
+ import { R as RunnerTransportCode, C as CommerceModelInvoker, M as ModelStep } from '../../types-BaLq_Wz6.js';
2
2
  import { CommerceModelProvider, CommerceProviderModelId } from './index.js';
3
- import '../../response-DUOmPh9C.js';
3
+ import '../../response-k0hO3yus.js';
4
4
  import 'zod';
5
5
  import '../../types-B32wDMLO.js';
6
6
 
@@ -4,7 +4,7 @@ import {
4
4
  } from "../../chunk-XB5NIOKJ.js";
5
5
  import {
6
6
  CommerceToolResultSchema
7
- } from "../../chunk-NA76IPIW.js";
7
+ } from "../../chunk-6OBYUIQ3.js";
8
8
  import "../../chunk-QVPEX7KY.js";
9
9
  import {
10
10
  COMMERCE_MODEL_CONFIGURATION_SCHEMA_VERSION,
@@ -1,6 +1,6 @@
1
- import { a as RunnerDiagnostic, b as RunCommerceTurnInput, c as RunCommerceTurnResult } from '../../types-COI4ckJc.js';
2
- export { C as CommerceModelInvoker, d as ModelCall, e as ModelRequest, M as ModelStep, f as RunnerDiagnosticReason, g as RunnerDiagnosticStage, h as RunnerErrorCode, i as RunnerTool } from '../../types-COI4ckJc.js';
3
- import '../../response-DUOmPh9C.js';
1
+ import { a as RunnerDiagnostic, b as RunCommerceTurnInput, c as RunCommerceTurnResult } from '../../types-BaLq_Wz6.js';
2
+ export { C as CommerceModelInvoker, d as ModelCall, e as ModelRequest, M as ModelStep, f as RunnerDiagnosticReason, g as RunnerDiagnosticStage, h as RunnerErrorCode, i as RunnerTool } from '../../types-BaLq_Wz6.js';
3
+ import '../../response-k0hO3yus.js';
4
4
  import 'zod';
5
5
  import '../../types-B32wDMLO.js';
6
6
 
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  manifestMatchesGrant
3
- } from "../../chunk-H7NE3H5R.js";
3
+ } from "../../chunk-C2PCRWOW.js";
4
4
  import {
5
5
  CommerceModelInvocationFailure,
6
6
  RunnerFailure,
@@ -20,7 +20,7 @@ import {
20
20
  finalResponseToolSchema,
21
21
  isBuiltInTool,
22
22
  verifyResponseContract
23
- } from "../../chunk-NA76IPIW.js";
23
+ } from "../../chunk-6OBYUIQ3.js";
24
24
  import {
25
25
  LanguageSchema
26
26
  } from "../../chunk-QVPEX7KY.js";
@@ -2,9 +2,9 @@ import { z } from 'zod';
2
2
  import { PrimitiveType } from 'intl-messageformat';
3
3
 
4
4
  declare const LanguageSourceSchema: z.ZodEnum<{
5
+ shopify: "shopify";
5
6
  "customer-explicit": "customer-explicit";
6
7
  detected: "detected";
7
- shopify: "shopify";
8
8
  "merchant-default": "merchant-default";
9
9
  "platform-default": "platform-default";
10
10
  }>;
@@ -45,9 +45,9 @@ declare const TimeZoneIdSchema: z.ZodPipe<z.ZodString, z.ZodTransform<string, st
45
45
  declare const InternationalContextSchema: z.ZodObject<{
46
46
  languageTag: z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
47
47
  languageSource: z.ZodNullable<z.ZodEnum<{
48
+ shopify: "shopify";
48
49
  "customer-explicit": "customer-explicit";
49
50
  detected: "detected";
50
- shopify: "shopify";
51
51
  "merchant-default": "merchant-default";
52
52
  "platform-default": "platform-default";
53
53
  }>>;
@@ -0,0 +1,10 @@
1
+ interface CredentialKeyring {
2
+ readonly keyIds: readonly string[];
3
+ hasKey(keyId: string): boolean;
4
+ }
5
+ /** Validate and retain canonical 32-byte AES key material without exposing the bytes. */
6
+ declare function parseCredentialKeyring(raw: string | undefined): CredentialKeyring;
7
+ /** An explicit writer selection; never select the first key or trim an input. */
8
+ declare function resolveActiveCredentialKey(keyring: CredentialKeyring, activeKeyId: string | undefined): string;
9
+
10
+ export { type CredentialKeyring as C, parseCredentialKeyring as p, resolveActiveCredentialKey as r };