import {z} from 'zod' export type CreateApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenarioArgs = {ruleId: string, body: {scenario: {name: string, request: {surface: 'onsite' | 'checkout' | 'post-purchase', cart: {currency: string, subtotal: number, itemCount: number, lines: Array<{productId: string, variantId: string, quantity: number, unitPrice: number, lineTotal: number, selectedOptions: Array<{name: string, value: string}>, isSubscriptionLine: boolean, flags: {giftCard: boolean | null, syntheticGift: boolean | null, bundleChild: boolean | null, igUpsell: boolean | null}, tags?: Array | undefined, collections?: Array | undefined}>} | null, order: {orderId: string, checkoutToken?: string | undefined, createdAt: string, currencyCode: string, presentmentCurrency: string, itemsSubtotal: number, discountTotal?: number | undefined, shippingTotal?: number | undefined, taxTotal?: number | undefined, total: number, lines: Array<{productId: string, variantId: string, quantity: number, unitPrice: number, lineTotal: number, selectedOptions: Array<{name: string, value: string}>, isSubscriptionLine: boolean, flags: {giftCard: boolean | null, syntheticGift: boolean | null, bundleChild: boolean | null, igUpsell: boolean | null}, tags?: Array | undefined, collections?: Array | undefined, title?: string | undefined, vendor?: string | undefined, productType?: string | undefined, sellingPlanId?: string | undefined, discountAllocations?: (Array<{amount: number, title?: string | undefined}>) | undefined}>} | null, pageProduct: {productId: string, handle: string, targeting?: ({tags: Array, collectionIds: Array, inventory: number, lowestVariantPrice: number} | null) | undefined} | null, customer: {id: string, ordersCount: number | null, amountSpent?: {amount: number, currency: string} | undefined} | null, shipping: {state: 'resolved' | 'assumed' | 'not-applicable' | 'unavailable', currency: string, freeShippingThreshold?: number | undefined, remainingToFreeShipping?: (number | null) | undefined, tiers?: Array<{threshold: number, label: string}> | undefined, delivery?: ({isLocalPickup: boolean, selected?: ({title?: string | undefined, isPickup: boolean, selected: boolean, cost?: number | undefined, currency?: string | undefined, carrierName?: string | undefined, transitDays?: ({min?: number | undefined, max?: number | undefined}) | undefined}) | undefined, options: Array<{title?: string | undefined, isPickup: boolean, selected: boolean, cost?: number | undefined, currency?: string | undefined, carrierName?: string | undefined, transitDays?: ({min?: number | undefined, max?: number | undefined}) | undefined}>}) | undefined}, country?: (string | null) | undefined, cartFingerprint?: string | undefined, placementId?: string | undefined}, context?: ({isPreview: boolean, slotsNeeded: number, excludeOutOfStock?: boolean | undefined}) | undefined, evaluatedAt?: number | undefined, description?: string | undefined, targetBranchId?: (string | null) | undefined, origin?: ('authored' | 'generated') | undefined}}}; export type CreateApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenarioOptions = {baseUrl?: string | undefined, intelligemsAccessToken?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenarioResponse = z.object({result: z.object({envelope: z.object({version: z.literal(1), items: z.array(z.object({kind: z.enum(["product", "variant", "image", "reviewRef", "metaobjectRef", "bundle"]), id: z.string(), defaultVariantId: z.string().optional(), allowedVariantIds: z.array(z.string()).optional(), sellingPlanId: z.string().optional(), intent: z.enum(["add", "replace"]).optional(), discount: z.object({type: z.enum(["percentage", "fixed"]), value: z.number().gte(0)}).optional(), sourceBranch: z.string().optional(), children: z.array(z.object({kind: z.enum(["product", "variant", "image", "reviewRef", "metaobjectRef", "bundle"]), id: z.string(), quantity: z.number().int().gt(0).lte(9007199254740991)})).optional()})), branchFired: z.object({base: z.string(), instance: z.string().optional()}).optional(), cartFingerprint: z.string().optional(), warnings: z.array(z.string()).optional(), metadata: z.record(z.string(), z.unknown()).optional()}), telemetry: z.object({outcome: z.enum(["result", "empty", "error"]), errorClass: z.string().optional(), datasetRevisions: z.array(z.object({key: z.string().max(128), revision: z.number().int().gt(0).lte(9007199254740991)})).optional(), removedByExclusion: z.array(z.object({itemId: z.string(), reason: z.enum(["product_id", "tag", "collection", "vendor", "metadata_unavailable"])})).optional(), attempts: z.array(z.object({base: z.string(), instance: z.string().optional(), contributed: z.number().int().gte(0).lte(9007199254740991), outcome: z.enum(["contributed", "empty", "not-selected", "skipped", "error"])})).optional(), evaluationSource: z.enum(["serving", "api", "preview"]).optional(), executionTier: z.enum(["template", "custom"]).optional(), deadlineMs: z.number().int().gte(0).lte(9007199254740991).optional(), fallback: z.enum(["not-applicable", "hidden", "materialized", "unavailable", "failed"]).optional(), classifierBreakerTripped: z.boolean().optional()})}), exclusions: z.object({evaluated: z.boolean(), removals: z.array(z.object({itemId: z.string(), reason: z.enum(["product_id", "tag", "collection", "vendor", "metadata_unavailable"]), matchedValue: z.string().nullable()}))}).optional(), coverage: z.object({firedBranchId: z.string().nullable(), branchStates: z.record(z.string(), z.enum(["fired", "attempted", "skipped"])), traversedNodeIds: z.array(z.string()), terminalNodeId: z.string()}).nullable(), hydratedItems: z.array(z.object({id: z.string(), variantId: z.string().nullable(), title: z.string(), variantTitle: z.string().nullable().optional(), price: z.string()})), onEmpty: z.enum(["hide", "smart-recs"]).optional(), evaluated: z.object({source: z.enum(["draft", "published_version", "template"]), version: z.number().int().gte(-9007199254740991).lte(9007199254740991).nullable()}), logs: z.array(z.object({level: z.enum(["log", "info", "warn", "error", "debug"]), message: z.string(), details: z.unknown(), invocationId: z.string().optional(), timestamp: z.string()})).optional(), logsTruncated: z.literal(true).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Evaluate a scenario * * POST /v25-10-beta/agentic-logic/rules/{ruleId}/evaluate-scenario */ export const createApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenario = async (args: CreateApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenarioArgs, options?: CreateApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenarioOptions) => { const {baseUrl = "https://api.intelligems.io", fetch: fetchFn = fetch, intelligemsAccessToken} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (intelligemsAccessToken !== undefined) headers.set("intelligems-access-token", intelligemsAccessToken) const url = `${baseUrl.replace(/\/+$/, '')}/v25-10-beta/agentic-logic/rules/${encodeURIComponent(String(args.ruleId))}/evaluate-scenario${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiV2510BetaAgenticLogicRulesRuleIdEvaluateScenarioResponse, await res.json()) };