import {z} from 'zod' export type GetApiEntitiesSegmentsIdPredictiveSegmentsGuessRuleAsyncArgs = {id: number}; export type GetApiEntitiesSegmentsIdPredictiveSegmentsGuessRuleAsyncOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const functionExpression = z.union([z.object({function: z.enum(["+", "-", "*", "/"]), arg: z.number().optional()}), z.object({function: z.literal("replace"), search: z.string().optional(), replacement: z.string().nullable().optional()}), z.object({function: z.literal("substr"), start: z.number().optional(), length: z.number().optional()}), z.object({function: z.literal("regexp_extract"), pattern: z.string().optional(), group: z.number().optional()}), z.object({function: z.enum(["day_of_week", "from_iso8601_timestamp", "ln", "elapsed_days", "td_ip_to_least_specific_subdivision_name", "td_ip_to_country_name", "td_ip_to_city_name", "td_ip_to_connection_type", "td_ip_to_domain"])}), z.object({function: z.literal("cast_as_quantitative"), default: z.number()}), z.object({function: z.literal("cast_as_categorical"), default: z.string()}), z.object({function: z.literal("cast_as_categorical_array")}), z.object({function: z.literal("if"), op: z.enum([">", "<", "<=", ">=", "=", "!=", "is", "is\", "not"]).optional(), right_value: z.number().nullable().optional(), then: z.number().optional(), else: z.number().optional()})]); export const predictiveSegmentPreprocessItem = z.object({column: z.string(), source: z.object({column: z.string().optional(), table: z.string().optional(), functions: z.array(functionExpression).optional()})}); export const predictiveSegmentRule = z.object({categoricalAsColumnNames: z.array(z.string()).optional(), categoricalArrayAsColumnNames: z.array(z.string()).optional(), quantitativeAsColumnNames: z.array(z.string()).optional(), preprocess: z.array(predictiveSegmentPreprocessItem).optional()}); export const entitiesSegmentPredictiveSegmentGuessRuleAsyncJsonApiResult = z.object({data: z.object({id: z.string().optional(), type: z.literal("predictive-segment-rule-guess-result").optional(), attributes: z.object({status: z.enum(["running", "success"]).optional(), rule: predictiveSegmentRule.optional()}).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 }; /** * Retrieve predictive scoring rules * * GET /entities/segments/{id}/predictive_segments/guess_rule_async */ export const getApiEntitiesSegmentsIdPredictiveSegmentsGuessRuleAsync = async (args: GetApiEntitiesSegmentsIdPredictiveSegmentsGuessRuleAsyncArgs, options?: GetApiEntitiesSegmentsIdPredictiveSegmentsGuessRuleAsyncOptions) => { const {baseUrl = "https://api-cdp.treasuredata.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/vnd.treasuredata.v1+json") const url = `${baseUrl.replace(/\/+$/, '')}/entities/segments/${encodeURIComponent(String(args.id))}/predictive_segments/guess_rule_async${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(entitiesSegmentPredictiveSegmentGuessRuleAsyncJsonApiResult, await res.json()) };