import {z} from 'zod' export type Wildcard = '*'; export type AddressPattern = unknown | unknown | unknown | unknown; export type AssetIdPattern = string; export type OutputReferencePattern = string; export type SlotNo = number; export type HeaderHash = string; export type ForcedRollback = {rollback_to: {slot_no: SlotNo, header_hash?: HeaderHash | undefined}, limit?: ('unsafe_allow_beyond_safe_zone' | 'within_safe_zone') | undefined}; export type UpdateApiPatternsPatternArgs = {pattern: Wildcard | AddressPattern | AssetIdPattern | OutputReferencePattern, body: ForcedRollback}; export type UpdateApiPatternsPatternOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const wildcard = z.literal("*"); export const addressPattern = z.union([z.unknown(), z.unknown(), z.unknown(), z.unknown()]); export const assetIdPattern = z.string(); export const outputReferencePattern = z.string(); export const pattern = z.union([wildcard, addressPattern, assetIdPattern, outputReferencePattern]); export const updateApiPatternsPatternResponse = z.array(pattern); 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 }; /** * Add Pattern (*) * * PUT /patterns/{pattern} */ export const updateApiPatternsPattern = async (args: UpdateApiPatternsPatternArgs, options?: UpdateApiPatternsPatternOptions) => { const {baseUrl = "http://localhost:1442", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json;charset=utf-8") headers.set('accept', "application/json;charset=utf-8") const url = `${baseUrl.replace(/\/+$/, '')}/patterns/${encodeURIComponent(String(args.pattern))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "PUT", 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(updateApiPatternsPatternResponse, await res.json()) };