import {z} from 'zod' export type LightBooleanFilterClause = {type: 'booleanFilter', field: string, params: {op: string, value: boolean}}; export type LightStringFilterClause = {type: 'stringFilter', field: string, params: {op: string, value: string | null}}; export type LightStringListFilterClause = {type: 'stringListFilter', field: string, params: {op: string, value: Array | null}}; export type LightNumberFilterClause = {type: 'numberFilter', field: string, params: {op: string, value: number}}; export type LightNumberRangeFilterClause = {type: 'numberRangeFilter', field: string, params: {op: string, value: {min: number | null, max: number | null}}}; export type LightDateRangeFilterClause = {type: 'dateRangeFilter', field: string, params: {op: string, value: string | null, min: string | null, max: string | null}}; export type LightLeadScoreFilterClause = {type: 'leadScoreFilter', field: string, params: {op: string, value: number, scoreId: string}}; export type LightLocationFilterClause = {type: 'location', field: 'city' | 'country' | 'country_region', params: {op: string, value: Array}}; export type LightWebVisitPagesFilterClause = {type: 'webVisitPages', field: 'memberWebVisitPagesViewed' | 'groupWebVisitPagesViewed', params: {op: string, pages: Array<{match: 'contains' | 'exact' | 'partial' | 'prefix', value: string}>, interval: string, minimumPageViews: number | null}}; export type LightPathSegment = {target: string, objectConfigId: string | null, assocType: string | null}; export type LightFilterGroupClause = {type: 'and' | 'or', clauses: Array, target: string | null, objectConfigId: string | null, targetAssocPaths: Array> | null}; export type LightFilterClause = LightBooleanFilterClause | LightStringFilterClause | LightStringListFilterClause | LightNumberFilterClause | LightNumberRangeFilterClause | LightDateRangeFilterClause | LightLeadScoreFilterClause | LightLocationFilterClause | LightWebVisitPagesFilterClause | LightFilterGroupClause; export type LightFilterExpression = {type: 'and' | 'or', clauses: Array}; export type GetApiObjectsArgs = {limit?: number | undefined, cursor?: string | undefined, sort?: ('id' | 'name') | undefined, direction?: ('asc' | 'desc') | undefined, objectTypeId: string, segmentId?: string | undefined, cols?: string | undefined, lightFilter?: LightFilterExpression | undefined}; export type GetApiObjectsOptions = {baseUrl?: string | undefined, BearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const apiFieldValue = z.union([z.object({type: z.literal("string"), value: z.string()}), z.object({type: z.literal("url"), value: z.string()}), z.object({type: z.literal("int"), value: z.number().int()}), z.object({type: z.literal("number"), value: z.number()}), z.object({type: z.literal("date"), value: z.string()}), z.object({type: z.literal("boolean"), value: z.boolean()})]); export const apiCustomObject = z.object({id: z.string(), name: z.string(), url: z.string().optional(), recordKey: z.string().optional(), tags: z.array(z.string()).optional(), customFields: z.record(z.string(), apiFieldValue).optional()}); export const customObjectList = z.object({success: z.literal(true), data: z.array(apiCustomObject), meta: z.object({nextCursor: z.string().nullable().optional(), recordCount: z.number().int().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 custom objects * * GET /objects */ export const getApiObjects = async (args: GetApiObjectsArgs, options?: GetApiObjectsOptions) => { const {baseUrl = "https://api.commonroom.io/api/v2", fetch: fetchFn = fetch, BearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.limit != null) query.append("limit", String(args.limit)) if (args.cursor != null) query.append("cursor", String(args.cursor)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.direction != null) query.append("direction", String(args.direction)) if (args.objectTypeId != null) query.append("objectTypeId", String(args.objectTypeId)) if (args.segmentId != null) query.append("segmentId", String(args.segmentId)) if (args.cols != null) query.append("cols", String(args.cols)) if (args.lightFilter != null) query.append("lightFilter", JSON.stringify(args.lightFilter)) if (BearerAuth !== undefined) headers.set('authorization', `Bearer ${BearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/objects${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(customObjectList, await res.json()) };