import {z} from 'zod' export type UploadManifestFile = {path: string, size: number, contentType: string, hash: string}; export type CreatePublishSessionInput = {files: Array, tempId?: string | undefined, title?: string | undefined, spaMode?: boolean | undefined}; export type CreateApiPublishSessionsArgs = {'X-Tempmd-Client'?: string | undefined, 'Idempotency-Key': string, body: CreatePublishSessionInput}; export type CreateApiPublishSessionsOptions = {baseUrl?: string | undefined, accountBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const publishSessionFile = z.object({fileId: z.string(), path: z.string(), size: z.number().int(), contentType: z.string(), hash: z.string(), status: z.enum(["expected", "uploaded"]), method: z.literal("PUT"), url: z.string(), headers: z.record(z.string(), z.string())}); export const publishSession = z.object({sessionId: z.string(), tempId: z.string(), versionId: z.string(), operation: z.enum(["create", "update"]), status: z.enum(["pending", "ready", "failed", "expired"]), uploadToken: z.string(), uploads: z.array(publishSessionFile), skipped: z.array(z.string()), finalizeUrl: z.string(), statusUrl: z.string(), expiresAt: z.string()}); 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 }; /** * Create or resume an idempotent upload session * * POST /publish-sessions * * Also accepts auth: tempCapability */ export const createApiPublishSessions = async (args: CreateApiPublishSessionsArgs, options?: CreateApiPublishSessionsOptions) => { const {baseUrl = "https://api.temp.md", fetch: fetchFn = fetch, accountBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Tempmd-Client'] != null) headers.set("X-Tempmd-Client", String(args['X-Tempmd-Client'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (accountBearer !== undefined) headers.set('authorization', `Bearer ${accountBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/publish-sessions${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(publishSession, await res.json()) };