import {z} from 'zod' export type PublishedPathWriteAttributes = {slug?: (string | null) | undefined, is_hidden?: (boolean | null) | undefined, strict_enforce_group_visibility?: (boolean | null) | undefined, visibility_override_type?: ('GROUP' | 'CATEGORY' | null) | undefined, catalog_layout?: ('EXPANDABLE' | 'TILE' | 'LIST' | null) | undefined, search_location?: ('HEADER_RIGHT' | 'LEFT_NAV_TOP' | 'HIDDEN' | null) | undefined, search_behavior?: ('GLOBAL' | 'LOCAL' | null) | undefined, unique_progress_per_enrollment?: (boolean | null) | undefined, enforce_sequential_navigation?: (boolean | null) | undefined, registration_status?: ('OPEN' | 'CLOSED' | null) | undefined, price_cents?: (number | null) | undefined, price_credits?: (number | null) | undefined, max_quantity?: (number | null) | undefined, sku?: (string | null) | undefined, timezone?: (string | null) | undefined, expires_at_duration?: (number | null) | undefined, expires_at_duration_unit?: ('MONTHS' | 'DAYS' | null) | undefined}; export type PathIdentifier = {id: string, type: 'paths'}; export type PathRelationship = {data: PathIdentifier}; export type DomainIdentifier = {type: 'domains', id: string}; export type DomainRelationship = {data: DomainIdentifier}; export type PublishRelationships = {path: PathRelationship, domain: DomainRelationship}; export type PublishData = {type: 'published-paths', attributes?: PublishedPathWriteAttributes | undefined, relationships: PublishRelationships}; export type PublishedPathCreateRequestEnvelope = {data: Array}; export type CreateApiV2PublishedPathsArgs = {body: PublishedPathCreateRequestEnvelope}; export type CreateApiV2PublishedPathsOptions = {baseUrl: string, JWTAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const publishedPathAttributes = z.object({external_id: z.string(), slug: z.string(), public_url: z.string(), is_hidden: z.boolean(), strict_enforce_group_visibility: z.boolean(), visibility_override_type: z.string(), catalog_layout: z.string(), search_location: z.string(), search_behavior: z.string(), unique_progress_per_enrollment: z.boolean(), enforce_sequential_navigation: z.boolean(), registration_status: z.string(), price_cents: z.number().int(), price_credits: z.number().int(), currency_code: z.string(), max_quantity: z.number().int(), sku: z.string(), timezone: z.string(), expires_at_duration: z.number().int().nullable(), expires_at_duration_unit: z.string(), created_at: z.string(), modified_at: z.string()}); export const publishedPathResource = z.object({type: z.string().optional(), id: z.string(), attributes: publishedPathAttributes, relationships: z.record(z.string(), z.unknown()).nullable().optional(), links: z.record(z.string(), z.unknown()).nullable().optional()}); export const batchSucceededItemPublishedPathResource = z.object({status: z.literal("succeeded").optional(), id: z.string().nullable().optional(), result: publishedPathResource}); export const batchItemError = z.object({code: z.enum(["duplicate_email", "duplicate_in_batch", "duplicate_name", "validation_error", "not_found", "internal_error", "not_in_domain", "already_enrolled", "already_published", "already_in_path"]), source: z.record(z.string(), z.unknown()).nullable().optional(), detail: z.string().nullable().optional()}); export const batchFailedItem = z.object({status: z.literal("failed").optional(), id: z.string().nullable().optional(), error: batchItemError}); export const batchSummary = z.object({total: z.number().int().gte(0), succeeded: z.number().int().gte(0), failed: z.number().int().gte(0)}); export const batchResultEnvelopePublishedPathResource = z.object({data: z.array(z.union([batchSucceededItemPublishedPathResource, batchFailedItem])), summary: batchSummary}); 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 }; /** * Publish paths * * POST /v2/published-paths/ */ export const createApiV2PublishedPaths = async (args: CreateApiV2PublishedPathsArgs, options: CreateApiV2PublishedPathsOptions) => { const {baseUrl, fetch: fetchFn = fetch, JWTAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/vnd.api+json") if (JWTAuth !== undefined) headers.set('authorization', `Bearer ${JWTAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v2/published-paths/${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(batchResultEnvelopePublishedPathResource, await res.json()) };