import {z} from 'zod' export type GetApi10CommerceInventoryArgs = {cursor?: string | undefined, Authorization: string, 'User-Agent': string}; export type GetApi10CommerceInventoryOptions = {baseUrl?: string | undefined, Authorization?: string | undefined, fetch?: typeof fetch | undefined}; export const inventoryItem = z.object({descriptor: z.string().optional(), isUnlimited: z.boolean().optional(), quantity: z.number().int().optional(), sku: z.string().optional(), variantId: z.string().optional()}); export const paginatedInventoryItemListResponse = z.object({inventory: z.array(inventoryItem).optional(), pagination: z.object({hasNextPage: z.boolean().optional(), nextPageCursor: z.string().optional(), nextPageUrl: z.string().optional()}).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 }; /** * List inventory * * GET /1.0/commerce/inventory */ export const getApi10CommerceInventory = async (args: GetApi10CommerceInventoryArgs, options?: GetApi10CommerceInventoryOptions) => { const {baseUrl = "https://api.squarespace.com", fetch: fetchFn = fetch, Authorization} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.Authorization != null) headers.set("Authorization", String(args.Authorization)) if (args['User-Agent'] != null) headers.set("User-Agent", String(args['User-Agent'])) if (Authorization !== undefined) headers.set('authorization', `Bearer ${Authorization}`) const url = `${baseUrl.replace(/\/+$/, '')}/1.0/commerce/inventory${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(paginatedInventoryItemListResponse, await res.json()) };