@adport/provider-reddit 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/provider.ts","../src/tools.ts","../src/index.ts"],"sourcesContent":["import { AdportError } from '@adport/core';\n\nexport interface RedditCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n /** Reddit requires an honest, uniquely identifying User-Agent on every request. */\n userAgent: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\n\nexport const REDDIT_API_VERSION = 'v3';\nexport const REDDIT_API_BASE = `https://ads-api.reddit.com/api/${REDDIT_API_VERSION}`;\nexport const REDDIT_TOKEN_URL = 'https://www.reddit.com/api/v1/access_token';\n\ninterface TokenState {\n accessToken: string;\n expiresAt: number;\n}\n\nexport interface RedditEnvelope<T> {\n data: T;\n pagination?: { next_url?: string; previous_url?: string; page_index?: number; total_count?: number };\n}\n\n/** OAuth-refreshing Reddit Ads API v3 client with exact next_url pagination. */\nexport class RedditAdsClient {\n private token?: TokenState;\n private refreshToken: string;\n\n constructor(\n private readonly credentials: RedditCredentials,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.refreshToken = credentials.refreshToken;\n }\n\n async get<T>(pathOrUrl: string, params: Record<string, unknown> = {}): Promise<RedditEnvelope<T>> {\n const url = this.url(pathOrUrl, params);\n return this.send<T>(url, { method: 'GET' });\n }\n\n async post<T>(pathOrUrl: string, body: Record<string, unknown>): Promise<RedditEnvelope<T>> {\n return this.send<T>(this.url(pathOrUrl), { method: 'POST', body: JSON.stringify(body) });\n }\n\n async patch<T>(pathOrUrl: string, body: Record<string, unknown>): Promise<RedditEnvelope<T>> {\n return this.send<T>(this.url(pathOrUrl), { method: 'PATCH', body: JSON.stringify(body) });\n }\n\n async delete<T>(pathOrUrl: string): Promise<RedditEnvelope<T>> {\n return this.send<T>(this.url(pathOrUrl), { method: 'DELETE' });\n }\n\n async getPaged<T>(path: string, params: Record<string, unknown> = {}, limit = 1000): Promise<T[]> {\n const rows: T[] = [];\n let page = await this.get<T[]>(path, params);\n while (true) {\n rows.push(...page.data.slice(0, Math.max(0, limit - rows.length)));\n if (rows.length >= limit || !page.pagination?.next_url) return rows;\n page = await this.get<T[]>(page.pagination.next_url);\n }\n }\n\n private url(pathOrUrl: string, params: Record<string, unknown> = {}): string {\n const normalized = pathOrUrl.trim();\n const url = normalized.startsWith('https://')\n ? new URL(normalized)\n : new URL(`${REDDIT_API_BASE}/${normalized.replace(/^\\/+/, '')}`);\n if (url.origin !== 'https://ads-api.reddit.com' || !url.pathname.startsWith('/api/v3/')) {\n throw new AdportError('INVALID_INPUT', 'reddit: pagination or API URL must stay within https://ads-api.reddit.com/api/v3/');\n }\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n url.searchParams.set(key, Array.isArray(value) ? value.join(',') : String(value));\n }\n return url.toString();\n }\n\n private async send<T>(url: string, init: { method: string; body?: string }): Promise<RedditEnvelope<T>> {\n const accessToken = await this.accessToken();\n const response = await this.fetchImpl(url, {\n method: init.method,\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'user-agent': this.credentials.userAgent,\n accept: 'application/json',\n ...(init.body ? { 'content-type': 'application/json' } : {}),\n },\n body: init.body,\n });\n const raw = await response.text();\n const parsed = raw ? safeJson(raw) : { data: {} };\n if (!response.ok) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Reddit Ads API ${response.status} ${init.method} ${new URL(url).pathname}: ${redditErrorMessage(parsed)}`,\n parsed,\n );\n }\n return parsed as RedditEnvelope<T>;\n }\n\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.accessToken;\n const response = await this.fetchImpl(REDDIT_TOKEN_URL, {\n method: 'POST',\n headers: {\n authorization: `Basic ${Buffer.from(`${this.credentials.clientId}:${this.credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'user-agent': this.credentials.userAgent,\n },\n body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }),\n });\n const data = (await response.json()) as {\n access_token?: string;\n expires_in?: number;\n refresh_token?: string;\n error?: string;\n message?: string;\n };\n if (!response.ok || !data.access_token) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Reddit OAuth refresh failed${data.error ? ` (${data.error})` : ''}: ${data.message ?? 'no access token returned'}`,\n data,\n );\n }\n if (data.refresh_token && data.refresh_token !== this.refreshToken) {\n this.refreshToken = data.refresh_token;\n await this.credentials.onRefreshToken?.(data.refresh_token);\n }\n this.token = {\n accessToken: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000,\n };\n return data.access_token;\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return { message: raw };\n }\n}\n\nfunction redditErrorMessage(value: unknown): string {\n if (!value || typeof value !== 'object') return String(value);\n const record = value as Record<string, unknown>;\n return String(record.message ?? record.error ?? record.detail ?? 'unknown provider error');\n}\n","import {\n AdportError,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n} from '@adport/core';\nimport { RedditAdsClient, type RedditEnvelope } from './client.js';\n\n/** Reddit budget, bid, spend, CPC, and CPM fields are integer micros. */\nexport const REDDIT_MICROS = 1_000_000;\n\ninterface RedditBusiness { id: string; name?: string }\ninterface RedditAdAccount {\n id: string;\n name?: string;\n currency?: string;\n admin_approval?: string;\n suspension_reason?: string;\n}\nexport interface RedditCampaign {\n id: string;\n ad_account_id: string;\n name: string;\n configured_status: string;\n effective_status?: string;\n objective?: string;\n funding_instrument_id?: string;\n goal_type?: string;\n goal_value?: number;\n spend_cap?: number;\n is_campaign_budget_optimization?: boolean;\n}\n\ninterface WritePlan {\n summary: string;\n changes: string[];\n coercions: string[];\n budgetDeltas: WritePreview['budgetDeltas'];\n execute: () => Promise<string[]>;\n}\n\n// Reddit v3 request enums are uppercase even though response object keys are lowercase.\nconst BREAKDOWN = { account: undefined, campaign: 'CAMPAIGN_ID', ad_group: 'AD_GROUP_ID', ad: 'AD_ID' } as const;\n\nexport class RedditAdsProvider implements AdProvider {\n readonly id = 'reddit';\n\n constructor(private readonly client: RedditAdsClient) {}\n\n capabilities(): ProviderCapabilities {\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'reddit_set_campaign_status',\n input: { account_id: accountId, campaign_id: campaignId, configured_status: 'PAUSED' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const businesses = await this.client.getPaged<RedditBusiness>('me/businesses', { 'page.size': 100 }, 1000);\n const byId = new Map<string, RedditAdAccount>();\n for (const business of businesses) {\n const accounts = await this.client.getPaged<RedditAdAccount>(\n `businesses/${encodeURIComponent(business.id)}/ad_accounts`,\n { 'page.size': 100 },\n 1000,\n );\n for (const account of accounts) byId.set(account.id, account);\n }\n return [...byId.values()].map((account) => ({\n provider: this.id,\n id: account.id,\n name: account.name ?? account.id,\n currency: account.currency,\n status: account.suspension_reason ? `SUSPENDED:${account.suspension_reason}` : account.admin_approval,\n }));\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((account) => account.id);\n const rows: ReportRow[] = [];\n for (const accountId of accountIds) {\n const breakdown = BREAKDOWN[query.level];\n const body = {\n data: {\n ...(breakdown ? { breakdowns: [breakdown] } : {}),\n fields: [\n 'SPEND',\n 'IMPRESSIONS',\n 'CLICKS',\n 'CONVERSION_PURCHASE_CLICKS',\n 'CONVERSION_PURCHASE_VIEWS',\n 'CONVERSION_PURCHASE_TOTAL_VALUE',\n ],\n starts_at: `${range.start}T00:00:00Z`,\n // The v3 schema accepts hourly granularity only. Midnight on the\n // following day keeps an inclusive Adport date range intact.\n ends_at: `${nextDay(range.end)}T00:00:00Z`,\n time_zone_id: 'UTC',\n },\n };\n const metrics = await this.fetchReportPages(accountId, body, query.limit ?? 1000);\n for (const metric of metrics) rows.push(this.toReportRow(metric, accountId, query, breakdown?.toLowerCase()));\n }\n return { rows };\n }\n\n async rawReport(input: {\n account_id: string;\n breakdowns?: string[];\n fields: string[];\n starts_at: string;\n ends_at: string;\n time_zone_id?: string;\n filter?: string;\n page_size?: number;\n }): Promise<{ metrics: Array<Record<string, unknown>>; metrics_updated_at?: string }> {\n const body = {\n data: {\n ...(input.breakdowns?.length ? { breakdowns: input.breakdowns } : {}),\n fields: input.fields,\n starts_at: input.starts_at,\n ends_at: input.ends_at,\n time_zone_id: input.time_zone_id ?? 'UTC',\n ...(input.filter ? { filter: input.filter } : {}),\n },\n };\n const first = await this.client.post<{ metrics?: Array<Record<string, unknown>>; metrics_updated_at?: string }>(\n `ad_accounts/${encodeURIComponent(input.account_id)}/reports?page.size=${Math.min(input.page_size ?? 200, 1000)}`,\n body,\n );\n const metrics = [...(first.data.metrics ?? [])];\n let next = first.pagination?.next_url;\n while (next && metrics.length < (input.page_size ?? 200)) {\n const page = await this.client.get<{ metrics?: Array<Record<string, unknown>> }>(next);\n metrics.push(...(page.data.metrics ?? []));\n next = page.pagination?.next_url;\n }\n return { metrics: metrics.slice(0, input.page_size ?? 200), metrics_updated_at: first.data.metrics_updated_at };\n }\n\n async apiRead(input: {\n account_id: string;\n path: string;\n method?: 'GET' | 'POST';\n params?: Record<string, unknown>;\n body?: Record<string, unknown>;\n limit?: number;\n }): Promise<unknown> {\n const path = validateRedditPath(input.path);\n assertReadScoped(path, input.account_id);\n if (input.method === 'POST') {\n if (!/(?:\\/reports|\\/history|\\/query|\\/search)$/.test(path)) {\n throw new AdportError('INVALID_INPUT', 'reddit: read-only POST is limited to documented reports, history, query, and search endpoints');\n }\n return this.client.post(path, input.body ?? {});\n }\n if (input.limit) return this.client.getPaged(path, input.params, input.limit);\n return this.client.get(path, input.params);\n }\n\n async listCampaigns(accountId: string, ids?: string[]): Promise<RedditCampaign[]> {\n return this.client.getPaged<RedditCampaign>(\n `ad_accounts/${encodeURIComponent(accountId)}/campaigns`,\n { ...(ids?.length ? { id: ids } : {}), 'page.size': Math.min(ids?.length ?? 100, 100) },\n ids?.length ?? 1000,\n );\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n return {\n summary: plan.summary,\n changes: plan.changes,\n coercions: plan.coercions,\n budgetDeltas: plan.budgetDeltas,\n serverValidated: false,\n };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n return { applied: true, resourceIds: await plan.execute() };\n }\n\n private async fetchReportPages(\n accountId: string,\n body: Record<string, unknown>,\n limit: number,\n ): Promise<Array<Record<string, unknown>>> {\n const first = await this.client.post<{ metrics?: Array<Record<string, unknown>> }>(\n `ad_accounts/${encodeURIComponent(accountId)}/reports?page.size=${Math.min(limit, 1000)}`,\n body,\n );\n const rows = [...(first.data.metrics ?? [])];\n let next = first.pagination?.next_url;\n while (next && rows.length < limit) {\n const page = await this.client.get<{ metrics?: Array<Record<string, unknown>> }>(next);\n rows.push(...(page.data.metrics ?? []));\n next = page.pagination?.next_url;\n }\n return rows.slice(0, limit);\n }\n\n private toReportRow(\n raw: Record<string, unknown>,\n accountId: string,\n query: NormalizedQuery,\n breakdown?: string,\n ): ReportRow {\n const value = (key: string) => Number(raw[key] ?? 0);\n const spend = value('spend') / REDDIT_MICROS;\n const impressions = value('impressions');\n const clicks = value('clicks');\n const conversions = value('conversion_purchase_clicks') + value('conversion_purchase_views');\n const conversionValue = value('conversion_purchase_total_value') / 100;\n const all: Record<MetricName, number> = {\n spend: round2(spend), impressions, clicks, conversions, conversion_value: round2(conversionValue),\n ctr: impressions ? round2((clicks / impressions) * 100) : 0,\n cpc: clicks ? round2(spend / clicks) : 0,\n cpm: impressions ? round2((spend / impressions) * 1000) : 0,\n cpa: conversions ? round2(spend / conversions) : 0,\n roas: spend ? round2(conversionValue / spend) : 0,\n };\n const entityId = breakdown ? String(raw[breakdown] ?? '') : accountId;\n return {\n provider: this.id,\n accountId,\n entity: { level: query.level, id: entityId, name: entityId },\n metrics: Object.fromEntries(query.metrics.map((metric) => [metric, all[metric]])),\n };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n const payload = op.payload as never;\n switch (op.tool) {\n case 'reddit_create_campaign': return this.planCreateCampaign(op.accountId, payload, guard);\n case 'reddit_set_campaign_status': return this.planSetStatus(op.accountId, payload);\n case 'reddit_set_budget': return this.planSetBudget(op.accountId, payload);\n case 'reddit_api_create': return this.planApiCreate(op.accountId, payload, guard);\n case 'reddit_api_update': return this.planApiUpdate(op.accountId, payload);\n case 'reddit_api_delete': return this.planApiDelete(op.accountId, payload);\n default: throw new AdportError('PROVIDER_ERROR', `reddit: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: {\n name: string;\n objective: string;\n funding_instrument_id: string;\n configured_status?: 'ACTIVE' | 'PAUSED';\n budget_micros?: number;\n budget_type?: 'DAILY_SPEND' | 'LIFETIME_SPEND';\n conversion_pixel_id?: string;\n spend_cap_micros?: number;\n },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n if (payload.budget_micros && !payload.conversion_pixel_id) {\n throw new AdportError('INVALID_INPUT', 'reddit: conversion_pixel_id is required for CBO campaigns (effective July 13, 2026)');\n }\n const requested = payload.configured_status ?? 'PAUSED';\n const status = guard.forcePausedCreation ? 'PAUSED' : requested;\n const coercions = requested !== status\n ? ['configured_status coerced to PAUSED by policy (paused_creation)']\n : [];\n const data: Record<string, unknown> = {\n name: payload.name,\n configured_status: status,\n objective: payload.objective,\n funding_instrument_id: payload.funding_instrument_id,\n is_campaign_budget_optimization: payload.budget_micros !== undefined,\n ...(payload.budget_micros ? {\n goal_type: payload.budget_type ?? 'DAILY_SPEND',\n goal_value: payload.budget_micros,\n conversion_pixel_id: payload.conversion_pixel_id,\n } : {}),\n ...(payload.spend_cap_micros ? { spend_cap: payload.spend_cap_micros } : {}),\n };\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n if (payload.budget_micros) budgetDeltas.push({ target: `new campaign \"${payload.name}\" budget`, toMicros: payload.budget_micros });\n if (payload.spend_cap_micros) budgetDeltas.push({ target: `new campaign \"${payload.name}\" spend cap`, toMicros: payload.spend_cap_micros });\n return {\n summary: `Create Reddit campaign \"${payload.name}\" (${payload.objective}, ${status.toLowerCase()})`,\n changes: [`+ POST /ad_accounts/${accountId}/campaigns ${JSON.stringify({ data })}`],\n coercions,\n budgetDeltas,\n execute: async () => extractIds(await this.client.post<RedditCampaign>(`ad_accounts/${encodeURIComponent(accountId)}/campaigns`, { data })),\n };\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_id: string; configured_status: 'ACTIVE' | 'PAUSED' },\n ): Promise<WritePlan> {\n const campaign = await this.getOwnedCampaign(accountId, payload.campaign_id);\n return {\n summary: `Set Reddit campaign \"${campaign.name}\" → ${payload.configured_status.toLowerCase()}`,\n changes: [`~ campaign ${campaign.id} configured_status ${campaign.configured_status} → ${payload.configured_status}`],\n coercions: [], budgetDeltas: [],\n execute: async () => extractIds(await this.client.patch<RedditCampaign>(`campaigns/${encodeURIComponent(campaign.id)}`, {\n data: { configured_status: payload.configured_status },\n })),\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; budget_micros: number; budget_type?: 'DAILY_SPEND' | 'LIFETIME_SPEND' },\n ): Promise<WritePlan> {\n const campaign = await this.getOwnedCampaign(accountId, payload.campaign_id);\n if (!campaign.is_campaign_budget_optimization) {\n throw new AdportError('INVALID_INPUT', `reddit: campaign \"${campaign.name}\" is not a CBO campaign; budget its ad groups instead`);\n }\n return {\n summary: `Change Reddit campaign \"${campaign.name}\" budget ${campaign.goal_value ?? '?'} → ${payload.budget_micros} micros`,\n changes: [`~ campaign ${campaign.id} ${campaign.goal_type ?? 'goal'} ${campaign.goal_value ?? '?'} → ${payload.budget_micros}`],\n coercions: [],\n budgetDeltas: [{ target: `campaign \"${campaign.name}\" budget`, fromMicros: campaign.goal_value, toMicros: payload.budget_micros }],\n execute: async () => extractIds(await this.client.patch<RedditCampaign>(`campaigns/${encodeURIComponent(campaign.id)}`, {\n data: { goal_value: payload.budget_micros, ...(payload.budget_type ? { goal_type: payload.budget_type } : {}) },\n })),\n };\n }\n\n private async planApiCreate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const path = validateRedditPath(payload.path);\n if (!path.startsWith(`ad_accounts/${accountId}/`)) {\n throw new AdportError('INVALID_INPUT', 'reddit: create path must be under the selected ad account');\n }\n const body = structuredClone(payload.body);\n const coercions: string[] = [];\n if (guard.forcePausedCreation) {\n coerceCreatedStatuses(body, coercions, /\\/(?:campaigns|ad_groups|ads)$/.test(path));\n }\n return {\n summary: `Create Reddit resource via /${path}`,\n changes: [`+ POST /${path} ${JSON.stringify(body)}`],\n coercions,\n budgetDeltas: collectMicros(body),\n execute: async () => extractIds(await this.client.post(path, body)),\n };\n }\n\n private async planApiUpdate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const path = validateRedditPath(payload.path);\n await this.assertOwnedResource(path, accountId);\n if (containsMoney(payload.body)) {\n throw new AdportError('INVALID_INPUT', 'reddit: budget, bid, goal, and spend-cap updates require a typed budget tool for policy checks');\n }\n return {\n summary: `Update Reddit resource via /${path}`,\n changes: [`~ PATCH /${path} ${JSON.stringify(payload.body)}`],\n coercions: [], budgetDeltas: [],\n execute: async () => extractIds(await this.client.patch(path, payload.body)),\n };\n }\n\n private async planApiDelete(accountId: string, payload: { path: string }): Promise<WritePlan> {\n const path = validateRedditPath(payload.path);\n await this.assertOwnedResource(path, accountId);\n return {\n summary: `Permanently delete Reddit resource via /${path}`,\n changes: [`- DELETE /${path}`],\n coercions: [], budgetDeltas: [],\n execute: async () => extractIds(await this.client.delete(path)),\n };\n }\n\n private async getOwnedCampaign(accountId: string, campaignId: string): Promise<RedditCampaign> {\n const campaign = (await this.client.get<RedditCampaign>(`campaigns/${encodeURIComponent(campaignId)}`)).data;\n if (campaign.ad_account_id !== accountId) {\n throw new AdportError('INVALID_INPUT', `reddit: campaign ${campaignId} does not belong to selected account ${accountId}`);\n }\n return campaign;\n }\n\n private async assertOwnedResource(path: string, accountId: string): Promise<void> {\n const resource = (await this.client.get<Record<string, unknown>>(path)).data;\n if (String(resource.ad_account_id ?? '') !== accountId) {\n throw new AdportError('INVALID_INPUT', `reddit: /${path} does not prove ownership by selected account ${accountId}`);\n }\n }\n}\n\nfunction nextDay(date: string): string {\n const value = new Date(`${date}T00:00:00Z`);\n value.setUTCDate(value.getUTCDate() + 1);\n return value.toISOString().slice(0, 10);\n}\n\nfunction validateRedditPath(path: string): string {\n const normalized = path.replace(/^\\/+|\\/+$/g, '').trim();\n if (!/^[A-Za-z0-9_.~/-]{3,220}$/.test(normalized) || normalized.includes('..') || normalized.includes('//')) {\n throw new AdportError('INVALID_INPUT', `reddit: invalid Ads API v3 path \"${path}\"`);\n }\n return normalized;\n}\n\nfunction assertReadScoped(path: string, accountId: string): void {\n if (path === `ad_accounts/${accountId}` || path.startsWith(`ad_accounts/${accountId}/`)) return;\n if (/^(campaigns|ad_groups|ads|structured_posts)\\/[^/]+$/.test(path)) return;\n throw new AdportError('INVALID_INPUT', 'reddit: read path must be selected-account scoped or a single campaign/ad-group/ad/post resource');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction coerceCreatedStatuses(value: Record<string, unknown>, coercions: string[], statusBearingPath: boolean): void {\n const data = isRecord(value.data) ? value.data : value;\n const visit = (item: unknown, path = 'body'): void => {\n if (Array.isArray(item)) return item.forEach((child, index) => visit(child, `${path}[${index}]`));\n if (!isRecord(item)) return;\n for (const [key, child] of Object.entries(item)) {\n if (key === 'configured_status' && child !== 'PAUSED') {\n item[key] = 'PAUSED';\n coercions.push(`${path}.${key} coerced to PAUSED by policy (paused_creation)`);\n } else visit(child, `${path}.${key}`);\n }\n };\n visit(value);\n if (statusBearingPath && data.configured_status === undefined) {\n data.configured_status = 'PAUSED';\n coercions.push('body.data.configured_status set to PAUSED by policy (paused_creation)');\n }\n}\n\nconst MONEY_KEY = /(?:goal_value|spend_cap|bid_value|budget(?:_micros)?|daily_budget|lifetime_budget)$/i;\n\nfunction containsMoney(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsMoney);\n if (!isRecord(value)) return false;\n return Object.entries(value).some(([key, child]) => MONEY_KEY.test(key) || containsMoney(child));\n}\n\nfunction collectMicros(value: unknown, path = 'body'): WritePreview['budgetDeltas'] {\n if (Array.isArray(value)) return value.flatMap((child, index) => collectMicros(child, `${path}[${index}]`));\n if (!isRecord(value)) return [];\n const deltas: WritePreview['budgetDeltas'] = [];\n for (const [key, child] of Object.entries(value)) {\n if (MONEY_KEY.test(key) && Number.isInteger(child) && Number(child) > 0) {\n deltas.push({ target: `${path}.${key}`, toMicros: Number(child) });\n }\n deltas.push(...collectMicros(child, `${path}.${key}`));\n }\n return deltas;\n}\n\nfunction extractIds(envelope: RedditEnvelope<unknown>): string[] {\n const ids: string[] = [];\n const visit = (value: unknown): void => {\n if (Array.isArray(value)) return value.forEach(visit);\n if (!isRecord(value)) return;\n if (typeof value.id === 'string' || typeof value.id === 'number') ids.push(String(value.id));\n for (const child of Object.values(value)) visit(child);\n };\n visit(envelope.data);\n return [...new Set(ids)];\n}\n\nfunction round2(value: number): number {\n return Math.round(value * 100) / 100;\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsProvider } from './provider.js';\n\nconst status = z.enum(['ACTIVE', 'PAUSED']);\n\nexport function redditTools(provider: RedditAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'reddit_api_read',\n namespace: 'reddit',\n description: 'Call a documented Reddit Ads API v3 GET or read-only reports/history/query/search POST endpoint, scoped to the selected ad account.',\n input: z.object({\n account_id: z.string(),\n path: z.string().min(3).describe('Relative v3 path, e.g. ad_accounts/{id}/ad_groups or campaigns/{campaign_id}'),\n method: z.enum(['GET', 'POST']).default('GET'),\n params: z.record(z.string(), z.unknown()).optional(),\n body: z.record(z.string(), z.unknown()).optional(),\n limit: z.number().int().positive().max(5000).optional().describe('Follow list pagination for GET responses'),\n }),\n annotations: { readOnly: true },\n handler: (input) => provider.apiRead(input),\n }),\n defineTool({\n name: 'reddit_campaigns',\n namespace: 'reddit',\n description: 'List Reddit campaigns and their native configured/effective status, CBO budget, objective, and funding instrument.',\n input: z.object({ account_id: z.string(), campaign_ids: z.array(z.string()).optional() }),\n annotations: { readOnly: true },\n async handler(input) { return { campaigns: await provider.listCampaigns(input.account_id, input.campaign_ids) }; },\n }),\n defineTool({\n name: 'reddit_report',\n namespace: 'reddit',\n description: 'Query Reddit Ads API v3 reporting directly. Spend, CPC, CPM, and applicable conversion fields are returned by Reddit in micros.',\n input: z.object({\n account_id: z.string(),\n breakdowns: z.array(z.string()).max(4).optional(),\n fields: z.array(z.string()).min(1).default(['spend', 'impressions', 'clicks']),\n starts_at: z.string().datetime({ offset: true }),\n ends_at: z.string().datetime({ offset: true }),\n time_zone_id: z.string().default('UTC'),\n filter: z.string().optional(),\n page_size: z.number().int().positive().max(1000).default(200),\n }),\n annotations: { readOnly: true },\n handler: (input) => provider.rawReport(input),\n }),\n guardedWriteTool({\n name: 'reddit_create_campaign',\n namespace: 'reddit',\n description: 'Create a Reddit campaign through API v3. Campaigns are forced PAUSED. CBO budgets and spend caps are integer micros.',\n provider: 'reddit', kind: 'create',\n payload: z.object({\n name: z.string().min(1),\n objective: z.string().min(1).default('TRAFFIC').describe('Current Reddit objective enum; Reddit has announced an enum migration for Sep 30, 2026'),\n funding_instrument_id: z.string().min(1),\n configured_status: status.optional(),\n budget_micros: z.number().int().positive().optional().describe('Sets CBO goal_value; requires conversion_pixel_id'),\n budget_type: z.enum(['DAILY_SPEND', 'LIFETIME_SPEND']).default('DAILY_SPEND'),\n conversion_pixel_id: z.string().optional(),\n spend_cap_micros: z.number().int().positive().optional(),\n }),\n }),\n guardedWriteTool({\n name: 'reddit_set_campaign_status', namespace: 'reddit',\n description: 'Activate or pause a Reddit campaign after verifying ad-account ownership.',\n provider: 'reddit', kind: 'update',\n payload: z.object({ campaign_id: z.string(), configured_status: status }),\n }),\n guardedWriteTool({\n name: 'reddit_set_budget', namespace: 'reddit',\n description: 'Change a Reddit CBO campaign goal_value in integer micros, with current-value lookup and policy checks.',\n provider: 'reddit', kind: 'update',\n payload: z.object({\n campaign_id: z.string(),\n budget_micros: z.number().int().positive(),\n budget_type: z.enum(['DAILY_SPEND', 'LIFETIME_SPEND']).optional(),\n }),\n }),\n guardedWriteTool({\n name: 'reddit_api_create', namespace: 'reddit',\n description: 'Create via an account-scoped Reddit Ads API v3 endpoint. Campaign status is forced PAUSED and native micros fields are policy-checked.',\n provider: 'reddit', kind: 'create',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'reddit_api_update', namespace: 'reddit',\n description: 'PATCH non-budget fields on a Reddit Ads API v3 resource after verifying ad-account ownership.',\n provider: 'reddit', kind: 'update',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'reddit_api_delete', namespace: 'reddit',\n description: 'Permanently DELETE a Reddit Ads API v3 resource after verifying ad-account ownership.',\n provider: 'reddit', kind: 'remove', destructive: true,\n payload: z.object({ path: z.string().min(3) }),\n }),\n ];\n}\n","import type { CredentialStore, ProviderModule } from '@adport/core';\nimport { RedditAdsClient, type RedditCredentials } from './client.js';\nimport { RedditAdsProvider } from './provider.js';\nimport { redditTools } from './tools.js';\n\nexport { RedditAdsClient, REDDIT_API_BASE, REDDIT_API_VERSION, REDDIT_TOKEN_URL, type RedditCredentials, type RedditEnvelope } from './client.js';\nexport { RedditAdsProvider, REDDIT_MICROS, type RedditCampaign } from './provider.js';\nexport { redditTools } from './tools.js';\n\nexport async function resolveRedditCredentials(store: CredentialStore): Promise<RedditCredentials | undefined> {\n const record = await store.get('reddit');\n const data = record?.data;\n if (data?.client_id && data.client_secret && data.refresh_token && data.user_agent) {\n const source = record?.source ?? 'byo';\n return {\n clientId: data.client_id,\n clientSecret: data.client_secret,\n refreshToken: data.refresh_token,\n userAgent: data.user_agent,\n onRefreshToken: async (refreshToken) => {\n await store.set({ provider: 'reddit', source, data: { ...data, refresh_token: refreshToken } });\n },\n };\n }\n if (process.env.REDDIT_ADS_CLIENT_ID && process.env.REDDIT_ADS_CLIENT_SECRET && process.env.REDDIT_ADS_REFRESH_TOKEN && process.env.REDDIT_ADS_USER_AGENT) {\n return {\n clientId: process.env.REDDIT_ADS_CLIENT_ID,\n clientSecret: process.env.REDDIT_ADS_CLIENT_SECRET,\n refreshToken: process.env.REDDIT_ADS_REFRESH_TOKEN,\n userAgent: process.env.REDDIT_ADS_USER_AGENT,\n };\n }\n return undefined;\n}\n\nexport async function createRedditModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveRedditCredentials(store);\n if (!credentials) return undefined;\n const provider = new RedditAdsProvider(new RedditAdsClient(credentials));\n return { provider, tools: redditTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,mBAAmB;AAWrB,IAAM,qBAAqB;AAC3B,IAAM,kBAAkB,kCAAkC,kBAAkB;AAC5E,IAAM,mBAAmB;AAazB,IAAM,kBAAN,MAAsB;AAAA,EAI3B,YACmB,aACA,YAA0B,OAC3C;AAFiB;AACA;AAEjB,SAAK,eAAe,YAAY;AAAA,EAClC;AAAA,EAJmB;AAAA,EACA;AAAA,EALX;AAAA,EACA;AAAA,EASR,MAAM,IAAO,WAAmB,SAAkC,CA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OAAO,iBAAiB;AACtC,cAAM,MAAM,IAAI,EAAE,UAAU,UAAU,QAAQ,MAAM,EAAE,GAAG,MAAM,eAAe,aAAa,EAAE,CAAC;AAAA,MAChG;AAAA,IACF;AAAA,EACF;AACA,MAAI,QAAQ,IAAI,wBAAwB,QAAQ,IAAI,4BAA4B,QAAQ,IAAI,4BAA4B,QAAQ,IAAI,uBAAuB;AACzJ,WAAO;AAAA,MACL,UAAU,QAAQ,IAAI;AAAA,MACtB,cAAc,QAAQ,IAAI;AAAA,MAC1B,cAAc,QAAQ,IAAI;AAAA,MAC1B,WAAW,QAAQ,IAAI;AAAA,IACzB;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,kBAAkB,IAAI,gBAAgB,WAAW,CAAC;AACvE,SAAO,EAAE,UAAU,OAAO,YAAY,QAAQ,EAAE;AAClD;","names":["AdportError","status"]}
1
+ {"version":3,"sources":["../src/catalog-access.ts","../src/schemas.ts","../src/client.ts","../src/provider.ts","../src/creatives.ts","../src/creative-tools.ts","../src/catalogs.ts","../src/catalog-schemas.ts","../src/catalog-content.ts","../src/catalog-content-schemas.ts","../src/catalog-feeds.ts","../src/catalog-feed-schemas.ts","../src/catalog-feed-timezones.ts","../src/catalog-products.ts","../src/catalog-product-schemas.ts","../src/management.ts","../src/management-tools.ts","../src/account-context.ts","../src/tools.ts","../src/catalog-tools.ts","../src/catalog-content-tools.ts","../src/catalog-feed-tools.ts","../src/catalog-product-tools.ts","../src/index.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { constants, promises as fs } from 'node:fs';\nimport path from 'node:path';\nimport { AdportError, adportHome } from '@adport/core';\nimport { z } from 'zod';\nimport { redditId } from './schemas.js';\nexport const redditBusinessId = z.string().regex(/^[a-fA-F0-9]{8}-(?:[a-fA-F0-9]{4}-){3}[a-fA-F0-9]{12}$/).toLowerCase();\nexport const redditCatalogId = redditId.min(1).max(256);\nconst accountId = redditCatalogId;\n\nexport const catalogScope = z.object({ accountId, businessId: redditBusinessId, resourceId: redditCatalogId, kind: z.enum(['catalog', 'catalog_creation']) }).strict();\nexport type RedditCatalogScope = z.infer<typeof catalogScope>;\nexport const catalogAccessMode = z.enum(['none', 'read', 'write', 'create']);\nexport type RedditCatalogAccessMode = z.infer<typeof catalogAccessMode>;\nexport interface RedditCatalogGrant { scope: RedditCatalogScope; mode: RedditCatalogAccessMode; revision: number; hash: string }\nexport interface RedditCatalogAccessStore {\n readonly canManage: boolean;\n readonly canWrite: boolean;\n get(scope: RedditCatalogScope): Promise<RedditCatalogGrant>;\n /** Recheck active account/principal scope before native resource access. */\n authorize(scope: RedditCatalogScope, write: boolean): Promise<RedditCatalogGrant>;\n list(accountId: string): Promise<RedditCatalogGrant[]>;\n /** Only the local owner or authenticated dashboard owner/admin may change access. */\n compareAndSet(scope: RedditCatalogScope, expectedHash: string, mode: RedditCatalogAccessMode): Promise<RedditCatalogGrant>;\n /** Internal creation receipt: adopt only a freshly created, independently verified native catalog. */\n adoptCreated?(scope: RedditCatalogScope, expectedCreationHash: string): Promise<RedditCatalogGrant>;\n}\nexport function catalogGrant(scope: RedditCatalogScope, mode: RedditCatalogAccessMode = 'none', revision = 0): RedditCatalogGrant {\n const parsed = catalogScope.parse(scope);catalogAccessMode.parse(mode);\n if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === 'catalog_creation' && (parsed.resourceId !== parsed.businessId || !['none', 'create'].includes(mode)) || parsed.kind === 'catalog' && mode === 'create') throw new AdportError('INVALID_INPUT', 'Invalid Reddit catalog access configuration.');\n return { scope: parsed, mode, revision, hash: createHash('sha256').update(JSON.stringify(['reddit', parsed.accountId, parsed.businessId, parsed.kind, parsed.resourceId, mode, revision])).digest('hex') };\n}\nexport function catalogScopeKey(scope: RedditCatalogScope) { return catalogGrant(scope).hash; }\nexport async function requireCatalogAccess(store: RedditCatalogAccessStore | undefined, scope: RedditCatalogScope, write = false) {\n if (!store) throw new AdportError('POLICY_VIOLATION', 'Catalog access has not been selected for this project. An owner or admin must grant the exact Business/catalog in Accounts.');\n if (write && !store.canWrite) throw new AdportError('POLICY_VIOLATION', 'This connection cannot modify Reddit catalogs.');\n const grant = await store.authorize(scope, write);\n if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope)) throw new AdportError('POLICY_VIOLATION', 'Catalog grant scope does not match the requested resource.');\n if (!(write ? grant.mode === 'write' : grant.mode === 'read' || grant.mode === 'write')) throw new AdportError('POLICY_VIOLATION', `This project does not have ${write ? 'write' : 'read'} access to the selected Reddit catalog. Ask an owner or admin to review catalog access in Accounts.`);\n return grant;\n}\n\nexport const creationScope = (accountId: string, businessId: string): RedditCatalogScope => { const normalized = redditBusinessId.parse(businessId);return catalogScope.parse({ accountId, businessId: normalized, resourceId: normalized, kind: 'catalog_creation' }); };\nexport async function requireCatalogCreationAccess(store: RedditCatalogAccessStore | undefined, scope: RedditCatalogScope, write = false) {\n if (!store || scope.kind !== 'catalog_creation' || scope.resourceId !== scope.businessId || write && !store.canWrite) throw new AdportError('POLICY_VIOLATION', 'Catalog creation requires owner-delegated creation access and a writable connection.');\n const grant = await store.authorize(scope, write);\n if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope) || grant.mode !== 'create') throw new AdportError('POLICY_VIOLATION', 'An owner must delegate catalog creation for this exact advertiser and Business. Existing catalog grants do not grant creation access.');\n return grant;\n}\n\n/** Local-owner scope, separate from OAuth secrets. No default Business wildcard. */\nexport class FileRedditCatalogAccessStore implements RedditCatalogAccessStore {\n readonly canManage = true;\n readonly canWrite = true;\n constructor(private readonly dir = path.join(adportHome(), 'catalog-access', 'reddit')) {}\n private file(scope: RedditCatalogScope) { return path.join(this.dir, catalogScopeKey(scope) + '.json'); }\n async authorize(scope: RedditCatalogScope, _write: boolean) { return this.get(scope); }\n async get(scope: RedditCatalogScope): Promise<RedditCatalogGrant> {\n const absent = catalogGrant(scope);let handle;\n try {\n handle = await fs.open(this.file(scope), constants.O_RDONLY | constants.O_NOFOLLOW);await handle.chmod(0o600);\n if ((await handle.stat()).size > 65536) throw new Error('size');\n const value = JSON.parse(await handle.readFile('utf8')) as { scope: RedditCatalogScope; mode: RedditCatalogAccessMode; revision: number };\n const grant = catalogGrant(value.scope, value.mode, value.revision);\n if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope)) throw new Error('scope');\n return grant;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return absent;\n throw new AdportError('POLICY_VIOLATION', 'Local Reddit catalog access could not be verified.');\n } finally { await handle?.close(); }\n }\n async list(accountId: string): Promise<RedditCatalogGrant[]> {\n if (!redditCatalogId.safeParse(accountId).success) throw new AdportError('INVALID_INPUT', 'Invalid advertiser ID.');\n let files: string[];\n try { files = await fs.readdir(this.dir); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];throw error; }\n const names = files.filter(value => /^[a-f0-9]{64}\\.json$/.test(value));\n if (names.length > 5000) throw new AdportError('POLICY_VIOLATION', 'Local catalog access inventory exceeds its verification bound.');\n const rows: RedditCatalogGrant[] = [];\n for (const name of names) {\n let handle;\n try {\n handle = await fs.open(path.join(this.dir, name), constants.O_RDONLY | constants.O_NOFOLLOW);\n await handle.chmod(0o600);\n if ((await handle.stat()).size > 65536) throw new Error('size');\n const value = JSON.parse(await handle.readFile('utf8')) as { scope: RedditCatalogScope; mode: RedditCatalogAccessMode; revision: number };\n const grant = catalogGrant(value.scope, value.mode, value.revision);\n if (catalogScopeKey(grant.scope) + '.json' !== name) throw new Error('scope');\n if (grant.scope.accountId === accountId && grant.mode !== 'none') rows.push(grant);\n } catch { throw new AdportError('POLICY_VIOLATION', 'Local Reddit catalog access inventory could not be verified.'); }\n finally { await handle?.close(); }\n }\n return rows;\n }\n async adoptCreated(value: RedditCatalogScope, expectedCreationHash: string) {\n const scope = catalogScope.parse(value);if (scope.kind !== 'catalog') throw new AdportError('POLICY_VIOLATION', 'Only a new exact catalog can be adopted.');\n const parent = creationScope(scope.accountId, scope.businessId);await fs.mkdir(this.dir, { recursive: true, mode: 0o700 });await fs.chmod(this.dir, 0o700);\n const lock = path.join(this.dir, catalogScopeKey(parent) + '.lock');\n try { await fs.mkdir(lock, { mode: 0o700 }); } catch { throw new AdportError('POLICY_VIOLATION', 'Catalog creation access is changing. Reconcile the known catalog before retrying.'); }\n try {\n const grant = await requireCatalogCreationAccess(this, parent, true);if (grant.hash !== expectedCreationHash) throw new AdportError('POLICY_VIOLATION', 'Creation delegation changed. The created catalog was not adopted.');\n return await this.compareAndSet(scope, catalogGrant(scope).hash, 'write');\n } finally { await fs.rmdir(lock); }\n }\n async compareAndSet(scope: RedditCatalogScope, expectedHash: string, mode: RedditCatalogAccessMode) {\n catalogGrant(scope, mode);if (!/^[a-f0-9]{64}$/.test(expectedHash)) throw new AdportError('INVALID_INPUT', 'Read the current catalog access hash first.');\n await fs.mkdir(this.dir, { recursive: true, mode: 0o700 });await fs.chmod(this.dir, 0o700);\n const lock = path.join(this.dir, catalogScopeKey(scope) + '.lock');\n try { await fs.mkdir(lock, { mode: 0o700 }); } catch { throw new AdportError('POLICY_VIOLATION', 'Catalog access is being changed by another local operation. Inspect it before retrying.'); }\n const temporary = path.join(this.dir, randomUUID() + '.tmp');\n try {\n const current = await this.get(scope);\n if (current.hash !== expectedHash) throw new AdportError('POLICY_VIOLATION', 'Catalog access changed. Read and review it again.');\n const next = catalogGrant(scope, mode, current.revision + 1), handle = await fs.open(temporary, 'wx', 0o600);\n try { await handle.writeFile(JSON.stringify(next) + '\\n');await handle.sync(); } finally { await handle.close(); }\n await fs.rename(temporary, this.file(scope));return next;\n } finally {\n await fs.unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });await fs.rmdir(lock);\n }\n }\n}\n","import { z } from 'zod';\n\n// Reddit-owned v3 OpenAPI, reviewed2026-11-03 (post-Sep2026 objective migration).\nexport const redditId = z.string().regex(/^[A-Za-z0-9_-]+$/);\nexport const micros = z.number().int().nonnegative().safe();\nexport const status = z.enum(['ACTIVE', 'PAUSED']);\nexport const objective = z.enum(['APP_INSTALLS', 'BRAND_AWARENESS', 'CATALOG_SALES', 'CLICKS', 'CONVERSIONS', 'IMPRESSIONS', 'LEAD_GENERATION', 'SALES', 'VIDEO_VIEWABLE_IMPRESSIONS']);\nexport const createCampaign = z.object({\n name: z.string().trim().min(1), objective: objective.default('CLICKS'), funding_instrument_id: redditId,\n configured_status: status.default('PAUSED'), budget_micros: micros.positive().optional(), budget_type: z.enum(['DAILY_SPEND', 'LIFETIME_SPEND']).default('DAILY_SPEND'),\n conversion_pixel_id: redditId.optional(), spend_cap_micros: micros.positive().optional(),\n}).refine(v => !v.budget_micros || Boolean(v.conversion_pixel_id), 'conversion_pixel_id is required for CBO campaigns');\nexport const setCampaignStatus = z.object({ campaign_id: redditId, configured_status: status });\nexport const setCampaignBudget = z.object({ campaign_id: redditId, budget_micros: micros.positive(), budget_type: z.enum(['DAILY_SPEND', 'LIFETIME_SPEND']).optional() });\n","import { AdportError } from '@adport/core';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\nexport interface RedditCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n /** Reddit requires an honest, uniquely identifying User-Agent on every request. */\n userAgent: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\n\nexport const REDDIT_API_VERSION = 'v3';\nexport const REDDIT_API_BASE = `https://ads-api.reddit.com/api/${REDDIT_API_VERSION}`;\nexport const REDDIT_TOKEN_URL = 'https://www.reddit.com/api/v1/access_token';\n\ninterface TokenState {\n accessToken: string;\n expiresAt: number;\n}\n\nexport interface RedditEnvelope<T> {\n data: T;\n pagination?: { next_url?: string; previous_url?: string; page_index?: number; total_count?: number };\n}\n\n/** OAuth-refreshing Reddit Ads API v3 client with exact next_url pagination. */\nexport class RedditAdsClient {\n private token?: TokenState;\n private refreshToken: string;\n private refreshing?: Promise<string>;\n\n constructor(\n private readonly credentials: RedditCredentials,\n private readonly fetchImpl: typeof fetch = fetch,\n ) {\n this.refreshToken = credentials.refreshToken;\n }\n\n /** Bind account-less native async job IDs to their approved create request. */\n resourceReceipt(kind: 'post_job' | 'asset_upload', accountId: string, profileId: string, resourceId: string): string {\n for (const value of [accountId, profileId, resourceId]) if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new AdportError('PROVIDER_ERROR', 'reddit: invalid resource ID in create receipt');\n const payload = Buffer.from(JSON.stringify({ kind, account_id: accountId, profile_id: profileId, resource_id: resourceId, expires_at: Math.floor(Date.now() / 1000) + 86_400 })).toString('base64url');\n return `${payload}.${this.receiptMac(payload).toString('base64url')}`;\n }\n\n verifyResourceReceipt(receipt: string, kind: 'post_job' | 'asset_upload', accountId: string, resourceId: string): { profile_id: string } {\n const invalid = () => new AdportError('INVALID_INPUT', 'reddit: invalid or expired resource receipt; use the receipt returned by the approved create operation');\n if (receipt.length > 2048 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();\n const [payload, signature] = receipt.split('.'), expected = this.receiptMac(payload!), supplied = Buffer.from(signature!, 'base64url');\n if (supplied.toString('base64url') !== signature || supplied.byteLength !== expected.byteLength || !timingSafeEqual(supplied, expected)) throw invalid();\n let value: unknown;\n try { value = JSON.parse(Buffer.from(payload!, 'base64url').toString('utf8')); } catch { throw invalid(); }\n const data = value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {};\n if (data.kind !== kind || data.account_id !== accountId || data.resource_id !== resourceId || typeof data.profile_id !== 'string' || !/^[A-Za-z0-9_-]{1,256}$/.test(data.profile_id) || typeof data.expires_at !== 'number' || !Number.isSafeInteger(data.expires_at) || data.expires_at <= Math.floor(Date.now() / 1000) || data.expires_at > Math.floor(Date.now() / 1000) + 86_400) throw invalid();\n return { profile_id: data.profile_id };\n }\n\n private receiptMac(payload: string): Buffer { return createHmac('sha256', this.credentials.clientSecret).update(`adport.reddit.resource.v1.${payload}`).digest(); }\n\n diagnostic(value: unknown): string | undefined { return typeof value === 'string' ? this.redact(value) : undefined; }\n\n async get<T>(pathOrUrl: string, params: Record<string, unknown> = {}): Promise<RedditEnvelope<T>> {\n const url = this.url(pathOrUrl, params);\n return this.send<T>(url, { method: 'GET' });\n }\n\n async post<T>(pathOrUrl: string, body: Record<string, unknown>): Promise<RedditEnvelope<T>> {\n return this.send<T>(this.url(pathOrUrl), { method: 'POST', body: JSON.stringify(body) });\n }\n\n async patch<T>(pathOrUrl: string, body: Record<string, unknown>): Promise<RedditEnvelope<T>> {\n return this.send<T>(this.url(pathOrUrl), { method: 'PATCH', body: JSON.stringify(body) });\n }\n\n async delete<T>(pathOrUrl: string): Promise<RedditEnvelope<T>> {\n return this.send<T>(this.url(pathOrUrl), { method: 'DELETE' });\n }\n\n async getPaged<T>(path: string, params: Record<string, unknown> = {}, limit = 1000): Promise<T[]> {\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'reddit: list limit must be a positive safe integer');\n const rows: T[] = [];\n let url = this.url(path, params);\n const seen = new Set<string>();\n while (true) {\n if (seen.has(url) || seen.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'reddit: pagination did not terminate');\n seen.add(url);\n const page = await this.get<T[]>(url);\n if (!Array.isArray(page.data)) throw new AdportError('PROVIDER_ERROR', 'reddit: expected a native list response');\n rows.push(...page.data.slice(0, Math.max(0, limit - rows.length)));\n if (rows.length >= limit || !page.pagination?.next_url) return rows;\n url = this.nextUrl(page.pagination.next_url, url);\n }\n }\n\n nextUrl(next: string, current: string): string {\n const target = this.url(next), previous = this.url(current);\n if (new URL(target).pathname !== new URL(previous).pathname) throw new AdportError('PROVIDER_ERROR', 'reddit: pagination changed resource scope');\n return target;\n }\n\n private url(pathOrUrl: string, params: Record<string, unknown> = {}): string {\n const normalized = pathOrUrl.trim();\n const url = normalized.startsWith('https://')\n ? new URL(normalized)\n : new URL(`${REDDIT_API_BASE}/${normalized.replace(/^\\/+/, '')}`);\n if (url.origin !== 'https://ads-api.reddit.com' || !url.pathname.startsWith('/api/v3/') || url.username || url.password || url.hash) {\n throw new AdportError('INVALID_INPUT', 'reddit: pagination or API URL must stay within https://ads-api.reddit.com/api/v3/');\n }\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined) continue;\n url.searchParams.set(key, Array.isArray(value) ? value.join(',') : String(value));\n }\n return url.toString();\n }\n\n private async send<T>(url: string, init: { method: string; body?: string }): Promise<RedditEnvelope<T>> {\n const accessToken = await this.accessToken();\n const response = await this.fetchImpl(url, {\n method: init.method,\n headers: {\n authorization: `Bearer ${accessToken}`,\n 'user-agent': this.credentials.userAgent,\n accept: 'application/json',\n ...(init.body ? { 'content-type': 'application/json' } : {}),\n },\n body: init.body,\n redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n const raw = await response.text();\n const parsed = raw ? safeJson(raw) : response.status === 204 ? { data: {} } : undefined;\n if (!response.ok) {\n const message = this.redact(redditErrorMessage(parsed));\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Reddit Ads API ${response.status} ${init.method} ${new URL(url).pathname}: ${message}`,\n { http_status: response.status, api_message: message },\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || !Object.hasOwn(parsed, 'data')) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed API response');\n return parsed as RedditEnvelope<T>;\n }\n\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.accessToken;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n\n private redact(value: string): string {\n return [this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, this.token?.accessToken, Buffer.from(`${this.credentials.clientId}:${this.credentials.clientSecret}`).toString('base64')].reduce<string>((text, secret) => secret ? text.replaceAll(secret, '[redacted]') : text, value).replace(/Bearer\\s+\\S+/gi, 'Bearer [redacted]').replace(/\\b[a-f0-9]{64}\\b/gi, '[redacted hash]').replace(/([?&](?:token|sig|signature|access_token|x-amz-signature|x-goog-signature)=)[^&\\s\"'<>]+/gi, '$1[redacted]').slice(0, 2000);\n }\n\n private async refresh(): Promise<string> {\n const response = await this.fetchImpl(REDDIT_TOKEN_URL, {\n method: 'POST',\n headers: {\n authorization: `Basic ${Buffer.from(`${this.credentials.clientId}:${this.credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n 'user-agent': this.credentials.userAgent,\n },\n body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }),\n redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n const raw: unknown = await response.json().catch(() => undefined);\n const data = (raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {}) as {\n access_token?: string;\n expires_in?: number;\n refresh_token?: string;\n error?: string;\n message?: string;\n };\n if (!response.ok || typeof data.access_token !== 'string' || !data.access_token || (data.expires_in !== undefined && (!Number.isFinite(data.expires_in) || data.expires_in <= 0))) {\n throw new AdportError(\n 'PROVIDER_ERROR',\n `Reddit OAuth refresh failed (HTTP ${response.status}); re-authorize if the existing grant was revoked or expired`,\n );\n }\n if (typeof data.refresh_token === 'string' && data.refresh_token && data.refresh_token !== this.refreshToken) {\n this.refreshToken = data.refresh_token;\n await this.credentials.onRefreshToken?.(data.refresh_token);\n }\n this.token = {\n accessToken: data.access_token,\n expiresAt: Date.now() + (data.expires_in ?? 3600) * 1000,\n };\n return data.access_token;\n }\n}\n\nfunction safeJson(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return undefined;\n }\n}\n\nfunction redditErrorMessage(value: unknown): string {\n if (!value || typeof value !== 'object' || Array.isArray(value)) return 'provider returned an invalid error response';\n const record = value as Record<string, unknown>;\n for (const key of ['message', 'error', 'detail']) if (typeof record[key] === 'string') return record[key];\n const error = record.error;\n if (error && typeof error === 'object' && !Array.isArray(error) && typeof (error as Record<string, unknown>).message === 'string') return (error as Record<string, unknown>).message as string;\n return 'provider request failed';\n}\n","import {\n AdportError,\n resolveDateRange,\n type Account,\n type AdProvider,\n type MetricName,\n type NormalizedQuery,\n type ProviderCapabilities,\n type Report,\n type ReportRow,\n type StandardActions,\n type WriteGuard,\n type WriteOperation,\n type WritePreview,\n type WriteResult,\n type MediaResolver,\n} from '@adport/core';\nimport { RedditAdsClient, type RedditEnvelope } from './client.js';\nimport { createCampaign, redditId, setCampaignBudget, setCampaignStatus } from './schemas.js';\nimport { RedditCreativeService } from './creatives.js';\nimport { RedditCatalogService } from './catalogs.js';\nimport { RedditCatalogContentService } from './catalog-content.js';\nimport { RedditCatalogFeeds } from './catalog-feeds.js';\nimport { RedditCatalogProducts } from './catalog-products.js';\nimport type { RedditCatalogAccessStore } from './catalog-access.js';\nimport { RedditManagementService } from './management.js';\nimport { readAccountContext } from './account-context.js';\n\n/** Reddit budget, bid, spend, CPC, and CPM fields are integer micros. */\nexport const REDDIT_MICROS = 1_000_000;\n\ninterface RedditBusiness { id: string; name?: string }\ninterface RedditAdAccount {\n id: string;\n name?: string;\n currency?: string;\n admin_approval?: string;\n suspension_reason?: string;\n}\nexport interface RedditCampaign {\n id: string;\n ad_account_id: string;\n name: string;\n configured_status: string;\n effective_status?: string;\n objective?: string;\n funding_instrument_id?: string;\n goal_type?: string;\n goal_value?: number;\n spend_cap?: number;\n is_campaign_budget_optimization?: boolean;\n}\n\ntype WritePlan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[] | WriteResult> };\n\n// Reddit v3 request enums are uppercase even though response object keys are lowercase.\nconst BREAKDOWN = { account: undefined, campaign: 'CAMPAIGN_ID', ad_group: 'AD_GROUP_ID', ad: 'AD_ID' } as const;\n\nexport class RedditAdsProvider implements AdProvider {\n readonly id = 'reddit';\n readonly creatives: RedditCreativeService;\n readonly management: RedditManagementService;\n readonly catalogs: RedditCatalogService;\n readonly catalogContent: RedditCatalogContentService;\n readonly catalogProducts: RedditCatalogProducts;\n readonly catalogFeeds: RedditCatalogFeeds;\n constructor(private readonly client: RedditAdsClient, media?: MediaResolver, catalogAccess?: RedditCatalogAccessStore) { this.creatives = new RedditCreativeService(client, media); this.management = new RedditManagementService(client, this.creatives);this.catalogs = new RedditCatalogService(client, catalogAccess);this.catalogContent = new RedditCatalogContentService(client, this.catalogs);this.catalogFeeds = new RedditCatalogFeeds(client, this.catalogs);this.catalogProducts = new RedditCatalogProducts(client, this.catalogs); }\n\n capabilities(): ProviderCapabilities {\n return { serverDryRun: false };\n }\n\n standardActions(): StandardActions {\n return {\n pauseCampaign: (accountId, campaignId) => ({\n tool: 'reddit_set_campaign_status',\n input: { account_id: accountId, campaign_id: campaignId, configured_status: 'PAUSED' },\n }),\n };\n }\n\n async listAccounts(): Promise<Account[]> {\n const businesses = await this.client.getPaged<RedditBusiness>('me/businesses', { 'page.size': 100 }, 1000);\n const byId = new Map<string, RedditAdAccount>();\n for (const business of businesses) {\n const accounts = await this.client.getPaged<RedditAdAccount>(\n `businesses/${encodeURIComponent(business.id)}/ad_accounts`,\n { 'page.size': 100 },\n 1000,\n );\n for (const account of accounts) byId.set(account.id, account);\n }\n return [...byId.values()].map((account) => ({\n provider: this.id,\n id: account.id,\n name: account.name ?? account.id,\n currency: account.currency,\n status: account.suspension_reason ? `SUSPENDED:${account.suspension_reason}` : account.admin_approval,\n }));\n }\n\n accountContext(accountId: string) { return readAccountContext(this.client, accountId); }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const accountIds = query.accountIds ?? (await this.listAccounts()).map((account) => account.id);\n const rows: ReportRow[] = [];\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'reddit: report limit must be a positive safe integer');\n let truncated = false;\n for (const accountId of accountIds) {\n if (rows.length >= limit) { truncated = true; break; }\n const breakdown = BREAKDOWN[query.level];\n const body = {\n data: {\n ...(breakdown ? { breakdowns: [breakdown] } : {}),\n fields: [\n 'SPEND',\n 'IMPRESSIONS',\n 'CLICKS',\n 'CONVERSION_PURCHASE_CLICKS',\n 'CONVERSION_PURCHASE_VIEWS',\n 'CONVERSION_PURCHASE_TOTAL_VALUE',\n ],\n starts_at: `${range.start}T00:00:00Z`,\n // The v3 schema accepts hourly granularity only. Midnight on the\n // following day keeps an inclusive Adport date range intact.\n ends_at: `${nextDay(range.end)}T00:00:00Z`,\n time_zone_id: 'UTC',\n },\n };\n const page = await this.fetchReportPages(accountId, body, limit - rows.length);\n for (const metric of page.metrics) rows.push(this.toReportRow(metric, accountId, query, breakdown?.toLowerCase()));\n truncated ||= page.truncated;\n }\n return { rows, ...(truncated ? { truncated: true } : {}) };\n }\n\n async rawReport(input: {\n account_id: string;\n breakdowns?: string[];\n fields: string[];\n starts_at: string;\n ends_at: string;\n time_zone_id?: string;\n filter?: string;\n page_size?: number;\n }): Promise<{ metrics: Array<Record<string, unknown>>; metrics_updated_at?: string; truncated: boolean }> {\n const body = {\n data: {\n ...(input.breakdowns?.length ? { breakdowns: input.breakdowns.map(value => value.toUpperCase()) } : {}),\n fields: input.fields.map(value => value.toUpperCase()),\n starts_at: input.starts_at,\n ends_at: input.ends_at,\n time_zone_id: input.time_zone_id ?? 'UTC',\n ...(input.filter ? { filter: input.filter } : {}),\n },\n };\n return this.fetchReportPages(input.account_id, body, input.page_size ?? 200);\n }\n\n async apiRead(input: {\n account_id: string;\n path: string;\n method?: 'GET' | 'POST';\n params?: Record<string, unknown>;\n body?: Record<string, unknown>;\n limit?: number;\n }): Promise<unknown> {\n const path = validateRedditPath(input.path);\n assertReadScoped(path, input.account_id);\n if (input.method === 'POST') {\n if (!/(?:\\/reports|\\/history|\\/query|\\/search)$/.test(path)) {\n throw new AdportError('INVALID_INPUT', 'reddit: read-only POST is limited to documented reports, history, query, and search endpoints');\n }\n return this.client.post(path, input.body ?? {});\n }\n if (!path.startsWith(`ad_accounts/${input.account_id}/`) && path !== `ad_accounts/${input.account_id}`) {\n // A global resource ID alone never proves account authorization.\n await this.assertOwnedResource(path, input.account_id);\n }\n if (input.limit) return this.client.getPaged(path, input.params, input.limit);\n return this.client.get(path, input.params);\n }\n\n async listCampaigns(accountId: string, ids?: string[]): Promise<RedditCampaign[]> {\n return this.client.getPaged<RedditCampaign>(\n `ad_accounts/${encodeURIComponent(accountId)}/campaigns`,\n { ...(ids?.length ? { id: ids } : {}), 'page.size': Math.min(ids?.length ?? 100, 100) },\n ids?.length ?? 1000,\n );\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const plan = await this.plan(op, guard);\n const { execute: _execute, ...preview } = plan;\n return { ...preview, serverValidated: false };\n }\n\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const plan = await this.plan(op, guard);\n const result = await plan.execute();\n return Array.isArray(result) ? { applied: true, resourceIds: result } : result;\n }\n\n private async fetchReportPages(\n accountId: string,\n body: Record<string, unknown>,\n limit: number,\n ): Promise<{ metrics: Array<Record<string, unknown>>; metrics_updated_at?: string; truncated: boolean }> {\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'reddit: report limit must be a positive safe integer');\n const path = `ad_accounts/${encodeURIComponent(accountId)}/reports?page.size=${Math.min(limit, 1000)}`;\n const rows: Array<Record<string, unknown>> = [], seen = new Set<string>();\n let url = this.client.nextUrl(path, path), updatedAt: string | undefined;\n while (true) {\n if (seen.has(url) || seen.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'reddit: report pagination did not terminate');\n seen.add(url);\n // The current v3 report operation is POST-only, including next_url pages.\n const page = await this.client.post<{ metrics?: Array<Record<string, unknown>>; metrics_updated_at?: string }>(url, body);\n if (!isRecord(page.data) || !Array.isArray(page.data.metrics) || page.data.metrics.some(row => !isRecord(row))) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed report metrics');\n rows.push(...page.data.metrics);\n if (updatedAt === undefined && typeof page.data.metrics_updated_at === 'string') updatedAt = page.data.metrics_updated_at;\n const next = page.pagination?.next_url;\n if (rows.length >= limit || !next) return { metrics: rows.slice(0, limit), truncated: rows.length > limit || Boolean(next), ...(updatedAt ? { metrics_updated_at: updatedAt } : {}) };\n url = this.client.nextUrl(next, path);\n }\n }\n\n private toReportRow(\n raw: Record<string, unknown>,\n accountId: string,\n query: NormalizedQuery,\n breakdown?: string,\n ): ReportRow {\n const value = (key: string) => { const v = raw[key]; if (v === null || v === undefined || v === '' || !['number', 'string'].includes(typeof v)) return undefined; const number = Number(v); if (!Number.isFinite(number)) throw new AdportError('PROVIDER_ERROR', `reddit: invalid numeric report field ${key}`); return number; };\n const all: Partial<Record<MetricName, number>> = {};\n for (const [metric, field, divisor] of [['spend', 'spend', REDDIT_MICROS], ['impressions', 'impressions', 1], ['clicks', 'clicks', 1], ['conversion_value', 'conversion_purchase_total_value', 100]] as const) { const v = value(field); if (v !== undefined) all[metric] = v / divisor; }\n const clickConversions = value('conversion_purchase_clicks'), viewConversions = value('conversion_purchase_views');\n if (clickConversions !== undefined && viewConversions !== undefined) all.conversions = clickConversions + viewConversions;\n for (const [metric, numerator, denominator, factor] of [['ctr', 'clicks', 'impressions', 100], ['cpc', 'spend', 'clicks', 1], ['cpm', 'spend', 'impressions', 1000], ['cpa', 'spend', 'conversions', 1], ['roas', 'conversion_value', 'spend', 1]] as const) if (all[numerator] !== undefined && all[denominator] !== undefined) all[metric] = all[denominator] ? all[numerator]! / all[denominator]! * factor : 0;\n const entityId = breakdown ? String(raw[breakdown] ?? '') : accountId;\n if (!entityId) throw new AdportError('PROVIDER_ERROR', 'reddit: report row is missing its requested entity breakdown');\n return {\n provider: this.id,\n accountId,\n entity: { level: query.level, id: entityId, name: entityId },\n metrics: Object.fromEntries(query.metrics.filter(metric => all[metric] !== undefined).map(metric => [metric, all[metric]])),\n };\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<WritePlan> {\n if (['reddit_create_catalog_products', 'reddit_update_catalog_products', 'reddit_delete_catalog_products'].includes(op.tool)) return this.catalogProducts.plan(op);\n if (['reddit_create_catalog_feed', 'reddit_update_catalog_feed', 'reddit_set_catalog_feed_schedule_status', 'reddit_delete_catalog_feed'].includes(op.tool)) return this.catalogFeeds.plan(op);\n if (['reddit_create_catalog_product_set', 'reddit_update_catalog_product_set', 'reddit_delete_catalog_product_set'].includes(op.tool)) return this.catalogContent.plan(op);\n if (['reddit_set_catalog_access', 'reddit_create_catalog', 'reddit_rename_catalog', 'reddit_set_catalog_event_sources', 'reddit_delete_catalog'].includes(op.tool)) return this.catalogs.plan(op);\n if (/^reddit_(?:create_(?:customer_audience|pixel_audience|engagement_audience|saved_audience)|update_(?:audience_users|saved_audience)|delete_(?:audience|saved_audience)|send_conversion_events)$/.test(op.tool)) return this.management.plan(op, guard);\n if (/^reddit_(?:create_(?:ad_group|ad|post|text_asset)|upload_asset|import_asset_url|stage_post_copy|update_(?:ad_group|ad|targeting)|set_(?:ad_group_budget|ad_group_bidding|ad_group_status|ad_status)|archive_entity|rename_asset|delete_asset)$/.test(op.tool)) return this.creatives.plan(op, guard);\n redditId.parse(op.accountId);\n const expectedKind = op.tool === 'reddit_api_delete' ? 'remove' : op.tool === 'reddit_create_campaign' || op.tool === 'reddit_api_create' ? 'create' : 'update';\n if (op.provider !== this.id || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'reddit: provider or operation kind mismatch');\n const payload = op.payload as never;\n switch (op.tool) {\n case 'reddit_create_campaign': return this.planCreateCampaign(op.accountId, createCampaign.parse(op.payload), guard);\n case 'reddit_set_campaign_status': return this.planSetStatus(op.accountId, setCampaignStatus.parse(op.payload));\n case 'reddit_set_budget': return this.planSetBudget(op.accountId, setCampaignBudget.parse(op.payload));\n case 'reddit_api_create': return this.planApiCreate(op.accountId, payload, guard);\n case 'reddit_api_update': return this.planApiUpdate(op.accountId, payload);\n case 'reddit_api_delete': return this.planApiDelete(op.accountId, payload);\n default: throw new AdportError('PROVIDER_ERROR', `reddit: unsupported write tool ${op.tool}`);\n }\n }\n\n private async planCreateCampaign(\n accountId: string,\n payload: {\n name: string;\n objective: string;\n funding_instrument_id: string;\n configured_status?: 'ACTIVE' | 'PAUSED';\n budget_micros?: number;\n budget_type?: 'DAILY_SPEND' | 'LIFETIME_SPEND';\n conversion_pixel_id?: string;\n spend_cap_micros?: number;\n },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n if (payload.budget_micros && !payload.conversion_pixel_id) {\n throw new AdportError('INVALID_INPUT', 'reddit: conversion_pixel_id is required for CBO campaigns (effective July 13, 2026)');\n }\n const requested = payload.configured_status ?? 'PAUSED';\n const status = guard.forcePausedCreation ? 'PAUSED' : requested;\n const coercions = requested !== status\n ? ['configured_status coerced to PAUSED by policy (paused_creation)']\n : [];\n const data: Record<string, unknown> = {\n name: payload.name,\n configured_status: status,\n objective: payload.objective,\n funding_instrument_id: payload.funding_instrument_id,\n is_campaign_budget_optimization: payload.budget_micros !== undefined,\n ...(payload.budget_micros ? {\n goal_type: payload.budget_type ?? 'DAILY_SPEND',\n goal_value: payload.budget_micros,\n conversion_pixel_id: payload.conversion_pixel_id,\n } : {}),\n ...(payload.spend_cap_micros ? { spend_cap: payload.spend_cap_micros } : {}),\n };\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n if (payload.budget_micros) budgetDeltas.push({ target: `new campaign \"${payload.name}\" budget`, toMicros: payload.budget_micros });\n if (payload.spend_cap_micros) budgetDeltas.push({ target: `new campaign \"${payload.name}\" spend cap`, toMicros: payload.spend_cap_micros });\n return {\n summary: `Create Reddit campaign \"${payload.name}\" (${payload.objective}, ${status.toLowerCase()})`,\n changes: [`+ POST /ad_accounts/${accountId}/campaigns ${JSON.stringify({ data })}`],\n coercions,\n budgetDeltas,\n execute: async () => verifyReceipt(await this.client.post<RedditCampaign>(`ad_accounts/${encodeURIComponent(accountId)}/campaigns`, { data }), accountId, data),\n };\n }\n\n private async planSetStatus(\n accountId: string,\n payload: { campaign_id: string; configured_status: 'ACTIVE' | 'PAUSED' },\n ): Promise<WritePlan> {\n const campaign = await this.getOwnedCampaign(accountId, payload.campaign_id);\n return {\n summary: `Set Reddit campaign \"${campaign.name}\" → ${payload.configured_status.toLowerCase()}`,\n changes: [`~ campaign ${campaign.id} configured_status ${campaign.configured_status} → ${payload.configured_status}`],\n coercions: [], budgetDeltas: [],\n execute: async () => verifyReceipt(await this.client.patch<RedditCampaign>(`campaigns/${encodeURIComponent(campaign.id)}`, {\n data: { configured_status: payload.configured_status },\n }), accountId, { id: campaign.id, configured_status: payload.configured_status }),\n };\n }\n\n private async planSetBudget(\n accountId: string,\n payload: { campaign_id: string; budget_micros: number; budget_type?: 'DAILY_SPEND' | 'LIFETIME_SPEND' },\n ): Promise<WritePlan> {\n const campaign = await this.getOwnedCampaign(accountId, payload.campaign_id);\n if (!campaign.is_campaign_budget_optimization) {\n throw new AdportError('INVALID_INPUT', `reddit: campaign \"${campaign.name}\" is not a CBO campaign; budget its ad groups instead`);\n }\n if (!['DAILY_SPEND', 'LIFETIME_SPEND'].includes(String(campaign.goal_type)) || !Number.isSafeInteger(campaign.goal_value) || Number(campaign.goal_value) < 0) throw new AdportError('INVALID_INPUT', 'reddit: current CBO budget/type is unavailable');\n if (payload.budget_type && payload.budget_type !== campaign.goal_type) throw new AdportError('INVALID_INPUT', 'reddit: campaign budget type is immutable; the existing type must be preserved');\n return {\n summary: `Change Reddit campaign \"${campaign.name}\" budget ${campaign.goal_value ?? '?'} → ${payload.budget_micros} micros`,\n changes: [`~ campaign ${campaign.id} ${campaign.goal_type ?? 'goal'} ${campaign.goal_value ?? '?'} → ${payload.budget_micros}`],\n coercions: [],\n budgetDeltas: [{ target: `campaign \"${campaign.name}\" budget`, fromMicros: campaign.goal_value, toMicros: payload.budget_micros }],\n execute: async () => verifyReceipt(await this.client.patch<RedditCampaign>(`campaigns/${encodeURIComponent(campaign.id)}`, {\n data: { goal_value: payload.budget_micros },\n }), accountId, { id: campaign.id, goal_value: payload.budget_micros }),\n };\n }\n\n private async planApiCreate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n guard: WriteGuard,\n ): Promise<WritePlan> {\n const path = validateRedditPath(payload.path);\n if (!new Set(['campaigns', 'ad_groups', 'ads', 'custom_audiences', 'saved_audiences']).has(path.split('/')[2] ?? '') || path.split('/').length !== 3 || !path.startsWith(`ad_accounts/${accountId}/`)) {\n throw new AdportError('INVALID_INPUT', 'reddit: create path must be under the selected ad account');\n }\n const body = structuredClone(payload.body);\n if (!isRecord(body.data)) throw new AdportError('INVALID_INPUT', 'reddit: native create requires one data object');\n if (body.data.ad_account_id !== undefined && body.data.ad_account_id !== accountId) throw new AdportError('INVALID_INPUT', 'reddit: create body account differs from the selected account');\n if (path.endsWith('/ad_groups')) {\n if (typeof body.data.campaign_id !== 'string') throw new AdportError('INVALID_INPUT', 'reddit: ad-group creation requires campaign_id');\n await this.getOwnedCampaign(accountId, body.data.campaign_id);\n }\n if (path.endsWith('/ads')) {\n if (typeof body.data.ad_group_id !== 'string') throw new AdportError('INVALID_INPUT', 'reddit: ad creation requires ad_group_id');\n const group = (await this.client.get<Record<string, unknown>>(`ad_groups/${encodeURIComponent(body.data.ad_group_id)}`)).data;\n if (!isRecord(group) || group.id !== body.data.ad_group_id || group.ad_account_id !== accountId || typeof group.campaign_id !== 'string') throw new AdportError('INVALID_INPUT', 'reddit: ad-group parent ownership mismatch');\n await this.getOwnedCampaign(accountId, group.campaign_id);\n if (typeof body.data.post_id === 'string') await this.creatives.assertPostOwned(accountId, body.data.post_id);\n if (typeof body.data.profile_id === 'string') await this.creatives.assertProfileAvailable(accountId, body.data.profile_id);\n }\n if (isRecord(body.data.targeting)) await this.creatives.assertTargetingAvailable(accountId, body.data.targeting);\n if (path.endsWith('/custom_audiences')) {\n const config = isRecord(body.data.pixel_audience_config) ? body.data.pixel_audience_config : {};\n if (Array.isArray(config.pixel_ids)) {\n const pixels = await this.client.getPaged<Record<string, unknown>>(`ad_accounts/${accountId}/pixels`, {}, 1000), known = new Set(pixels.map(row => row.id));\n if (config.pixel_ids.some(value => !known.has(value))) throw new AdportError('INVALID_INPUT', 'reddit: retargeting Pixel is not available to this account');\n }\n const engagement = isRecord(body.data.engagement_audience_config) ? body.data.engagement_audience_config : {};\n if (Array.isArray(engagement.campaign_ids)) for (const value of engagement.campaign_ids) await this.getOwnedCampaign(accountId, redditId.parse(value));\n }\n const coercions: string[] = [];\n if (guard.forcePausedCreation) {\n coerceCreatedStatuses(body, coercions, /\\/(?:campaigns|ad_groups|ads)$/.test(path));\n }\n return {\n summary: `Create Reddit resource via /${path}`,\n changes: [`+ POST /${path} ${JSON.stringify(body)}`],\n coercions,\n budgetDeltas: collectMicros(body),\n execute: async () => verifyReceipt(await this.client.post(path, body), accountId, body.data as Record<string, unknown>),\n };\n }\n\n private async planApiUpdate(\n accountId: string,\n payload: { path: string; body: Record<string, unknown> },\n ): Promise<WritePlan> {\n const path = validateRedditPath(payload.path);\n const current = await this.assertOwnedResource(path, accountId);\n if (containsMoney(payload.body)) {\n throw new AdportError('INVALID_INPUT', 'reddit: budget, bid, goal, and spend-cap updates require a typed budget tool for policy checks');\n }\n if (!isRecord(payload.body.data)) throw new AdportError('INVALID_INPUT', 'reddit: native update requires one data object');\n for (const key of ['ad_account_id', 'account_id', 'campaign_id', 'ad_group_id']) if (payload.body.data[key] !== undefined && payload.body.data[key] !== current[key]) throw new AdportError('INVALID_INPUT', 'reddit: parent/account changes require a dedicated tool and cannot be forwarded as generic metadata');\n if (typeof payload.body.data.post_id === 'string') await this.creatives.assertPostOwned(accountId, payload.body.data.post_id);\n if (typeof payload.body.data.profile_id === 'string') await this.creatives.assertProfileAvailable(accountId, payload.body.data.profile_id);\n if (isRecord(payload.body.data.targeting)) await this.creatives.assertTargetingAvailable(accountId, payload.body.data.targeting);\n return {\n summary: `Update Reddit resource via /${path}`,\n changes: [`~ PATCH /${path} ${JSON.stringify(payload.body)}`],\n coercions: [], budgetDeltas: [],\n execute: async () => verifyReceipt(await this.client.patch(path, payload.body), accountId, { ...payload.body.data as Record<string, unknown>, id: path.split('/').at(-1) }),\n };\n }\n\n private async planApiDelete(accountId: string, payload: { path: string }): Promise<WritePlan> {\n const path = validateRedditPath(payload.path);\n await this.assertOwnedResource(path, accountId);\n return {\n summary: `Permanently delete Reddit resource via /${path}`,\n changes: [`- DELETE /${path}`],\n coercions: [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.delete(path), ids = extractIds(result), expected = path.split('/').at(-1)!;\n if (ids.length && (ids.length !== 1 || ids[0] !== expected)) throw new AdportError('PROVIDER_ERROR', 'reddit: deletion receipt ID mismatch; reconcile before retrying', { resource_ids: ids });\n return [expected];\n },\n };\n }\n\n private async getOwnedCampaign(accountId: string, campaignId: string): Promise<RedditCampaign> {\n const campaign = (await this.client.get<RedditCampaign>(`campaigns/${encodeURIComponent(campaignId)}`)).data;\n if (!campaign || campaign.id !== campaignId || campaign.ad_account_id !== accountId) {\n throw new AdportError('INVALID_INPUT', `reddit: campaign ${campaignId} does not belong to selected account ${accountId}`);\n }\n return campaign;\n }\n\n private async assertOwnedResource(path: string, accountId: string): Promise<Record<string, unknown>> {\n const resource = (await this.client.get<Record<string, unknown>>(path)).data;\n if (!isRecord(resource) || String(resource.ad_account_id ?? '') !== accountId) {\n throw new AdportError('INVALID_INPUT', `reddit: /${path} does not prove ownership by selected account ${accountId}`);\n }\n if (resource.id !== path.split('/').at(-1)) throw new AdportError('INVALID_INPUT', 'reddit: resource response ID mismatch');\n return resource;\n }\n}\n\nfunction nextDay(date: string): string {\n const value = new Date(`${date}T00:00:00Z`);\n value.setUTCDate(value.getUTCDate() + 1);\n return value.toISOString().slice(0, 10);\n}\n\nfunction validateRedditPath(path: string): string {\n const normalized = path.replace(/^\\/+|\\/+$/g, '').trim();\n if (!/^[A-Za-z0-9_.~/-]{3,220}$/.test(normalized) || normalized.includes('..') || normalized.includes('//')) {\n throw new AdportError('INVALID_INPUT', `reddit: invalid Ads API v3 path \"${path}\"`);\n }\n return normalized;\n}\n\nfunction assertReadScoped(path: string, accountId: string): void {\n if (path === `ad_accounts/${accountId}` || path.startsWith(`ad_accounts/${accountId}/`)) return;\n if (/^(campaigns|ad_groups|ads|structured_posts)\\/[^/]+$/.test(path)) return;\n throw new AdportError('INVALID_INPUT', 'reddit: read path must be selected-account scoped or a single campaign/ad-group/ad/post resource');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction coerceCreatedStatuses(value: Record<string, unknown>, coercions: string[], statusBearingPath: boolean): void {\n const data = isRecord(value.data) ? value.data : value;\n const visit = (item: unknown, path = 'body'): void => {\n if (Array.isArray(item)) return item.forEach((child, index) => visit(child, `${path}[${index}]`));\n if (!isRecord(item)) return;\n for (const [key, child] of Object.entries(item)) {\n if (key === 'configured_status' && child !== 'PAUSED') {\n item[key] = 'PAUSED';\n coercions.push(`${path}.${key} coerced to PAUSED by policy (paused_creation)`);\n } else visit(child, `${path}.${key}`);\n }\n };\n visit(value);\n if (statusBearingPath && data.configured_status === undefined) {\n data.configured_status = 'PAUSED';\n coercions.push('body.data.configured_status set to PAUSED by policy (paused_creation)');\n }\n}\n\nconst MONEY_KEY = /(?:goal_value|spend_cap|bid_value|budget(?:_micros)?|daily_budget|lifetime_budget)$/i;\n\nfunction containsMoney(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsMoney);\n if (!isRecord(value)) return false;\n return Object.entries(value).some(([key, child]) => MONEY_KEY.test(key) || containsMoney(child));\n}\n\nfunction collectMicros(value: unknown, path = 'body'): WritePreview['budgetDeltas'] {\n if (Array.isArray(value)) return value.flatMap((child, index) => collectMicros(child, `${path}[${index}]`));\n if (!isRecord(value)) return [];\n const deltas: WritePreview['budgetDeltas'] = [];\n for (const [key, child] of Object.entries(value)) {\n if (MONEY_KEY.test(key) && child !== null) {\n if (typeof child !== 'number' || !Number.isSafeInteger(child) || child < 0) throw new AdportError('INVALID_INPUT', 'reddit: native monetary create fields must be non-negative safe integer micros');\n deltas.push({ target: `${path}.${key}`, toMicros: Number(child) });\n }\n deltas.push(...collectMicros(child, `${path}.${key}`));\n }\n return deltas;\n}\n\nfunction extractIds(envelope: RedditEnvelope<unknown>): string[] {\n const rows = Array.isArray(envelope.data) ? envelope.data : [envelope.data];\n return rows.filter(isRecord).flatMap(row => typeof row.id === 'string' ? [row.id] : []);\n}\nfunction verifyReceipt(envelope: RedditEnvelope<unknown>, account: string, expected: Record<string, unknown>): string[] {\n const ids = extractIds(envelope), row = envelope.data;\n const keys = ['id', 'name', 'configured_status', 'goal_value', 'goal_type', 'spend_cap', 'bid_value', 'campaign_id', 'ad_group_id', 'post_id', 'objective', 'is_campaign_budget_optimization'];\n if (!isRecord(row) || ids.length !== 1 || row.ad_account_id !== account || keys.some(key => expected[key] !== undefined && row[key] !== expected[key])) throw new AdportError('PROVIDER_ERROR', 'reddit: mutation receipt ID/account/status/money mismatch; reconcile before retrying', { resource_ids: ids });\n return ids;\n}\n","import { AdportError, LocalMediaResolver, creativeStatusAction, type Creative, type MediaResolver, type MediaSource, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport { RedditAdsClient } from './client.js';\nimport { bidStrategy, createAd, createGroup, createPost, importAsset, stageCopy, targeting, textAsset, updateAd, updateGroup, uploadAsset } from './creative-tools.js';\nimport { micros, redditId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Entity = 'campaigns' | 'ad_groups' | 'ads';\ninterface Page { account_id: string; page_size: number; cursor?: string }\nexport interface RedditCreativePlan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<WriteResult> }\nconst rowSchema = z.looseObject({ id }), record = (v: unknown): Row => v && typeof v === 'object' && !Array.isArray(v) ? v as Row : {};\nconst string = (v: unknown): v is string => typeof v === 'string' && Boolean(v);\nconst safeUrl = (v: unknown): string | undefined => { if (!string(v)) return undefined; try { const u = new URL(v); return u.protocol === 'https:' && !u.username && !u.password ? v : undefined; } catch { return undefined; } };\nconst landing = (v: unknown): string[] => { if (!string(v)) return []; try { const u = new URL(v); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password ? [v] : []; } catch { return []; } };\n\n/** Typed manual campaign children and current structured-post/asset APIs. */\nexport class RedditCreativeService {\n constructor(private readonly client: RedditAdsClient, private readonly media: MediaResolver = new LocalMediaResolver()) {}\n private async one(path: string) {\n const result = await this.client.get<unknown>(path), parsed = rowSchema.safeParse(result.data);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed entity response');\n return parsed.data;\n }\n async owned(account: string, entity: Entity, resource: string): Promise<Row> {\n id.parse(account); id.parse(resource);\n const row = await this.one(`${entity}/${resource}`);\n if (row.id !== resource || (row.ad_account_id !== undefined && row.ad_account_id !== account)) throw new AdportError('INVALID_INPUT', 'reddit: entity ID/account ownership mismatch');\n if (entity === 'campaigns') { if (row.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'reddit: campaign is not owned by this account'); }\n else if (entity === 'ad_groups') await this.owned(account, 'campaigns', id.parse(row.campaign_id));\n else { const parent = await this.owned(account, 'ad_groups', id.parse(row.ad_group_id)); if (row.campaign_id !== undefined && row.campaign_id !== parent.campaign_id) throw new AdportError('PROVIDER_ERROR', 'reddit: ad parent hierarchy mismatch'); }\n return row;\n }\n private async page(path: string, input: Page, params: Row = {}) {\n const url = input.cursor ? this.client.nextUrl(input.cursor, path) : path;\n const data = await this.client.get<unknown>(url, input.cursor ? {} : { ...params, 'page.size': input.page_size });\n if (!Array.isArray(data.data) || data.data.some(row => !row || typeof row !== 'object' || Array.isArray(row))) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed collection response');\n const next = data.pagination?.next_url ? this.client.nextUrl(data.pagination.next_url, path) : undefined;\n if (next === this.client.nextUrl(url, path)) throw new AdportError('PROVIDER_ERROR', 'reddit: pagination repeated the current page');\n return { items: data.data as Row[], truncated: Boolean(next), ...(next ? { next_cursor: next } : {}) };\n }\n async profiles(account: string) {\n // Account profile pages cap at 100; business profile pages allow 1,000.\n const rows = await this.client.getPaged<unknown>(`ad_accounts/${id.parse(account)}/profiles`, { 'page.size': 100 }, 5000);\n return rows.map(row => rowSchema.parse(row));\n }\n private async profile(account: string, profileId: string) {\n const rows = (await this.profiles(account)).filter(row => row.id === profileId || row.reddit_user_id === profileId);\n if (rows.length !== 1) throw new AdportError('INVALID_INPUT', 'reddit: profile is not unambiguously associated with the selected account');\n return rows[0]!;\n }\n private profileMatch(value: unknown, profile: Row) { return value === profile.id || value === profile.reddit_user_id; }\n async groups(input: Page & { campaign_id?: string; ad_group_ids?: string[] }) {\n if (input.campaign_id) await this.owned(input.account_id, 'campaigns', input.campaign_id);\n const data = await this.page(`ad_accounts/${id.parse(input.account_id)}/ad_groups`, input, { campaign_id: input.campaign_id, id: input.ad_group_ids });\n data.items.forEach(row => rowSchema.parse(row));\n if (data.items.some(row => (row.ad_account_id !== undefined && row.ad_account_id !== input.account_id) || (input.campaign_id && row.campaign_id !== input.campaign_id))) throw new AdportError('PROVIDER_ERROR', 'reddit: ad-group collection account/parent mismatch');\n return data;\n }\n private async post(postId: string): Promise<Row> {\n if (!/^t3_[A-Za-z0-9]+$/.test(postId)) throw new AdportError('INVALID_INPUT', 'reddit: invalid post ID');\n let row: Row;\n try { row = await this.one(`structured_posts/${postId}`); }\n catch (error) { if (!(error instanceof AdportError) || record(error.details).http_status !== 404) throw error; row = await this.one(`posts/${postId}`); }\n if (row.id !== postId) throw new AdportError('PROVIDER_ERROR', 'reddit: post ID mismatch');\n return row;\n }\n private async ownedPost(account: string, postId: string) {\n const profiles = await this.profiles(account), row = await this.post(postId);\n if (!profiles.some(profile => this.profileMatch(row.profile_id, profile))) throw new AdportError('INVALID_INPUT', 'reddit: post author is not associated with this account');\n return row;\n }\n async assertPostOwned(account: string, postId: string) { await this.ownedPost(account, postId); }\n async assertProfileAvailable(account: string, profileId: string) { await this.profile(account, profileId); }\n async assertTargetingAvailable(account: string, value: unknown) { await this.verifyTargeting(account, targeting.parse(value)); }\n async posts(input: Page & { profile_id: string }) {\n const profile = await this.profile(input.account_id, input.profile_id), data = await this.page(`profiles/${profile.id}/structured_posts`, input);\n if (data.items.some(row => !rowSchema.safeParse(row).success || !this.profileMatch(row.profile_id, profile))) throw new AdportError('PROVIDER_ERROR', 'reddit: post collection profile mismatch');\n const creatives: Creative[] = data.items.map(row => { const content = record(row.creative), title = string(content.headline) ? content.headline : String(row.id); return { id: String(row.id), provider: 'reddit', account_id: input.account_id, name: title, type: String(content.type ?? 'POST'), headlines: [title], descriptions: string(content.body) ? [content.body] : [], landing_urls: landing(record(content.destination).url), media: postMedia(content, row), actions: [] }; });\n return { ...data, creatives };\n }\n private async asset(account: string, profileId: string, assetId: string) {\n const profile = await this.profile(account, profileId);\n const rows = await this.client.getPaged<Row>(`profiles/${profile.id}/creative_assets`, { 'page.size': 1000 }, 5000);\n const asset = rows.map(row => record(row.result)).find(row => row.id === assetId);\n if (!asset) throw new AdportError('INVALID_INPUT', 'reddit: asset is not in the associated profile’s first5000library entries');\n return { profile, asset };\n }\n private async readyAsset(account: string, profile: string, assetId: string, type: string) {\n const { asset } = await this.asset(account, profile, assetId);\n if (asset.type !== type || !['ACTIVE', 'DUPLICATE_ASSET'].includes(String(asset.status))) throw new AdportError('INVALID_INPUT', 'reddit: asset is not ready or has the wrong type');\n const url = safeUrl(record(asset.media).permanent_url) ?? safeUrl(record(asset.media).url);\n if (!url) throw new AdportError('INVALID_INPUT', 'reddit: asset has no usable HTTPS media URL');\n return { media: { type: 'URL', url } };\n }\n async assets(input: Page & { profile_id: string }) {\n const profile = await this.profile(input.account_id, input.profile_id), data = await this.page(`profiles/${profile.id}/creative_assets`, input);\n const items = data.items.map(row => rowSchema.parse(row.result));\n const creatives: Creative[] = items.map(row => {\n const url = safeUrl(record(row.media).permanent_url) ?? safeUrl(record(row.media).url);\n return { id: row.id, provider: 'reddit', account_id: input.account_id, name: String(row.name ?? row.text ?? row.call_to_action ?? row.id), type: `${row.type}_ASSET`, ...(string(row.status) ? { status: row.status } : {}), headlines: string(row.text) ? [row.text] : [], descriptions: [`Library readiness: ${row.status ?? 'unknown'}`, ...(string(row.call_to_action) ? [row.call_to_action] : [])], landing_urls: [], media: url && ['IMAGE', 'VIDEO'].includes(String(row.type)) ? [{ type: row.type === 'VIDEO' ? 'video' : 'image', url }] : [], actions: row.status === 'DELETED' ? [] : [{ label: 'Rename shared profile asset', tool: 'reddit_rename_asset', arguments: { account_id: input.account_id, profile_id: profile.id, creative_asset_id: row.id }, fields: [{ key: 'name', label: 'Asset name', type: 'text', value: String(row.name ?? '') }] }] };\n });\n return { ...data, items, creatives };\n }\n async ads(input: Page & { ad_ids?: string[]; ad_group_ids?: string[]; campaign_ids?: string[]; include_post_details: boolean }) {\n const data = await this.page(`ad_accounts/${id.parse(input.account_id)}/ads`, input, { id: input.ad_ids, ad_group_id: input.ad_group_ids, campaign_id: input.campaign_ids });\n data.items.forEach(row => rowSchema.parse(row));\n if (data.items.some(row => row.ad_account_id !== input.account_id)) throw new AdportError('PROVIDER_ERROR', 'reddit: ad collection returned another account');\n const posts = new Map<string, Row>(), warnings: Array<{ provider: string; message: string }> = [], profiles = input.include_post_details ? await this.profiles(input.account_id) : [];\n const postIds = [...new Set(data.items.map(row => row.post_id).filter(string))]; let cursor = 0;\n if (input.include_post_details) await Promise.all(Array.from({ length: Math.min(4, postIds.length) }, async () => { while (cursor < postIds.length) { const postId = postIds[cursor++]!; try { posts.set(postId, await this.post(postId)); } catch (error) { warnings.push({ provider: 'reddit', message: `Referenced post ${postId} unavailable: ${error instanceof Error ? error.message : 'provider read failed'}` }); } } }));\n const creatives: Creative[] = data.items.map(row => {\n const post = posts.get(String(row.post_id)), content = record(post?.creative), profile = profiles.find(profile => this.profileMatch(post?.profile_id, profile)), args = { account_id: input.account_id, ad_id: row.id };\n const status = String(row.configured_status ?? ''), body = string(content.body) ? content.body : string(post?.body) ? post.body : undefined;\n const title = string(content.headline) ? content.headline : string(post?.headline) ? post.headline : undefined;\n const actions: Creative['actions'] = ['ACTIVE', 'PAUSED'].includes(status) ? [creativeStatusAction('reddit_set_ad_status', args, status, ['ACTIVE', 'PAUSED']), { label: 'Edit ad name', tool: 'reddit_update_ad', arguments: args, fields: [{ key: 'name', label: 'Ad name', type: 'text', value: String(row.name ?? '') }] }] : [];\n if (profile && ['TEXT', 'IMAGE', 'VIDEO', 'CAROUSEL'].includes(String(content.type)) && !['ARCHIVED', 'DELETED'].includes(status)) actions.push({ label: 'Stage a creative copy', tool: 'reddit_stage_post_copy', arguments: { ...args, source_post_id: row.post_id, profile_id: profile.id }, fields: [{ key: 'headline', label: 'Headline', type: 'text', value: title ?? '', max_length: 300 }, ...(body ? [{ key: 'body', label: 'Body', type: 'text' as const, value: body, max_length: 40_000 }] : [])] });\n return { id: String(row.id), provider: 'reddit', account_id: input.account_id, name: String(row.name ?? row.id), type: String(content.type ?? 'POST_AD'), status, ...(string(row.campaign_id) ? { campaign_id: row.campaign_id } : {}), ...(string(row.ad_group_id) ? { ad_group_id: row.ad_group_id } : {}), headlines: title ? [title] : [], descriptions: body ? [body] : [], landing_urls: landing(row.click_url).length ? landing(row.click_url) : landing(record(content.destination).url), media: postMedia(content, post), actions };\n });\n return { ...data, creatives, warnings };\n }\n async postJob(input: { account_id: string; job_id: string; resource_receipt: string }) {\n const bound = this.client.verifyResourceReceipt(input.resource_receipt, 'post_job', input.account_id, input.job_id), profile = await this.profile(input.account_id, bound.profile_id), row = await this.one(`structured_posts/jobs/${id.parse(input.job_id)}`);\n if (row.id !== input.job_id || !['PROCESSING', 'SUCCESS', 'CLIENT_ERROR', 'SERVER_ERROR', 'QUEUED'].includes(String(row.status))) throw new AdportError('PROVIDER_ERROR', 'reddit: post job receipt ID/status mismatch');\n if (row.status === 'SUCCESS') { const post = await this.post(String(row.post_id)); if (!this.profileMatch(post.profile_id, profile)) throw new AdportError('PROVIDER_ERROR', 'reddit: created post belongs to a different profile'); }\n return { job_id: row.id, status: row.status, post_id: row.post_id ?? null, ...(this.client.diagnostic(row.error_message) ? { error_message: this.client.diagnostic(row.error_message) } : {}) };\n }\n async uploadStatus(input: { account_id: string; upload_id: string; resource_receipt: string }) {\n const bound = this.client.verifyResourceReceipt(input.resource_receipt, 'asset_upload', input.account_id, input.upload_id); await this.profile(input.account_id, bound.profile_id);\n const row = await this.one(`creative_assets/uploads/${id.parse(input.upload_id)}`);\n if (row.id !== input.upload_id || !['PROCESSING_MEDIA', 'ACTIVE', 'INVALID_MEDIA'].includes(String(row.status))) throw new AdportError('PROVIDER_ERROR', 'reddit: asset upload receipt ID/status mismatch');\n if (row.status !== 'PROCESSING_MEDIA' && (!rowSchema.safeParse(row.result).success || !['IMAGE', 'VIDEO', 'HEADLINE', 'CTA'].includes(String(record(row.result).type)))) throw new AdportError('PROVIDER_ERROR', 'reddit: completed asset upload is missing a valid stored asset');\n return { upload_id: row.id, status: row.status, ...(row.result ? { result: row.result } : {}), ...(record(row.result).status === 'DUPLICATE_ASSET' ? { warning: 'Reddit reused an existing asset. This is not proof that the asset was newly created.' } : {}) };\n }\n async targetingOptions(input: Page & { dimension: string; query?: string; country?: string; postal_code?: string; cities_search?: string }) {\n id.parse(input.account_id); const dimensions = ['carriers', 'communities', 'communities_search', 'devices', 'geolocations', 'interests', 'languages', 'third_party_audiences'];\n if (!dimensions.includes(input.dimension)) throw new AdportError('INVALID_INPUT', 'reddit: unsupported targeting dimension');\n const path = `targeting/${input.dimension === 'communities_search' ? 'communities/search' : input.dimension}`;\n if (['geolocations', 'interests'].includes(input.dimension)) {\n if (input.cursor) throw new AdportError('INVALID_INPUT', 'reddit: this native dimension is not paginated; narrow its query instead');\n const data = await this.client.get<unknown>(path, input.dimension === 'geolocations' ? { country: input.country, postal_code: input.postal_code, cities_search: input.cities_search } : {});\n if (!Array.isArray(data.data) || data.data.some(row => !row || typeof row !== 'object' || Array.isArray(row))) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed targeting choices');\n return { items: data.data.slice(0, input.page_size), truncated: data.data.length > input.page_size, ...(data.data.length > input.page_size ? { warning: 'Native endpoint has no pagination. Narrow the filter or increase page_size to inspect more choices.' } : {}) };\n }\n return this.page(path, input, { ...(input.dimension === 'communities_search' ? { query: input.query } : {}), ...(input.dimension === 'geolocations' ? { country: input.country, postal_code: input.postal_code, cities_search: input.cities_search } : {}) });\n }\n private async verifyTargeting(account: string, value: Row) {\n const references = [...(Array.isArray(value.custom_audience_ids) ? value.custom_audience_ids : []), ...(Array.isArray(value.excluded_custom_audience_ids) ? value.excluded_custom_audience_ids : [])];\n if (references.length) { const audiences = await this.client.getPaged<Row>(`ad_accounts/${account}/custom_audiences`, { 'page.size': 1000 }, 5000), known = new Set(audiences.map(row => row.id)); if (references.some(value => !known.has(value))) throw new AdportError('INVALID_INPUT', 'reddit: targeting audience is not available to this account'); }\n }\n private async mutation(account: string, path: string, method: 'POST' | 'PATCH', fields: Row, expected: Row): Promise<WriteResult> {\n const response = method === 'POST' ? await this.client.post<unknown>(path, { data: fields }) : await this.client.patch<unknown>(path, { data: fields }), row = record(response.data), ids = string(row.id) ? [row.id] : [];\n if (ids.length !== 1 || row.ad_account_id !== account || Object.entries(expected).some(([key, value]) => value !== undefined && (key === 'targeting' ? !targetingMatches(row[key], value) : ['start_time', 'end_time'].includes(key) && value !== null ? Date.parse(String(row[key])) !== Date.parse(String(value)) : row[key] !== value))) throw new AdportError('PROVIDER_ERROR', 'reddit: child receipt ID/account/status/money mismatch; reconcile before retrying', { resource_ids: ids });\n return { applied: true, resourceIds: ids };\n }\n private async assetUpload(account: string, profile: Row, payload: Row): Promise<WriteResult> {\n const data = await this.client.post<unknown>(`profiles/${profile.id}/creative_assets/uploads`, { data: [payload] });\n const rows = Array.isArray(data.data) ? data.data : [], ids = rows.map(row => record(row).id).filter(string);\n if (rows.length !== 1 || ids.length !== 1 || !id.safeParse(ids[0]).success) throw new AdportError('PROVIDER_ERROR', 'reddit: asset upload did not return one native handle; reconcile before retrying', { resource_ids: ids });\n return { applied: true, resourceIds: ids, details: { upload_id: ids[0], resource_receipt: this.client.resourceReceipt('asset_upload', account, String(profile.id), ids[0]!), next_tool: 'reddit_asset_upload_status' } };\n }\n private async postCreate(account: string, profile: Row, payload: Row): Promise<WriteResult> {\n const data = await this.client.post<unknown>(`profiles/${profile.id}/structured_posts/jobs`, { data: payload }), row = record(data.data), ids = string(row.id) ? [row.id] : [];\n if (ids.length !== 1 || !['PROCESSING', 'QUEUED', 'SUCCESS'].includes(String(row.status))) throw new AdportError('PROVIDER_ERROR', 'reddit: post job was not accepted; reconcile before retrying', { resource_ids: ids, job_status: row.status });\n return { applied: true, resourceIds: ids, details: { job_id: row.id, status: row.status, resource_receipt: this.client.resourceReceipt('post_job', account, String(profile.id), ids[0]!), next_tool: 'reddit_post_job' } };\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<RedditCreativePlan> {\n const account = id.parse(op.accountId), p = op.payload, expectedKind = /^reddit_(?:create_|stage_|upload_|import_)/.test(op.tool) ? 'create' : op.tool === 'reddit_delete_asset' ? 'remove' : 'update';\n if (op.provider !== 'reddit' || op.kind !== expectedKind) throw new AdportError('INVALID_INPUT', 'reddit: provider or write kind mismatch');\n const coercions: string[] = [], budgetDeltas: WritePreview['budgetDeltas'] = [], notes: string[] = [];\n let fields: Row = {}, current: Row = {}, expected: Row = {}, path = '', method: 'POST' | 'PATCH' = 'PATCH';\n const paused = (value: string) => { if (guard.forcePausedCreation && value !== 'PAUSED') coercions.push('configured_status coerced to PAUSED by policy (paused_creation)'); return guard.forcePausedCreation ? 'PAUSED' : value; };\n switch (op.tool) {\n case 'reddit_create_ad_group': {\n const input = createGroup.parse(p), parent = await this.owned(account, 'campaigns', input.campaign_id);\n if (parent.type === 'AUTOMATED' || parent.is_max === true) throw new AdportError('INVALID_INPUT', 'reddit: this tool creates MANUAL ad groups; Reddit Max requires its own authoring flow');\n await this.verifyTargeting(account, input.targeting);\n const cbo = parent.is_campaign_budget_optimization === true;\n if (cbo && (input.budget_micros !== undefined || input.bid_micros !== undefined || input.bid_type !== null || input.bid_strategy !== null)) throw new AdportError('INVALID_INPUT', 'reddit: CBO ad groups inherit budget/bidding; use null bid settings and omit child money');\n if (!cbo && (!input.budget_micros || !input.budget_type || !input.bid_type || !input.bid_strategy || (input.bid_strategy !== 'BIDLESS' && !input.bid_micros))) throw new AdportError('INVALID_INPUT', 'reddit: non-CBO ad groups require explicit budget, budget type, bid type and bidding settings');\n if (input.bid_strategy === 'BIDLESS' && input.bid_micros) throw new AdportError('INVALID_INPUT', 'reddit: BIDLESS requires no monetary bid');\n if (input.conversion_pixel_id) { const pixels = await this.client.getPaged<Row>(`ad_accounts/${account}/pixels`, {}, 1000); if (!pixels.some(row => row.id === input.conversion_pixel_id)) throw new AdportError('INVALID_INPUT', 'reddit: Pixel is not available to this account'); }\n if (input.app_id) { const apps = await this.client.getPaged<Row>(`ad_accounts/${account}/apps`, {}, 1000); if (!apps.some(row => row.id === input.app_id)) throw new AdportError('INVALID_INPUT', 'reddit: app is not available to this account'); }\n if (input.saved_audience_id) { const audience = await this.one(`saved_audiences/${input.saved_audience_id}`); if (audience.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'reddit: saved audience is not owned by this account'); }\n const { budget_micros, budget_type, bid_micros, ...native } = input;\n fields = { ...native, type: 'MANUAL', configured_status: paused(input.configured_status), targeting: { expand_targeting: false, ...input.targeting }, goal_value: cbo ? null : budget_micros, goal_type: cbo ? null : budget_type, bid_value: cbo || input.bid_strategy === 'BIDLESS' ? null : bid_micros };\n path = `ad_accounts/${account}/ad_groups`; method = 'POST'; expected = { campaign_id: input.campaign_id, type: 'MANUAL' }; break;\n }\n case 'reddit_update_ad_group': { const { ad_group_id, ...input } = updateGroup.parse(p); current = await this.owned(account, 'ad_groups', ad_group_id); path = `ad_groups/${ad_group_id}`; fields = input; expected = { id: ad_group_id, campaign_id: current.campaign_id }; break; }\n case 'reddit_update_targeting': {\n const nativeId = id.parse(p.ad_group_id), input = targeting.parse(p.targeting); current = await this.owned(account, 'ad_groups', nativeId);\n const previous = record(current.targeting);\n if (!targeting.safeParse(previous).success) throw new AdportError('INVALID_INPUT', 'reddit: current targeting contains unsupported fields; refusing a partial update that could reset them');\n const merged = { ...previous, ...input }; await this.verifyTargeting(account, merged);\n path = `ad_groups/${nativeId}`; fields = { targeting: merged }; expected = { id: nativeId, campaign_id: current.campaign_id }; break;\n }\n case 'reddit_set_ad_group_budget':\n case 'reddit_set_ad_group_bidding': {\n const nativeId = id.parse(p.ad_group_id); current = await this.owned(account, 'ad_groups', nativeId); const parent = await this.owned(account, 'campaigns', String(current.campaign_id));\n if (parent.is_campaign_budget_optimization === true) throw new AdportError('INVALID_INPUT', 'reddit: CBO budgets and bidding belong to the parent campaign');\n path = `ad_groups/${nativeId}`; expected = { id: nativeId, campaign_id: current.campaign_id };\n if (op.tool.endsWith('_budget')) { if (!['DAILY_SPEND', 'LIFETIME_SPEND'].includes(String(current.goal_type)) || !Number.isSafeInteger(current.goal_value)) throw new AdportError('INVALID_INPUT', 'reddit: current ad-group budget/type is unavailable'); fields = { goal_value: micros.positive().parse(p.budget_micros) }; }\n else {\n const strategy = p.bid_strategy !== undefined ? bidStrategy.parse(p.bid_strategy) : current.bid_strategy;\n if (current.bid_strategy !== 'BIDLESS' && (current.bid_value === undefined || current.bid_value === null)) throw new AdportError('INVALID_INPUT', 'reddit: current monetary bid is unavailable');\n if (strategy === 'BIDLESS' && (p.bid_micros !== undefined || Number(current.bid_value) > 0)) throw new AdportError('INVALID_INPUT', 'reddit: removing an existing monetary bid cap cannot be represented by the current policy; preserve a bounded bid');\n if (strategy !== 'BIDLESS' && !(p.bid_micros ?? current.bid_value)) throw new AdportError('INVALID_INPUT', 'reddit: the strategy requires a monetary bid');\n fields = { ...(p.bid_strategy !== undefined ? { bid_strategy: strategy } : {}), ...(p.bid_micros !== undefined ? { bid_value: micros.positive().parse(p.bid_micros) } : {}) };\n }\n break;\n }\n case 'reddit_create_ad': { const input = createAd.parse(p); await this.owned(account, 'ad_groups', input.ad_group_id); await this.ownedPost(account, input.post_id); fields = { ...input, type: 'UNSPECIFIED', configured_status: paused(input.configured_status) }; path = `ad_accounts/${account}/ads`; method = 'POST'; expected = { ad_group_id: input.ad_group_id, post_id: input.post_id }; break; }\n case 'reddit_update_ad': { const { ad_id, ...input } = updateAd.parse(p); current = await this.owned(account, 'ads', ad_id); if (input.post_id) { if (!['ACTIVE', 'PAUSED'].includes(String(current.configured_status))) throw new AdportError('INVALID_INPUT', 'reddit: creative replacement requires a readable ACTIVE/PAUSED configured status'); await this.ownedPost(account, input.post_id); expected.configured_status = current.configured_status; notes.push(`Post replacement preserves configured status ${current.configured_status} and can trigger review.`); } fields = input; path = `ads/${ad_id}`; expected = { ...expected, id: ad_id, ad_group_id: current.ad_group_id }; break; }\n case 'reddit_set_ad_status':\n case 'reddit_set_ad_group_status': { const entity = op.tool === 'reddit_set_ad_status' ? 'ads' : 'ad_groups', nativeId = id.parse(p[entity === 'ads' ? 'ad_id' : 'ad_group_id']); current = await this.owned(account, entity, nativeId); path = `${entity}/${nativeId}`; fields = { configured_status: z.enum(['ACTIVE', 'PAUSED']).parse(p.configured_status) }; expected = { id: nativeId }; break; }\n case 'reddit_archive_entity': { const entity = z.enum(['campaigns', 'ad_groups', 'ads']).parse(p.entity), nativeId = id.parse(p.resource_id); current = await this.owned(account, entity, nativeId); path = `${entity}/${nativeId}`; fields = { configured_status: 'ARCHIVED' }; expected = { id: nativeId }; break; }\n case 'reddit_upload_asset': {\n const input = uploadAsset.parse(p), profile = await this.profile(account, input.profile_id);\n if (!this.media.providerUrl) throw new AdportError('INVALID_INPUT', 'reddit: exact-file uploads require a hosted immutable media source. Local CLI can use reddit_import_asset_url for an existing HTTPS asset.');\n const options = { maxBytes: 100 * 1024 * 1024, contentTypes: input.type === 'IMAGE' ? ['image/png', 'image/jpeg', 'image/webp'] : ['video/mp4', 'video/quicktime'] };\n const file = await this.media.read(input, options), poster: MediaSource | undefined = input.type === 'VIDEO' ? { media_id: input.poster_media_id, expected_sha256: input.poster_expected_sha256! } : undefined;\n if (poster) await this.media.read(poster, { contentTypes: ['image/png', 'image/jpeg', 'image/webp'] });\n return { summary: `Import approved Reddit ${input.type} asset`, changes: [`Profile ${profile.id}; ${file.name}, ${file.bytes.byteLength}bytes, SHA-256 ${file.sha256}. Reddit downloads a temporary immutable project source after approval; no ad is created.`], coercions, budgetDeltas, execute: async () => {\n const source = await this.media.providerUrl!(input, options), payload: Row = { type: input.type, name: input.name, media: { type: 'URL', url: source.url } };\n if (source.sha256 !== file.sha256 || !safeUrl(source.url) || !Number.isFinite(Date.parse(source.expires_at)) || Date.parse(source.expires_at) <= Date.now()) throw new AdportError('INVALID_INPUT', 'reddit: invalid or changed immutable provider media source');\n if (poster) { const image = await this.media.providerUrl!(poster, { contentTypes: ['image/png', 'image/jpeg', 'image/webp'] }); if (image.sha256 !== poster.expected_sha256.toLowerCase() || !safeUrl(image.url) || !Number.isFinite(Date.parse(image.expires_at)) || Date.parse(image.expires_at) <= Date.now()) throw new AdportError('INVALID_INPUT', 'reddit: invalid poster source'); payload.poster = { type: 'URL', url: image.url }; }\n return this.assetUpload(account, profile, payload);\n } };\n }\n case 'reddit_import_asset_url': { const input = importAsset.parse(p), profile = await this.profile(account, input.profile_id), payload = { name: input.name, type: input.type, media: { type: 'URL', url: input.media_url }, ...(input.poster_url ? { poster: { type: 'URL', url: input.poster_url } } : {}) }; return { summary: 'Import a Reddit media URL', changes: [`Reddit fetches the supplied URL; approval binds this URL rather than remote bytes: ${JSON.stringify(payload)}`], coercions, budgetDeltas, execute: () => this.assetUpload(account, profile, payload) }; }\n case 'reddit_create_text_asset': { const { profile_id, ...input } = textAsset.parse(p), profile = await this.profile(account, profile_id); return { summary: `Create Reddit ${input.type} asset`, changes: [JSON.stringify(input)], coercions, budgetDeltas, execute: () => this.assetUpload(account, profile, input) }; }\n case 'reddit_rename_asset':\n case 'reddit_delete_asset': {\n const assetId = id.parse(p.creative_asset_id), { profile, asset } = await this.asset(account, id.parse(p.profile_id), assetId), remove = op.tool === 'reddit_delete_asset', name = remove ? undefined : z.string().trim().min(1).parse(p.name);\n return { summary: `${remove ? 'Delete' : 'Rename'} shared Reddit profile asset ${assetId}`, changes: [`Profile ${profile.id}; current ${asset.name ?? asset.id}. ${remove ? 'Permanently delete from the shared profile library.' : `Rename to ${name}.`}`], coercions, budgetDeltas, execute: async () => { if (remove) { const result = await this.client.delete(`creative_assets/${assetId}`); if (result.data !== null && (!result.data || typeof result.data !== 'object' || Object.keys(result.data).length)) throw new AdportError('PROVIDER_ERROR', 'reddit: unexpected asset deletion receipt; reconcile before retrying', { resource_ids: [assetId] }); return { applied: true, resourceIds: [assetId] }; } const result = await this.client.patch<Row>(`creative_assets/${assetId}`, { data: { name } }); if (result.data.id !== assetId || result.data.name !== name) throw new AdportError('PROVIDER_ERROR', 'reddit: asset rename receipt mismatch', { resource_ids: [assetId] }); return { applied: true, resourceIds: [assetId] }; } };\n }\n case 'reddit_create_post': {\n const input = createPost.parse(p), profile = await this.profile(account, input.profile_id), creative: Row = { type: input.type, headline: input.headline, ...(input.body !== undefined ? { body: input.body, text_format: 'PLAIN_TEXT' } : {}) };\n if (input.destination_url) creative.destination = { type: 'URL', url: input.destination_url, ...(input.call_to_action ? { call_to_action: input.call_to_action } : {}) };\n if (input.type === 'IMAGE') creative.image = await this.readyAsset(account, String(profile.id), input.image_asset_id!, 'IMAGE');\n if (input.type === 'VIDEO') creative.video = await this.readyAsset(account, String(profile.id), input.video_asset_id!, 'VIDEO');\n if (input.thumbnail_asset_id) creative.thumbnail = await this.readyAsset(account, String(profile.id), input.thumbnail_asset_id, 'IMAGE');\n if (input.type === 'CAROUSEL') creative.carousel = await Promise.all(input.carousel!.map(async card => ({ image: await this.readyAsset(account, String(profile.id), card.image_asset_id, 'IMAGE'), destination: { type: 'URL', url: card.destination_url, ...(card.call_to_action ? { call_to_action: card.call_to_action } : {}) }, ...(card.caption !== undefined ? { caption: card.caption } : {}) })));\n const payload = { allow_comments: input.allow_comments, creative }; return { summary: 'Create a Reddit structured-post job', changes: [`Create a new post under profile ${profile.id}; ad attachment requires a separate approval. ${JSON.stringify(payload)}`], coercions, budgetDeltas, execute: () => this.postCreate(account, profile, payload) };\n }\n case 'reddit_stage_post_copy': {\n const input = stageCopy.parse(p), ad = await this.owned(account, 'ads', input.ad_id), profile = await this.profile(account, input.profile_id);\n if (ad.post_id !== input.source_post_id) throw new AdportError('INVALID_INPUT', 'reddit: source post no longer matches the selected ad');\n const post = await this.post(input.source_post_id);\n if (!this.profileMatch(post.profile_id, profile)) throw new AdportError('INVALID_INPUT', 'reddit: source post belongs to a different associated profile');\n const creative = writableCopy(record(post.creative));\n if (input.headline !== undefined) creative.headline = input.headline;\n if (input.body !== undefined) { creative.body = input.body; creative.text_format = 'PLAIN_TEXT'; }\n const payload = { allow_comments: post.allow_comments === true, creative };\n return { summary: `Stage a new creative copy for Reddit ad ${input.ad_id}`, changes: [`Create a new post under profile ${profile.id}. The original ${input.source_post_id} and ad reference remain unchanged until a separate reddit_update_ad approval. ${JSON.stringify(payload)}`], coercions, budgetDeltas, execute: () => this.postCreate(account, profile, payload) };\n }\n default: throw new AdportError('INVALID_INPUT', `reddit: unsupported creative write ${op.tool}`);\n }\n const effective = { ...current, ...fields };\n if (effective.end_time && (!effective.start_time || Date.parse(String(effective.end_time)) <= Date.parse(String(effective.start_time)))) throw new AdportError('INVALID_INPUT', 'reddit: end_time requires a preceding start_time');\n for (const key of ['goal_value', 'bid_value']) if (fields[key] !== undefined && fields[key] !== null) budgetDeltas.push({ target: `${path} ${key}`, ...(current[key] !== undefined && current[key] !== null ? { fromMicros: micros.parse(current[key]) } : {}), toMicros: micros.parse(fields[key]) });\n for (const key of ['name', 'configured_status', 'goal_value', 'bid_value', 'bid_strategy', 'post_id', 'start_time', 'end_time', 'targeting']) if (fields[key] !== undefined) expected[key] = fields[key];\n return { summary: `Reddit ${op.tool.replace('reddit_', '').replaceAll('_', ' ')}`, changes: [...notes, `${method} ${path}: ${JSON.stringify({ data: fields })}`], coercions, budgetDeltas, execute: () => this.mutation(account, path, method, fields, expected) };\n }\n}\n\nfunction postMedia(creative: Row, legacy?: Row): Creative['media'] {\n const result: Creative['media'] = [];\n for (const [key, type] of [['image', 'image'], ['video', 'video'], ['thumbnail', 'image']] as const) { const asset = record(creative[key]), media = record(asset.media), url = safeUrl(media.url) ?? safeUrl(media.permanent_url); if (url) result.push({ type, url }); }\n if (Array.isArray(creative.carousel)) for (const card of creative.carousel) { const url = safeUrl(record(record(record(card).image).media).url); if (url) result.push({ type: 'image', url }); }\n if (!result.length && Array.isArray(legacy?.content)) for (const card of legacy.content) { const url = safeUrl(record(card).media_url); if (url && ['IMAGE', 'VIDEO', 'CAROUSEL'].includes(String(legacy?.type))) result.push({ type: legacy?.type === 'VIDEO' ? 'video' : 'image', url }); }\n return result.slice(0, 40);\n}\nfunction writableCopy(source: Row): Row {\n if (!['TEXT', 'IMAGE', 'VIDEO', 'CAROUSEL'].includes(String(source.type))) throw new AdportError('INVALID_INPUT', 'reddit: this post format requires a dedicated authoring flow');\n const allowed = ['type', 'headline', 'body', 'text_format', 'destination', 'image', 'video', 'thumbnail', 'carousel', 'supplementary_text', 'event', 'enhancements'];\n if (Object.keys(source).some(key => !allowed.includes(key))) throw new AdportError('INVALID_INPUT', 'reddit: source creative contains unsupported fields; refusing a copy that could omit them');\n const result = structuredClone(source);\n const cleanMedia = (value: unknown) => { const asset = record(value), media = record(asset.media), url = safeUrl(media.url) ?? safeUrl(media.permanent_url); if (!url) throw new AdportError('INVALID_INPUT', 'reddit: source creative media has no safe HTTPS URL'); return { ...Object.fromEntries(Object.entries(asset).filter(([key]) => ['crop', 'name', 'gifify'].includes(key))), media: { type: 'URL', url } }; };\n for (const key of ['image', 'video', 'thumbnail']) if (result[key] !== undefined && result[key] !== null) result[key] = cleanMedia(result[key]);\n if (Array.isArray(result.carousel)) result.carousel = result.carousel.map(value => { const card = record(value); return { ...card, image: cleanMedia(card.image) }; });\n return result;\n}\nfunction targetingMatches(actual: unknown, expected: unknown): boolean {\n const canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, child]) => [key, canonical(child)])) : value;\n if (Array.isArray(expected)) return JSON.stringify(canonical(actual)) === JSON.stringify(canonical(expected));\n if (expected && typeof expected === 'object') return actual !== null && typeof actual === 'object' && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => targetingMatches((actual as Row)[key], value));\n return actual === expected;\n}\n","import { creativesOutput, defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsProvider } from './provider.js';\nimport { micros, redditId as id, status } from './schemas.js';\n\nconst strings = z.array(z.string().min(1)).max(500), ids = z.array(id).min(1).max(200);\nconst url = z.string().url().max(4096).refine(value => { const u = new URL(value); return ['http:', 'https:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without embedded credentials');\nconst mediaUrl = url.refine(value => { const u = new URL(value), host = u.hostname.toLowerCase().replace(/\\.$/, ''); return u.protocol === 'https:' && !u.hash && host.includes('.') && !host.endsWith('.local') && !host.endsWith('.localhost') && !/^[\\d.]+$/.test(host) && !host.includes(':'); }, 'Use an externally accessible HTTPS media hostname');\nconst name = z.string().trim().min(1), headline = z.string().min(1).max(300), copy = z.string().max(40_000), cta = z.string().regex(/^[A-Z_]+$/);\nexport const targeting = z.object({ carriers: strings.nullable().optional(), communities: strings.optional(), custom_audience_ids: strings.optional(), excluded_communities: strings.optional(), excluded_custom_audience_ids: strings.optional(), excluded_geolocations: strings.optional(), excluded_interests: strings.optional(), excluded_keywords: strings.optional(), expand_targeting: z.boolean().nullable().optional(), gender: z.enum(['FEMALE', 'MALE']).nullable().optional(), geolocations: strings.optional(), interests: strings.optional(), keywords: strings.optional(), locations: z.array(z.enum(['FEED', 'COMMENTS_PAGE'])).optional(), platforms: z.array(z.enum(['ALL', 'DESKTOP', 'MOBILE_NATIVE', 'MOBILE_WEB', 'MOBILE_WEB_3X', 'SHREDTOP'])).optional(), suppression_event_types: z.array(z.literal('ALL_FEATURES')).optional(), view_modes: z.array(z.enum(['ALL', 'CARD', 'CLASSIC', 'COMPACT', 'IMMERSIVE'])).optional(), languages: strings.nullable().optional(), devices: z.array(z.object({ type: z.enum(['DESKTOP', 'MOBILE']), os: z.enum(['ANDROID', 'IOS']).nullable().optional(), min_version: z.string().nullable().optional(), max_version: z.string().nullable().optional(), label_map: z.record(z.string(), strings).nullable().optional() }).strict()).optional() }).strict();\nconst dates = { start_time: z.iso.datetime({ offset: true }).nullable().optional(), end_time: z.iso.datetime({ offset: true }).nullable().optional() };\nexport const bidStrategy = z.enum(['BIDLESS', 'MANUAL_BIDDING', 'MAXIMIZE_VOLUME', 'TARGET_CPX']);\nconst bidType = z.enum(['CPC', 'CPM', 'CPV', 'CPV6', 'CPV15']);\nexport const createGroup = z.object({ campaign_id: id, name, configured_status: status.default('PAUSED'), targeting, bid_strategy: bidStrategy.nullable(), bid_type: bidType.nullable(), bid_micros: micros.positive().optional(), budget_micros: micros.positive().optional(), budget_type: z.enum(['DAILY_SPEND', 'LIFETIME_SPEND']).optional(), ...dates, optimization_goal: z.string().regex(/^[A-Z0-9_]+$/).nullable().optional(), conversion_pixel_id: id.optional(), app_id: id.optional(), saved_audience_id: id.optional() });\nexport const updateGroup = z.object({ ad_group_id: id, name: name.optional(), ...dates }).refine(v => Object.keys(v).length > 1, 'Provide an ad-group field');\nexport const createAd = z.object({ ad_group_id: id, post_id: z.string().regex(/^t3_[A-Za-z0-9]+$/), name, configured_status: status.default('PAUSED'), click_url: url.optional(), click_url_query_parameters: z.string().optional() });\nexport const updateAd = z.object({ ad_id: id, name: name.optional(), post_id: z.string().regex(/^t3_[A-Za-z0-9]+$/).optional(), click_url: url.optional(), click_url_query_parameters: z.string().optional() }).refine(v => Object.keys(v).length > 1, 'Provide an ad field');\nconst source = { ...mediaSourceFields };\nexport const uploadAsset = z.object({ profile_id: id, type: z.enum(['IMAGE', 'VIDEO']), name, ...source, poster_media_id: z.string().uuid().optional(), poster_expected_sha256: z.string().regex(/^[a-fA-F0-9]{64}$/).optional() }).refine(v => Boolean(v.media_id) !== Boolean(v.file_path), 'Choose a project media_id or local file_path').refine(v => v.type !== 'VIDEO' || Boolean(v.poster_media_id && v.poster_expected_sha256), 'Video requires an approved project poster image');\nexport const importAsset = z.object({ profile_id: id, type: z.enum(['IMAGE', 'VIDEO']), name, media_url: mediaUrl, poster_url: mediaUrl.optional() }).refine(v => v.type !== 'VIDEO' || Boolean(v.poster_url), 'Video requires poster_url');\nexport const textAsset = z.object({ profile_id: id, type: z.enum(['HEADLINE', 'CTA']), text: headline.optional(), call_to_action: cta.optional() }).refine(v => v.type === 'HEADLINE' ? Boolean(v.text) && !v.call_to_action : Boolean(v.call_to_action) && !v.text, 'Provide text for HEADLINE or call_to_action for CTA');\nexport const createPost = z.object({ profile_id: id, type: z.enum(['TEXT', 'IMAGE', 'VIDEO', 'CAROUSEL']), headline, body: copy.optional(), allow_comments: z.boolean().default(false), destination_url: url.optional(), call_to_action: cta.optional(), image_asset_id: id.optional(), video_asset_id: id.optional(), thumbnail_asset_id: id.optional(), carousel: z.array(z.object({ image_asset_id: id, destination_url: url, call_to_action: cta.optional(), caption: z.string().max(180).optional() }).strict()).min(1).max(40).optional() }).refine(v => v.type !== 'TEXT' || Boolean(v.body), 'TEXT requires body').refine(v => v.type !== 'IMAGE' || Boolean(v.image_asset_id && v.destination_url), 'IMAGE requires an owned image and destination').refine(v => v.type !== 'VIDEO' || Boolean(v.video_asset_id && v.thumbnail_asset_id), 'VIDEO requires an owned video and thumbnail').refine(v => v.type !== 'CAROUSEL' || Boolean(v.carousel?.length), 'CAROUSEL requires cards');\nexport const stageCopy = z.object({ ad_id: id, source_post_id: z.string().regex(/^t3_[A-Za-z0-9]+$/), profile_id: id, headline: headline.optional(), body: copy.optional() }).refine(v => v.headline !== undefined || v.body !== undefined, 'Provide headline or body edits');\n\nexport function redditCreativeTools(provider: RedditAdsProvider): AnyToolDefinition[] {\n const account = { account_id: id }, page = { page_size: z.number().int().min(1).max(1000).default(50), cursor: z.string().url().optional().describe('Native next_url returned as next_cursor; followed exactly within the same resource') };\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'reddit', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove' = 'update') => guardedWriteTool({ name, namespace: 'reddit', provider: 'reddit', description, payload, kind });\n return [\n read('reddit_get_entity', 'Read a native campaign, ad group or ad by ID and verify the selected account and parent hierarchy.', z.object({ ...account, entity: z.enum(['campaigns', 'ad_groups', 'ads']), resource_id: id }), v => provider.creatives.owned(v.account_id, v.entity, v.resource_id)),\n read('reddit_ad_groups', 'Read account ad-group configuration, targeting, bids and budgets with native pagination.', z.object({ ...account, campaign_id: id.optional(), ad_group_ids: ids.optional(), ...page }), v => provider.creatives.groups(v)),\n defineTool({ name: 'reddit_ads', namespace: 'reddit', description: 'View account ad settings and referenced structured-post copy/media. Creative edit actions stage a separate copy; original posts remain unchanged.', input: z.object({ ...account, ad_ids: ids.optional(), ad_group_ids: ids.optional(), campaign_ids: ids.optional(), include_post_details: z.boolean().default(true), ...page, page_size: z.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: v => provider.creatives.ads(v) }),\n read('reddit_profiles', 'List profiles already associated with this ad account, including native profile IDs and Reddit user IDs.', z.object(account), v => provider.creatives.profiles(v.account_id)),\n defineTool({ name: 'reddit_posts', namespace: 'reddit', description: 'View structured-post copy/media belonging to an account-associated profile, including unattached posts staged for review.', input: z.object({ ...account, profile_id: id, ...page, page_size: z.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: v => provider.creatives.posts(v) }),\n defineTool({ name: 'reddit_assets', namespace: 'reddit', description: 'View an associated profile’s native image/video/headline/CTA asset library and processing readiness.', input: z.object({ ...account, profile_id: id, ...page, page_size: z.number().int().min(1).max(50).default(20) }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: v => provider.creatives.assets(v) }),\n read('reddit_post_job', 'Read a created post job using its account-bound resource_receipt. Rechecks current profile association; arbitrary global job IDs are rejected.', z.object({ ...account, job_id: id, resource_receipt: z.string().max(2048) }), v => provider.creatives.postJob(v)),\n read('reddit_asset_upload_status', 'Read native asset-processing status using the account-bound resource_receipt from its approved upload.', z.object({ ...account, upload_id: id, resource_receipt: z.string().max(2048) }), v => provider.creatives.uploadStatus(v)),\n read('reddit_targeting_options', 'Read native carriers, communities/search, devices, geolocations, interests, languages and third-party audience choices.', z.object({ ...account, dimension: z.enum(['carriers', 'communities', 'communities_search', 'devices', 'geolocations', 'interests', 'languages', 'third_party_audiences']), query: z.string().optional(), country: z.string().optional(), postal_code: z.string().optional(), cities_search: z.string().optional(), ...page }), v => provider.creatives.targetingOptions(v)),\n write('reddit_create_ad_group', 'Create a MANUAL ad group, paused by policy. Non-CBO groups require an explicit budget and bid settings; pass null bid fields only to inherit CBO settings.', createGroup, 'create'),\n write('reddit_update_ad_group', 'Patch an owned ad group’s supplied name/start/end fields while preserving omitted settings.', updateGroup),\n write('reddit_update_targeting', 'Edit supplied targeting dimensions, preserving omitted dimensions and replacing supplied arrays. Explicit expansion settings are retained.', z.object({ ad_group_id: id, targeting }).refine(v => Object.keys(v.targeting).length > 0, 'Provide targeting dimensions')),\n write('reddit_set_ad_group_budget', 'Change a non-CBO ad-group budget in integer micros using the current value; preserves its daily/lifetime type.', z.object({ ad_group_id: id, budget_micros: micros.positive() })),\n write('reddit_set_ad_group_bidding', 'Change a non-CBO strategy/monetary bid in integer micros. Removing an existing monetary cap is rejected until policy can represent an unbounded change.', z.object({ ad_group_id: id, bid_strategy: bidStrategy.optional(), bid_micros: micros.positive().optional() }).refine(v => Boolean(v.bid_strategy || v.bid_micros), 'Provide a bidding field')),\n write('reddit_create_ad', 'Create a paused ad from an account-owned ad group and an eligible post; verifies referenced profile/content before creation.', createAd, 'create'),\n write('reddit_update_ad', 'Patch name, destination or post reference on one verified ad. A post replacement preserves configured status and can trigger review.', updateAd),\n ...(['ad_group', 'ad'] as const).map(entity => write(`reddit_set_${entity}_status`, 'Pause or activate a child after verifying its entire account/parent hierarchy.', z.object({ [entity === 'ad' ? 'ad_id' : 'ad_group_id']: id, configured_status: status }))),\n write('reddit_archive_entity', 'Archive a verified campaign/ad group/ad using native PATCH; this changes delivery without inventing an unsupported DELETE endpoint.', z.object({ entity: z.enum(['campaigns', 'ad_groups', 'ads']), resource_id: id })),\n write('reddit_upload_asset', 'Stage checksum-bound project image/video bytes for Reddit’s URL-pull asset processor. Requires a hosted immutable media resolver; private source URLs are omitted from previews.', uploadAsset, 'create'),\n write('reddit_import_asset_url', 'Ask Reddit to import an existing HTTPS image/video URL. Approval binds the URL, not mutable remote bytes; prefer reddit_upload_asset for exact project files. No file is fetched by Adport.', importAsset, 'create'),\n write('reddit_create_text_asset', 'Create a headline or CTA asset through the native asset-processing API. Does not create or activate an ad.', textAsset, 'create'),\n write('reddit_rename_asset', 'Rename an asset in an account-associated profile library; the name is shared by users of that profile.', z.object({ profile_id: id, creative_asset_id: id, name })),\n write('reddit_delete_asset', 'Permanently remove an asset from an account-associated profile library. Review shared profile usage before approval.', z.object({ profile_id: id, creative_asset_id: id }), 'remove'),\n write('reddit_create_post', 'Create an async structured advertising-post job from owned ready assets. Comments default off. Ad creation and activation remain separate approvals.', createPost, 'create'),\n write('reddit_stage_post_copy', 'Stage a new structured-post copy for one verified ad with supplied headline/body edits. Does not mutate the original post or attach the result to the ad.', stageCopy, 'create'),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsClient } from './client.js';\nimport { catalogGrant, catalogScopeKey, creationScope, redditBusinessId, redditCatalogId, requireCatalogAccess, requireCatalogCreationAccess, type RedditCatalogAccessStore, type RedditCatalogScope } from './catalog-access.js';\nimport { catalogInput, creationContext, sourceContext, catalogCreate, catalogRename, catalogSources, catalogDelete, permissionSnapshot, permissionChange } from './catalog-schemas.js';\n\ntype Scope = z.infer<typeof catalogInput>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst count = z.number().int().nonnegative().safe(), eventSources = z.array(redditCatalogId.max(50)).max(5000).refine(ids => new Set(ids).size === ids.length);\nconst nativeCatalog = z.object({ id: redditCatalogId, business_id: redditBusinessId, name: z.string().min(1).max(200), default_language: z.string().min(1).max(32), default_currency: z.string().regex(/^[A-Z]{3}$/), event_sources: eventSources.optional(), data_sources: z.array(z.string()).max(100).optional(), summary: z.object({ products_count: count.optional(), approved_products_count: count.optional(), rejected_products_count: count.optional(), invalid_products_count: count.optional() }).optional() });\ntype Catalog = z.infer<typeof nativeCatalog>;\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst config = (row: Catalog) => ({ id: row.id, business_id: row.business_id, name: row.name, default_language: row.default_language, default_currency: row.default_currency, event_sources: row.event_sources ? [...row.event_sources].sort() : undefined });\nconst configurationHash = (scope: Scope, row: Catalog) => digest({ account_id: scope.account_id, business_id: scope.business_id, catalog_id: scope.catalog_id, configuration: config(row) });\nconst resource = (input: Scope): RedditCatalogScope => ({ accountId: input.account_id, businessId: input.business_id, resourceId: input.catalog_id, kind: 'catalog' });\nconst permissionResource = (input: { account_id: string; business_id: string; catalog_id?: string; resource_kind?: string }) => input.resource_kind === 'catalog_creation' ? creationScope(input.account_id, input.business_id) : resource({ ...input, catalog_id: input.catalog_id! });\nconst failure = (error: unknown, message: string, ids?: string[]) => {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n return new AdportError('PROVIDER_ERROR', message + ' Provider bodies stay hidden; no native write was retried.', { ...(Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}), ...(ids ? { resourceIds: ids } : {}) });\n};\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'Reddit catalog/Business scope or native response shape could not be verified.');\n\n/** Explicit Business-resource permissions are independent from enabled ad-account access. */\nexport class RedditCatalogService {\n constructor(private readonly client: Pick<RedditAdsClient, 'get' | 'post' | 'patch' | 'delete' | 'getPaged'>, private readonly store?: RedditCatalogAccessStore) {}\n private manager() { if (!this.store?.canManage) throw new AdportError('POLICY_VIOLATION', 'Only the local owner or a signed-in project owner/admin can administer catalog access.');return this.store; }\n private async read(path: string, absent = false) {\n try { return (await this.client.get<unknown>(path)).data; } catch (error) {\n if (error instanceof AdportError && ['POLICY_VIOLATION', 'NOT_CONNECTED'].includes(error.code)) throw error;\n if (absent && error instanceof AdportError && (error.details as Record<string, unknown> | undefined)?.http_status === 404) return undefined;\n throw failure(error, 'Reddit catalog read failed. Check native Business/catalog access.');\n }\n }\n private async native(scope: Scope, absent = false) {\n const value = await this.read(`product_catalogs/${encodeURIComponent(scope.catalog_id)}`, absent);if (value === undefined && absent) return;\n const parsed = nativeCatalog.safeParse(value);if (!parsed.success || parsed.data.id !== scope.catalog_id || parsed.data.business_id !== scope.business_id) throw invalid();return parsed.data;\n }\n private async parent(scope: Scope, write = false) { await requireCatalogAccess(this.store, resource(scope), write);return (await this.native(scope))!; }\n async authorize(value: unknown, write = false) { const input = catalogInput.parse(value), row = await this.parent(input, write);return { ...row, configuration_hash: configurationHash(input, row) }; }\n private async business(id: string) {\n const parsed = z.object({ id: redditBusinessId, name: z.string().max(4000) }).safeParse(await this.read(`businesses/${encodeURIComponent(id)}`));if (!parsed.success || parsed.data.id !== id) throw invalid();return parsed.data;\n }\n private async selectedSources(input: { account_id: string; business_id: string; catalog_id?: string }, ids: string[]) {\n const selected = [...ids].sort();if (selected.length) {\n let raw: unknown[];\n try { raw = await this.client.getPaged<unknown>(`ad_accounts/${encodeURIComponent(input.account_id)}/pixels`, { 'page.size': 1000 }, 5000); } catch (error) { throw failure(error, 'Selected-account Pixel lookup failed.'); }\n const parsed = z.array(z.object({ id: redditCatalogId, ad_account_id: redditCatalogId.optional() })).max(5000).safeParse(raw);\n if (!parsed.success || parsed.data.some(row => row.ad_account_id !== undefined && row.ad_account_id !== input.account_id) || new Set(parsed.data.map(row => row.id)).size !== parsed.data.length) throw invalid();\n if (selected.some(id => !parsed.data.some(row => row.id === id))) throw new AdportError('INVALID_INPUT', 'Every selected event-source Pixel must be available to the selected ad account within the bounded native lookup.');\n }\n return digest({ account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id ?? null, event_sources: selected });\n }\n async access(account: string) { redditCatalogId.parse(account);const grants = await this.store?.list(account) ?? [];if (grants.some(grant => grant.scope.accountId !== account)) throw new AdportError('POLICY_VIOLATION', 'Catalog access does not match this advertiser.');return { grants, records: grants.map(grant => ({ id: grant.scope.resourceId, name: grant.scope.kind === 'catalog_creation' ? 'New catalogs' : 'Catalog ' + grant.scope.resourceId, business_id: grant.scope.businessId, access: grant.mode })), notes: ['Only explicit project grants are listed. Enabled ad-account access does not authorize Business catalogs.'] }; }\n async snapshot(value: unknown) { const input = permissionSnapshot.parse(value), scope = permissionResource(input), grant = await this.manager().get(scope);return { grant, records: [{ id: scope.resourceId, name: 'Catalog access', business_id: scope.businessId, access: grant.mode }] }; }\n async get(value: unknown) {\n const input = catalogInput.parse(value), current = await this.parent(input);return { catalog: { ...current, configuration_hash: configurationHash(input, current) }, records: [{ id: current.id, name: current.name, business_id: current.business_id, currency: current.default_currency, language: current.default_language, products: current.summary?.products_count, event_source_count: current.event_sources?.length }], notes: ['Native counts/fields that are absent stay unavailable. This is configuration, not full product or dependent-ad inventory.'] };\n }\n async creationContext(value: unknown) {\n const input = creationContext.parse(value), grant = await requireCatalogCreationAccess(this.store, creationScope(input.account_id, input.business_id)), business = await this.business(input.business_id), sourcesHash = await this.selectedSources(input, input.event_sources);\n return { expected_creation_access_hash: grant.hash, expected_event_sources_hash: sourcesHash, event_sources: input.event_sources, business, records: [{ id: business.id, name: business.name, access: 'Create and manage verified new catalogs', selected_event_sources: input.event_sources.length }], complete: true, truncated: false, notes: ['Delegation authorizes creation and management of verified new IDs only. Existing Business catalogs are not enumerated or granted.', 'Selected event-source Pixel IDs are checked under the selected ad account; empty selection installs no binding. No events, products, ads or spend are created by this context.'] };\n }\n async sourceContext(value: unknown) {\n const input = sourceContext.parse(value), current = await this.parent(input), sourcesHash = await this.selectedSources(input, input.event_sources);\n if (!current.event_sources) throw new AdportError('PROVIDER_ERROR', 'Current catalog event sources are unavailable. No replacement preview was prepared.');\n return { expected_configuration_hash: configurationHash(input, current), expected_event_sources_hash: sourcesHash, current_event_sources: current.event_sources, event_sources: input.event_sources, records: [{ id: current.id, name: current.name, previous_sources: current.event_sources.length, selected_sources: input.event_sources.length }], complete: true, truncated: false, notes: ['This replaces the entire event-source list. Empty explicitly clears it. Shared matching and existing ads may be affected; no events are sent.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n if (op.provider !== 'reddit') throw new AdportError('INVALID_INPUT', 'Reddit catalog provider differs.');\n if (op.tool === 'reddit_set_catalog_access' && op.kind === 'update') {\n const store = this.manager(), input = permissionChange.parse(op.payload), scope = permissionResource({ ...input, account_id: op.accountId }), before = await store.get(scope);if (before.hash !== input.expected_access_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog access changed. Read and review it again.');\n const creation = scope.kind === 'catalog_creation';let subject = creation ? 'New catalogs' : input.catalog_id!;\n if (input.mode !== 'none') { const business = await this.business(input.business_id);subject = creation ? business.name : (await this.native({ account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id! }))!.name; }\n const notes = ['Changes Adport project access, not Reddit native user permissions. Native Business/catalog eligibility remains authoritative.', 'Creation delegates management of verified new catalog IDs only. Existing catalogs require separate grants. Revoking creation leaves existing catalog grants independent.'];\n return { summary: `${input.mode === 'none' ? 'Revoke' : 'Grant'} Reddit catalog access · ${subject}`, changes: [`~ Project access ${before.mode} → ${input.mode} for Business ${input.business_id}, ${creation ? 'new catalogs only' : 'catalog ' + input.catalog_id}`], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'reddit', accountId: op.accountId, kind: 'update', title: input.mode === 'none' ? 'Revoke catalog access' : creation ? 'Delegate catalog creation' : 'Grant catalog access', subject, fields: [{ label: 'Business', after: input.business_id }, { label: 'Resource', after: creation ? 'Verified new catalogs only' : input.catalog_id }, { label: 'Project access', before: before.mode, after: input.mode === 'create' ? 'Create and manage new catalogs' : input.mode }], notices: notes },\n execute: async () => { const result = await store.compareAndSet(scope, input.expected_access_hash, input.mode), actual = await store.get(scope);if (catalogScopeKey(result.scope) !== catalogScopeKey(scope) || result.mode !== input.mode || actual.hash !== result.hash) throw new AdportError('POLICY_VIOLATION', 'Catalog access receipt could not be confirmed.');return [scope.resourceId]; } };\n }\n if (op.tool === 'reddit_create_catalog' && op.kind === 'create') {\n const input = catalogCreate.parse(op.payload), selection = { account_id: op.accountId, business_id: input.business_id }, store = this.store;if (!store?.adoptCreated) throw new AdportError('NOT_CONNECTED', 'This runtime cannot adopt independently verified new catalogs.');\n const prepare = async () => { await requireCatalogCreationAccess(store, creationScope(op.accountId, input.business_id), true);const context = await this.creationContext({ ...selection, event_sources: input.event_sources });if (context.expected_creation_access_hash !== input.expected_creation_access_hash || context.expected_event_sources_hash !== input.expected_event_sources_hash) throw new AdportError('PENDING_MISMATCH', 'Creation delegation or selected sources changed. Read context and request a new preview.'); };\n await prepare();const data = { name: input.name, default_currency: input.default_currency, default_language: input.default_language, event_sources: input.event_sources }, notes = ['Creates an empty Business catalog. No products, ads, spend or conversion events are submitted.', 'Default currency/language are not patchable through the current catalog endpoint. Project write access is adopted only for this verified new native ID.', 'Native creation and project access are not atomic. Reconcile a known ID after uncertain creation/readback/adoption; never replay automatically.'];\n return { summary: `Create Reddit catalog \"${input.name}\"`, changes: ['+ Catalog ' + canonical(data), '+ Project read/write access for the verified new ID only'], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'reddit', accountId: op.accountId, kind: 'create', title: 'Create catalog', subject: input.name, fields: [{ label: 'Business', after: input.business_id }, { label: 'Default currency', after: input.default_currency }, { label: 'Default language', after: input.default_language }, { label: 'Event-source Pixels', after: input.event_sources.join(', ') || 'None' }, { label: 'New catalog project access', after: 'Read and write' }], notices: notes },\n execute: async () => { await prepare();let id: string | undefined;try {\n const raw = (await this.client.post<unknown>(`businesses/${encodeURIComponent(input.business_id)}/product_catalogs`, { data })).data, knownId = z.object({ id: redditCatalogId }).safeParse(raw);if (knownId.success) id = knownId.data.id;\n const receipt = nativeCatalog.parse(raw);id = receipt.id;if (receipt.business_id !== input.business_id) throw invalid();\n await requireCatalogCreationAccess(store, creationScope(op.accountId, input.business_id), true);const actual = await this.native({ ...selection, catalog_id: id });if (!actual || canonical(config(actual)) !== canonical({ id, business_id: input.business_id, ...data, event_sources: [...data.event_sources].sort() })) throw new Error('Creation readback differs');\n const adopted = await store.adoptCreated!({ accountId: op.accountId, businessId: input.business_id, resourceId: id, kind: 'catalog' }, input.expected_creation_access_hash);if (adopted.mode !== 'write' || adopted.scope.resourceId !== id || adopted.scope.businessId !== input.business_id || adopted.scope.accountId !== op.accountId || adopted.scope.kind !== 'catalog') throw new Error('Adoption receipt differs');return [id];\n } catch (error) { throw failure(error, 'Reddit catalog creation or project adoption is unconfirmed. Reconcile known IDs before another create.', id ? [id] : undefined); } } };\n }\n const rename = op.tool === 'reddit_rename_catalog', sources = op.tool === 'reddit_set_catalog_event_sources', remove = op.tool === 'reddit_delete_catalog';\n if (!(rename && op.kind === 'update' || sources && op.kind === 'update' || remove && op.kind === 'remove')) throw new AdportError('INVALID_INPUT', 'Unsupported Reddit catalog operation or kind.');\n const input = rename ? catalogRename.parse(op.payload) : sources ? catalogSources.parse(op.payload) : catalogDelete.parse(op.payload), scope: Scope = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id };\n const prepare = async () => { const current = await this.parent(scope, true);if (configurationHash(scope, current) !== input.expected_configuration_hash || 'confirm_catalog_name' in input && current.name !== input.confirm_catalog_name) throw new AdportError('PENDING_MISMATCH', 'Catalog configuration/name changed. Read and preview again.');if (!remove && !current.event_sources) throw new AdportError('PROVIDER_ERROR', 'Current event sources are unavailable; preservation cannot be verified.');if ('expected_event_sources_hash' in input && await this.selectedSources(scope, input.event_sources) !== input.expected_event_sources_hash) throw new AdportError('PENDING_MISMATCH', 'Selected event sources changed. Request a fresh preview.');return current; };\n const current = await prepare(), data = 'name' in input ? { name: input.name } : 'event_sources' in input ? { event_sources: input.event_sources } : {}, title = rename ? 'Rename catalog' : sources ? 'Replace catalog event sources' : 'Delete catalog permanently', notes = remove ? ['Permanently removes the entire shared catalog and affects its current contents/consumers. Contents are not enumerated or frozen by this configuration snapshot.', 'Checks native acknowledgement and exact lookup absence. Other errors are not absence; no restore/global usage guarantee or automatic replay. Project grants remain separate owner settings.'] : ['Changes a shared Business catalog; other accounts/ads may be affected. Unselected configuration is checked after the write.', ...(sources ? ['Replaces the entire event-source list, including clearing it when explicitly empty. Selected Pixel IDs are checked under this ad account. No conversion events are sent.'] : []), 'No automatic write replay; reconcile the known catalog after any uncertain result.'];\n return { summary: `${title} \"${current.name}\"`, changes: [remove ? '- Entire catalog ' + current.id + ' and its current contents' : '~ Catalog configuration ' + canonical(data)], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'reddit', accountId: op.accountId, kind: remove ? 'remove' : 'update', title, subject: current.name, fields: [{ label: 'Catalog', after: current.id }, { label: 'Business', after: current.business_id }, ...(rename ? [{ label: 'Name', before: current.name, after: (input as z.infer<typeof catalogRename>).name }] : sources ? [{ label: 'Event-source Pixels', before: current.event_sources!.join(', ') || 'None', after: (input as z.infer<typeof catalogSources>).event_sources.join(', ') || 'None' }] : [{ label: 'Contents affected', after: 'Entire catalog; contents not enumerated or frozen' }])], notices: notes },\n execute: async () => { const fresh = await prepare();try {\n if (remove) { const receipt = await this.client.delete<unknown>(`product_catalogs/${encodeURIComponent(current.id)}`);if (receipt.data === null || typeof receipt.data !== 'object' || Array.isArray(receipt.data)) throw new Error('Unexpected deletion acknowledgement');await requireCatalogAccess(this.store, resource(scope), true);if (await this.native(scope, true)) throw new Error('Catalog remains visible'); }\n else { const receipt = nativeCatalog.parse((await this.client.patch<unknown>(`product_catalogs/${encodeURIComponent(current.id)}`, { data })).data);if (receipt.id !== current.id || receipt.business_id !== scope.business_id) throw invalid();await requireCatalogAccess(this.store, resource(scope), true);const actual = await this.native(scope), expected = config({ ...fresh, ...data });if (!actual || canonical(config(actual)) !== canonical(expected)) throw new Error('Catalog preservation readback differs'); }\n return [current.id];\n } catch (error) { throw failure(error, 'Reddit catalog mutation or independent preservation/absence readback is unconfirmed. Inspect the known catalog before another write.', [current.id]); } } };\n }\n}\n","import { z } from 'zod';\nimport { redditCatalogId, redditBusinessId } from './catalog-access.js';\nexport const hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const catalogInput = z.object({ account_id: redditCatalogId, business_id: redditBusinessId, catalog_id: redditCatalogId }).strict();\nexport const creationInput = catalogInput.omit({ catalog_id: true });\nexport const sourceIds = z.array(redditCatalogId.max(50)).max(100).refine(ids => new Set(ids).size === ids.length, 'Pixel IDs must be unique');\nexport const sourceContext = catalogInput.extend({ event_sources: sourceIds }).strict();\nexport const creationContext = creationInput.extend({ event_sources: sourceIds.default([]) }).strict();\nexport const catalogCreate = z.object({ business_id: redditBusinessId, name: z.string().min(1).max(200), default_language: z.enum(['en', 'de', 'es', 'fr', 'it', 'pt']), default_currency: z.enum(['USD', 'GBP', 'CAD', 'EUR', 'AUD', 'JPY', 'CHF', 'NZD', 'SEK', 'NOK', 'BRL']), event_sources: sourceIds.default([]), expected_creation_access_hash: hash, expected_event_sources_hash: hash, acknowledge_new_catalog_management: z.literal(true) }).strict();\nexport const catalogRename = catalogInput.omit({ account_id: true }).extend({ name: z.string().min(1).max(200), expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true) }).strict();\nexport const catalogSources = catalogInput.omit({ account_id: true }).extend({ event_sources: sourceIds, expected_configuration_hash: hash, expected_event_sources_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_measurement_effects: z.literal(true) }).strict();\nexport const catalogDelete = catalogInput.omit({ account_id: true }).extend({ expected_configuration_hash: hash, confirm_catalog_name: z.string().min(1).max(200), acknowledge_shared_effects: z.literal(true), acknowledge_delete_contents: z.literal(true) }).strict();\nexport const permissionSelection = z.object({ account_id: redditCatalogId, business_id: redditBusinessId, catalog_id: redditCatalogId.optional(), resource_kind: z.enum(['catalog', 'catalog_creation']).optional() }).strict();\nexport const validPermission = (input: { catalog_id?: string; resource_kind?: string; mode?: string }) => input.resource_kind === 'catalog_creation' ? !input.catalog_id && (!input.mode || ['none', 'create'].includes(input.mode)) : !!input.catalog_id && input.mode !== 'create';\nexport const permissionSnapshot = permissionSelection.refine(validPermission, 'Choose an exact catalog or creation delegation without a catalog ID');\nexport const permissionChange = permissionSelection.omit({ account_id: true }).extend({ mode: z.enum(['none', 'read', 'write', 'create']), expected_access_hash: hash }).strict().refine(validPermission, 'Choose catalog read/write/none or new-catalog create/none access');\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsClient, RedditEnvelope } from './client.js';\nimport type { RedditCatalogService } from './catalogs.js';\nimport { redditCatalogId } from './catalog-access.js';\nimport { catalogInput } from './catalog-schemas.js';\nimport { productId, productList, setProductList, setInput, setList, setCreate, setUpdate, setDelete, importInput, importList, importIssues, validFilter } from './catalog-content-schemas.js';\n\ntype Scope = z.infer<typeof catalogInput>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\ntype Client = Pick<RedditAdsClient, 'get' | 'post' | 'patch' | 'delete' | 'nextUrl' | 'diagnostic'>;\nconst scope = (input: Scope): Scope => ({ account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id });\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst filterValue = (value: string) => { try { return JSON.parse(value) as unknown; } catch { return value; } };\nfunction filterText(value: string) {\n if (!validFilter(value)) return value;\n const labels: Record<string, string> = { contains: 'contains', not_contains: 'does not contain', i_contains: 'contains (case insensitive)', i_not_contains: 'does not contain (case insensitive)', starts_with: 'starts with', i_starts_with: 'starts with (case insensitive)', is_any: 'matches any of', is_not_any: 'matches none of', i_is_any: 'matches any of (case insensitive)', i_is_not_any: 'matches none of (case insensitive)', eq: 'equals', neq: 'does not equal', lt: 'is less than', lte: 'is at most', gt: 'is greater than', gte: 'is at least' };\n const text = (item: Record<string, unknown>): string => { const [key, condition] = Object.entries(item)[0]!;if (key === 'and' || key === 'or') return (key === 'and' ? 'All conditions' : 'Any condition') + ': (' + (condition as Record<string, unknown>[]).map(text).join('; ') + ')';const [operator, operand] = Object.entries(condition as Record<string, unknown>)[0]!;return key.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase()) + ' ' + labels[operator] + ' ' + (Array.isArray(operand) ? operand.join(', ') : String(operand)); };\n return text(JSON.parse(value));\n}\nconst count = z.number().int().nonnegative().safe();\nconst setRow = z.object({ id: redditCatalogId, catalog_id: redditCatalogId, name: z.string().min(1).max(100), filter: z.string().max(65_536), summary: z.object({ products_count: count.optional(), approved_products_count: count.nullable().optional(), rejected_products_count: count.nullable().optional(), invalid_products_count: count.nullable().optional() }).optional() });\ntype ProductSet = z.infer<typeof setRow>;\nconst setConfig = (row: ProductSet) => ({ id: row.id, catalog_id: row.catalog_id, name: row.name, filter: filterValue(row.filter) });\nconst setHash = (input: Scope, row: ProductSet) => digest({ ...scope(input), configuration: setConfig(row) });\nconst issueRow = z.object({ field: z.string().max(1000).nullable().optional(), severity: z.enum(['WARNING', 'CRITICAL']), code: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/), message: z.string().max(40_000).optional() });\nconst productRow = z.object({ id: productId, title: z.string().max(40_000).nullable().optional(), description: z.string().max(40_000).nullable().optional(), price: z.string().max(256).optional(), link: z.string().max(8192).optional(), image_link: z.string().max(8192).optional(), item_group_id: z.string().max(1000).nullable().optional(), brand: z.string().max(4000).nullable().optional(), availability: z.enum(['BACKORDER', 'IN_STOCK', 'OUT_OF_STOCK', 'PREORDER']).nullable().optional(), reddit: z.object({ id: redditCatalogId.optional(), catalog_id: redditCatalogId, image_link: z.string().max(8192).nullable().optional(), approval_decision: z.enum(['PENDING', 'APPROVED', 'REJECTED']).optional(), issues: z.array(issueRow).max(1000).nullable().optional() }) });\nconst importRow = z.object({ id: redditCatalogId, catalog_id: redditCatalogId, feed_id: redditCatalogId.optional(), filename: z.string().max(4000).optional(), status: z.enum(['PENDING', 'PROCESSING', 'COMPLETED', 'FAILED', 'SKIPPED']), summary: z.object({ added_products_count: count.nullable().optional(), modified_products_count: count.nullable().optional(), deleted_products_count: count.nullable().optional(), invalid_products_count: count.nullable().optional() }).nullable().optional() });\nconst nativePage = z.object({ next_url: z.string().url().max(8192).nullable().optional() });\nfunction failure(error: unknown, message: string, ids?: string[]) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n return new AdportError('PROVIDER_ERROR', message + ' No native mutation was retried; provider bodies stay hidden.', { ...(Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}), ...(ids ? { resourceIds: ids } : {}) });\n}\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'Reddit catalog child scope or response shape could not be verified.');\nfunction safeUrl(value: string | null | undefined, image = false) {\n try { const url = new URL(value!);if (!(image ? url.protocol === 'https:' && /\\.(redd\\.it|redditmedia\\.com|redditstatic\\.com)$/.test(url.hostname) : ['https:', 'http:'].includes(url.protocol)) || url.username || url.password) return;return url.href; } catch { return; }\n}\n\n/** Catalog grants cover children only after independent native parent/catalog verification. */\nexport class RedditCatalogContentService {\n constructor(private readonly client: Client, private readonly catalogs: RedditCatalogService) {}\n private async request(path: string, absent = false): Promise<RedditEnvelope<unknown> | undefined> {\n try { return await this.client.get<unknown>(path); } catch (error) {\n if (absent && error instanceof AdportError && (error.details as Record<string, unknown> | undefined)?.http_status === 404) return;\n throw failure(error, 'Reddit catalog content read failed.');\n }\n }\n private url(path: string, params: Record<string, string | number | string[] | undefined> = {}) {\n const url = new URL('https://ads-api.reddit.com/api/v3/' + path);\n for (const [key, value] of Object.entries(params)) if (Array.isArray(value)) value.forEach(item => url.searchParams.append(key, item));else if (value !== undefined) url.searchParams.set(key, String(value));\n return url.href;\n }\n private async page<T>(path: string, params: Record<string, string | number | string[] | undefined>, schema: z.ZodType<T>, cursor?: string) {\n const first = this.url(path, params), current = cursor ? this.client.nextUrl(cursor, first) : first, response = (await this.request(current))!, parsed = z.array(schema).max(1000).safeParse(response.data), pagination = nativePage.safeParse(response.pagination);\n if (!parsed.success || !pagination.success || parsed.data.length > Number(params['page.size'])) throw invalid();\n const next = pagination.data.next_url ? this.client.nextUrl(pagination.data.next_url, first) : undefined;if (next === current) throw new AdportError('PROVIDER_ERROR', 'Reddit catalog pagination did not advance.');\n return { rows: parsed.data, next_cursor: next, truncated: !!next, complete: !next };\n }\n private async set(input: z.infer<typeof setInput>, absent = false) {\n const response = await this.request('product_sets/' + encodeURIComponent(input.product_set_id), absent);if (!response && absent) return;\n const parsed = setRow.safeParse(response?.data);if (!parsed.success || parsed.data.id !== input.product_set_id || parsed.data.catalog_id !== input.catalog_id) throw invalid();return parsed.data;\n }\n async sets(value: unknown) {\n const input = setList.parse(value);await this.catalogs.authorize(scope(input));const result = await this.page('product_catalogs/' + encodeURIComponent(input.catalog_id) + '/product_sets', { 'page.size': input.page_size }, setRow, input.cursor);\n if (result.rows.some(row => row.catalog_id !== input.catalog_id) || new Set(result.rows.map(row => row.id)).size !== result.rows.length) throw invalid();\n return { product_sets: result.rows.map(row => ({ ...row, configuration_hash: setHash(input, row) })), records: result.rows.map(row => ({ id: row.id, name: row.name, filter: filterText(row.filter), products: row.summary?.products_count })), next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete };\n }\n async getSet(value: unknown) {\n const input = setInput.parse(value);await this.catalogs.authorize(scope(input));const row = (await this.set(input))!;\n return { product_set: { ...row, configuration_hash: setHash(input, row) }, records: [{ id: row.id, name: row.name, filter: filterText(row.filter), products: row.summary?.products_count }], complete: true, truncated: false, notes: ['The hash binds the exact account/Business/catalog/set configuration, excluding volatile product counts. Project access is checked separately. Set membership can change independently.'] };\n }\n async products(value: unknown, inSet = false) {\n const selectedSet = inSet ? setProductList.parse(value) : undefined, input = selectedSet ?? productList.parse(value);await this.catalogs.authorize(scope(input));\n if (selectedSet) await this.set(selectedSet);\n const path = selectedSet ? 'product_sets/' + encodeURIComponent(selectedSet.product_set_id) + '/products' : 'product_catalogs/' + encodeURIComponent(input.catalog_id) + '/products', result = await this.page(path, { 'page.size': input.page_size, ids: input.ids, approval_decision: input.approval_decision, search: input.search, issue_code: selectedSet?.issue_code }, productRow, input.cursor);\n if (result.rows.some(row => row.reddit.catalog_id !== input.catalog_id || input.ids && !input.ids.includes(row.id)) || new Set(result.rows.map(row => row.id)).size !== result.rows.length) throw invalid();\n const products = result.rows.map(row => ({ ...row, link: safeUrl(row.link), image_link: safeUrl(row.image_link), reddit: { ...row.reddit, image_link: safeUrl(row.reddit.image_link), issues: row.reddit.issues?.map(issue => ({ ...issue, message: this.client.diagnostic(issue.message) })) } }));\n const creatives: Creative[] = products.map(row => { const image = safeUrl(row.reddit.image_link, true), landing = safeUrl(row.link);return { id: row.id, provider: 'reddit', account_id: input.account_id, name: row.title ?? row.id, type: 'CATALOG_PRODUCT', status: row.reddit.approval_decision, headlines: row.title ? [row.title] : [], descriptions: [row.description, row.price, row.brand, row.availability].filter((v): v is string => typeof v === 'string'), landing_urls: landing ? [landing] : [], media: image ? [{ type: 'image', url: image, alt: row.id }] : [], actions: [] }; });\n return { products, creatives, next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete, notes: ['Native product IDs and supplied filters are preserved. Missing titles/descriptions or approval/count fields remain unavailable. Only Reddit-hosted native preview images are embedded; merchant hosts are not added to widget CSP.'] };\n }\n async imports(value: unknown) {\n const input = importList.parse(value);await this.catalogs.authorize(scope(input));const result = await this.page('product_catalogs/' + encodeURIComponent(input.catalog_id) + '/catalog_imports', { 'page.size': input.page_size, feed_ids: input.feed_ids, statuses: input.statuses?.join(',') }, importRow, input.cursor);\n if (result.rows.some(row => row.catalog_id !== input.catalog_id || input.feed_ids && (!row.feed_id || !input.feed_ids.includes(row.feed_id)) || input.statuses && !input.statuses.includes(row.status)) || new Set(result.rows.map(row => row.id)).size !== result.rows.length) throw invalid();\n return { imports: result.rows, records: result.rows.map(row => ({ id: row.id, name: row.filename ?? 'Catalog import', status: row.status, feed_id: row.feed_id, ...row.summary })), next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete };\n }\n private async selectedImport(input: z.infer<typeof importInput>) {\n await this.catalogs.authorize(scope(input));let cursor: string | undefined;const seen = new Set<string>(), ids = new Set<string>();\n for (let pages = 0; pages < 10; pages++) {\n const result = await this.page('product_catalogs/' + encodeURIComponent(input.catalog_id) + '/catalog_imports', { 'page.size': 1000 }, importRow, cursor);\n if (result.rows.some(row => row.catalog_id !== input.catalog_id || ids.has(row.id)) || new Set(result.rows.map(row => row.id)).size !== result.rows.length) throw invalid();result.rows.forEach(row => ids.add(row.id));\n const selected = result.rows.find(row => row.id === input.import_id);if (selected) return selected;\n if (!result.next_cursor) throw new AdportError('INVALID_INPUT', 'The import is not in this catalog.');\n if (seen.has(result.next_cursor)) throw invalid();seen.add(result.next_cursor);cursor = result.next_cursor;\n }\n throw new AdportError('PROVIDER_ERROR', 'Selected import membership was not established within the 10,000-row verification bound. Narrow catalog access or inspect native import history.');\n }\n async issues(value: unknown) {\n const input = importIssues.parse(value);await this.selectedImport(input);const schema = issueRow.extend({ id: redditCatalogId, import_id: redditCatalogId, line: count.nullable().optional(), product_id: productId.nullable().optional() }), result = await this.page('catalog_imports/' + encodeURIComponent(input.import_id) + '/issues', { 'page.size': input.page_size, code: input.code }, schema, input.cursor);\n if (result.rows.some(row => row.import_id !== input.import_id || input.code && row.code !== input.code) || new Set(result.rows.map(row => row.id)).size !== result.rows.length) throw invalid();\n const issues = result.rows.map(row => ({ ...row, message: this.client.diagnostic(row.message) }));return { issues, records: issues.map(row => ({ ...row, name: row.code })), next_cursor: result.next_cursor, truncated: result.truncated, complete: result.complete };\n }\n async report(value: unknown) {\n const input = importInput.parse(value);await this.selectedImport(input);const result = (await this.request('catalog_imports/' + encodeURIComponent(input.import_id) + '/report'))!, raw = result.data;\n if (raw && typeof raw === 'object' && !Array.isArray(raw) && Object.keys(raw).length === 0) return { report_available: false, records: [{ id: input.import_id, name: 'Import report unavailable' }], notes: ['The native response supplied no report. This is not evidence that the import has no issues.'] };\n const parsed = z.object({ url: z.string().url().max(8192), expires_at: z.iso.datetime({ offset: true }) }).safeParse(raw);if (!parsed.success || !safeUrl(parsed.data.url) || new URL(parsed.data.url).protocol !== 'https:' || Date.parse(parsed.data.expires_at) <= Date.now()) throw invalid();\n return { report_available: true, import_id: input.import_id, download_url: parsed.data.url, expires_at: parsed.data.expires_at, records: [{ id: input.import_id, name: 'Catalog import report', expires_at: parsed.data.expires_at }], notes: ['Temporary native download URL for this verified catalog/import only. Adport does not fetch it or forward Reddit credentials to its host.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'reddit_create_catalog_product_set', update = op.tool === 'reddit_update_catalog_product_set', remove = op.tool === 'reddit_delete_catalog_product_set';\n if (op.provider !== 'reddit' || !(create && op.kind === 'create' || update && op.kind === 'update' || remove && op.kind === 'remove')) throw new AdportError('INVALID_INPUT', 'Unsupported catalog product-set operation/kind.');\n const input = create ? setCreate.parse(op.payload) : update ? setUpdate.parse(op.payload) : setDelete.parse(op.payload), selected: Scope = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id };\n const prepare = async () => {\n const parent = await this.catalogs.authorize(selected, true);\n if ('expected_catalog_configuration_hash' in input) { if (parent.configuration_hash !== input.expected_catalog_configuration_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog configuration changed; read it and preview again.');return; }\n const current = (await this.set({ ...selected, product_set_id: input.product_set_id }))!;if (setHash(selected, current) !== input.expected_configuration_hash || 'confirm_name' in input && current.name !== input.confirm_name) throw new AdportError('PENDING_MISMATCH', 'Product-set configuration/name changed; read and preview again.');return current;\n };\n const current = await prepare(), data = { ...('name' in input && input.name !== undefined ? { name: input.name } : {}), ...('filter' in input && input.filter !== undefined ? { filter: input.filter } : {}) }, title = create ? 'Create product set' : update ? 'Update product set' : 'Delete product set permanently', notes = ['This is a shared Business catalog; set membership and ads using it may be affected. No ads, spend or conversion events are submitted.', ...(remove ? ['Deletes the set definition, not a snapshot of products. Dependent ads and current matching membership are not enumerated or frozen. No native restore/global usage guarantee.'] : ['Filter JSON is sent once as the native string. Omitted set configuration is preserved and independently checked after updates.']), 'Native results are never replayed automatically. Reconcile known IDs after uncertain mutation or readback.'];\n return { summary: `${title} · ${'name' in input && input.name !== undefined ? input.name : current!.name}`, changes: [remove ? '- Product set ' + current!.id : (create ? '+ ' : '~ ') + 'Product set ' + canonical(data)], coercions: [], budgetDeltas: [], notes,\n review: { provider: 'reddit', accountId: op.accountId, kind: op.kind, title, subject: 'name' in input && input.name !== undefined ? input.name : current!.name, fields: [{ label: 'Catalog', after: input.catalog_id }, { label: 'Business', after: input.business_id }, ...(!create ? [{ label: 'Product set', after: current!.id }] : []), ...('name' in data ? [{ label: 'Name', before: current?.name, after: data.name }] : []), ...('filter' in data ? [{ label: 'Filter', before: current ? filterText(current.filter) : undefined, after: filterText(data.filter!) }] : []), ...(remove ? [{ label: 'Definition removed', after: filterText(current!.filter) }] : [])], notices: notes },\n execute: async () => { const fresh = await prepare();let id = current?.id;try {\n if (remove) { const response = await this.client.delete<unknown>('product_sets/' + encodeURIComponent(id!));if (!response.data || typeof response.data !== 'object' || Array.isArray(response.data)) throw invalid();await this.catalogs.authorize(selected, true);if (await this.set({ ...selected, product_set_id: id! }, true)) throw invalid(); }\n else {\n const raw = create ? (await this.client.post<unknown>('product_catalogs/' + encodeURIComponent(input.catalog_id) + '/product_sets', { data })).data : (await this.client.patch<unknown>('product_sets/' + encodeURIComponent(id!), { data })).data, known = z.object({ id: redditCatalogId }).safeParse(raw);if (create && known.success) id = known.data.id;\n const receipt = setRow.safeParse(raw);if (!receipt.success || receipt.data.id !== id || receipt.data.catalog_id !== input.catalog_id) throw invalid();await this.catalogs.authorize(selected, true);\n const actual = (await this.set({ ...selected, product_set_id: id! }))!, expected = create ? { id: id!, catalog_id: input.catalog_id, name: (input as z.infer<typeof setCreate>).name, filter: (input as z.infer<typeof setCreate>).filter } : { ...fresh!, ...data };\n if (canonical(setConfig(actual)) !== canonical(setConfig(expected))) throw invalid();\n }\n return [id!];\n } catch (error) { throw failure(error, 'Product-set mutation or independent preservation/absence readback is unconfirmed.', id ? [id] : undefined); } } };\n }\n}\n","import { z } from 'zod';\nimport { catalogInput, hash } from './catalog-schemas.js';\nimport { redditCatalogId } from './catalog-access.js';\n\nexport const productId = z.string().min(1).max(128).regex(/^[^\\x00-\\x1f\\x7f]+$/);\nexport const page = { page_size: z.number().int().positive().max(1000).default(20), cursor: z.string().url().max(8192).optional() };\nexport const setInput = catalogInput.extend({ product_set_id: redditCatalogId }).strict();\nexport const setList = catalogInput.extend(page).strict();\nexport const productFilters = { ids: z.array(productId).min(1).max(100).refine(ids => new Set(ids).size === ids.length).optional(), approval_decision: z.enum(['PENDING', 'APPROVED', 'REJECTED']).optional(), search: z.string().min(1).max(100).optional() };\nexport const productList = catalogInput.extend({ ...page, ...productFilters }).strict();\nexport const setProductList = setInput.extend({ ...page, ...productFilters, issue_code: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/).optional() }).strict();\nconst attributes = new Set(['id', 'title', 'description', 'price', 'currency', 'sale_price', 'availability', 'brand', 'color', 'gender', 'product_type', 'item_group_id', 'condition', 'age_group', 'size', 'pattern', 'material', 'custom_label_0', 'custom_label_1', 'custom_label_2', 'custom_label_3', 'custom_label_4']);\nconst operators = new Set(['contains', 'not_contains', 'i_contains', 'i_not_contains', 'starts_with', 'i_starts_with', 'eq', 'neq', 'lt', 'lte', 'gt', 'gte']);\nconst arrayOperators = new Set(['is_any', 'is_not_any', 'i_is_any', 'i_is_not_any']);\n/** Native filter is a JSON string. Validate its documented grammar without evaluating it. */\nexport function validFilter(value: string) {\n let nodes = 0;\n const visit = (item: unknown, depth: number): boolean => {\n if (++nodes > 500 || depth > 8 || !item || typeof item !== 'object' || Array.isArray(item)) return false;\n const entries = Object.entries(item);if (entries.length !== 1) return false;\n const [key, condition] = entries[0]!;\n if (key === 'and' || key === 'or') return Array.isArray(condition) && condition.length > 0 && condition.length <= 100 && condition.every(child => visit(child, depth + 1));\n if (!attributes.has(key) || !condition || typeof condition !== 'object' || Array.isArray(condition)) return false;\n const checks = Object.entries(condition);if (checks.length !== 1) return false;\n const [operator, operand] = checks[0]!;\n return operators.has(operator) ? typeof operand === 'string' && operand.length > 0 && operand.length <= 4000 : arrayOperators.has(operator) && Array.isArray(operand) && operand.length > 0 && operand.length <= 100 && operand.every(v => typeof v === 'string' && v.length > 0 && v.length <= 4000);\n };\n try { return visit(JSON.parse(value), 0); } catch { return false; }\n}\nexport const setFilter = z.string().min(2).max(65_536).refine(value => Buffer.byteLength(value, 'utf8') <= 65_536, 'Filter JSON must not exceed 64 KiB in UTF-8').refine(validFilter, 'Use the documented Reddit product-filter JSON grammar');\nexport const setCreate = catalogInput.omit({ account_id: true }).extend({ name: z.string().min(1).max(100), filter: setFilter, expected_catalog_configuration_hash: hash, acknowledge_shared_effects: z.literal(true) }).strict();\nexport const setUpdate = setInput.omit({ account_id: true }).extend({ name: z.string().min(1).max(100).optional(), filter: setFilter.optional(), expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true) }).strict().refine(input => input.name !== undefined || input.filter !== undefined, 'Provide a name or filter');\nexport const setDelete = setInput.omit({ account_id: true }).extend({ expected_configuration_hash: hash, confirm_name: z.string().min(1).max(100), acknowledge_shared_effects: z.literal(true), acknowledge_remove_set: z.literal(true) }).strict();\nexport const importInput = catalogInput.extend({ import_id: redditCatalogId }).strict();\nexport const importList = catalogInput.extend({ ...page, feed_ids: z.array(redditCatalogId).min(1).max(100).refine(ids => new Set(ids).size === ids.length).optional(), statuses: z.array(z.enum(['PENDING', 'PROCESSING', 'COMPLETED', 'FAILED', 'SKIPPED'])).min(1).max(5).refine(values => new Set(values).size === values.length).optional() }).strict();\nexport const importIssues = importInput.extend({ ...page, code: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/).optional() }).strict();\n","import { createHash } from 'node:crypto';\nimport { AdportError, type ReviewField, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsClient } from './client.js';\nimport type { RedditCatalogService } from './catalogs.js';\nimport { redditCatalogId } from './catalog-access.js';\nimport { catalogInput } from './catalog-schemas.js';\nimport { feedInput, feedList, feedCreate, feedUpdate, feedStatus, feedDelete, feedSchedule, feedMode } from './catalog-feed-schemas.js';\n\ntype Scope = z.infer<typeof catalogInput>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\nconst nativeSchedule = z.object({ is_paused: z.boolean().nullable().optional(), interval: z.enum(['HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY']).nullable().optional(), interval_count: z.number().int().positive().safe().nullable().optional(), day_of_month: z.number().int().min(1).max(31).nullable().optional(), day_of_week: z.enum(['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']).nullable().optional(), hour: z.number().int().min(0).max(23).nullable().optional(), minute: z.number().int().min(0).max(59).nullable().optional(), timezone: z.string().max(128).nullable().optional(), next_import_at: z.iso.datetime({ offset: true }).nullable().optional() }).strict();\nconst feedRow = z.object({ id: redditCatalogId, catalog_id: redditCatalogId, name: z.string().min(1).max(4000).nullable().optional(), url: z.string().min(1).max(8192), mode: feedMode, schedule: nativeSchedule.nullable().optional(), username: z.string().max(100).nullable().optional(), password: z.string().max(100).nullable().optional() });\ntype Feed = z.infer<typeof feedRow>;\nconst scope = (input: Scope): Scope => ({ account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id });\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nfunction scheduleConfig(value: Feed['schedule']) {\n if (value === null || value === undefined) return value;\n const { next_import_at: _volatile, ...config } = value;return { ...config, day_of_month: config.day_of_month ?? null, day_of_week: config.day_of_week ?? null };\n}\nconst config = (row: Feed) => ({ id: row.id, catalog_id: row.catalog_id, name: row.name, url: row.url, mode: row.mode, schedule: scheduleConfig(row.schedule) });\nconst configurationHash = (input: Scope, row: Feed) => digest({ ...scope(input), configuration: config(row) });\nconst origin = (value: string) => { try { const url = new URL(value);return url.protocol + '//' + url.host; } catch { return 'Unavailable'; } };\nfunction secrets(row?: Pick<Feed, 'url' | 'username' | 'password'>) {\n if (!row) return [];const values = [row.url, row.username, row.password].filter((value): value is string => typeof value === 'string' && value.length > 0);\n try { const url = new URL(row.url);for (const value of url.searchParams.values()) if (value) values.push(value);for (const entry of url.search.slice(1).split('&')) { const value = entry.slice(entry.indexOf('=') + 1);if (entry.includes('=') && value) values.push(value); } } catch { /* Unreadable native sources still remain private. */ }\n return values;\n}\nfunction redact(text: string, values: string[]) {\n const alternatives = [...new Set(values)].filter(Boolean).sort((a, b) => b.length - a.length).map(value => value.replace(/[\\\\^$.*+?()[\\]{}|]/g, '\\\\$&'));\n return alternatives.length ? text.replace(new RegExp(alternatives.join('|'), 'g'), '[redacted]') : text;\n}\nfunction publicValue(value: unknown, privateValues: string[]): unknown {\n if (typeof value === 'string') return redact(value, privateValues);\n if (Array.isArray(value)) return value.map(item => publicValue(item, privateValues));\n if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, publicValue(item, privateValues)]));\n return value;\n}\nfunction publicFeed(input: Scope, row: Feed) {\n const privateValues = secrets(row);\n return { feed_id: row.id, catalog_id: row.catalog_id, name: row.name == null ? row.name : redact(row.name, privateValues), mode: row.mode, source_origin: redact(origin(row.url), privateValues), source_fingerprint: digest(row.url), schedule: row.schedule === undefined ? undefined : row.schedule === null ? null : { ...scheduleConfig(row.schedule), timezone: row.schedule.timezone == null ? row.schedule.timezone : redact(row.schedule.timezone, privateValues), next_import_at: row.schedule.next_import_at }, configuration_hash: configurationHash(input, row), authentication_values_reported: false };\n}\nconst notes = ['This shared feed can change products used by existing ads. No ads, spend or conversion events are submitted by this operation.', 'Choose native REPLACE or UPDATE explicitly. Feed processing can change shared catalog products; native import results and downstream effects require separate inspection.', 'Source URLs/authentication are private in tool results and widget approval metadata. Source, authentication and name changes must be applied by the agent with the identical arguments.', 'Authentication values are not independently verified by native reads. Configuration hashes exclude them and cannot detect authentication-only changes.', 'Source lifetime and successful ingestion are not established by configuration readback. A short-lived private upload URL is unsuitable for an ongoing recurring feed.', 'Source fingerprints identify the URL, not immutable feed bytes. Approval binds the URL/configuration; remote source contents can change between imports.', 'Never replay a native write automatically. Reconcile known IDs after uncertain mutation or readback.'];\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'Reddit feed identifier, catalog scope or native configuration could not be verified.');\nfunction failure(error: unknown, message: string, ids?: string[]) { const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};return new AdportError('PROVIDER_ERROR', message + ' Provider bodies and source credentials stay hidden; no mutation was retried.', { ...(Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}), ...(ids ? { resourceIds: ids } : {}) }); }\nfunction knownSchedule(value: Feed['schedule']) {\n if (value === null) return null;if (value === undefined) throw new AdportError('PROVIDER_ERROR', 'Current feed schedule is unavailable; preservation cannot be verified.');\n const parsed = feedSchedule.safeParse(scheduleConfig(value));if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'Current feed schedule is incomplete or unsupported; read native configuration before changing it.');return parsed.data;\n}\n\n/** Native unpaged feeds with exact catalog grants and private source handling. */\nexport class RedditCatalogFeeds {\n constructor(private readonly client: Pick<RedditAdsClient, 'get' | 'post' | 'patch' | 'delete'>, private readonly catalogs: RedditCatalogService) {}\n private async native(input: Scope, id?: string, absent = false) {\n const path = id ? 'product_feeds/' + encodeURIComponent(id) : 'product_catalogs/' + encodeURIComponent(input.catalog_id) + '/product_feeds';let response;\n try { response = await this.client.get<unknown>(path); } catch (error) { if (absent && error instanceof AdportError && (error.details as Record<string, unknown> | undefined)?.http_status === 404) return [];throw failure(error, 'Reddit catalog feed read failed.'); }\n const parsed = (id ? feedRow.transform(value => [value]) : z.array(feedRow).max(5000)).safeParse(response.data);\n if (!parsed.success || response.pagination?.next_url || parsed.data.some(row => row.catalog_id !== input.catalog_id || id && row.id !== id) || new Set(parsed.data.map(row => row.id)).size !== parsed.data.length) throw invalid();return parsed.data;\n }\n async list(value: unknown) {\n const input = feedList.parse(value);await this.catalogs.authorize(scope(input));const rows = (await this.native(input)).sort((a, b) => a.id.localeCompare(b.id)), snapshot = digest({ ...scope(input), page_size: input.page_size, feeds: rows.map(config) });let offset = 0;\n if (input.cursor) { let parsed;try { parsed = z.object({ offset: z.number().int().positive().max(4999), snapshot: z.string().regex(/^[a-f0-9]{64}$/) }).strict().parse(JSON.parse(Buffer.from(input.cursor, 'base64url').toString('utf8'))); } catch { throw new AdportError('INVALID_INPUT', 'Invalid feed cursor; refresh the first page.'); }if (parsed.snapshot !== snapshot || parsed.offset >= rows.length || parsed.offset % input.page_size !== 0) throw new AdportError('PENDING_MISMATCH', 'Feed configuration or selection changed; refresh the first page.');offset = parsed.offset; }\n const feeds = rows.slice(offset, offset + input.page_size).map(row => publicFeed(input, row)), more = offset + feeds.length < rows.length;\n return { feeds, records: feeds.map(row => ({ id: row.feed_id, name: row.name ?? 'Feed ' + row.feed_id, mode: row.mode, source: row.source_origin, schedule: row.schedule === undefined ? 'Unavailable' : row.schedule === null ? 'No recurring schedule' : row.schedule.is_paused === true ? 'Paused' : row.schedule.is_paused === false ? 'Running' : 'Unavailable' })), complete: !more, truncated: more, ...(more ? { next_cursor: Buffer.from(JSON.stringify({ offset: offset + feeds.length, snapshot })).toString('base64url') } : {}), notes: ['Native feed lists are unpaged. Adport bounds them to 5,000 and pages a configuration snapshot locally; this is not a product inventory.', ...notes.slice(2, 5)] };\n }\n async get(value: unknown) { const input = feedInput.parse(value);await this.catalogs.authorize(scope(input));const feed = publicFeed(input, (await this.native(input, input.feed_id))[0]!);return { feed, records: [{ id: feed.feed_id, name: feed.name ?? 'Feed ' + feed.feed_id, mode: feed.mode, source: feed.source_origin }], complete: true, truncated: false, notes: notes.slice(2, 5) }; }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'reddit_create_catalog_feed', update = op.tool === 'reddit_update_catalog_feed', toggle = op.tool === 'reddit_set_catalog_feed_schedule_status', remove = op.tool === 'reddit_delete_catalog_feed';\n if (op.provider !== 'reddit' || !(create && op.kind === 'create' || (update || toggle) && op.kind === 'update' || remove && op.kind === 'remove')) throw new AdportError('INVALID_INPUT', 'Reddit feed operation/provider kind mismatch.');\n const input = create ? feedCreate.parse(op.payload) : update ? feedUpdate.parse(op.payload) : toggle ? feedStatus.parse(op.payload) : feedDelete.parse(op.payload), selected = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id };\n const prepare = async () => {\n const parent = await this.catalogs.authorize(selected, true);\n if ('expected_catalog_configuration_hash' in input) { if (parent.configuration_hash !== input.expected_catalog_configuration_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog configuration changed; read and preview again.');return; }\n const current = (await this.native(selected, input.feed_id))[0]!;if (configurationHash(selected, current) !== input.expected_configuration_hash) throw new AdportError('PENDING_MISMATCH', 'Feed configuration changed; read and preview again.');\n if (!remove) { const schedule = knownSchedule(current.schedule);if ('is_paused' in input && (schedule === null || schedule.is_paused === input.is_paused)) throw new AdportError('INVALID_INPUT', 'A configured schedule must change to its opposite pause state.'); }\n return current;\n };\n const before = await prepare(), data: Record<string, unknown> = {};\n const writable = new Set(['name', 'url', 'mode', 'schedule', 'username', 'password']);\n for (const [key, value] of Object.entries(input)) if (writable.has(key) && value !== undefined) data[key] = value;\n if ('is_paused' in input) data.schedule = { ...knownSchedule(before!.schedule)!, is_paused: input.is_paused };\n const privateValues = [...secrets(before), ...secrets({ url: 'url' in input ? input.url ?? '' : '', username: 'username' in input ? input.username : undefined, password: 'password' in input ? input.password : undefined })], display = (value: string) => redact(value, privateValues), fields: ReviewField[] = [{ label: 'Catalog', after: input.catalog_id }, { label: 'Business', after: input.business_id }];\n if (before) fields.push({ label: 'Feed', after: before.id });\n if ('name' in data) fields.push({ label: 'Name', before: before?.name == null ? before?.name : display(before.name), after: data.name === null ? 'Cleared' : display(String(data.name)) });\n if ('url' in data) fields.push({ label: 'Source', ...(before ? { before: { origin: display(origin(before.url)), fingerprint: digest(before.url) } } : {}), after: { origin: display(origin(String(data.url))), fingerprint: digest(String(data.url)) } });\n if ('mode' in data) fields.push({ label: 'Product processing', ...(before ? { before: before.mode } : {}), after: data.mode });\n if ('username' in data || 'password' in data) fields.push({ label: 'Source authentication', after: { username: 'username' in data ? data.username === null ? 'Cleared' : 'Supplied; hidden' : 'Preserved', password: 'password' in data ? data.password === null ? 'Cleared' : 'Supplied; hidden' : 'Preserved' } });\n if ('schedule' in data) fields.push({ label: 'Schedule', ...(before ? { before: scheduleConfig(before.schedule) } : {}), after: data.schedule === null ? 'No recurring schedule' : data.schedule });\n if (remove) fields.push({ label: 'Feed removed', before: before!.name == null ? 'Feed ' + before!.id : display(before!.name), after: 'Permanently deleted' });\n const title = create ? 'Create catalog feed' : remove ? 'Delete catalog feed permanently' : toggle ? 'Change feed schedule status' : 'Update catalog feed', subject = 'name' in input && typeof input.name === 'string' ? display(input.name) : before?.name == null ? create ? 'New catalog feed' : 'Feed ' + before!.id : display(before.name), safeFields = publicValue(fields, privateValues) as ReviewField[];\n const notices = [notes[0]!];\n if (remove) notices.push('Permanently removes the shared feed definition. Imported products and dependent ads are not enumerated or frozen; their effects require separate inspection.', 'No restore or automatic write replay is available. Reconcile the known feed after an uncertain result.');\n else if (toggle) notices.push('Pausing controls future scheduling; this does not certify cancellation or reversal of an existing import.');\n else {\n if (['url', 'mode', 'schedule', 'username', 'password'].some(key => key in data)) notices.push('The selected changes may start native product processing immediately. Configuration readback does not certify source authentication, successful ingestion or product retention.');\n if (['url', 'name', 'username', 'password'].some(key => key in data)) notices.push('Private source/name arguments stay with the agent. Review in chat, then ask it to apply the identical arguments.');\n if ('url' in data) notices.push('The fingerprint identifies the URL, not immutable feed bytes. The source can change between imports and must remain available for its intended schedule.');\n }\n return { summary: title + ' · ' + subject, changes: safeFields.map(field => (remove ? '- ' : create ? '+ ' : '~ ') + field.label + ': ' + canonical(field.after)), coercions: [], budgetDeltas: [], notes: notices,\n review: { provider: 'reddit', accountId: op.accountId, kind: op.kind, title, subject, fields: safeFields, notices },\n execute: async () => { const fresh = await prepare();let id = before?.id;try {\n if (remove) { const receipt = await this.client.delete<unknown>('product_feeds/' + encodeURIComponent(id!));if (!receipt.data || typeof receipt.data !== 'object' || Array.isArray(receipt.data)) throw invalid();await this.catalogs.authorize(selected, true);if ((await this.native(selected, id, true)).length) throw invalid(); }\n else {\n const raw = create ? (await this.client.post<unknown>('product_catalogs/' + encodeURIComponent(input.catalog_id) + '/product_feeds', { data })).data : (await this.client.patch<unknown>('product_feeds/' + encodeURIComponent(id!), { data })).data, known = z.object({ id: redditCatalogId }).safeParse(raw);if (create && known.success) id = known.data.id;\n const receipt = feedRow.safeParse(raw);if (!receipt.success || receipt.data.id !== id || receipt.data.catalog_id !== input.catalog_id) throw invalid();await this.catalogs.authorize(selected, true);const actual = (await this.native(selected, id))[0]!;\n const expected = create ? { id: id!, catalog_id: input.catalog_id, name: 'name' in data ? data.name : actual.name, url: data.url, mode: data.mode, schedule: data.schedule } : { ...fresh!, ...data };\n if (canonical(config(actual)) !== canonical(config(feedRow.parse(expected)))) throw invalid();\n }\n return { applied: true, resourceIds: [id!], ...('username' in data || 'password' in data ? { details: { authentication_readback_verified: false }, warnings: ['Native configuration was read back; source authentication and ingestion success were not independently verified.'] } : {}) };\n } catch (error) { throw failure(error, 'Reddit feed mutation or independent configuration/absence readback is unconfirmed. Reconcile known IDs before another write.', id ? [id] : undefined); } } };\n }\n}\n","import { z } from 'zod';\nimport { catalogInput, hash } from './catalog-schemas.js';\nimport { redditCatalogId } from './catalog-access.js';\nimport { REDDIT_CATALOG_TIMEZONES } from './catalog-feed-timezones.js';\n\nconst timezone = z.string().min(1).max(128).refine(value => REDDIT_CATALOG_TIMEZONES.has(value), 'Use a time zone from Reddit’s published IANA list');\nexport const sourceUrl = z.string().min(1).max(8192).refine(value => {\n try { const url = new URL(value), host = url.hostname.toLowerCase().replace(/\\.$/, '');return ['https:', 'ftp:', 'sftp:'].includes(url.protocol) && !url.username && !url.password && !url.hash && !/[\\x00-\\x20\\x7f]/.test(value) && host.includes('.') && !/[^\\w.-]/.test(host) && !/^[\\d.]+$/.test(host) && !['.local', '.localhost', '.internal'].some(suffix => host.endsWith(suffix)); } catch { return false; }\n}, 'Use an externally hosted HTTPS, FTP or SFTP URL without embedded credentials, whitespace or a fragment');\nexport const feedMode = z.enum(['REPLACE', 'UPDATE']);\nexport const feedSchedule = z.object({\n is_paused: z.boolean(), interval: z.enum(['HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY']),\n interval_count: z.number().int().positive().safe(), hour: z.number().int().min(0).max(23), minute: z.number().int().min(0).max(59),\n timezone, day_of_month: z.number().int().min(1).max(31).nullable().optional(),\n day_of_week: z.enum(['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY']).nullable().optional(),\n}).strict().superRefine((input, ctx) => {\n if (input.interval === 'MONTHLY' ? input.day_of_month == null : input.day_of_month != null) ctx.addIssue({ code: 'custom', path: ['day_of_month'], message: 'Choose a day_of_month only for a monthly schedule' });\n if (input.interval === 'WEEKLY' ? input.day_of_week == null : input.day_of_week != null) ctx.addIssue({ code: 'custom', path: ['day_of_week'], message: 'Choose a day_of_week only for a weekly schedule' });\n});\nexport const feedInput = catalogInput.extend({ feed_id: redditCatalogId }).strict();\nexport const feedList = catalogInput.extend({ page_size: z.number().int().min(1).max(100).default(20), cursor: z.string().min(1).max(512).optional() }).strict();\nconst name = z.string().min(1).max(4000).nullable(), authentication = { username: z.string().max(100).nullable().optional(), password: z.string().max(100).nullable().optional() };\nconst selected = feedInput.omit({ account_id: true });\nexport const feedCreate = catalogInput.omit({ account_id: true }).extend({\n name: name.optional(), url: sourceUrl, mode: feedMode, schedule: feedSchedule.nullable(), ...authentication,\n expected_catalog_configuration_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_automatic_processing: z.literal(true),\n}).strict();\nexport const feedUpdate = selected.extend({\n name: name.optional(), url: sourceUrl.optional(), mode: feedMode.optional(), schedule: feedSchedule.nullable().optional(), ...authentication,\n expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_automatic_processing: z.literal(true).optional(),\n}).strict().refine(input => ['name', 'url', 'mode', 'schedule', 'username', 'password'].some(key => Object.hasOwn(input, key)), 'Provide a feed field')\n .refine(input => !['url', 'mode', 'schedule', 'username', 'password'].some(key => Object.hasOwn(input, key)) || input.acknowledge_automatic_processing === true, 'Source/mode/schedule/authentication changes require automatic-processing acknowledgement');\nexport const feedStatus = selected.extend({ is_paused: z.boolean(), expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_automatic_processing: z.literal(true) }).strict();\nexport const feedDelete = selected.extend({ expected_configuration_hash: hash, acknowledge_shared_effects: z.literal(true), acknowledge_delete_feed: z.literal(true) }).strict();\n","// Reddit v3 published time-zone choices, refreshed 2026-11-05.\n// https://ads-api.reddit.com/api/v3/openapi.json\n// Refine against this set without inflating every MCP input schema with 596 values.\nexport const REDDIT_CATALOG_TIMEZONES: ReadonlySet<string> = new Set([\n \"Africa/Abidjan\",\n \"Africa/Accra\",\n \"Africa/Addis_Ababa\",\n \"Africa/Algiers\",\n \"Africa/Asmara\",\n \"Africa/Asmera\",\n \"Africa/Bamako\",\n \"Africa/Bangui\",\n \"Africa/Banjul\",\n \"Africa/Bissau\",\n \"Africa/Blantyre\",\n \"Africa/Brazzaville\",\n \"Africa/Bujumbura\",\n \"Africa/Cairo\",\n \"Africa/Casablanca\",\n \"Africa/Ceuta\",\n \"Africa/Conakry\",\n \"Africa/Dakar\",\n \"Africa/Dar_es_Salaam\",\n \"Africa/Djibouti\",\n \"Africa/Douala\",\n \"Africa/El_Aaiun\",\n \"Africa/Freetown\",\n \"Africa/Gaborone\",\n \"Africa/Harare\",\n \"Africa/Johannesburg\",\n \"Africa/Juba\",\n \"Africa/Kampala\",\n \"Africa/Khartoum\",\n \"Africa/Kigali\",\n \"Africa/Kinshasa\",\n \"Africa/Lagos\",\n \"Africa/Libreville\",\n \"Africa/Lome\",\n \"Africa/Luanda\",\n \"Africa/Lubumbashi\",\n \"Africa/Lusaka\",\n \"Africa/Malabo\",\n \"Africa/Maputo\",\n \"Africa/Maseru\",\n \"Africa/Mbabane\",\n \"Africa/Mogadishu\",\n \"Africa/Monrovia\",\n \"Africa/Nairobi\",\n \"Africa/Ndjamena\",\n \"Africa/Niamey\",\n \"Africa/Nouakchott\",\n \"Africa/Ouagadougou\",\n \"Africa/Porto-Novo\",\n \"Africa/Sao_Tome\",\n \"Africa/Timbuktu\",\n \"Africa/Tripoli\",\n \"Africa/Tunis\",\n \"Africa/Windhoek\",\n \"America/Adak\",\n \"America/Anchorage\",\n \"America/Anguilla\",\n \"America/Antigua\",\n \"America/Araguaina\",\n \"America/Argentina/Buenos_Aires\",\n \"America/Argentina/Catamarca\",\n \"America/Argentina/ComodRivadavia\",\n \"America/Argentina/Cordoba\",\n \"America/Argentina/Jujuy\",\n \"America/Argentina/La_Rioja\",\n \"America/Argentina/Mendoza\",\n \"America/Argentina/Rio_Gallegos\",\n \"America/Argentina/Salta\",\n \"America/Argentina/San_Juan\",\n \"America/Argentina/San_Luis\",\n \"America/Argentina/Tucuman\",\n \"America/Argentina/Ushuaia\",\n \"America/Aruba\",\n \"America/Asuncion\",\n \"America/Atikokan\",\n \"America/Atka\",\n \"America/Bahia\",\n \"America/Bahia_Banderas\",\n \"America/Barbados\",\n \"America/Belem\",\n \"America/Belize\",\n \"America/Blanc-Sablon\",\n \"America/Boa_Vista\",\n \"America/Bogota\",\n \"America/Boise\",\n \"America/Buenos_Aires\",\n \"America/Cambridge_Bay\",\n \"America/Campo_Grande\",\n \"America/Cancun\",\n \"America/Caracas\",\n \"America/Catamarca\",\n \"America/Cayenne\",\n \"America/Cayman\",\n \"America/Chicago\",\n \"America/Chihuahua\",\n \"America/Ciudad_Juarez\",\n \"America/Coral_Harbour\",\n \"America/Cordoba\",\n \"America/Costa_Rica\",\n \"America/Creston\",\n \"America/Cuiaba\",\n \"America/Curacao\",\n \"America/Danmarkshavn\",\n \"America/Dawson\",\n \"America/Dawson_Creek\",\n \"America/Denver\",\n \"America/Detroit\",\n \"America/Dominica\",\n \"America/Edmonton\",\n \"America/Eirunepe\",\n \"America/El_Salvador\",\n \"America/Ensenada\",\n \"America/Fort_Nelson\",\n \"America/Fort_Wayne\",\n \"America/Fortaleza\",\n \"America/Glace_Bay\",\n \"America/Godthab\",\n \"America/Goose_Bay\",\n \"America/Grand_Turk\",\n \"America/Grenada\",\n \"America/Guadeloupe\",\n \"America/Guatemala\",\n \"America/Guayaquil\",\n \"America/Guyana\",\n \"America/Halifax\",\n \"America/Havana\",\n \"America/Hermosillo\",\n \"America/Indiana/Indianapolis\",\n \"America/Indiana/Knox\",\n \"America/Indiana/Marengo\",\n \"America/Indiana/Petersburg\",\n \"America/Indiana/Tell_City\",\n \"America/Indiana/Vevay\",\n \"America/Indiana/Vincennes\",\n \"America/Indiana/Winamac\",\n \"America/Indianapolis\",\n \"America/Inuvik\",\n \"America/Iqaluit\",\n \"America/Jamaica\",\n \"America/Jujuy\",\n \"America/Juneau\",\n \"America/Kentucky/Louisville\",\n \"America/Kentucky/Monticello\",\n \"America/Knox_IN\",\n \"America/Kralendijk\",\n \"America/La_Paz\",\n \"America/Lima\",\n \"America/Los_Angeles\",\n \"America/Louisville\",\n \"America/Lower_Princes\",\n \"America/Maceio\",\n \"America/Managua\",\n \"America/Manaus\",\n \"America/Marigot\",\n \"America/Martinique\",\n \"America/Matamoros\",\n \"America/Mazatlan\",\n \"America/Mendoza\",\n \"America/Menominee\",\n \"America/Merida\",\n \"America/Metlakatla\",\n \"America/Mexico_City\",\n \"America/Miquelon\",\n \"America/Moncton\",\n \"America/Monterrey\",\n \"America/Montevideo\",\n \"America/Montreal\",\n \"America/Montserrat\",\n \"America/Nassau\",\n \"America/New_York\",\n \"America/Nipigon\",\n \"America/Nome\",\n \"America/Noronha\",\n \"America/North_Dakota/Beulah\",\n \"America/North_Dakota/Center\",\n \"America/North_Dakota/New_Salem\",\n \"America/Nuuk\",\n \"America/Ojinaga\",\n \"America/Panama\",\n \"America/Pangnirtung\",\n \"America/Paramaribo\",\n \"America/Phoenix\",\n \"America/Port-au-Prince\",\n \"America/Port_of_Spain\",\n \"America/Porto_Acre\",\n \"America/Porto_Velho\",\n \"America/Puerto_Rico\",\n \"America/Punta_Arenas\",\n \"America/Rainy_River\",\n \"America/Rankin_Inlet\",\n \"America/Recife\",\n \"America/Regina\",\n \"America/Resolute\",\n \"America/Rio_Branco\",\n \"America/Rosario\",\n \"America/Santa_Isabel\",\n \"America/Santarem\",\n \"America/Santiago\",\n \"America/Santo_Domingo\",\n \"America/Sao_Paulo\",\n \"America/Scoresbysund\",\n \"America/Shiprock\",\n \"America/Sitka\",\n \"America/St_Barthelemy\",\n \"America/St_Johns\",\n \"America/St_Kitts\",\n \"America/St_Lucia\",\n \"America/St_Thomas\",\n \"America/St_Vincent\",\n \"America/Swift_Current\",\n \"America/Tegucigalpa\",\n \"America/Thule\",\n \"America/Thunder_Bay\",\n \"America/Tijuana\",\n \"America/Toronto\",\n \"America/Tortola\",\n \"America/Vancouver\",\n \"America/Virgin\",\n \"America/Whitehorse\",\n \"America/Winnipeg\",\n \"America/Yakutat\",\n \"America/Yellowknife\",\n \"Antarctica/Casey\",\n \"Antarctica/Davis\",\n \"Antarctica/DumontDUrville\",\n \"Antarctica/Macquarie\",\n \"Antarctica/Mawson\",\n \"Antarctica/McMurdo\",\n \"Antarctica/Palmer\",\n \"Antarctica/Rothera\",\n \"Antarctica/South_Pole\",\n \"Antarctica/Syowa\",\n \"Antarctica/Troll\",\n \"Antarctica/Vostok\",\n \"Arctic/Longyearbyen\",\n \"Asia/Aden\",\n \"Asia/Almaty\",\n \"Asia/Amman\",\n \"Asia/Anadyr\",\n \"Asia/Aqtau\",\n \"Asia/Aqtobe\",\n \"Asia/Ashgabat\",\n \"Asia/Ashkhabad\",\n \"Asia/Atyrau\",\n \"Asia/Baghdad\",\n \"Asia/Bahrain\",\n \"Asia/Baku\",\n \"Asia/Bangkok\",\n \"Asia/Barnaul\",\n \"Asia/Beirut\",\n \"Asia/Bishkek\",\n \"Asia/Brunei\",\n \"Asia/Calcutta\",\n \"Asia/Chita\",\n \"Asia/Choibalsan\",\n \"Asia/Chongqing\",\n \"Asia/Chungking\",\n \"Asia/Colombo\",\n \"Asia/Dacca\",\n \"Asia/Damascus\",\n \"Asia/Dhaka\",\n \"Asia/Dili\",\n \"Asia/Dubai\",\n \"Asia/Dushanbe\",\n \"Asia/Famagusta\",\n \"Asia/Gaza\",\n \"Asia/Harbin\",\n \"Asia/Hebron\",\n \"Asia/Ho_Chi_Minh\",\n \"Asia/Hong_Kong\",\n \"Asia/Hovd\",\n \"Asia/Irkutsk\",\n \"Asia/Istanbul\",\n \"Asia/Jakarta\",\n \"Asia/Jayapura\",\n \"Asia/Jerusalem\",\n \"Asia/Kabul\",\n \"Asia/Kamchatka\",\n \"Asia/Karachi\",\n \"Asia/Kashgar\",\n \"Asia/Kathmandu\",\n \"Asia/Katmandu\",\n \"Asia/Khandyga\",\n \"Asia/Kolkata\",\n \"Asia/Krasnoyarsk\",\n \"Asia/Kuala_Lumpur\",\n \"Asia/Kuching\",\n \"Asia/Kuwait\",\n \"Asia/Macao\",\n \"Asia/Macau\",\n \"Asia/Magadan\",\n \"Asia/Makassar\",\n \"Asia/Manila\",\n \"Asia/Muscat\",\n \"Asia/Nicosia\",\n \"Asia/Novokuznetsk\",\n \"Asia/Novosibirsk\",\n \"Asia/Omsk\",\n \"Asia/Oral\",\n \"Asia/Phnom_Penh\",\n \"Asia/Pontianak\",\n \"Asia/Pyongyang\",\n \"Asia/Qatar\",\n \"Asia/Qostanay\",\n \"Asia/Qyzylorda\",\n \"Asia/Rangoon\",\n \"Asia/Riyadh\",\n \"Asia/Saigon\",\n \"Asia/Sakhalin\",\n \"Asia/Samarkand\",\n \"Asia/Seoul\",\n \"Asia/Shanghai\",\n \"Asia/Singapore\",\n \"Asia/Srednekolymsk\",\n \"Asia/Taipei\",\n \"Asia/Tashkent\",\n \"Asia/Tbilisi\",\n \"Asia/Tehran\",\n \"Asia/Tel_Aviv\",\n \"Asia/Thimbu\",\n \"Asia/Thimphu\",\n \"Asia/Tokyo\",\n \"Asia/Tomsk\",\n \"Asia/Ujung_Pandang\",\n \"Asia/Ulaanbaatar\",\n \"Asia/Ulan_Bator\",\n \"Asia/Urumqi\",\n \"Asia/Ust-Nera\",\n \"Asia/Vientiane\",\n \"Asia/Vladivostok\",\n \"Asia/Yakutsk\",\n \"Asia/Yangon\",\n \"Asia/Yekaterinburg\",\n \"Asia/Yerevan\",\n \"Atlantic/Azores\",\n \"Atlantic/Bermuda\",\n \"Atlantic/Canary\",\n \"Atlantic/Cape_Verde\",\n \"Atlantic/Faeroe\",\n \"Atlantic/Faroe\",\n \"Atlantic/Jan_Mayen\",\n \"Atlantic/Madeira\",\n \"Atlantic/Reykjavik\",\n \"Atlantic/South_Georgia\",\n \"Atlantic/St_Helena\",\n \"Atlantic/Stanley\",\n \"Australia/ACT\",\n \"Australia/Adelaide\",\n \"Australia/Brisbane\",\n \"Australia/Broken_Hill\",\n \"Australia/Canberra\",\n \"Australia/Currie\",\n \"Australia/Darwin\",\n \"Australia/Eucla\",\n \"Australia/Hobart\",\n \"Australia/LHI\",\n \"Australia/Lindeman\",\n \"Australia/Lord_Howe\",\n \"Australia/Melbourne\",\n \"Australia/NSW\",\n \"Australia/North\",\n \"Australia/Perth\",\n \"Australia/Queensland\",\n \"Australia/South\",\n \"Australia/Sydney\",\n \"Australia/Tasmania\",\n \"Australia/Victoria\",\n \"Australia/West\",\n \"Australia/Yancowinna\",\n \"Brazil/Acre\",\n \"Brazil/DeNoronha\",\n \"Brazil/East\",\n \"Brazil/West\",\n \"CET\",\n \"CST6CDT\",\n \"Canada/Atlantic\",\n \"Canada/Central\",\n \"Canada/Eastern\",\n \"Canada/Mountain\",\n \"Canada/Newfoundland\",\n \"Canada/Pacific\",\n \"Canada/Saskatchewan\",\n \"Canada/Yukon\",\n \"Chile/Continental\",\n \"Chile/EasterIsland\",\n \"Cuba\",\n \"EET\",\n \"EST\",\n \"EST5EDT\",\n \"Egypt\",\n \"Eire\",\n \"Etc/GMT\",\n \"Etc/GMT+0\",\n \"Etc/GMT+1\",\n \"Etc/GMT+10\",\n \"Etc/GMT+11\",\n \"Etc/GMT+12\",\n \"Etc/GMT+2\",\n \"Etc/GMT+3\",\n \"Etc/GMT+4\",\n \"Etc/GMT+5\",\n \"Etc/GMT+6\",\n \"Etc/GMT+7\",\n \"Etc/GMT+8\",\n \"Etc/GMT+9\",\n \"Etc/GMT-0\",\n \"Etc/GMT-1\",\n \"Etc/GMT-10\",\n \"Etc/GMT-11\",\n \"Etc/GMT-12\",\n \"Etc/GMT-13\",\n \"Etc/GMT-14\",\n \"Etc/GMT-2\",\n \"Etc/GMT-3\",\n \"Etc/GMT-4\",\n \"Etc/GMT-5\",\n \"Etc/GMT-6\",\n \"Etc/GMT-7\",\n \"Etc/GMT-8\",\n \"Etc/GMT-9\",\n \"Etc/GMT0\",\n \"Etc/Greenwich\",\n \"Etc/UCT\",\n \"Etc/UTC\",\n \"Etc/Universal\",\n \"Etc/Zulu\",\n \"Europe/Amsterdam\",\n \"Europe/Andorra\",\n \"Europe/Astrakhan\",\n \"Europe/Athens\",\n \"Europe/Belfast\",\n \"Europe/Belgrade\",\n \"Europe/Berlin\",\n \"Europe/Bratislava\",\n \"Europe/Brussels\",\n \"Europe/Bucharest\",\n \"Europe/Budapest\",\n \"Europe/Busingen\",\n \"Europe/Chisinau\",\n \"Europe/Copenhagen\",\n \"Europe/Dublin\",\n \"Europe/Gibraltar\",\n \"Europe/Guernsey\",\n \"Europe/Helsinki\",\n \"Europe/Isle_of_Man\",\n \"Europe/Istanbul\",\n \"Europe/Jersey\",\n \"Europe/Kaliningrad\",\n \"Europe/Kiev\",\n \"Europe/Kirov\",\n \"Europe/Kyiv\",\n \"Europe/Lisbon\",\n \"Europe/Ljubljana\",\n \"Europe/London\",\n \"Europe/Luxembourg\",\n \"Europe/Madrid\",\n \"Europe/Malta\",\n \"Europe/Mariehamn\",\n \"Europe/Minsk\",\n \"Europe/Monaco\",\n \"Europe/Moscow\",\n \"Europe/Nicosia\",\n \"Europe/Oslo\",\n \"Europe/Paris\",\n \"Europe/Podgorica\",\n \"Europe/Prague\",\n \"Europe/Riga\",\n \"Europe/Rome\",\n \"Europe/Samara\",\n \"Europe/San_Marino\",\n \"Europe/Sarajevo\",\n \"Europe/Saratov\",\n \"Europe/Simferopol\",\n \"Europe/Skopje\",\n \"Europe/Sofia\",\n \"Europe/Stockholm\",\n \"Europe/Tallinn\",\n \"Europe/Tirane\",\n \"Europe/Tiraspol\",\n \"Europe/Ulyanovsk\",\n \"Europe/Uzhgorod\",\n \"Europe/Vaduz\",\n \"Europe/Vatican\",\n \"Europe/Vienna\",\n \"Europe/Vilnius\",\n \"Europe/Volgograd\",\n \"Europe/Warsaw\",\n \"Europe/Zagreb\",\n \"Europe/Zaporozhye\",\n \"Europe/Zurich\",\n \"GB\",\n \"GB-Eire\",\n \"GMT\",\n \"GMT+0\",\n \"GMT-0\",\n \"GMT0\",\n \"Greenwich\",\n \"HST\",\n \"Hongkong\",\n \"Iceland\",\n \"Indian/Antananarivo\",\n \"Indian/Chagos\",\n \"Indian/Christmas\",\n \"Indian/Cocos\",\n \"Indian/Comoro\",\n \"Indian/Kerguelen\",\n \"Indian/Mahe\",\n \"Indian/Maldives\",\n \"Indian/Mauritius\",\n \"Indian/Mayotte\",\n \"Indian/Reunion\",\n \"Iran\",\n \"Israel\",\n \"Jamaica\",\n \"Japan\",\n \"Kwajalein\",\n \"Libya\",\n \"MET\",\n \"MST\",\n \"MST7MDT\",\n \"Mexico/BajaNorte\",\n \"Mexico/BajaSur\",\n \"Mexico/General\",\n \"NZ\",\n \"NZ-CHAT\",\n \"Navajo\",\n \"PRC\",\n \"PST8PDT\",\n \"Pacific/Apia\",\n \"Pacific/Auckland\",\n \"Pacific/Bougainville\",\n \"Pacific/Chatham\",\n \"Pacific/Chuuk\",\n \"Pacific/Easter\",\n \"Pacific/Efate\",\n \"Pacific/Enderbury\",\n \"Pacific/Fakaofo\",\n \"Pacific/Fiji\",\n \"Pacific/Funafuti\",\n \"Pacific/Galapagos\",\n \"Pacific/Gambier\",\n \"Pacific/Guadalcanal\",\n \"Pacific/Guam\",\n \"Pacific/Honolulu\",\n \"Pacific/Johnston\",\n \"Pacific/Kanton\",\n \"Pacific/Kiritimati\",\n \"Pacific/Kosrae\",\n \"Pacific/Kwajalein\",\n \"Pacific/Majuro\",\n \"Pacific/Marquesas\",\n \"Pacific/Midway\",\n \"Pacific/Nauru\",\n \"Pacific/Niue\",\n \"Pacific/Norfolk\",\n \"Pacific/Noumea\",\n \"Pacific/Pago_Pago\",\n \"Pacific/Palau\",\n \"Pacific/Pitcairn\",\n \"Pacific/Pohnpei\",\n \"Pacific/Ponape\",\n \"Pacific/Port_Moresby\",\n \"Pacific/Rarotonga\",\n \"Pacific/Saipan\",\n \"Pacific/Samoa\",\n \"Pacific/Tahiti\",\n \"Pacific/Tarawa\",\n \"Pacific/Tongatapu\",\n \"Pacific/Truk\",\n \"Pacific/Wake\",\n \"Pacific/Wallis\",\n \"Pacific/Yap\",\n \"Poland\",\n \"Portugal\",\n \"ROC\",\n \"ROK\",\n \"Singapore\",\n \"Turkey\",\n \"UCT\",\n \"US/Alaska\",\n \"US/Aleutian\",\n \"US/Arizona\",\n \"US/Central\",\n \"US/East-Indiana\",\n \"US/Eastern\",\n \"US/Hawaii\",\n \"US/Indiana-Starke\",\n \"US/Michigan\",\n \"US/Mountain\",\n \"US/Pacific\",\n \"US/Samoa\",\n \"UTC\",\n \"Universal\",\n \"W-SU\",\n \"WET\",\n \"Zulu\"\n]);\n","import { createHash } from 'node:crypto';\nimport { z } from 'zod';\nimport { AdportError, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport type { RedditAdsClient } from './client.js';\nimport type { RedditCatalogService } from './catalogs.js';\nimport { redditCatalogId } from './catalog-access.js';\nimport { catalogInput } from './catalog-schemas.js';\nimport { catalogProduct, completeCatalogProduct, productContext, productsCreate, productsUpdate, productsDelete } from './catalog-product-schemas.js';\nimport { productId } from './catalog-content-schemas.js';\n\ntype Scope = z.infer<typeof catalogInput>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\nconst nativeProduct = z.object({ id: productId, reddit: z.object({ id: redditCatalogId.optional(), catalog_id: redditCatalogId }).passthrough() }).catchall(z.json());\ntype Product = z.infer<typeof nativeProduct>;\nconst keys = new Set(Object.keys(catalogProduct.shape));\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst config = (row: Product) => Object.fromEntries(Object.entries(row).filter(([key]) => keys.has(key)));\nconst snapshot = (row: Product) => ({ ...config(row), reddit_id: row.reddit.id, created_at: row.created_at, modified_at: row.modified_at, unknown: Object.fromEntries(Object.entries(row).filter(([key]) => !keys.has(key) && !['reddit', 'created_at', 'modified_at'].includes(key))) });\nconst normalized = (row: Record<string, unknown>) => Object.fromEntries(Object.entries(row).filter(([, value]) => value != null));\nconst invalid = () => new AdportError('PROVIDER_ERROR', 'Reddit product selection scope, pagination or native receipt could not be verified.');\nconst notes = ['Products belong to a shared Business catalog. These changes can affect existing product sets and ads; no ads, spend or conversion events are submitted.', 'Native batch upsert has no conditional-write guarantee. Concurrent feed/product writers can race the final preflight; scheduled feeds can overwrite these changes or recreate deleted products.', 'Updates send all currently known writable fields, merged with the selected changes. Readback checks the complete known configuration. Unknown fields refuse an update; absent optional fields and null are equivalent only for verification.', 'There is no native server dry run or atomic batch guarantee. Partial or uncertain outcomes consume approval and are never replayed automatically. Reconcile each selected SKU before another preview.'];\n\nexport class RedditCatalogProducts {\n constructor(private readonly client: Pick<RedditAdsClient, 'get' | 'post' | 'nextUrl'>, private readonly catalogs: RedditCatalogService) {}\n private async selected(input: Scope, ids: string[]): Promise<Product[]> {\n const url = new URL('https://ads-api.reddit.com/api/v3/product_catalogs/' + encodeURIComponent(input.catalog_id) + '/products');\n url.searchParams.set('page.size', '1000');for (const id of ids) url.searchParams.append('ids', id);\n const first = url.href, seen = new Set<string>(), rows: Product[] = [];let current = first;\n for (let page = 0; page < 10; page++) {\n if (seen.has(current)) throw invalid();seen.add(current);\n const response = await this.client.get<unknown>(current), parsed = z.array(nativeProduct).max(1000).safeParse(response.data), pagination = z.object({ next_url: z.string().url().max(8192).nullable().optional() }).safeParse(response.pagination);\n if (!parsed.success || !pagination.success) throw invalid();\n for (const row of parsed.data) { if (row.reddit.catalog_id !== input.catalog_id || !ids.includes(row.id) || rows.some(previous => previous.id === row.id)) throw invalid();rows.push(row); }\n if (!pagination.data.next_url) return rows.sort((a, b) => a.id.localeCompare(b.id));\n const next = new URL(this.client.nextUrl(pagination.data.next_url, first)), nextIds = next.searchParams.getAll('ids');\n if ([...next.searchParams.keys()].some(key => !['ids', 'page.token', 'page.size'].includes(key)) || !next.searchParams.get('page.token') || nextIds.length && canonical([...nextIds].sort()) !== canonical([...ids].sort())) throw invalid();\n // Native cursors may omit filters: repeat the exact opaque SKUs on every page.\n next.searchParams.delete('ids');for (const id of ids) next.searchParams.append('ids', id);next.searchParams.set('page.size', '1000');current = next.href;\n }\n throw new AdportError('PROVIDER_ERROR', 'Reddit selected-product verification exceeded ten pages; missing SKUs cannot be inferred.');\n }\n private async selection(input: Scope, ids: string[], write = false) {\n const parent = await this.catalogs.authorize(input, write), products = await this.selected(input, ids);\n return { products, selection_hash: digest({ ...input, catalog_configuration_hash: parent.configuration_hash, product_ids: [...ids].sort(), products: products.map(snapshot) }) };\n }\n async context(value: unknown) {\n const input = productContext.parse(value), selected = { account_id: input.account_id, business_id: input.business_id, catalog_id: input.catalog_id }, result = await this.selection(selected, input.product_ids);\n return { selection_hash: result.selection_hash, records: input.product_ids.map(id => { const row = result.products.find(row => row.id === id);return { id, name: typeof row?.title === 'string' ? row.title : id, state: row ? 'Present' : 'Absent' }; }), products: result.products.map(row => ({ ...config(row), reddit_id: row.reddit.id })), missing_product_ids: input.product_ids.filter(id => !result.products.some(row => row.id === id)), complete: true, truncated: false, notes: ['External product SKUs are distinct from Reddit-assigned internal product IDs. The hash binds this exact account/Business/catalog and exhausted selected-product snapshot; it is not a frozen global inventory.', ...notes] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'reddit_create_catalog_products', update = op.tool === 'reddit_update_catalog_products', remove = op.tool === 'reddit_delete_catalog_products';\n if (op.provider !== 'reddit' || !(create && op.kind === 'create' || update && op.kind === 'update' || remove && op.kind === 'remove')) throw new AdportError('INVALID_INPUT', 'Reddit product operation/provider kind mismatch.');\n const input = create ? productsCreate.parse(op.payload) : update ? productsUpdate.parse(op.payload) : productsDelete.parse(op.payload), scope = { account_id: op.accountId, business_id: input.business_id, catalog_id: input.catalog_id }, ids = 'products' in input ? input.products.map(row => row.id) : input.product_ids;\n const prepare = async () => {\n const result = await this.selection(scope, ids, true);\n if (result.selection_hash !== input.expected_selection_hash) throw new AdportError('PENDING_MISMATCH', 'Catalog or selected products changed; read the product context and preview again.');\n if (create ? result.products.length !== 0 : result.products.length !== ids.length) throw new AdportError('INVALID_INPUT', create ? 'Create requires every selected SKU to be absent.' : 'Update/delete requires every selected external SKU to be present.');\n const products = 'products' in input ? input.products.map(row => {\n const before = result.products.find(previous => previous.id === row.id);\n if (before && Object.keys(before).some(key => !keys.has(key) && !['reddit', 'created_at', 'modified_at'].includes(key))) throw new AdportError('INVALID_INPUT', 'A selected product has unknown fields; its configuration cannot be preserved by this update.');\n return completeCatalogProduct.parse({ ...(before ? config(before) : {}), ...row });\n }) : [];\n if (Buffer.byteLength(JSON.stringify({ data: remove ? ids : products }), 'utf8') > 1_000_000) throw new AdportError('INVALID_INPUT', 'Product batch exceeds the 1 MB Adport bound; use a smaller selection.');\n return { before: result.products, products };\n };\n const initial = await prepare(), title = create ? 'Create catalog products' : update ? 'Update catalog products' : 'Delete catalog products permanently';\n return { summary: `${title} · ${ids.length} selected`, changes: ids.map(id => `${create ? '+' : remove ? '-' : '~'} Product ${id}`), coercions: [], budgetDeltas: [], notes,\n review: { provider: 'reddit', accountId: op.accountId, kind: op.kind, title, subject: `${ids.length} selected products`, fields: [{ label: 'Business', after: scope.business_id }, { label: 'Catalog', after: scope.catalog_id }, ...ids.map(id => ({ label: id, ...(create ? {} : { before: config(initial.before.find(row => row.id === id)!) }), after: remove ? 'Permanently deleted' : initial.products.find(row => row.id === id) }))], notices: notes },\n execute: async () => {\n const fresh = await prepare();let outcomes: Array<{ id?: string; status: string }> = [];\n try {\n const response = await this.client.post<unknown>('product_catalogs/' + encodeURIComponent(scope.catalog_id) + '/products/' + (remove ? 'batch_delete' : 'batch_upsert'), { data: remove ? ids : fresh.products });\n let receiptValid = false;\n if (remove) {\n const parsed = z.record(z.string(), z.enum(['DELETED', 'NOT_FOUND'])).safeParse(response.data);\n if (parsed.success) { outcomes = Object.entries(parsed.data).filter(([id]) => ids.includes(id)).map(([id, status]) => ({ id, status }));receiptValid = Object.keys(parsed.data).length === ids.length && ids.every(id => Object.hasOwn(parsed.data, id)); }\n } else {\n const parsed = z.array(z.object({ status: z.enum(['CREATED', 'UPDATED', 'INVALID', 'UNCHANGED']), product: nativeProduct.nullable().optional() })).max(100).safeParse(response.data);\n if (parsed.success) {\n outcomes = parsed.data.map(row => ({ ...(row.product && ids.includes(row.product.id) ? { id: row.product.id } : {}), status: row.status }));\n receiptValid = parsed.data.length === ids.length && parsed.data.every(row => (create ? row.status === 'CREATED' : ['UPDATED', 'UNCHANGED'].includes(row.status)) && row.product && row.product.reddit.catalog_id === scope.catalog_id && ids.includes(row.product.id)) && new Set(outcomes.map(row => row.id)).size === ids.length;\n }\n }\n await this.catalogs.authorize(scope, true);const actual = await this.selected(scope, ids);\n const verified = remove ? ids.filter(id => !actual.some(row => row.id === id)) : fresh.products.filter(expected => { const row = actual.find(row => row.id === expected.id);return row && canonical(normalized(config(row))) === canonical(normalized(expected)); }).map(row => row.id);\n if (!receiptValid || verified.length !== ids.length) throw new AdportError('PROVIDER_ERROR', 'Native batch receipt or independent product configuration/absence readback is unconfirmed.', { verified_product_ids: verified });\n return { applied: true, resourceIds: ids, details: { outcomes, independently_verified: true }, warnings: [...notes.slice(0, 2), ...(outcomes.some(row => row.status === 'NOT_FOUND') ? ['Some SKUs were already absent at native deletion; they are not reported as deleted by this request.'] : [])] };\n } catch (error) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n throw new AdportError('PROVIDER_ERROR', 'Reddit product batch outcome may be partial or unknown. No mutation was retried; reconcile selected SKUs before another preview.', { resourceIds: ids, outcomes, ...(Number.isInteger(details.http_status) ? { http_status: details.http_status } : {}), ...(Array.isArray(details.verified_product_ids) ? { verified_product_ids: details.verified_product_ids } : {}) });\n }\n } };\n }\n}\n","import { z } from 'zod';\nimport { catalogInput, hash } from './catalog-schemas.js';\nimport { productId } from './catalog-content-schemas.js';\n\nconst text = z.string().max(40_000), optionalText = text.nullable().optional();\nconst url = z.string().max(8192).url().refine(value => { const parsed = new URL(value);return ['http:', 'https:'].includes(parsed.protocol) && !parsed.username && !parsed.password; }, 'Use an HTTP(S) URL without credentials');\nconst money = z.string().regex(/^\\d+(?:\\.\\d+)? [A-Z]{3}$/).max(256);\nconst number = z.number().int().safe().nullable().optional();\nconst period = z.string().max(256).refine(value => { const parts = value.split('/');return parts.length === 2 && parts.every(v => /T.*(?:Z|[+-]\\d{2}:?\\d{2})$/.test(v) && Number.isFinite(Date.parse(v))) && Date.parse(parts[0]!) < Date.parse(parts[1]!); }, 'Use an ordered ISO datetime interval with timezones');\n/** All 45 writable fields in the official v3 batch-upsert contract, refreshed 2026-11-06. */\nexport const catalogProduct = z.object({\n id: productId, title: optionalText, description: optionalText, price: money.nullable().optional(), link: url.nullable().optional(), image_link: url.nullable().optional(),\n item_group_id: optionalText, sale_price: money.nullable().optional(), sale_price_effective_date: period.nullable().optional(), cost_of_goods_sold: money.nullable().optional(),\n mobile_link: url.nullable().optional(), platform_specific_link: z.object({ android: url.nullable().optional(), ios: url.nullable().optional() }).strict().nullable().optional(),\n lifestyle_image_link: url.nullable().optional(), additional_image_links: z.array(url).max(10).refine(values => new Set(values).size === values.length).nullable().optional(),\n product_type: optionalText, product_detail: optionalText, product_highlight: optionalText, google_product_category: optionalText, brand: optionalText, gtin: optionalText, mpn: optionalText,\n size: optionalText, size_type: optionalText, condition: optionalText, color: optionalText, gender: optionalText, material: optionalText, pattern: optionalText, age_group: optionalText,\n adult: z.boolean().nullable().optional(), is_bundle: z.boolean().nullable().optional(),\n custom_label_0: optionalText, custom_label_1: optionalText, custom_label_2: optionalText, custom_label_3: optionalText, custom_label_4: optionalText,\n custom_number_0: number, custom_number_1: number, custom_number_2: number, custom_number_3: number, custom_number_4: number,\n expiration_date: z.iso.datetime({ offset: true }).nullable().optional(), average_review_rating: optionalText, number_of_ratings: z.number().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable().optional(),\n availability: z.enum(['BACKORDER', 'IN_STOCK', 'OUT_OF_STOCK', 'PREORDER']).optional(),\n}).strict();\nexport const completeCatalogProduct = catalogProduct.extend({ title: text.min(1), description: text.min(1), price: money, link: url, image_link: url, availability: z.enum(['BACKORDER', 'IN_STOCK', 'OUT_OF_STOCK', 'PREORDER']) });\nexport const productIds = z.array(productId).min(1).max(100).refine(ids => new Set(ids).size === ids.length, 'Select unique external product SKUs');\nexport const productContext = catalogInput.extend({ product_ids: productIds }).strict();\nconst write = catalogInput.omit({ account_id: true }).extend({ expected_selection_hash: hash, acknowledge_shared_effects: z.literal(true) });\nconst batch = <T extends z.ZodType<{ id: string }>>(schema: T) => z.array(schema).min(1).max(100).refine(rows => new Set(rows.map(row => row.id)).size === rows.length, 'Select unique external product SKUs');\nexport const productsCreate = write.extend({ products: batch(completeCatalogProduct) }).strict();\nexport const productsUpdate = write.extend({ products: batch(catalogProduct.refine(row => Object.keys(row).some(key => key !== 'id'), 'Provide a product field to change')) }).strict();\nexport const productsDelete = write.extend({ product_ids: productIds, acknowledge_permanent_deletion: z.literal(true) }).strict();\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteGuard, type WriteOperation, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport { RedditAdsClient } from './client.js';\nimport type { RedditCreativePlan, RedditCreativeService } from './creatives.js';\nimport { audienceUsers, createSaved, customAudience, savedTargeting, sendEvents, updateSaved } from './management-tools.js';\nimport { redditId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Collection = 'custom_audiences' | 'saved_audiences' | 'pixels';\nconst row = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};\nconst digest = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');\n\nexport class RedditManagementService {\n constructor(private readonly client: RedditAdsClient, private readonly creatives: RedditCreativeService) {}\n async list(input: { account_id: string; page_size: number; cursor?: string; name?: string }, collection: Collection) {\n const path = `ad_accounts/${id.parse(input.account_id)}/${collection}`, url = input.cursor ? this.client.nextUrl(input.cursor, path) : path;\n const response = await this.client.get<unknown>(url, input.cursor ? {} : { 'page.size': input.page_size, ...(input.name !== undefined ? { name: input.name } : {}) });\n if (!Array.isArray(response.data) || response.data.some(value => !id.safeParse(row(value).id).success)) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed audience/Pixel collection');\n const next = response.pagination?.next_url ? this.client.nextUrl(response.pagination.next_url, path) : undefined;\n if (next === this.client.nextUrl(url, path)) throw new AdportError('PROVIDER_ERROR', 'reddit: pagination repeated the current page');\n return { items: response.data as Row[], truncated: Boolean(next), ...(next ? { next_cursor: next } : {}) };\n }\n private async available(account: string, collection: Collection, resource: string) {\n id.parse(account); id.parse(resource);\n const rows = await this.client.getPaged<unknown>(`ad_accounts/${account}/${collection}`, { 'page.size': 1000 }, 5000);\n const found = rows.map(row).find(value => value.id === resource);\n if (!found) throw new AdportError('INVALID_INPUT', 'reddit: resource is not in the account’s first 5,000 available audience/Pixel entries');\n return found;\n }\n async audience(account: string, resource: string, requireOwned = false) {\n await this.available(account, 'custom_audiences', resource);\n const value = row((await this.client.get<unknown>(`custom_audiences/${resource}`)).data);\n if (value.id !== resource || (requireOwned && value.ad_account_id !== account)) throw new AdportError('INVALID_INPUT', 'reddit: audience ownership mismatch; shared audiences cannot be mutated');\n return value;\n }\n async saved(account: string, resource: string) {\n id.parse(account); id.parse(resource);\n const value = row((await this.client.get<unknown>(`saved_audiences/${resource}`)).data);\n if (value.id !== resource || value.ad_account_id !== account) throw new AdportError('INVALID_INPUT', 'reddit: saved-audience ownership mismatch');\n return value;\n }\n async lastFired(account: string, pixel: string) {\n await this.available(account, 'pixels', pixel);\n const value = (await this.client.get<unknown>(`pixels/${pixel}/last_fired_at`)).data;\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new AdportError('PROVIDER_ERROR', 'reddit: malformed Pixel activity response');\n return { pixel_id: pixel, last_fired_at: value };\n }\n async validateAudienceSource(account: string, payload: unknown) {\n const data = customAudience.parse(payload);\n if (data.type === 'PIXEL_RETARGETING') for (const pixel of data.pixel_audience_config.pixel_ids) await this.available(account, 'pixels', pixel);\n if (data.type === 'ENGAGEMENT_RETARGETING') for (const campaign of data.engagement_audience_config.campaign_ids) await this.creatives.owned(account, 'campaigns', campaign);\n return data;\n }\n private async receipt(path: string, method: 'POST' | 'PATCH', fields: Row, account: string, resource?: string): Promise<WriteResult> {\n const result = method === 'POST' ? await this.client.post<unknown>(path, { data: fields }) : await this.client.patch<unknown>(path, { data: fields }), value = row(result.data);\n const ids = id.safeParse(value.id).success ? [String(value.id)] : [];\n if (ids.length !== 1 || (resource && value.id !== resource) || value.ad_account_id !== account || Object.entries(fields).some(([key, expected]) => !matches(value[key], expected))) throw new AdportError('PROVIDER_ERROR', 'reddit: audience receipt ID/account/settings mismatch; reconcile before retrying', { resource_ids: ids });\n return { applied: true, resourceIds: ids };\n }\n private empty(value: unknown, resource: string): WriteResult {\n if (value !== null && (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length)) throw new AdportError('PROVIDER_ERROR', 'reddit: unexpected empty mutation receipt; reconcile before retrying', { resource_ids: [resource] });\n return { applied: true, resourceIds: [resource] };\n }\n async plan(op: WriteOperation, _guard: WriteGuard): Promise<RedditCreativePlan> {\n const account = id.parse(op.accountId), p = op.payload, type = op.tool;\n const create = ['reddit_create_customer_audience', 'reddit_create_pixel_audience', 'reddit_create_engagement_audience', 'reddit_create_saved_audience', 'reddit_send_conversion_events'].includes(type);\n const remove = ['reddit_delete_audience', 'reddit_delete_saved_audience'].includes(type);\n if (op.provider !== 'reddit' || op.kind !== (create ? 'create' : remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'reddit: provider or operation kind mismatch');\n const plan = (summary: string, changes: string[], execute: () => Promise<WriteResult>): RedditCreativePlan => ({ summary, changes, coercions: [], budgetDeltas: [], execute });\n switch (type) {\n case 'reddit_create_customer_audience':\n case 'reddit_create_pixel_audience':\n case 'reddit_create_engagement_audience': {\n const nativeType = type === 'reddit_create_customer_audience' ? 'CUSTOMER_LIST' : type === 'reddit_create_pixel_audience' ? 'PIXEL_RETARGETING' : 'ENGAGEMENT_RETARGETING';\n const data = await this.validateAudienceSource(account, { ...p, type: nativeType });\n return plan(`Create Reddit ${nativeType} audience`, [JSON.stringify(data), 'Does not create an ad or change existing targeting.'], () => this.receipt(`ad_accounts/${account}/custom_audiences`, 'POST', data, account));\n }\n case 'reddit_update_audience_users': {\n const { audience_id, ...data } = audienceUsers.parse(p), audience = await this.audience(account, audience_id, true);\n if (audience.type !== 'CUSTOMER_LIST' || audience.customer_list_config) throw new AdportError('INVALID_INPUT', 'reddit: direct membership changes require an owned customer list without an external data-provider configuration');\n const sha256 = digest(data);\n return plan(`${data.action_type} ${data.user_data.length} Reddit audience rows`, [`Audience ${audience_id}; columns ${data.column_order.join(',')}; payload SHA-256 ${sha256}. Changes affect targeting using this audience; identifiers are omitted from preview.`], async () => { const result = this.empty((await this.client.patch(`custom_audiences/${audience_id}/users`, { data })).data, audience_id); return { ...result, details: { submitted_rows: data.user_data.length, action_type: data.action_type, payload_sha256: sha256 } }; });\n }\n case 'reddit_delete_audience': {\n const audience = await this.audience(account, id.parse(p.audience_id), true);\n return plan(`Permanently delete Reddit audience ${audience.id}`, [`${audience.name}; type ${audience.type}; targeting using this shared resource can lose eligibility.`], async () => this.empty((await this.client.delete(`custom_audiences/${audience.id}`)).data, String(audience.id)));\n }\n case 'reddit_create_saved_audience': {\n const input = createSaved.parse(p), data = { ...input, type: 'REDDIT_AUDIENCE', targeting: { expand_targeting: false, ...input.targeting } };\n await this.creatives.assertTargetingAvailable(account, data.targeting);\n return plan('Create Reddit saved targeting audience', [JSON.stringify(data)], () => this.receipt(`ad_accounts/${account}/saved_audiences`, 'POST', data, account));\n }\n case 'reddit_update_saved_audience':\n case 'reddit_delete_saved_audience': {\n const input = remove ? { saved_audience_id: id.parse(p.saved_audience_id) } : updateSaved.parse(p), current = await this.saved(account, input.saved_audience_id);\n if (current.status === 'DELETED') throw new AdportError('INVALID_INPUT', 'reddit: saved audience is already deleted');\n const data: Row = remove ? { status: 'DELETED' } : { ...('name' in input && input.name !== undefined ? { name: input.name } : {}) };\n if ('targeting' in input && input.targeting !== undefined) {\n const previous = savedTargeting.safeParse(current.targeting);\n if (!previous.success) throw new AdportError('INVALID_INPUT', 'reddit: current saved targeting contains unsupported fields; refusing a partial reset');\n data.targeting = { ...previous.data, ...input.targeting }; await this.creatives.assertTargetingAvailable(account, data.targeting);\n }\n return plan(`${remove ? 'Delete' : 'Update'} Reddit saved audience ${current.id}`, [`Active ad groups: ${current.active_ad_groups_count ?? 'unavailable'}; changes affect all users of this audience. ${JSON.stringify(data)}`], () => this.receipt(`saved_audiences/${current.id}`, 'PATCH', data, account, String(current.id)));\n }\n case 'reddit_send_conversion_events': {\n const input = sendEvents.parse(p); await this.available(account, 'pixels', input.pixel_id);\n const data = { ...(input.test_id ? { test_id: input.test_id } : {}), events: input.events }, sha256 = digest(data), counts: Record<string, number> = {};\n for (const event of input.events) counts[event.type.tracking_type] = (counts[event.type.tracking_type] ?? 0) + 1;\n return plan(`Submit ${input.events.length} ${input.mode} Reddit conversion events`, [`Pixel ${input.pixel_id}; event types ${JSON.stringify(counts)}; payload SHA-256 ${sha256}. ${input.mode === 'LIVE' ? 'Real measurement submission can affect attribution and optimization.' : 'Uses the supplied Events Manager test ID.'} Event identifiers, match keys and source URLs are omitted from preview.`], async () => {\n const result = row((await this.client.post(`pixels/${input.pixel_id}/conversion_events`, { data })).data);\n if (typeof result.message !== 'string' || !result.message.trim()) throw new AdportError('PROVIDER_ERROR', 'reddit: conversion receipt has no processing message; reconcile deduplicated IDs before retrying', { resource_ids: [input.pixel_id] });\n return { applied: true, resourceIds: [input.pixel_id], details: { mode: input.mode, submitted_events: input.events.length, payload_sha256: sha256, message: this.client.diagnostic(result.message), note: 'Native acceptance does not prove attribution or final processing.' } };\n });\n }\n default: throw new AdportError('INVALID_INPUT', `reddit: unsupported management write ${type}`);\n }\n }\n}\n\nfunction matches(actual: unknown, expected: unknown): boolean {\n if (Array.isArray(expected)) return Array.isArray(actual) && actual.length === expected.length && expected.every(value => actual.some(candidate => matches(candidate, value)));\n if (expected && typeof expected === 'object') return actual !== null && typeof actual === 'object' && !Array.isArray(actual) && Object.entries(expected).every(([key, value]) => matches((actual as Row)[key], value));\n return actual === expected;\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { targeting } from './creative-tools.js';\nimport type { RedditAdsProvider } from './provider.js';\nimport { redditId as id } from './schemas.js';\n\nconst name = z.string().trim().min(1).max(200), hash = z.string().regex(/^[a-f0-9]{64}$/), unique = (values: string[]) => new Set(values).size === values.length;\nexport const trackingType = z.enum(['PAGE_VISIT', 'VIEW_CONTENT', 'SEARCH', 'ADD_TO_CART', 'ADD_TO_WISHLIST', 'PURCHASE', 'LEAD', 'SIGN_UP', 'CUSTOM']);\nexport const customerAudience = z.object({ name, type: z.literal('CUSTOMER_LIST') }).strict();\nexport const pixelAudience = z.object({ name, type: z.literal('PIXEL_RETARGETING'), pixel_audience_config: z.object({ pixel_ids: z.array(id).length(1), targetings: z.array(trackingType).min(1).refine(unique, 'Use unique tracking types'), lookback_window_days: z.number().int().min(1).max(90), custom_targetings: z.array(z.string().min(1)).max(50).optional() }).strict() }).strict();\nexport const engagementAudience = z.object({ name, type: z.literal('ENGAGEMENT_RETARGETING'), engagement_audience_config: z.object({ campaign_ids: z.array(id).min(1).max(500).refine(unique, 'Use unique campaign IDs'), tracking_types: z.array(z.enum(['IMPRESSIONS', 'CLICKS', 'UPVOTES', 'COMMENT_SUBMISSIONS', 'VIDEO_WATCHED_50_PERCENT', 'VIDEO_WATCHED_100_PERCENT', 'VIDEO_STARTED'])).min(1).refine(unique, 'Use unique tracking types'), lookback_window_days: z.number().int().min(1).max(180) }).strict() }).strict();\nexport const customAudience = z.discriminatedUnion('type', [customerAudience, pixelAudience, engagementAudience]);\nexport const audienceUsers = z.object({ audience_id: id, action_type: z.enum(['ADD', 'REMOVE']), column_order: z.array(z.enum(['EMAIL_SHA256', 'MAID_SHA256'])).min(1).max(2).refine(unique, 'Use unique columns'), user_data: z.array(z.array(hash).min(1).max(2)).min(1).max(2500) }).refine(v => v.user_data.every(row => row.length === v.column_order.length), 'Each row must match column_order').refine(v => new Set(v.user_data.map(row => JSON.stringify(row))).size === v.user_data.length, 'Use unique rows');\n// Saved audiences omit the ad-group-only placements dimension in current v3.\nexport const savedTargeting = targeting.omit({ locations: true });\nexport const createSaved = z.object({ name, targeting: savedTargeting });\nexport const updateSaved = z.object({ saved_audience_id: id, name: name.optional(), targeting: savedTargeting.optional() }).refine(v => v.name !== undefined || v.targeting !== undefined, 'Provide audience changes');\nconst href = z.string().url().max(4096).refine(value => { const url = new URL(value); return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) URL without embedded credentials');\nconst text = z.string().min(1).max(2000), amount = z.number().finite().nonnegative();\nexport const conversionEvent = z.object({\n event_at: z.number().int().positive().safe().describe('Unix epoch milliseconds'), action_source: z.enum(['WEBSITE', 'APP', 'OTHER', 'PHYSICAL_STORE']),\n click_id: text.optional(), event_source_url: href.optional(), referrer_url: href.optional(),\n type: z.object({ tracking_type: trackingType, custom_event_name: z.string().min(1).max(64).optional() }).strict().refine(v => v.tracking_type !== 'CUSTOM' || Boolean(v.custom_event_name), 'CUSTOM needs custom_event_name'),\n metadata: z.object({ conversion_id: z.string().min(1).max(200).describe('Stable deduplication ID; reuse for retries'), order_id: z.string().max(100).optional(), currency: z.string().regex(/^[A-Z]{3}$/).optional(), item_count: z.number().int().nonnegative().optional(), value: amount.optional(), products: z.array(z.object({ id: text, category: text.optional(), name: text.optional(), quantity: z.number().int().nonnegative().optional(), item_price: amount.optional() }).strict()).optional() }).strict().refine(v => v.value === undefined || Boolean(v.currency), 'Revenue value requires currency'),\n user: z.object({ email: hash.optional(), external_id: hash.optional(), phone_number: hash.optional(), aaid: hash.optional(), idfa: hash.optional(), ip_address: z.union([z.ipv4(), z.ipv6()]).optional(), user_agent: text.optional(), uuid: text.optional(), data_processing_options: z.object({ country: text.optional(), region: text.optional(), modes: z.array(z.literal('LDU')).optional() }).strict().optional(), screen_dimensions: z.object({ height: z.number().int().min(0).max(32767), width: z.number().int().min(0).max(32767) }).strict().optional() }).strict().optional().describe('Pre-hash customer match keys using Reddit’s normalization rules; device IP/user-agent and Pixel UUID stay unhashed'),\n}).strict();\nexport const sendEvents = z.object({ pixel_id: id, mode: z.enum(['TEST', 'LIVE']).default('TEST'), test_id: z.string().min(1).optional(), events: z.array(conversionEvent).min(1).max(1000) }).refine(v => v.mode === 'TEST' ? Boolean(v.test_id) : !v.test_id, 'TEST requires test_id; LIVE must omit test_id').refine(v => new Set(v.events.map(e => `${e.action_source}:${e.metadata.conversion_id}`)).size === v.events.length, 'Use unique conversion IDs within each action source');\n\nexport function redditManagementTools(provider: RedditAdsProvider): AnyToolDefinition[] {\n const account = { account_id: id }, page = { page_size: z.number().int().min(1).max(1000).default(50), cursor: z.string().url().optional() };\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (input: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'reddit', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove' = 'update') => guardedWriteTool({ name, namespace: 'reddit', provider: 'reddit', description, payload, kind });\n return [\n read('reddit_audiences', 'List custom audiences available to the account, including ownership, type, size and processing readiness.', z.object({ ...account, name: z.string().optional(), ...page }), v => provider.management.list(v, 'custom_audiences')),\n read('reddit_get_audience', 'Read one custom audience already available to the selected account. Availability does not grant editing rights to a shared audience.', z.object({ ...account, audience_id: id }), v => provider.management.audience(v.account_id, v.audience_id)),\n write('reddit_create_customer_audience', 'Create an empty customer-list audience. Membership upload is a separate approval with pre-hashed identifiers.', customerAudience.omit({ type: true }), 'create'),\n write('reddit_create_pixel_audience', 'Create website retargeting from one account-available Pixel and explicit event/window settings.', pixelAudience.omit({ type: true }), 'create'),\n write('reddit_create_engagement_audience', 'Create engagement retargeting from verified account-owned campaigns with explicit events/window settings.', engagementAudience.omit({ type: true }), 'create'),\n write('reddit_update_audience_users', 'Add/remove at most 2,500 pre-hashed customer rows from an owned CUSTOMER_LIST audience. Preview shows count and digest, not identifiers.', audienceUsers),\n write('reddit_delete_audience', 'Permanently delete an account-owned custom audience. Ads using it can lose eligibility; shared foreign audiences cannot be deleted.', z.object({ audience_id: id }), 'remove'),\n read('reddit_saved_audiences', 'List reusable saved targeting audiences and their native readiness/usage counts.', z.object({ ...account, ...page }), v => provider.management.list(v, 'saved_audiences')),\n read('reddit_get_saved_audience', 'Read an account-owned saved audience and its native targeting.', z.object({ ...account, saved_audience_id: id }), v => provider.management.saved(v.account_id, v.saved_audience_id)),\n write('reddit_create_saved_audience', 'Create reusable native REDDIT_AUDIENCE targeting, with expansion explicitly off unless supplied. Audience references must be account-available.', createSaved, 'create'),\n write('reddit_update_saved_audience', 'Change name or supplied saved targeting dimensions, preserving omitted settings. Changes can affect all ad groups using it.', updateSaved),\n write('reddit_delete_saved_audience', 'Mark an owned saved audience DELETED using native PATCH. Reports active ad-group usage before approval.', z.object({ saved_audience_id: id }), 'remove'),\n read('reddit_pixels', 'List Pixels already available to the selected ad account. Current v3 has no public Pixel creation/update endpoint.', z.object({ ...account, ...page }), v => provider.management.list(v, 'pixels')),\n read('reddit_pixel_last_fired', 'Read native last-fired timestamps after proving the Pixel is available to this account. Missing timestamps remain unavailable.', z.object({ ...account, pixel_id: id }), v => provider.management.lastFired(v.account_id, v.pixel_id)),\n write('reddit_send_conversion_events', 'Submit up to 1,000 deduplicated events to an account-available Pixel. Requires existing adsconversions scope. TEST needs Events Manager test_id; explicit LIVE affects measurement. Customer keys must be pre-hashed.', sendEvents, 'create'),\n ];\n}\n","import { AdportError } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsClient } from './client.js';\nimport { redditBusinessId } from './catalog-access.js';\nimport { redditId } from './schemas.js';\n\nconst accountMetadata = z.object({\n id: redditId,\n name: z.string().min(1).optional(),\n business_id: redditBusinessId.optional(),\n currency: z.string().regex(/^[A-Z]{3}$/).optional(),\n admin_approval: z.string().min(1).optional(),\n});\n\nexport const redditAccountContext = accountMetadata.extend({\n catalog_access: z.literal('EXPLICIT_PROJECT_GRANT_REQUIRED'),\n});\n\nexport async function readAccountContext(client: RedditAdsClient, accountId: string): Promise<z.infer<typeof redditAccountContext>> {\n redditId.parse(accountId);\n const response = await client.get<unknown>(`ad_accounts/${encodeURIComponent(accountId)}`);\n const parsed = accountMetadata.safeParse(response.data);\n if (!parsed.success || parsed.data.id !== accountId) {\n throw new AdportError('PROVIDER_ERROR', 'reddit: account context did not return valid metadata for the selected account');\n }\n return { ...parsed.data, catalog_access: 'EXPLICIT_PROJECT_GRANT_REQUIRED' };\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsProvider } from './provider.js';\nimport { createCampaign, redditId, setCampaignBudget, setCampaignStatus } from './schemas.js';\nimport { redditAccountContext } from './account-context.js';\nimport { redditCreativeTools } from './creative-tools.js';\nimport { redditCatalogTools } from './catalog-tools.js';\nimport { redditCatalogContentTools } from './catalog-content-tools.js';\nimport { redditCatalogFeedTools } from './catalog-feed-tools.js';\nimport { redditCatalogProductTools } from './catalog-product-tools.js';\nimport { redditManagementTools } from './management-tools.js';\n\nexport function redditTools(provider: RedditAdsProvider, options: { catalogAccessManagement?: boolean } = {}): AnyToolDefinition[] {\n return [\n defineTool({\n name: 'reddit_account_context',\n namespace: 'reddit',\n description: 'Read the selected ad account’s basic metadata and parent Business ID. Business/catalog enumeration and catalog access require separate explicit project grants.',\n input: z.object({ account_id: redditId }).strict(),\n output: redditAccountContext,\n catalog: { category: 'core', exposure: 'standard' },\n annotations: { readOnly: true },\n handler: input => provider.accountContext(input.account_id),\n }),\n ...redditCatalogProductTools(provider),\n ...redditCatalogFeedTools(provider),\n ...redditCatalogContentTools(provider),\n ...redditCatalogTools(provider, options.catalogAccessManagement === true),\n ...redditCreativeTools(provider),\n ...redditManagementTools(provider),\n defineTool({\n name: 'reddit_api_read',\n namespace: 'reddit',\n description: 'Call a documented Reddit Ads API v3 GET or read-only reports/history/query/search POST endpoint, scoped to the selected ad account.',\n input: z.object({\n account_id: z.string(),\n path: z.string().min(3).describe('Relative v3 path, e.g. ad_accounts/{id}/ad_groups or campaigns/{campaign_id}'),\n method: z.enum(['GET', 'POST']).default('GET'),\n params: z.record(z.string(), z.unknown()).optional(),\n body: z.record(z.string(), z.unknown()).optional(),\n limit: z.number().int().positive().max(5000).optional().describe('Follow list pagination for GET responses'),\n }),\n annotations: { readOnly: true },\n handler: (input) => provider.apiRead(input),\n }),\n defineTool({\n name: 'reddit_campaigns',\n namespace: 'reddit',\n description: 'List Reddit campaigns and their native configured/effective status, CBO budget, objective, and funding instrument.',\n input: z.object({ account_id: z.string(), campaign_ids: z.array(z.string()).optional() }),\n annotations: { readOnly: true },\n async handler(input) { return { campaigns: await provider.listCampaigns(input.account_id, input.campaign_ids) }; },\n }),\n defineTool({\n name: 'reddit_report',\n namespace: 'reddit',\n description: 'Query Reddit Ads API v3 reporting directly. Spend/CPC/CPM use micros; conversion TOTAL_VALUE fields use cents. Missing metrics remain unavailable.',\n input: z.object({\n account_id: z.string(),\n breakdowns: z.array(z.string()).max(4).optional(),\n fields: z.array(z.string()).min(1).default(['SPEND', 'IMPRESSIONS', 'CLICKS']),\n starts_at: z.string().datetime({ offset: true }),\n ends_at: z.string().datetime({ offset: true }),\n time_zone_id: z.string().default('UTC'),\n filter: z.string().optional(),\n page_size: z.number().int().positive().max(1000).default(200),\n }),\n annotations: { readOnly: true },\n handler: (input) => provider.rawReport(input),\n }),\n guardedWriteTool({\n name: 'reddit_create_campaign',\n namespace: 'reddit',\n description: 'Create a Reddit campaign through API v3. Campaigns are forced PAUSED. CBO budgets and spend caps are integer micros.',\n provider: 'reddit', kind: 'create',\n payload: createCampaign,\n }),\n guardedWriteTool({\n name: 'reddit_set_campaign_status', namespace: 'reddit',\n description: 'Activate or pause a Reddit campaign after verifying ad-account ownership.',\n provider: 'reddit', kind: 'update',\n payload: setCampaignStatus,\n }),\n guardedWriteTool({\n name: 'reddit_set_budget', namespace: 'reddit',\n description: 'Change a Reddit CBO campaign goal_value in integer micros, with current-value lookup and policy checks.',\n provider: 'reddit', kind: 'update',\n payload: setCampaignBudget,\n }),\n guardedWriteTool({\n name: 'reddit_api_create', namespace: 'reddit',\n description: 'Create via an account-scoped Reddit Ads API v3 endpoint. Campaign status is forced PAUSED and native micros fields are policy-checked.',\n provider: 'reddit', kind: 'create',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'reddit_api_update', namespace: 'reddit',\n description: 'PATCH non-budget fields on a Reddit Ads API v3 resource after verifying ad-account ownership.',\n provider: 'reddit', kind: 'update',\n payload: z.object({ path: z.string().min(3), body: z.record(z.string(), z.unknown()) }),\n }),\n guardedWriteTool({\n name: 'reddit_api_delete', namespace: 'reddit',\n description: 'Permanently DELETE a Reddit Ads API v3 resource after verifying ad-account ownership.',\n provider: 'reddit', kind: 'remove', destructive: true,\n payload: z.object({ path: z.string().min(3) }),\n }),\n ];\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { redditCatalogId } from './catalog-access.js';\nimport { catalogInput, creationContext, sourceContext, catalogCreate, catalogRename, catalogSources, catalogDelete, permissionSnapshot, permissionChange } from './catalog-schemas.js';\nimport type { RedditCatalogService } from './catalogs.js';\nexport function redditCatalogTools(provider: { catalogs: RedditCatalogService }, administration = false): AnyToolDefinition[] {\n const read = { namespace: 'reddit', catalog: { category: 'creatives' as const, exposure: 'specialist' as const }, annotations: { readOnly: true }, presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) };\n return [\n defineTool({ ...read, catalog: { category: 'administration', exposure: 'specialist' }, name: 'reddit_catalog_access', description: 'List this project/ad-account’s explicit catalog and creation grants. Does not enumerate native Business catalogs or infer Business authority from enabled advertiser access.', input: z.object({ account_id: redditCatalogId }).strict(), handler: input => provider.catalogs.access(input.account_id) }),\n defineTool({ ...read, name: 'reddit_get_catalog', description: 'Read one explicitly granted Business catalog, native counts and configuration_hash. Verifies native catalog/Business IDs; missing fields remain unavailable. No dependent product/ad inventory claim.', input: catalogInput, handler: input => provider.catalogs.get(input) }),\n defineTool({ ...read, name: 'reddit_catalog_creation_context', description: 'Read exact owner creation-delegation and selected-account Pixel snapshots for a new Business catalog. Verifies selected Business and optional event-source IDs. No existing catalog enumeration or automatic authority expansion.', input: creationContext, handler: input => provider.catalogs.creationContext(input) }),\n defineTool({ ...read, catalog: { category: 'measurement', exposure: 'specialist' }, name: 'reddit_catalog_event_source_context', description: 'Read current catalog configuration and verify selected Pixel IDs under this ad account before replacing all catalog event sources. Empty explicitly clears them. Shared effects require a separate guarded preview.', input: sourceContext, handler: input => provider.catalogs.sourceContext(input) }),\n guardedWriteTool({ name: 'reddit_create_catalog', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: false, description: 'Create an empty catalog under exact owner Business delegation using fresh access/Pixel hashes. Verifies native ID/configuration then adopts only the verified new ID for project write access. No products, ads, spend or events; uncertain results are never replayed.', payload: catalogCreate }),\n guardedWriteTool({ name: 'reddit_rename_catalog', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: false, description: 'Rename one writable shared Business catalog using its configuration_hash and shared-effects acknowledgement. Independently checks preserved defaults/event sources. No automatic replay.', payload: catalogRename }),\n guardedWriteTool({ name: 'reddit_set_catalog_event_sources', namespace: 'reddit', provider: 'reddit', catalog: { category: 'measurement', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Replace all event-source Pixel IDs using fresh catalog/source-context hashes and shared/measurement-effects acknowledgement. Empty explicitly clears. Verifies selected-account availability and preserved configuration; sends no events and never replays.', payload: catalogSources }),\n guardedWriteTool({ name: 'reddit_delete_catalog', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Permanently delete one exact writable catalog using its current hash, exact name and shared/contents acknowledgement. Verifies native acknowledgement and exact lookup absence; other errors remain errors. Contents are not frozen. No restore or automatic replay.', payload: catalogDelete }),\n ...(administration ? [\n defineTool({ ...read, catalog: { category: 'administration' as const, exposure: 'specialist' as const }, name: 'reddit_catalog_access_snapshot', description: 'Owner settings/local owner only: inspect exact catalog or creation permission hash. Omitted from hosted MCP and public REST catalogs.', input: permissionSnapshot, handler: input => provider.catalogs.snapshot(input) }),\n guardedWriteTool({ name: 'reddit_set_catalog_access', namespace: 'reddit', provider: 'reddit', catalog: { category: 'administration', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Owner settings/local owner only: grant exact catalog read/write access, delegate creation/management of verified new IDs in one Business, or revoke access. Shared policy/audit gate; no native permissions granted. Omitted from hosted MCP/public REST.', payload: permissionChange }),\n ] : []),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsProvider } from './provider.js';\nimport { productList, setProductList, setInput, setList, setCreate, setUpdate, setDelete, importInput, importList, importIssues } from './catalog-content-schemas.js';\n\nexport function redditCatalogContentTools(provider: RedditAdsProvider): AnyToolDefinition[] {\n const read = { namespace: 'reddit', catalog: { category: 'creatives' as const, exposure: 'specialist' as const }, annotations: { readOnly: true }, presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) }, pagination = { cursorInput: 'cursor' };\n return [\n defineTool({ ...read, name: 'reddit_catalog_product_sets', description: 'Page through product sets in one explicitly granted Business catalog. Verifies each native parent; no global set enumeration.', input: setList, pagination, handler: input => provider.catalogContent.sets(input) }),\n defineTool({ ...read, name: 'reddit_get_catalog_product_set', description: 'Read an exact native catalog/set, filter and configuration_hash. Product counts are native snapshots; absent fields remain unavailable.', input: setInput, handler: input => provider.catalogContent.getSet(input) }),\n defineTool({ ...read, name: 'reddit_catalog_products', description: 'Page catalog products and native approval/issues through one exact catalog grant. Preserves repeated ID query parameters and opaque SKUs. Embeds Reddit-hosted native previews only.', input: productList, presentation: 'creatives', output: creativesOutput.passthrough(), pagination, handler: input => provider.catalogContent.products(input) }),\n defineTool({ ...read, name: 'reddit_catalog_product_set_products', description: 'Page products matching one independently verified catalog/set. Rechecks catalog and set scope on every page; membership can change between pages.', input: setProductList, presentation: 'creatives', output: creativesOutput.passthrough(), pagination, handler: input => provider.catalogContent.products(input, true) }),\n guardedWriteTool({ name: 'reddit_create_catalog_product_set', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: false, description: 'Create a shared catalog product set with a documented filter JSON string and fresh catalog hash. Uses normal approval and independent ID/catalog/configuration readback; creates no ads or spend.', payload: setCreate }),\n guardedWriteTool({ name: 'reddit_update_catalog_product_set', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Update selected name/filter fields using the exact set configuration_hash and shared-effects acknowledgement. A filter replaces matching rules; omitted configuration is independently checked.', payload: setUpdate }),\n guardedWriteTool({ name: 'reddit_delete_catalog_product_set', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Permanently delete an exact shared product-set definition using current hash/name and acknowledgements. Verifies native acknowledgement and exact GET404; dependent membership/ads are not frozen and errors are not absence.', payload: setDelete }),\n defineTool({ ...read, name: 'reddit_catalog_imports', description: 'Page import history for one explicitly granted catalog, with repeated feed IDs and native status filters. Processing counts and missing fields remain native snapshots.', input: importList, pagination, handler: input => provider.catalogContent.imports(input) }),\n defineTool({ ...read, name: 'reddit_catalog_import_issues', description: 'Read one catalog import’s issues after proving import membership in the selected catalog within 10,000 rows. Global/foreign IDs are rejected; each page rechecks current catalog access.', input: importIssues, pagination, handler: input => provider.catalogContent.issues(input) }),\n defineTool({ ...read, name: 'reddit_catalog_import_report', description: 'Obtain a temporary native report download URL only after current catalog/import membership proof. Does not fetch it or forward Reddit credentials. Missing/expired reports are not clean diagnostics.', input: importInput, handler: input => provider.catalogContent.report(input) }),\n ];\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsProvider } from './provider.js';\nimport { feedInput, feedList, feedCreate, feedUpdate, feedStatus, feedDelete } from './catalog-feed-schemas.js';\n\nexport function redditCatalogFeedTools(provider: RedditAdsProvider): AnyToolDefinition[] {\n const read = { namespace: 'reddit', catalog: { category: 'creatives' as const, exposure: 'specialist' as const }, annotations: { readOnly: true }, presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }) };\n return [\n defineTool({ ...read, name: 'reddit_catalog_feeds', description: 'Browse feeds in one explicitly granted Business catalog. Native lists are unpaged; Adport bounds to5,000 and snapshot-pages locally. Source paths, query values and authentication stay private.', input: feedList, pagination: { cursorInput: 'cursor' }, handler: input => provider.catalogFeeds.list(input) }),\n defineTool({ ...read, name: 'reddit_get_catalog_feed', description: 'Read one exact catalog/feed with safe source origin/fingerprint, reported schedule and configuration_hash. Missing schedule fields remain unavailable; authentication values are never returned.', input: feedInput, handler: input => provider.catalogFeeds.get(input) }),\n guardedWriteTool({ name: 'reddit_create_catalog_feed', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'create', destructive: true, description: 'Create a native catalog feed with explicit REPLACE/UPDATE and schedule/null, fresh catalog hash and shared/automatic-processing acknowledgements. Can start ingestion and affect existing ads. Private source/name arguments stay out of widget approvals; apply through the agent. Readback is not ingestion/authentication proof.', payload: feedCreate, sensitiveInputs: ['url', 'username', 'password', 'name'] }),\n guardedWriteTool({ name: 'reddit_update_catalog_feed', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Change selected native feed fields using current configuration_hash. Omitted source/authentication fields are not sent; supplied schedule replaces timing. Source/mode/auth/schedule changes need automatic-processing acknowledgement. Private source/name arguments stay out of widget approvals; no automatic replay.', payload: feedUpdate, sensitiveInputs: ['url', 'username', 'password', 'name'] }),\n guardedWriteTool({ name: 'reddit_set_catalog_feed_schedule_status', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'update', destructive: true, description: 'Pause or resume one verified feed schedule with a current hash and shared/automatic-processing acknowledgements. Uses the opposite known pause state and preserves reported timing/source/mode. Does not cancel or undo an existing import.', payload: feedStatus }),\n guardedWriteTool({ name: 'reddit_delete_catalog_feed', namespace: 'reddit', provider: 'reddit', catalog: { category: 'creatives', exposure: 'specialist' }, kind: 'remove', destructive: true, description: 'Permanently delete an exact writable catalog/feed using its current configuration_hash and shared/deletion acknowledgements. Checks native204 acknowledgement and exactGET404. Other errors remain errors; imported products/ads are not frozen or automatically removed.', payload: feedDelete }),\n ];\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { RedditAdsProvider } from './provider.js';\nimport { productContext, productsCreate, productsUpdate, productsDelete } from './catalog-product-schemas.js';\n\nexport function redditCatalogProductTools(provider: RedditAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'creatives' as const, exposure: 'specialist' as const }, write = { namespace: 'reddit', provider: 'reddit', catalog };\n return [\n defineTool({ name: 'reddit_catalog_product_context', namespace: 'reddit', catalog, annotations: { readOnly: true }, presentation: 'records', description: 'Read up to 100 exact external SKUs in one granted Business catalog, exhausting scoped native pagination. Returns a selection_hash and present/absent state for manual product changes; not a global inventory.', input: productContext, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }), handler: input => provider.catalogProducts.context(input) }),\n guardedWriteTool({ ...write, name: 'reddit_create_catalog_products', kind: 'create', destructive: false, description: 'Create up to 100 absent SKUs through native batch upsert with fresh selection_hash and complete product copy/price/URLs. Rechecks absence, uses normal approval and independent readback. Native concurrent upsert races and feed overwrites remain possible.', payload: productsCreate }),\n guardedWriteTool({ ...write, name: 'reddit_update_catalog_products', kind: 'update', destructive: true, description: 'Update selected fields on up to 100 existing external SKUs with current selection_hash. Merges all known writable fields, refuses unknown configuration, verifies complete readback and reports uncertain/partial outcomes without replay.', payload: productsUpdate }),\n guardedWriteTool({ ...write, name: 'reddit_delete_catalog_products', kind: 'remove', destructive: true, description: 'Permanently delete up to 100 exact present external SKUs with selection_hash and explicit acknowledgement. Verifies per-SKU native receipts and exhausted absence readback. Feeds can recreate products; internal Reddit IDs are not SKUs.', payload: productsDelete }),\n ];\n}\n","import { FileRedditCatalogAccessStore } from './catalog-access.js';\nimport type { CredentialStore, ProviderModule } from '@adport/core';\nimport { RedditAdsClient, type RedditCredentials } from './client.js';\nimport { RedditAdsProvider } from './provider.js';\nimport { redditTools } from './tools.js';\n\nexport { RedditAdsClient, REDDIT_API_BASE, REDDIT_API_VERSION, REDDIT_TOKEN_URL, type RedditCredentials, type RedditEnvelope } from './client.js';\nexport { RedditAdsProvider, REDDIT_MICROS, type RedditCampaign } from './provider.js';\nexport { redditTools } from './tools.js';\n\nexport async function resolveRedditCredentials(store: CredentialStore): Promise<RedditCredentials | undefined> {\n const record = await store.get('reddit');\n const data = record?.data;\n if (data?.client_id && data.client_secret && data.refresh_token && data.user_agent) {\n const source = record?.source ?? 'byo';\n return {\n clientId: data.client_id,\n clientSecret: data.client_secret,\n refreshToken: data.refresh_token,\n userAgent: data.user_agent,\n onRefreshToken: async (refreshToken) => {\n await store.set({ provider: 'reddit', source, data: { ...data, refresh_token: refreshToken } });\n },\n };\n }\n if (process.env.REDDIT_ADS_CLIENT_ID && process.env.REDDIT_ADS_CLIENT_SECRET && process.env.REDDIT_ADS_REFRESH_TOKEN && process.env.REDDIT_ADS_USER_AGENT) {\n return {\n clientId: process.env.REDDIT_ADS_CLIENT_ID,\n clientSecret: process.env.REDDIT_ADS_CLIENT_SECRET,\n refreshToken: process.env.REDDIT_ADS_REFRESH_TOKEN,\n userAgent: process.env.REDDIT_ADS_USER_AGENT,\n };\n }\n return undefined;\n}\n\nexport async function createRedditModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveRedditCredentials(store);\n if (!credentials) return undefined;\n const provider = new RedditAdsProvider(new RedditAdsClient(credentials), undefined, new FileRedditCatalogAccessStore());\n return { provider, tools: redditTools(provider, { catalogAccessManagement: true }) };\n}\n\nexport { RedditCatalogService } from './catalogs.js';\nexport { redditCatalogTools } from './catalog-tools.js';\nexport { FileRedditCatalogAccessStore, catalogGrant, catalogScope, catalogScopeKey, creationScope, requireCatalogAccess, requireCatalogCreationAccess, redditBusinessId, redditCatalogId, type RedditCatalogAccessMode, type RedditCatalogAccessStore, type RedditCatalogGrant, type RedditCatalogScope } from './catalog-access.js';\n"],"mappings":";AAAA,SAAS,YAAY,kBAAkB;AACvC,SAAS,WAAW,YAAY,UAAU;AAC1C,OAAO,UAAU;AACjB,SAAS,aAAa,kBAAkB;AACxC,SAAS,KAAAA,UAAS;;;ACJlB,SAAS,SAAS;AAGX,IAAM,WAAW,EAAE,OAAO,EAAE,MAAM,kBAAkB;AACpD,IAA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A,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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IACzB;AAAA,EACF;AACA,SAAO;AACT;AAEA,eAAsB,mBAAmB,OAA6D;AACpG,QAAM,cAAc,MAAM,yBAAyB,KAAK;AACxD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,kBAAkB,IAAI,gBAAgB,WAAW,GAAG,QAAW,IAAI,6BAA6B,CAAC;AACtH,SAAO,EAAE,UAAU,OAAO,YAAY,UAAU,EAAE,yBAAyB,KAAK,CAAC,EAAE;AACrF;","names":["z","z","scope","write","accountId","normalized","name","AdportError","accountId","invalid","url","path","page","normalized","text","record","AdportError","AdportError","z","z","z","page","name","write","z","path","AdportError","resource","row","url","profile","status","value","ids","notes","source","name","result","canonical","createHash","AdportError","z","z","z","ids","z","ids","createHash","row","scope","AdportError","path","write","selected","input","notes","prepare","data","current","createHash","AdportError","z","z","z","ids","canonical","digest","createHash","text","count","z","row","failure","ids","AdportError","invalid","safeUrl","url","path","landing","selected","current","notes","createHash","AdportError","z","z","z","url","name","z","scope","canonical","digest","createHash","config","row","configurationHash","url","text","invalid","AdportError","failure","ids","path","snapshot","selected","createHash","z","AdportError","z","z","url","ids","row","z","canonical","digest","createHash","config","row","invalid","AdportError","notes","ids","url","page","write","selected","scope","status","createHash","AdportError","defineTool","guardedWriteTool","z","name","z","hash","row","url","text","page","defineTool","write","guardedWriteTool","digest","createHash","path","url","AdportError","resource","ids","AdportError","z","z","accountId","AdportError","accountId","AdportError","page","path","ids","url","row","number","status","config","resource","normalized","keys","defineTool","guardedWriteTool","z","defineTool","guardedWriteTool","z","z","defineTool","guardedWriteTool","creativesOutput","defineTool","guardedWriteTool","z","z","defineTool","creativesOutput","guardedWriteTool","defineTool","guardedWriteTool","z","z","defineTool","guardedWriteTool","defineTool","guardedWriteTool","z","write","defineTool","z","guardedWriteTool","defineTool","z","guardedWriteTool","record","source"]}