import {z} from 'zod' export type GetApiBrandIdSignalsArgs = {brand_id: number, scope?: ('account' | 'account_platform' | 'topic' | 'topic_platform' | null) | undefined, platform?: (string | null) | undefined, metric?: (string | null) | undefined, alert_type?: ('level_change' | 'trend' | null) | undefined, direction?: ('up' | 'down' | 'none' | null) | undefined, tier?: ('high' | 'confident' | 'worth_a_look' | 'provisional' | 'low_confidence' | 'underpowered' | 'untested' | null) | undefined, subject_kind?: ('brand' | 'competitor' | null) | undefined, anchor_from?: (string | null) | undefined, anchor_to?: (string | null) | undefined, fingerprint?: (string | null) | undefined, mover_url?: (string | null) | undefined, sort?: ('score_desc' | 'delta_desc' | 'detected_desc') | undefined, limit?: number | undefined, offset?: number | undefined}; export type GetApiBrandIdSignalsOptions = {baseUrl?: string | undefined, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const aPISignalNarrative = z.object({what_happened: z.string().nullable().optional(), why_it_matters: z.string().nullable().optional(), what_to_do: z.string().nullable().optional()}); export const aPISignalSlice = z.object({platforms: z.array(z.string()).optional(), topic_labels: z.array(z.string()).optional(), geo_country: z.string().nullable().optional()}); export const aPISignalUrlMover = z.object({normalized_url: z.string(), owner: z.enum(["brand", "competitor"]), competitor_id: z.number().int().nullable().optional(), competitor_name: z.string().nullable().optional(), current_responses: z.number().int(), baseline_responses: z.number().int(), current_prompts: z.number().int(), baseline_prompts: z.number().int(), contribution: z.number().nullable().optional()}); export const aPISignal = z.object({id: z.number().int(), detected_for_date: z.string(), fingerprint: z.string(), subject_kind: z.enum(["brand", "competitor"]), alert_type: z.enum(["level_change", "trend"]), scope: z.enum(["account", "account_platform", "topic", "topic_platform"]), metric: z.string(), platform: z.string(), direction: z.enum(["up", "down", "none"]), tier: z.enum(["high", "confident", "worth_a_look", "provisional", "low_confidence", "underpowered", "untested"]), current_value: z.number(), baseline_value: z.number(), delta_absolute: z.number(), score: z.number().nullable().optional(), narrative_what: z.string(), narrative: aPISignalNarrative.nullable().optional(), slice: aPISignalSlice, window_current_start: z.string().nullable().optional(), window_current_end: z.string().nullable().optional(), baseline_definition: z.string().nullable().optional(), url_movers: z.array(aPISignalUrlMover).optional(), created_at: z.string()}); export const aggregationGranularity = z.enum(["daily", "weekly", "monthly"]); export const topDomainSummary = z.object({domain: z.string(), domain_owner: z.string(), observation_count: z.number().int()}); export const ownerTimeSeriesPoint = z.object({time_bucket: z.string(), brand: z.number().int(), competitor: z.number().int(), other: z.number().int()}); export const segmentTotal = z.object({name: z.string(), observation_count: z.number().int()}); export const topDomainsMetadata = z.object({domains: z.array(topDomainSummary), grand_total: z.number().int(), owner_totals: z.record(z.string(), z.number().int()), owner_time_series: z.array(ownerTimeSeriesPoint).nullable().optional(), segment_totals: z.array(segmentTotal).optional()}); export const timeSeriesMetadata = z.object({aggregation_granularity: aggregationGranularity, period_count: z.number().int(), start_date: z.string(), end_date: z.string(), top_domains: topDomainsMetadata.nullable().optional()}); export const collectionResponseAPISignal = z.object({total: z.number().int(), offset: z.number().int().optional(), limit: z.number().int().nullable().optional(), items: z.array(aPISignal), metadata: timeSeriesMetadata.nullable().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 Signals * * GET /{brand_id}/signals */ export const getApiBrandIdSignals = async (args: GetApiBrandIdSignalsArgs, options?: GetApiBrandIdSignalsOptions) => { const {baseUrl = "https://api.scrunchai.com/v1", fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.scope != null) query.append("scope", String(args.scope)) if (args.platform != null) query.append("platform", String(args.platform)) if (args.metric != null) query.append("metric", String(args.metric)) if (args.alert_type != null) query.append("alert_type", String(args.alert_type)) if (args.direction != null) query.append("direction", String(args.direction)) if (args.tier != null) query.append("tier", String(args.tier)) if (args.subject_kind != null) query.append("subject_kind", String(args.subject_kind)) if (args.anchor_from != null) query.append("anchor_from", String(args.anchor_from)) if (args.anchor_to != null) query.append("anchor_to", String(args.anchor_to)) if (args.fingerprint != null) query.append("fingerprint", String(args.fingerprint)) if (args.mover_url != null) query.append("mover_url", String(args.mover_url)) if (args.sort != null) query.append("sort", String(args.sort)) if (args.limit != null) query.append("limit", String(args.limit)) if (args.offset != null) query.append("offset", String(args.offset)) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/${encodeURIComponent(String(args.brand_id))}/signals${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(collectionResponseAPISignal, await res.json()) };