@adport/provider-spotify 0.9.0 → 0.11.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/index.ts","../src/client.ts","../src/provider.ts","../src/creatives.ts","../src/creative-schemas.ts","../src/schemas.ts","../src/management.ts","../src/management-tools.ts","../src/measurement.ts","../src/measurement-schemas.ts","../src/capi-credentials.ts","../src/measurement-tools.ts","../src/tools.ts","../src/creative-tools.ts"],"sourcesContent":["import { FileResourceSecretStore, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { SpotifyAdsClient, type SpotifyCredentials } from './client.js';\nimport { SpotifyAdsProvider } from './provider.js';\nimport { spotifyTools } from './tools.js';\nexport { SpotifyAdsClient, SPOTIFY_API_BASE, SPOTIFY_TOKEN_URL, buildSpotifyAuthUrl, exchangeSpotifyCode, type SpotifyCredentials } from './client.js';\nexport { SpotifyAdsProvider } from './provider.js';\nexport { spotifyTools } from './tools.js';\nexport { accountSchema, campaignSchema, draftSchema, adSetSchema, reportSchema } from './schemas.js';\n\nexport async function resolveSpotifyCredentials(store: CredentialStore): Promise<SpotifyCredentials | undefined> {\n const data = (await store.get('spotify'))?.data;\n if (data?.client_id && data.client_secret && data.refresh_token) return {\n clientId: data.client_id, clientSecret: data.client_secret, refreshToken: data.refresh_token,\n onRefreshToken: async refreshToken => {\n const latest = await store.get('spotify');\n if (latest) await store.set({ provider: 'spotify', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.SPOTIFY_CLIENT_ID && process.env.SPOTIFY_CLIENT_SECRET && process.env.SPOTIFY_REFRESH_TOKEN) return {\n clientId: process.env.SPOTIFY_CLIENT_ID, clientSecret: process.env.SPOTIFY_CLIENT_SECRET, refreshToken: process.env.SPOTIFY_REFRESH_TOKEN,\n };\n return undefined;\n}\n\nexport async function createSpotifyModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveSpotifyCredentials(store);\n if (!credentials) return undefined;\n const provider = new SpotifyAdsProvider(new SpotifyAdsClient(credentials), undefined, { resourceSecrets: new FileResourceSecretStore() });\n return { provider, tools: spotifyTools(provider) };\n}\n","import { AdportError } from '@adport/core';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { z } from 'zod';\n\nexport const SPOTIFY_API_BASE = 'https://api-partner.spotify.com/ads/v3/';\nexport const SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token';\nexport interface SpotifyCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\nconst tokenSchema = z.object({\n access_token: z.string().min(1), expires_in: z.number().positive(),\n refresh_token: z.string().min(1).optional(),\n});\n\nexport function buildSpotifyAuthUrl(clientId: string, redirectUri: string, state: string): string {\n // Ads API access is granted to the app, not through Web API music scopes.\n return `https://accounts.spotify.com/authorize/?${new URLSearchParams({\n client_id: clientId, response_type: 'code', redirect_uri: redirectUri, state,\n })}`;\n}\n\nasync function tokenRequest(credentials: Pick<SpotifyCredentials, 'clientId' | 'clientSecret'>, body: URLSearchParams, fetchImpl: typeof fetch) {\n const response = await fetchImpl(SPOTIFY_TOKEN_URL, {\n method: 'POST', headers: {\n authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n }, body, redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `spotify: OAuth ${body.get('grant_type')} failed (HTTP ${response.status})`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed OAuth response');\n return parsed.data;\n}\n\nexport async function exchangeSpotifyCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string }, fetchImpl: typeof fetch = fetch): Promise<string> {\n const token = await tokenRequest(input, new URLSearchParams({ grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri }), fetchImpl);\n if (!token.refresh_token) throw new AdportError('PROVIDER_ERROR', 'spotify: OAuth exchange did not return a refresh token');\n return token.refresh_token;\n}\n\nexport class SpotifyAdsClient {\n private token?: { value: string; expiresAt: number };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: SpotifyCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\n }\n\n measurementReceipt(value: Record<string, unknown>): string {\n const payload = Buffer.from(JSON.stringify(value)).toString('base64url');\n return `${payload}.${createHmac('sha256', this.measurementReceiptKey()).update(payload).digest('base64url')}`;\n }\n verifyMeasurementReceipt(receipt: string): unknown {\n const invalid = () => new AdportError('INVALID_INPUT', 'spotify: invalid measurement resource receipt');\n if (receipt.length > 4096 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();\n const [payload, signature] = receipt.split('.'), supplied = Buffer.from(signature!, 'base64url');\n const expected = createHmac('sha256', this.measurementReceiptKey()).update(payload!).digest();\n if (Buffer.from(payload!, 'base64url').toString('base64url') !== payload || supplied.toString('base64url') !== signature || supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) throw invalid();\n try { return JSON.parse(Buffer.from(payload!, 'base64url').toString('utf8')); } catch { throw invalid(); }\n }\n private measurementReceiptKey(): Buffer {\n // Stable across OAuth refresh rotation; every use also rechecks native account/business access.\n return createHmac('sha256', this.credentials.clientSecret).update(`adport:spotify:measurement:v1:${this.credentials.clientId}`).digest();\n }\n\n async get<T>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, 'GET', schema, undefined, params);\n }\n async mutate<T>(path: string, method: 'POST' | 'PATCH' | 'DELETE', body: unknown, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, method, schema, body, params);\n }\n async upload<T>(path: string, body: FormData, schema: z.ZodType<T>): Promise<T> {\n return this.request(path, 'POST', schema, body);\n }\n\n private async request<T>(path: string, method: 'GET' | 'POST' | 'PATCH' | 'DELETE', schema: z.ZodType<T>, body?: unknown, params = new URLSearchParams(), retry = true): Promise<T> {\n // Resource paths are built from schema-checked IDs. Reject foreign URLs,\n // absolute paths, queries and dot segments before sending any credentials.\n if (!/^[a-z_]+(?:\\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'spotify: invalid API resource path');\n const url = new URL(path, SPOTIFY_API_BASE);\n url.search = params.toString();\n const token = await this.accessToken();\n const response = await this.fetchImpl(url.href, {\n method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined && !(body instanceof FormData) ? { 'content-type': 'application/json' } : {}) },\n ...(body !== undefined ? { body: body instanceof FormData ? body : JSON.stringify(body) } : {}), redirect: 'error', signal: AbortSignal.timeout(60_000),\n });\n if (response.status === 401 && method === 'GET' && retry) {\n if (this.token?.value === token) this.token = undefined;\n return this.request(path, method, schema, body, params, false);\n }\n if (!response.ok) {\n const advice = response.status === 403 ? ' Check Ads API terms/allowlisting and ad-account permissions; reauthorization alone may not help.' : '';\n const details: Record<string, unknown> = { http_status: response.status };\n if ([400, 404, 409, 422].includes(response.status)) {\n const errors = z.object({ messages: z.array(z.string().max(2000)).max(30).optional(), sp_trace_id: z.uuid().optional(), error_codes: z.array(z.object({ code: z.string().max(200), definition: z.string().max(2000).optional() })).max(30).optional() });\n const parsed = errors.safeParse(await response.json().catch(() => undefined));\n if (parsed.success) {\n const redact = (value: string) => [this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, token].reduce((text, secret) => secret ? text.replaceAll(secret, '[redacted]') : text, value);\n if (parsed.data.messages) details.messages = parsed.data.messages.map(redact);\n if (parsed.data.sp_trace_id) details.sp_trace_id = parsed.data.sp_trace_id;\n if (parsed.data.error_codes) details.error_codes = parsed.data.error_codes.map(error => ({ code: redact(error.code), ...(error.definition ? { definition: redact(error.definition) } : {}) }));\n }\n }\n const messages = Array.isArray(details.messages) ? ` ${details.messages.join('; ')}` : '';\n throw new AdportError('PROVIDER_ERROR', `spotify: HTTP ${response.status}.${advice}${messages}`, details);\n }\n const parsed = schema.safeParse(response.status === 204 ? undefined : await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed API response', { api_path: path, response_issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })) });\n return parsed.data;\n }\n\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n private async refresh(): Promise<string> {\n const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }), this.fetchImpl);\n if (token.refresh_token && token.refresh_token !== this.refreshToken) {\n this.refreshToken = token.refresh_token;\n await this.credentials.onRefreshToken?.(token.refresh_token);\n }\n this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1000 };\n return token.access_token;\n }\n}\n","import { z } from 'zod';\nimport {\n AdportError, LocalMediaResolver, resolveDateRange, type Account, type AdProvider, type MediaResolver, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult, type ResourceSecretStore,\n} from '@adport/core';\nimport { SpotifyAdsClient } from './client.js';\nimport { SpotifyCreativeService } from './creatives.js';\nimport { SpotifyManagementService } from './management.js';\nimport { managementWriteNames } from './management-tools.js';\nimport { SpotifyMeasurementService } from './measurement.js';\nimport { measurementWriteNames } from './measurement-tools.js';\nimport {\n accountSchema, adSetSchema, businessSchema, campaignSchema, createDraftSchema,\n draftSchema, pagingSchema, reportSchema, setBudgetSchema, setDeliverySchema,\n setStatusSchema, spotifyId,\n} from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[] | WriteResult> }\nconst LEVEL = { account: 'AD_ACCOUNT', campaign: 'CAMPAIGN', ad_group: 'AD_SET', ad: 'AD' } as const;\nconst FIELDS = { spend: 'SPEND', impressions: 'IMPRESSIONS', clicks: 'CLICKS', conversions: 'PURCHASES', conversion_value: 'REVENUE' } as const;\nconst DERIVED = {\n ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000],\n cpa: ['spend', 'conversions', 1], roas: ['conversion_value', 'spend', 1],\n} as const;\n\nexport class SpotifyAdsProvider implements AdProvider {\n readonly id = 'spotify';\n readonly creatives: SpotifyCreativeService;\n readonly management: SpotifyManagementService;\n readonly measurement: SpotifyMeasurementService;\n constructor(private readonly client: SpotifyAdsClient, media: MediaResolver = new LocalMediaResolver(), options: { resourceSecrets?: ResourceSecretStore } = {}) { this.creatives = new SpotifyCreativeService(client, media); this.management = new SpotifyManagementService(client, this.creatives); this.measurement = new SpotifyMeasurementService(client, options.resourceSecrets); }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({ tool: 'spotify_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) };\n }\n\n async listAccounts(): Promise<Account[]> {\n const { businesses } = await this.client.get('businesses', z.object({ businesses: z.array(businessSchema) }));\n const accounts = new Map<string, Account>();\n for (const business of businesses) {\n const { ad_accounts } = await this.client.get(`businesses/${business.id}/ad_accounts`, z.object({ ad_accounts: z.array(accountSchema) }));\n for (const account of ad_accounts) accounts.set(account.id, { provider: this.id, id: account.id, name: account.name, currency: account.currency_code, status: account.status });\n }\n return [...accounts.values()];\n }\n\n async listCampaigns(accountId: string) {\n const path = `ad_accounts/${spotifyId.parse(accountId)}/campaigns`;\n const schema = z.object({ paging: pagingSchema, campaigns: z.array(campaignSchema) });\n const rows: z.infer<typeof campaignSchema>[] = [];\n const seen = new Set<string>();\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.client.get(path, schema, new URLSearchParams({ limit: '50', offset: String(offset), sort_field: 'ID', sort_direction: 'ASC' }));\n if (data.paging.offset !== offset) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination changed offset');\n for (const campaign of data.campaigns) {\n if (seen.has(campaign.id)) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination repeated an entity');\n seen.add(campaign.id);\n rows.push(campaign);\n }\n offset += data.campaigns.length;\n if (offset >= data.paging.total_results) return rows;\n if (!data.campaigns.length) break;\n }\n throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination did not terminate; refusing incomplete results');\n }\n\n async getAdSet(accountId: string, adSetId: string) {\n const data = await this.client.get(`ad_accounts/${spotifyId.parse(accountId)}/ad_sets/${spotifyId.parse(adSetId)}`, adSetSchema);\n if (data.id !== adSetId) throw new AdportError('PROVIDER_ERROR', 'spotify: ad set response ID mismatch');\n return data;\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const start = z.iso.date().parse(range.start), end = z.iso.date().parse(range.end);\n const days = (Date.parse(end) - Date.parse(start)) / 86_400_000;\n if (days < 0 || days > 90) throw new AdportError('INVALID_INPUT', 'spotify: report end must be on/after start and within 90 days');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'spotify: report limit must be a positive integer');\n const fields = new Set<string>();\n for (const metric of query.metrics) {\n if (metric in FIELDS) fields.add(FIELDS[metric as keyof typeof FIELDS]);\n else if (metric in DERIVED) for (const dependency of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) fields.add(FIELDS[dependency as keyof typeof FIELDS]);\n }\n if (!fields.size) throw new AdportError('INVALID_INPUT', 'spotify: report requires at least one supported metric');\n const accountIds = [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))];\n const rows: ReportRow[] = [];\n for (const id of accountIds) {\n const accountId = spotifyId.parse(id);\n let params = new URLSearchParams({ entity_type: LEVEL[query.level], report_start: `${start}T00:00:00Z`, report_end: `${end}T00:00:00Z`, granularity: 'LIFETIME', limit: '50' });\n for (const field of fields) params.append('fields', field);\n const tokens = new Set<string>();\n const entities = new Set<string>();\n while (true) {\n const data = await this.client.get(`ad_accounts/${accountId}/aggregate_reports`, reportSchema, params);\n if (data.granularity !== 'LIFETIME') throw new AdportError('PROVIDER_ERROR', 'spotify: unexpected report granularity');\n for (const row of data.rows) {\n if (row.entity_type !== LEVEL[query.level] || (query.level === 'account' && row.entity_id !== accountId) || entities.has(row.entity_id)) {\n throw new AdportError('PROVIDER_ERROR', 'spotify: incorrectly scoped or duplicate report row');\n }\n entities.add(row.entity_id);\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: row.entity_id, name: row.entity_name, status: row.entity_status }, metrics: normalize(row.stats, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n if (!data.continuation_token) break;\n if (tokens.has(data.continuation_token) || tokens.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'spotify: report pagination did not terminate');\n tokens.add(data.continuation_token);\n // Other parameters are ignored by Spotify when a continuation is supplied.\n params = new URLSearchParams({ continuation_token: data.continuation_token });\n }\n }\n return { rows };\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const result = await (await this.plan(op, guard)).execute();\n return Array.isArray(result) ? { applied: true, resourceIds: result } : result;\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = spotifyId.parse(op.accountId);\n const base = `ad_accounts/${accountId}`;\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'spotify: provider mismatch');\n if (measurementWriteNames.has(op.tool)) return this.measurement.plan(op);\n if (op.tool === 'spotify_create_campaign_draft' && op.kind === 'create') {\n const input = createDraftSchema.parse(op.payload);\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const body = { ...input, status };\n return {\n summary: `Create Spotify campaign draft \"${input.name}\" (not published)`, changes: [`+ ${JSON.stringify(body)}`],\n coercions: input.status !== status ? ['status coerced to PAUSED by policy (paused_creation)'] : [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.mutate(`${base}/drafts/campaigns`, 'POST', body, draftSchema);\n if (result.ad_account_id !== accountId || result.status !== status) throw new AdportError('PROVIDER_ERROR', 'spotify: created draft response violated account/status expectations; inspect the draft before retrying');\n return [result.id];\n },\n };\n }\n if (op.tool === 'spotify_set_campaign_status' && op.kind === 'update') {\n const input = setStatusSchema.parse(op.payload);\n const path = `${base}/campaigns/${input.campaign_id}`;\n const current = await this.client.get(path, campaignSchema);\n if (current.id !== input.campaign_id) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign response ID mismatch');\n return {\n summary: `Change Spotify campaign \"${current.name}\" status`, changes: [`~ ${current.id} status: ${current.status} → ${input.status}`], coercions: [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.mutate(path, 'PATCH', { status: input.status }, campaignSchema);\n if (result.id !== current.id || result.status !== input.status) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign update response mismatch; inspect before retrying');\n return [result.id];\n },\n };\n }\n if (op.kind === 'update' && ['spotify_set_budget', 'spotify_set_ad_set_delivery'].includes(op.tool)) {\n const input = op.tool === 'spotify_set_budget' ? setBudgetSchema.parse(op.payload) : setDeliverySchema.parse(op.payload);\n const current = await this.getAdSet(accountId, input.ad_set_id);\n const budget = 'budget_micros' in input ? { micro_amount: input.budget_micros, type: current.budget.type } : undefined;\n // Delivery must be the sole field in an ad-set PATCH. Budget changes keep\n // the existing budget type so DAILY/LIFETIME deltas stay comparable.\n const body = budget ? { budget } : { delivery: 'delivery' in input ? input.delivery : current.delivery };\n return {\n summary: `Change Spotify ad set \"${current.name}\" ${budget ? 'budget' : 'delivery'}`,\n changes: [budget ? `~ ${current.id} ${budget.type} budget micros: ${current.budget.micro_amount} → ${budget.micro_amount}` : `~ ${current.id} delivery: ${current.delivery} → ${body.delivery}`],\n coercions: [], budgetDeltas: budget ? [{ target: `ad set ${current.id} ${budget.type} budget`, fromMicros: current.budget.micro_amount, toMicros: budget.micro_amount }] : [],\n execute: async () => {\n const result = await this.client.mutate(`${base}/ad_sets/${current.id}`, 'PATCH', body, adSetSchema);\n if (result.id !== current.id || result.campaign_id !== current.campaign_id\n || (budget && (result.budget.type !== budget.type || result.budget.micro_amount !== budget.micro_amount))\n || (!budget && result.delivery !== body.delivery)) {\n throw new AdportError('PROVIDER_ERROR', 'spotify: ad set update response mismatch; inspect before retrying');\n }\n return [result.id];\n },\n };\n }\n return managementWriteNames.has(op.tool) ? this.management.plan(op) : this.creatives.plan(op, guard);\n }\n}\n\nfunction normalize(stats: Array<{ field_type: string; field_value: number }>, requested: MetricName[]) {\n const raw = new Map<string, number>();\n for (const stat of stats) {\n if (raw.has(stat.field_type)) throw new AdportError('PROVIDER_ERROR', 'spotify: duplicate report metric');\n raw.set(stat.field_type, stat.field_value);\n }\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = raw.get(field);\n // Suppressed conversion counts (-5) and missing metrics are not zero.\n if (value !== undefined && value >= 0) mapped[metric as MetricName] = value;\n }\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {\n if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) mapped[metric as MetricName] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n }\n return Object.fromEntries(requested.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { AdportError, type Creative, type MediaResolver, type MediaSource, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport { assetResponse, createAd, createAsset, createGroup, draftMutation, draftResponse, publishDraft, updateAd, updateCampaign, updateGroup, uploadAsset } from './creative-schemas.js';\nimport { budgetSchema, spotifyId } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Entity = 'campaigns' | 'ad_sets' | 'ads';\ninterface Page { account_id: string; limit: number; offset: number }\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst object = z.record(z.string(), z.unknown());\nconst paging = z.looseObject({ offset: z.number().int().nonnegative(), total_results: z.number().int().nonnegative() });\nconst keys = { campaigns: 'campaign_drafts', ad_sets: 'ad_set_drafts', ads: 'ad_drafts' } as const;\n\n/** Spotify's live v3 OpenAPI is the wire authority, including native draft versions. */\nexport class SpotifyCreativeService {\n constructor(private readonly client: SpotifyAdsClient, private readonly media: MediaResolver) {}\n private base(account: string) { return `ad_accounts/${spotifyId.parse(account)}`; }\n\n async page(input: Page, path: string, key: string, params: Row = {}): Promise<Row & { truncated: boolean; next_offset?: number }> {\n const data = await this.client.get(`${this.base(input.account_id)}/${path}`, z.looseObject({ paging }), query({ limit: input.limit, offset: input.offset, ...params }));\n if (data.paging.offset !== input.offset) throw new AdportError('PROVIDER_ERROR', 'spotify: pagination offset mismatch');\n const rows = z.array(draftResponse).parse(data[key]);\n for (const row of rows) this.checkAccount(input.account_id, row);\n const next = input.offset + rows.length, truncated = next < data.paging.total_results;\n if (truncated && !rows.length) throw new AdportError('PROVIDER_ERROR', 'spotify: pagination stalled');\n return { ...data, truncated, ...(truncated ? { next_offset: next } : {}) };\n }\n\n async drafts(input: Page & { entity: Entity; campaign_ids?: string[]; ad_set_ids?: string[] }) {\n return this.page(input, `drafts/${input.entity}`, keys[input.entity], { campaign_ids: input.campaign_ids, ad_set_ids: input.ad_set_ids });\n }\n\n async get(account: string, entity: Entity, id: string, draft = true) {\n const row = await this.getOwned(account, entity, id, draft);\n if (entity === 'ad_sets') await this.get(account, 'campaigns', spotifyId.parse(row.campaign_id), draft);\n else if (entity === 'ads') await this.get(account, 'ad_sets', spotifyId.parse(row.ad_set_id), draft);\n return row;\n }\n\n private async getOwned(account: string, entity: Entity, id: string, draft = true) {\n const row = await this.client.get(`${this.base(account)}/${draft ? 'drafts/' : ''}${entity}/${spotifyId.parse(id)}`, draftResponse);\n if (row.id !== id) throw new AdportError('PROVIDER_ERROR', 'spotify: response ID mismatch');\n this.checkAccount(account, row);\n if (entity === 'campaigns') {\n if (draft && row.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign account mismatch');\n if (!draft && row.ad_account_id == null) await this.verifyPublishedCampaign(account, id);\n }\n return row;\n }\n\n private checkAccount(account: string, row: Row) {\n if (row.ad_account_id != null && row.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'spotify: resource belongs to another account');\n }\n\n private async verifyPublishedCampaign(account: string, id: string) {\n // Live campaign GET/list responses can have ad_account_id:null. Prove\n // membership in the selected account's paged collection instead.\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.page({ account_id: account, limit: 50, offset }, 'campaigns', 'campaigns', { sort_field: 'ID', sort_direction: 'ASC' });\n if ((data.campaigns as Row[]).some(campaign => campaign.id === id)) return;\n if (!data.truncated) break;\n offset = data.next_offset!;\n }\n throw new AdportError('INVALID_INPUT', 'spotify: campaign is not present in the selected account’s published campaign list');\n }\n\n async assets(input: Page & { asset_types?: string[]; asset_statuses?: string[]; name?: string }) {\n const data = await this.client.get(`${this.base(input.account_id)}/assets`, z.looseObject({ paging, assets: z.array(assetResponse) }), query({ limit: input.limit, offset: input.offset, asset_types: input.asset_types, asset_statuses: input.asset_statuses, name: input.name }));\n if (data.paging.offset !== input.offset) throw new AdportError('PROVIDER_ERROR', 'spotify: asset pagination offset mismatch');\n for (const asset of data.assets) this.checkAccount(input.account_id, asset);\n const next = input.offset + data.assets.length, truncated = next < data.paging.total_results;\n if (truncated && !data.assets.length) throw new AdportError('PROVIDER_ERROR', 'spotify: asset pagination stalled');\n const creatives: Creative[] = data.assets.map(asset => ({ id: asset.id, provider: 'spotify', account_id: input.account_id, name: asset.name, type: asset.asset_type, status: asset.status, headlines: [], descriptions: [], landing_urls: [], media: mediaFor(asset), actions: [] }));\n return { ...data, creatives, truncated, ...(truncated ? { next_offset: next } : {}) };\n }\n\n async asset(account: string, id: string) {\n const asset = await this.client.get(`${this.base(account)}/assets/${spotifyId.parse(id)}`, assetResponse);\n if (asset.id !== id) throw new AdportError('PROVIDER_ERROR', 'spotify: asset response ID mismatch');\n this.checkAccount(account, asset);\n return asset;\n }\n\n async ads(input: Page & { draft: boolean; ad_set_ids?: string[] }) {\n const data = await this.page(input, `${input.draft ? 'drafts/' : ''}ads`, input.draft ? 'ad_drafts' : 'ads', { ad_set_ids: input.ad_set_ids });\n const rows = data[input.draft ? 'ad_drafts' : 'ads'] as Row[];\n const cache = new Map<string, Awaited<ReturnType<typeof this.asset>>>();\n const creatives: Creative[] = [];\n for (const ad of rows) {\n const assets = record(ad.assets), media: Creative['media'] = [];\n for (const id of new Set(Object.values(assets).filter((value): value is string => typeof value === 'string' && spotifyId.safeParse(value).success))) {\n if (!cache.has(id)) cache.set(id, await this.asset(input.account_id, id));\n media.push(...mediaFor(cache.get(id)!));\n }\n const args = { account_id: input.account_id, draft_id: ad.id };\n creatives.push({ id: String(ad.id), provider: 'spotify', account_id: input.account_id, name: String(ad.name ?? ad.id), type: input.draft ? 'DRAFT_AD' : 'AD', ...(typeof ad.status === 'string' ? { status: ad.status } : {}), ...(typeof ad.ad_set_id === 'string' ? { ad_group_id: ad.ad_set_id } : {}),\n headlines: typeof ad.advertiser_name === 'string' ? [ad.advertiser_name] : [], descriptions: typeof ad.tagline === 'string' ? [ad.tagline] : [], landing_urls: safeUrl(record(ad.call_to_action).clickthrough_url), media,\n actions: input.draft ? [{ label: 'Edit draft copy', tool: 'spotify_update_draft_ad', arguments: args, fields: [{ key: 'name', label: 'Ad name', type: 'text', value: String(ad.name ?? ''), max_length: 200 }, ...(typeof ad.tagline === 'string' ? [{ key: 'tagline', label: 'Tagline', type: 'text' as const, value: ad.tagline, max_length: 200 }] : [])] }] : [{ label: 'Stage a draft for editing', tool: 'spotify_create_draft_from_published', arguments: { account_id: input.account_id, entity: 'ads', draft_id: ad.id }, fields: [] }],\n });\n }\n return { ...data, creatives };\n }\n\n async read(account: string, path: string, params: Row = {}) { return this.client.get(`${this.base(account)}/${path}`, object, query(params)); }\n async targeting(input: { account_id: string; kind: string } & Row) {\n const { account_id, kind, ...params } = input;\n return this.client.get(`targets/${kind}`, object, query({ ...params, ...(kind === 'languages' ? { ad_account_id: account_id } : {}) }));\n }\n async categories(q?: string) { return this.client.get('ad_categories', object, query({ q })); }\n async estimate(kind: 'audience' | 'bid', input: { account_id: string } & Row) {\n const { account_id, ...body } = input;\n return this.client.mutate(`estimates/${kind}`, 'POST', { ...body, ...(kind === 'audience' ? { ad_account_id: account_id } : {}) }, object);\n }\n async validate(account: string, id: string, version: number) {\n const campaign = await this.get(account, 'campaigns', id);\n this.version(campaign, version);\n return this.client.mutate(`${this.base(account)}/drafts/campaigns/${id}`, 'POST', { action: 'VALIDATE', draft_hierarchy_version: version }, object);\n }\n private version(campaign: Row, version: number) {\n if (campaign.draft_hierarchy_version !== version) throw new AdportError('PENDING_MISMATCH', 'spotify: draft hierarchy changed. Read its current version and prepare a new preview.');\n }\n private async allDrafts(account: string, entity: Entity, campaign: string) {\n const rows: Row[] = [], seen = new Set<string>();\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.drafts({ account_id: account, entity, campaign_ids: [campaign], limit: 50, offset });\n const nextRows = data[keys[entity]] as Row[];\n for (const row of nextRows) { if (seen.has(String(row.id))) throw new AdportError('PROVIDER_ERROR', 'spotify: repeated draft resource'); seen.add(String(row.id)); rows.push(row); }\n if (!data.truncated) return rows;\n offset = data.next_offset!;\n }\n throw new AdportError('PROVIDER_ERROR', 'spotify: draft hierarchy pagination did not terminate');\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const base = this.base(op.accountId), coercions: string[] = [], budgetDeltas: WritePreview['budgetDeltas'] = [];\n let path: string, body: Row, method: 'POST' | 'PATCH' = 'PATCH', expectedId: string | undefined;\n const payload = op.payload;\n switch (op.tool) {\n case 'spotify_create_draft_ad_set': {\n const input = createGroup.parse(payload);\n await this.get(op.accountId, 'campaigns', input.campaign_id);\n body = input; path = `${base}/drafts/ad_sets`; method = 'POST';\n checkGroup(body);\n monetaryDeltas(body, {}, `draft ad set ${input.name}`, budgetDeltas);\n break;\n }\n case 'spotify_create_draft_ad': {\n const input = createAd.parse(payload);\n await this.get(op.accountId, 'ad_sets', input.ad_set_id);\n await this.verifyAssets(op.accountId, input.assets);\n body = input; path = `${base}/drafts/ads`; method = 'POST'; break;\n }\n case 'spotify_update_draft_campaign':\n case 'spotify_update_draft_ad_set':\n case 'spotify_update_draft_ad': {\n const entity = op.tool === 'spotify_update_draft_campaign' ? 'campaigns' : op.tool === 'spotify_update_draft_ad_set' ? 'ad_sets' : 'ads';\n const input = (entity === 'campaigns' ? updateCampaign : entity === 'ad_sets' ? updateGroup : updateAd).parse(payload);\n const { draft_id, ...fields } = input;\n const current = await this.get(op.accountId, entity, draft_id);\n body = { ...fields }; expectedId = draft_id;\n if (body.targets !== undefined) body.targets = { ...record(current.targets), ...record(body.targets) };\n for (const key of ['assets', 'call_to_action']) if (body[key] !== undefined) {\n const writable = key === 'assets' ? ['asset_id', 'logo_asset_id', 'companion_asset_id', 'canvas_asset_id'] : ['key', 'language', 'clickthrough_url'];\n body[key] = { ...Object.fromEntries(Object.entries(record(current[key])).filter(([field, value]) => writable.includes(field) && value !== null)), ...record(body[key]) };\n }\n if (entity === 'ad_sets') { checkGroup({ ...current, ...body }); monetaryDeltas(body, current, `draft ad set ${draft_id}`, budgetDeltas); }\n if (entity === 'ads') await this.verifyAssets(op.accountId, body.assets);\n path = `${base}/drafts/${entity}/${draft_id}`; break;\n }\n case 'spotify_create_draft_from_published': {\n const input = draftMutation.parse(payload);\n await this.get(op.accountId, input.entity, input.draft_id, false);\n try {\n await this.get(op.accountId, input.entity, input.draft_id);\n throw new AdportError('INVALID_INPUT', 'spotify: a draft already exists. Read and edit it instead of overwriting pending changes.');\n } catch (error) { if (!isNotFound(error)) throw error; }\n path = `${base}/${input.entity}/${input.draft_id}/drafts`; method = 'POST'; expectedId = input.draft_id; body = {}; break;\n }\n case 'spotify_delete_draft': {\n const input = draftMutation.parse(payload);\n // Spotify can retain orphan ad drafts after deleting a parent campaign.\n // The account-scoped resource read still proves ownership for cleanup.\n const current = await this.getOwned(op.accountId, input.entity, input.draft_id);\n if (input.entity === 'campaigns') {\n const groups = await this.allDrafts(op.accountId, 'ad_sets', input.draft_id);\n for (const group of groups) await this.ensureNoAdDrafts(op.accountId, String(group.id));\n } else if (input.entity === 'ad_sets') await this.ensureNoAdDrafts(op.accountId, input.draft_id);\n return { summary: `Delete Spotify draft ${input.entity}/${input.draft_id}`, changes: [`- ${current.name ?? current.id}; draft children may also be deleted. Published entities remain unchanged.`], coercions, budgetDeltas, execute: async () => { await this.client.mutate(`${base}/drafts/${input.entity}/${input.draft_id}`, 'DELETE', undefined, z.undefined()); return [input.draft_id]; } };\n }\n case 'spotify_delete_draft_ads':\n case 'spotify_delete_draft_ad_sets': {\n const ads = op.tool === 'spotify_delete_draft_ads', entity = ads ? 'ads' : 'ad_sets';\n const input = z.object({ draft_ids: z.array(spotifyId).min(1).max(ads ? 100 : 40).refine(ids => new Set(ids).size === ids.length, 'IDs must be unique') }).parse(payload);\n for (const id of input.draft_ids) { await this.getOwned(op.accountId, entity, id); if (!ads) await this.ensureNoAdDrafts(op.accountId, id); }\n return { summary: `Delete ${input.draft_ids.length} Spotify ${entity} drafts`, changes: input.draft_ids.map(id => `- draft ${id}${ads ? '' : ' and child ad drafts'}; published entities remain unchanged`), coercions, budgetDeltas, execute: async () => { await this.client.mutate(`${base}/drafts/${entity}`, 'DELETE', undefined, z.undefined(), query({ [ads ? 'ad_draft_ids' : 'ad_set_draft_ids']: input.draft_ids })); return input.draft_ids; } };\n }\n case 'spotify_publish_draft': return this.publish(op, guard);\n case 'spotify_create_asset': {\n const input = createAsset.parse(payload);\n return { summary: `Create Spotify ${input.asset_type} asset metadata`, changes: [`+ ${JSON.stringify(input)}; file upload is a separate approved operation`], coercions, budgetDeltas, execute: async () => { const asset = await this.client.mutate(`${base}/assets`, 'POST', input, assetResponse); this.checkAccount(op.accountId, asset); if (asset.asset_type !== input.asset_type) throw new AdportError('PROVIDER_ERROR', 'spotify: created asset type mismatch; inspect before retrying'); return [asset.id]; } };\n }\n case 'spotify_rename_asset': {\n const input = z.object({ asset_id: spotifyId, name: z.string().trim().min(2).max(120) }).parse(payload);\n const current = await this.asset(op.accountId, input.asset_id);\n return { summary: 'Rename Spotify asset', changes: [`~ ${current.id} name: ${current.name} → ${input.name}`], coercions, budgetDeltas, execute: async () => { const result = await this.client.mutate(`${base}/assets/${current.id}`, 'PATCH', { asset_type: current.asset_type, name: input.name }, assetResponse); if (result.id !== current.id || result.name !== input.name) throw new AdportError('PROVIDER_ERROR', 'spotify: asset update response mismatch'); return [current.id]; } };\n }\n case 'spotify_upload_asset': return this.upload(op);\n default: throw new AdportError('INVALID_INPUT', `spotify: unsupported write ${op.tool}`);\n }\n const parent = body.campaign_id ?? body.ad_set_id;\n return { summary: `Spotify ${op.tool.replace(/^spotify_/, '').replaceAll('_', ' ')}`, changes: [`${method} /${path} ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: async () => {\n const result = await this.client.mutate(path, method, op.tool === 'spotify_create_draft_from_published' ? undefined : body, draftResponse);\n this.checkAccount(op.accountId, result);\n if ((expectedId && result.id !== expectedId) || (parent && parent !== (result.campaign_id ?? result.ad_set_id))) throw new AdportError('PROVIDER_ERROR', 'spotify: draft mutation response mismatch; inspect before retrying');\n return [result.id];\n } };\n }\n\n private async verifyAssets(account: string, assets: unknown) {\n for (const value of Object.values(record(assets))) await this.asset(account, spotifyId.parse(value));\n }\n\n private async ensureNoAdDrafts(account: string, group: string) {\n const data = await this.drafts({ account_id: account, entity: 'ads', ad_set_ids: [group], limit: 1, offset: 0 });\n if ((data.ad_drafts as Row[]).length || data.truncated) throw new AdportError('INVALID_INPUT', 'spotify: delete draft ads before deleting their parent. Spotify can otherwise leave undeletable orphan ad drafts.');\n }\n\n private async publish(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n if (guard.forcePausedCreation) throw new AdportError('POLICY_VIOLATION', 'spotify: publication is blocked by paused_creation. The live PUBLISH endpoint activates even a PAUSED draft; Spotify cannot guarantee paused publication. Keep this hierarchy as a draft.');\n const input = publishDraft.parse(op.payload), account = op.accountId;\n if (!input.acknowledge_active_publication) throw new AdportError('INVALID_INPUT', 'spotify: publishing activates the campaign. Explicit acknowledge_active_publication=true is required.');\n const campaign = await this.get(account, 'campaigns', input.draft_campaign_id);\n this.version(campaign, input.draft_hierarchy_version);\n const groups = await this.allDrafts(account, 'ad_sets', campaign.id);\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n for (const group of groups) {\n if (group.campaign_id !== campaign.id) throw new AdportError('PROVIDER_ERROR', 'spotify: draft ad set belongs to another campaign');\n let current: Row = {};\n try { current = await this.get(account, 'ad_sets', String(group.id), false); } catch (error) { if (!isNotFound(error)) throw error; }\n monetaryDeltas(group, current, `publish ad set ${group.id}`, budgetDeltas);\n }\n return { summary: `Publish Spotify campaign ${campaign.name ?? campaign.id} as ACTIVE`, changes: [`PUBLISH hierarchy version ${input.draft_hierarchy_version}; ${groups.length} draft ad sets. Spotify changes campaign status ${campaign.status} → ACTIVE, regardless of the draft's paused state.`], coercions: [], budgetDeltas, execute: async () => {\n const validation = await this.validate(account, campaign.id, input.draft_hierarchy_version);\n assertValidation(validation);\n const result = await this.client.mutate(`${this.base(account)}/drafts/campaigns/${campaign.id}`, 'POST', { action: 'PUBLISH', draft_hierarchy_version: input.draft_hierarchy_version }, object);\n assertValidation(result);\n const published = record(result.campaign);\n if (published.id !== campaign.id || (published.ad_account_id != null && published.ad_account_id !== account) || published.status !== 'ACTIVE') throw new AdportError('PROVIDER_ERROR', 'spotify: publish receipt does not confirm the expected campaign/account/status. Inspect before retrying.', { resource_ids: spotifyId.safeParse(published.id).success ? [published.id] : [], observed_status: published.status });\n if (published.ad_account_id == null) await this.verifyPublishedCampaign(account, campaign.id);\n return [campaign.id];\n } };\n }\n\n private async upload(op: WriteOperation): Promise<Plan> {\n const input = uploadAsset.parse(op.payload), current = await this.asset(op.accountId, input.asset_id);\n if (current.status !== 'WAITING_UPLOAD') throw new AdportError('INVALID_INPUT', 'spotify: upload only to a new WAITING_UPLOAD asset. Create a separate asset instead of replacing media used by ads.');\n const types = { IMAGE: ['image/png', 'image/jpeg'], AUDIO: ['audio/mpeg', 'audio/wav', 'audio/ogg'], VIDEO: ['video/mp4', 'video/quicktime'] };\n const file = await this.media.read(input as MediaSource, { maxBytes: 100 * 1024 * 1024, contentTypes: types[current.asset_type] });\n const path = `${this.base(op.accountId)}/assets/${current.id}`;\n return { summary: `Upload Spotify ${current.asset_type} asset ${current.name}`, changes: [`+ ${file.name}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}; existing ads are unchanged`], coercions: [], budgetDeltas: [], execute: async () => {\n let result: z.infer<typeof assetResponse>;\n if (file.bytes.byteLength <= 20_000_000) {\n result = await this.client.upload(`${path}/upload`, form(file.bytes, file.name, file.contentType, { asset_type: current.asset_type }), assetResponse);\n } else {\n const session = await this.client.mutate(`${path}/chunked_upload/start`, 'POST', undefined, z.object({ upload_session_id: spotifyId, max_chunk_size_mb: z.number().int().positive().max(100) }));\n const size = session.max_chunk_size_mb * 1_000_000, sections = Math.ceil(file.bytes.byteLength / size);\n if (sections > 1000) throw new AdportError('PROVIDER_ERROR', 'spotify: upload requires too many chunks');\n for (let index = 0; index < sections; index++) {\n const reply = await this.client.upload(`${path}/chunked_upload/transfer`, form(file.bytes.slice(index * size, (index + 1) * size), file.name, file.contentType, { asset_type: current.asset_type, upload_session_id: session.upload_session_id, upload_section: String(index + 1) }), z.object({ success: z.boolean() }));\n if (!reply.success) throw new AdportError('PROVIDER_ERROR', `spotify: upload section ${index + 1} failed. Inspect the asset before retrying.`);\n }\n result = await this.client.mutate(`${path}/chunked_upload/complete`, 'POST', { asset_type: current.asset_type, upload_session_id: session.upload_session_id, number_of_sections: sections }, assetResponse);\n }\n if (result.id !== current.id || result.asset_type !== current.asset_type || result.status === 'ERROR') throw new AdportError('PROVIDER_ERROR', 'spotify: uploaded asset response mismatch/error; inspect before retrying');\n return [current.id];\n } };\n }\n}\n\nfunction record(value: unknown): Row { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {}; }\nfunction query(input: Row) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(input)) if (value !== undefined) { if (Array.isArray(value)) for (const item of value) params.append(key, String(item)); else params.set(key, String(value)); } return params; }\nfunction safeUrl(value: unknown): string[] { if (typeof value !== 'string') return []; try { const url = new URL(value); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? [value] : []; } catch { return []; } }\nfunction mediaFor(asset: z.infer<typeof assetResponse>): Creative['media'] { return safeUrl(asset.url).filter(url => url.startsWith('https:')).map(url => ({ type: asset.asset_type === 'IMAGE' ? 'image' : asset.asset_type === 'VIDEO' ? 'video' : 'audio', url })); }\nfunction isNotFound(error: unknown) { return error instanceof AdportError && record(error.details).http_status === 404; }\nfunction form(bytes: Uint8Array<ArrayBuffer>, name: string, type: string, fields: Record<string, string>) { const data = new FormData(); for (const [key, value] of Object.entries(fields)) data.set(key, value); data.set('media', new Blob([bytes], { type }), name); return data; }\nfunction checkGroup(row: Row) {\n const target = record(row.targets), budget = record(row.budget);\n if (row.targets !== undefined && (!Array.isArray(target.placements) || !target.placements.length)) throw new AdportError('INVALID_INPUT', 'spotify: supplied targeting must include placements');\n if (budget.type === 'LIFETIME' && !row.end_time) throw new AdportError('INVALID_INPUT', 'spotify: lifetime budget requires end_time');\n if (row.start_time && row.end_time && String(row.end_time) <= String(row.start_time)) throw new AdportError('INVALID_INPUT', 'spotify: end_time must be after start_time');\n}\nfunction monetaryDeltas(next: Row, current: Row, target: string, deltas: WritePreview['budgetDeltas']) {\n if (next.budget !== undefined) {\n const budget = budgetSchema.parse(next.budget), old = current.budget === undefined ? undefined : budgetSchema.parse(current.budget);\n if (old && old.type !== budget.type) throw new AdportError('INVALID_INPUT', 'spotify: budget type changes require a separate ad set');\n deltas.push({ target: `${target} ${budget.type} budget`, ...(old ? { fromMicros: old.micro_amount } : {}), toMicros: budget.micro_amount });\n }\n if (next.bid_micro_amount !== undefined) {\n const amount = z.number().int().nonnegative().safe().parse(next.bid_micro_amount);\n const old = current.bid_micro_amount === undefined ? undefined : z.number().int().nonnegative().safe().parse(current.bid_micro_amount);\n deltas.push({ target: `${target} bid`, ...(old !== undefined ? { fromMicros: old } : {}), toMicros: amount });\n }\n}\nfunction assertValidation(result: Row) {\n if (result.validation_errors !== undefined && result.validation_errors !== null && !Array.isArray(result.validation_errors)) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed draft validation result');\n if (Array.isArray(result.validation_errors) && result.validation_errors.length) throw new AdportError('PROVIDER_ERROR', 'spotify: draft hierarchy failed validation; nothing was published', { validation_errors: result.validation_errors });\n}\n","import { mediaSourceFields } from '@adport/core';\nimport { z } from 'zod';\nimport { budgetSchema, spotifyId } from './schemas.js';\n\nconst strings = z.array(z.string().min(1)).max(1000);\nconst money = z.number().int().nonnegative().safe();\nconst url = z.string().url().refine(value => { const u = new URL(value); return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) destination without embedded credentials');\nexport const assetType = z.enum(['AUDIO', 'IMAGE', 'VIDEO']);\nexport const assetFormat = z.enum(['AUDIO', 'IMAGE', 'VIDEO', 'MULTI', 'CATALOG']);\nconst adLanguage = z.enum(['ARABIC', 'ARABIC_EGYPT', 'BULGARIAN', 'CHINESE', 'CHINESE_HK', 'CHINESE_TAIWAN', 'CROATIAN', 'CZECH', 'DANISH', 'DUTCH', 'ENGLISH', 'FINNISH', 'FRENCH', 'FRENCH_CANADA', 'GERMAN', 'GREEK', 'HEBREW', 'HUNGARIAN', 'INDONESIAN', 'ITALIAN', 'JAPANESE', 'KOREAN', 'NORWEGIAN', 'POLISH', 'PORTUGUESE', 'PORTUGUESE_PORTUGAL', 'ROMANIAN', 'RUSSIAN', 'SLOVAK', 'SPANISH', 'SPANISH_ARGENTINA', 'SPANISH_LATAM_CARIBBEAN', 'SPANISH_MEXICO', 'SWEDISH', 'THAI', 'TURKISH', 'UKRAINIAN', 'VIETNAMESE']);\nexport const deliveryGoal = z.enum(['UNSET', 'IMPRESSIONS', 'REACH', 'VIDEO_VIEWS', 'CLICKS', 'PAGE_VIEWS', 'APP_INSTALLS', 'STREAMS', 'LEADS']);\nexport const bidStrategy = z.enum(['COST_PER_RESULT', 'MAX_BID', 'AUTOBID', 'UNSET']);\nexport const frequencyCaps = z.array(z.object({ frequency_unit: z.enum(['DAY', 'WEEK', 'MONTH']), frequency_period: z.number().int().positive(), max_impressions: z.number().int().positive() }).strict()).max(6);\nexport const targets = z.object({\n age_ranges: z.array(z.object({ min: z.number().int().min(13).max(99), max: z.number().int().min(13).max(99) }).refine(v => v.max >= v.min)).optional(),\n artist_ids: strings.optional(), genre_ids: strings.optional(), interest_ids: z.array(spotifyId).optional(),\n geo_targets: z.object({ country_code: z.string().regex(/^[A-Z]{2}$/).optional(), city_ids: strings.optional(), postal_code_ids: strings.optional(), region_ids: strings.optional() }).strict().optional(),\n genders: z.array(z.enum(['MALE', 'FEMALE', 'NON_BINARY'])).optional(), platforms: z.array(z.enum(['ANDROID', 'DESKTOP', 'IOS'])).optional(),\n podcast_episode_topic_ids: strings.optional(), language: z.string().regex(/^[a-z]{2}$/).optional(), playlist_ids: strings.optional(),\n placements: z.array(z.enum(['MUSIC', 'PODCAST', 'PODCAST_SAI', 'PODCAST_DAI'])).min(1).optional(),\n audience_ids: z.array(spotifyId).optional(), audience_ids_exclusions: z.array(spotifyId).optional(),\n sensitive_topic_exclusions: z.object({ topics: z.array(z.object({ id: z.string().min(1), filter_option: z.enum(['STANDARD', 'LIMITED', 'PARTIAL', 'RESTRICTED']) }).strict()).optional(), filter_option: z.enum(['STANDARD', 'LIMITED', 'PARTIAL', 'RESTRICTED']).optional() }).strict().refine(v => Boolean(v.topics) !== Boolean(v.filter_option), 'Choose topics or a global filter').optional(),\n user_day_parts: z.array(z.object({ day_of_week: z.array(z.enum(['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'])), hour_of_day: z.array(z.object({ min: z.number().int().min(0).max(23), max: z.number().int().min(0).max(23) }).refine(v => v.max >= v.min)) }).strict()).optional(),\n}).strict();\nexport const campaignPatch = z.object({ name: z.string().trim().min(2).max(200).optional(), purchase_order: z.string().min(2).max(45).optional(), delivery_goal_group: z.enum(['AWARENESS', 'WEBSITE_TRAFFIC', 'APP_PROMOTION', 'ENGAGEMENT_ON_SPOTIFY', 'LEAD_GEN', 'VIDEO_VIEWS']).optional(), status: z.enum(['PAUSED', 'ACTIVE', 'ARCHIVED']).optional() }).strict();\nexport const groupPatch = z.object({\n name: z.string().trim().min(2).max(200).optional(), start_time: z.iso.datetime().optional(), end_time: z.iso.datetime().optional(),\n budget: budgetSchema.optional(), bid_micro_amount: money.optional(), bid_strategy: bidStrategy.optional(), targets: targets.optional(),\n category: z.string().regex(/^ADV_\\d+_\\d+$/).optional(), asset_format: assetFormat.optional(), delivery_goal: deliveryGoal.optional(),\n pacing: z.enum(['PACING_ASAP', 'PACING_EVEN']).optional(), frequency_caps: frequencyCaps.optional(), dataset_id: spotifyId.optional(), mobile_app_id: spotifyId.optional(),\n}).strict();\nexport const adPatch = z.object({\n name: z.string().trim().min(2).max(200).optional(), advertiser_name: z.string().min(1).max(200).optional(), tagline: z.string().min(1).max(200).optional(),\n assets: z.object({ asset_id: spotifyId.optional(), logo_asset_id: spotifyId.optional(), companion_asset_id: spotifyId.optional(), canvas_asset_id: spotifyId.optional() }).strict().optional(),\n asset_format: assetFormat.optional(), call_to_action: z.object({ key: z.enum(['APPLY_NOW', 'BOOK_NOW', 'BUY_NOW', 'BUY_TICKETS', 'CLICK_NOW', 'DOWNLOAD', 'FIND_STORES', 'GET_COUPON', 'GET_INFO', 'INSTALL_NOW', 'LEARN_MORE', 'LISTEN_NOW', 'MORE_INFO', 'ORDER_NOW', 'PRE_SAVE', 'SAVE_NOW', 'SHARE', 'SHOP_NOW', 'SIGN_UP', 'VISIT_PROFILE', 'VISIT_SITE', 'WATCH_NOW']).optional(), language: adLanguage.optional(), clickthrough_url: url.optional() }).strict().optional(),\n third_party_tracking: z.array(z.object({ measurement_partner: z.enum(['IAS', 'DCM', 'UNSET']), url }).strict()).max(11).optional(),\n weight: z.number().int().min(1).max(100).optional(),\n}).strict();\nexport const createGroup = groupPatch.extend({ campaign_id: spotifyId, name: z.string().trim().min(2).max(200) });\nexport const createAd = adPatch.extend({ ad_set_id: spotifyId, name: z.string().trim().min(2).max(200) });\nexport const draftEntity = z.enum(['campaigns', 'ad_sets', 'ads']);\nexport const draftMutation = z.object({ entity: draftEntity, draft_id: spotifyId });\nexport const updateCampaign = campaignPatch.extend({ draft_id: spotifyId }).refine(v => Object.keys(v).length > 1, 'Provide a change');\nexport const updateGroup = groupPatch.extend({ draft_id: spotifyId }).refine(v => Object.keys(v).length > 1, 'Provide a change');\nexport const updateAd = adPatch.extend({ draft_id: spotifyId }).refine(v => Object.keys(v).length > 1, 'Provide a change');\nexport const publishDraft = z.object({ draft_campaign_id: spotifyId, draft_hierarchy_version: z.number().int().positive(), acknowledge_active_publication: z.literal(true).optional().describe('Required for publication when policy permits active creation. Spotify publishes ACTIVE even when the draft is PAUSED.') });\nexport const createAsset = z.object({ name: z.string().trim().min(2).max(120), asset_type: assetType, asset_subtype: z.enum(['BACKGROUND_MUSIC', 'USER_UPLOADED_AUDIO']).optional() }).refine(v => !v.asset_subtype || v.asset_type === 'AUDIO', 'Asset subtype is audio-only');\nexport const uploadAsset = z.object({ asset_id: spotifyId, ...mediaSourceFields }).refine(v => Number(Boolean(v.media_id)) + Number(Boolean(v.file_path)) === 1, 'Choose media_id or file_path');\nexport const assetResponse = z.looseObject({ id: spotifyId, name: z.string(), asset_type: assetType, status: z.string(), url: z.string().optional() });\nexport const draftResponse = z.looseObject({ id: spotifyId, name: z.string().nullable().optional(), ad_account_id: spotifyId.nullable().optional(), campaign_id: spotifyId.optional(), ad_set_id: spotifyId.optional(), status: z.string().nullable().optional(), draft_hierarchy_version: z.number().int().positive().nullable().optional() });\n","import { z } from 'zod';\n\n// Spotify Ads v3 reference contracts, reviewed 2026-08-31.\n// Response objects remain forward-compatible; fields consumed for policy and\n// reporting are validated instead of interpreting malformed data as empty data.\nexport const spotifyId = z.uuid();\nexport const businessSchema = z.looseObject({ id: spotifyId, name: z.string() });\nexport const accountSchema = z.looseObject({\n id: spotifyId, name: z.string(), currency_code: z.string(), status: z.string(),\n business_id: spotifyId.optional(), test_account_type: z.string().optional(),\n});\nexport const campaignSchema = z.looseObject({ id: spotifyId, name: z.string(), status: z.string() });\nexport const draftSchema = campaignSchema.extend({ ad_account_id: spotifyId });\nexport const budgetSchema = z.object({ micro_amount: z.number().int().nonnegative().safe(), type: z.enum(['DAILY', 'LIFETIME']) });\nexport const adSetSchema = z.looseObject({\n id: spotifyId, campaign_id: spotifyId, name: z.string(), budget: budgetSchema, delivery: z.enum(['ON', 'OFF']),\n});\nexport const pagingSchema = z.object({\n page_size: z.number().int().nonnegative(), total_results: z.number().int().nonnegative(),\n offset: z.number().int().nonnegative(), current_page: z.number().int().nonnegative(),\n});\nexport const reportRowSchema = z.looseObject({\n entity_type: z.enum(['AD_ACCOUNT', 'CAMPAIGN', 'AD_SET', 'AD']),\n entity_id: spotifyId, entity_name: z.string(), entity_status: z.string(),\n stats: z.array(z.object({ field_type: z.string(), field_value: z.number() })),\n});\nexport const reportSchema = z.looseObject({\n continuation_token: z.string().nullable().optional(),\n granularity: z.enum(['LIFETIME', 'DAY', 'HOUR']), rows: z.array(reportRowSchema),\n});\nexport const createDraftSchema = z.object({\n name: z.string().trim().min(2).max(200),\n purchase_order: z.string().min(2).max(45).optional(),\n delivery_goal_group: z.enum(['AWARENESS', 'WEBSITE_TRAFFIC', 'APP_PROMOTION', 'ENGAGEMENT_ON_SPOTIFY', 'LEAD_GEN', 'VIDEO_VIEWS']),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n});\nexport const setStatusSchema = z.object({ campaign_id: spotifyId, status: z.enum(['PAUSED', 'ACTIVE']) });\nexport const setBudgetSchema = z.object({ ad_set_id: spotifyId, budget_micros: z.number().int().positive().safe() });\nexport const setDeliverySchema = z.object({ ad_set_id: spotifyId, delivery: z.enum(['OFF', 'ON']) });\n","import { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport type { SpotifyCreativeService } from './creatives.js';\nimport { createAudience, createLookalike, createReport, deleteAudience, updateAudience } from './management-tools.js';\nimport { spotifyId } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst object = z.record(z.string(), z.unknown());\nconst audienceSchema = z.looseObject({ id: spotifyId, type: z.enum(['CUSTOM', 'LOOKALIKE']), name: z.string() });\nfunction query(input: Row) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(input)) if (value !== undefined) { if (Array.isArray(value)) value.forEach(item => params.append(key, String(item))); else params.set(key, String(value)); } return params; }\n\nexport class SpotifyManagementService {\n constructor(private readonly client: SpotifyAdsClient, private readonly creatives: SpotifyCreativeService) {}\n private base(account: string) { return `ad_accounts/${spotifyId.parse(account)}`; }\n async read(input: { account_id: string } & Row, path: string) { const { account_id, ...params } = input; return this.client.get(`${this.base(account_id)}/${path}`, object, query(params)); }\n async audiences(input: { account_id: string; limit: number; offset: number } & Row) { const { account_id: _account, limit: _limit, offset: _offset, ...params } = input; return this.creatives.page(input, 'audiences', 'audiences', params); }\n async insights(input: { account_id: string; ad_set_id: string } & Row) {\n const { ad_set_id, ...params } = input;\n await this.creatives.get(input.account_id, 'ad_sets', ad_set_id, false);\n return this.read({ ...params, entity_ids: [ad_set_id], entity_ids_type: 'AD_SET' }, 'insight_reports');\n }\n async audience(account: string, id: string) {\n const result = await this.client.get(`${this.base(account)}/audiences/${spotifyId.parse(id)}`, audienceSchema);\n if (result.id !== id || (result.ad_account_id !== undefined && result.ad_account_id !== account)) throw new AdportError('PROVIDER_ERROR', 'spotify: audience account/ID mismatch');\n return result;\n }\n async eligibleDatasets(input: { account_id: string; limit: number; q?: string }) {\n const result = await this.read(input, 'audiences/datasets');\n const data = z.looseObject({ datasets: z.array(z.looseObject({ id: spotifyId })), paging: z.looseObject({ total_results: z.number().int().nonnegative(), offset: z.number().int().nonnegative() }).optional() }).parse(result);\n return { ...data, truncated: data.paging ? data.paging.offset + data.datasets.length < data.paging.total_results : data.datasets.length === input.limit };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const base = this.base(op.accountId);\n let path: string, method: 'POST' | 'PATCH' = 'POST', body: Row, expected: string | undefined;\n switch (op.tool) {\n case 'spotify_create_report': {\n const input = createReport.parse(op.payload);\n for (const id of input.campaign_ids ?? []) await this.creatives.get(op.accountId, 'campaigns', id, false);\n return { summary: `Submit Spotify CSV export ${input.name}`, changes: [`+ export job ${JSON.stringify(input)}; no ad delivery changes`], coercions: [], budgetDeltas: [], execute: async () => { const result = await this.client.mutate(`${base}/async_reports`, 'POST', input, z.object({ id: spotifyId })); return [result.id]; } };\n }\n case 'spotify_create_audience': {\n const input = createAudience.parse(op.payload);\n if (input.subtype === 'WEB_EVENT') {\n const data = await this.eligibleDatasets({ account_id: op.accountId, limit: 50 });\n if (input.dataset_ids!.some(id => !data.datasets.some(dataset => dataset.id === id))) throw new AdportError('INVALID_INPUT', 'spotify: dataset is not present in the selected account’s eligible audience datasets.');\n }\n for (const id of input.campaign_ids ?? []) await this.creatives.get(op.accountId, 'campaigns', id, false);\n for (const id of input.ad_set_ids ?? []) await this.creatives.get(op.accountId, 'ad_sets', id, false);\n body = { ...input, audience_type: 'CUSTOM' }; path = `${base}/audiences`; break;\n }\n case 'spotify_create_lookalike_audience': {\n const input = createLookalike.parse(op.payload); await this.audience(op.accountId, input.seed_audience_id);\n body = { ...input, audience_type: 'LOOKALIKE' }; path = `${base}/audiences`; break;\n }\n case 'spotify_update_audience': {\n const input = updateAudience.parse(op.payload), current = await this.audience(op.accountId, input.audience_id);\n const { audience_id, ...patch } = input; expected = audience_id; body = { ...patch, audience_type: current.type }; path = `${base}/audiences/${audience_id}`; method = 'PATCH'; break;\n }\n case 'spotify_delete_audience': {\n const input = deleteAudience.parse(op.payload), current = await this.audience(op.accountId, input.audience_id);\n return { summary: `Delete Spotify audience ${current.name}`, changes: [`- account-owned audience ${current.id}; targeting dependencies may be affected`], coercions: [], budgetDeltas: [], execute: async () => { const result = await this.client.mutate(`${base}/audiences/${current.id}`, 'DELETE', undefined, z.object({ deletion_count: z.number().int().nonnegative() })); if (result.deletion_count !== 1) throw new AdportError('PROVIDER_ERROR', 'spotify: audience deletion did not confirm one removed record; inspect before retrying'); return [current.id]; } };\n }\n default: throw new AdportError('INVALID_INPUT', `spotify: unsupported write ${op.tool}`);\n }\n return { summary: `Spotify ${op.tool.replace(/^spotify_/, '').replaceAll('_', ' ')}`, changes: [`${method} /${path} ${JSON.stringify(body)}`], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.client.mutate(path, method, body, audienceSchema);\n if ((expected && result.id !== expected) || result.type !== body.audience_type || (result.ad_account_id !== undefined && result.ad_account_id !== op.accountId)) throw new AdportError('PROVIDER_ERROR', 'spotify: audience mutation receipt mismatch; inspect before retrying');\n return [result.id];\n } };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { spotifyId } from './schemas.js';\n\nconst account = { account_id: spotifyId };\nconst page = { limit: z.number().int().positive().max(50).default(50), offset: z.number().int().nonnegative().default(0) };\nconst ids = z.array(spotifyId).min(1).max(100);\nconst nativeFields = z.array(z.string().regex(/^[A-Z][A-Z0-9_]*$/)).min(1).max(100);\nconst insightDimension = z.enum(['ACT_AND_SET', 'AGE', 'AUDIENCE', 'CITY', 'COUNTRY', 'DEVICE_TYPE', 'FORMAT', 'GENDER', 'GENRE', 'INTERESTS', 'METRO', 'PLACEMENT', 'PLACEMENT_TYPE', 'PLATFORM', 'PODCAST_EPISODE_TOPIC', 'REGION', 'TONE']);\nconst audienceName = z.string().trim().min(2).max(80);\nconst description = z.string().max(80).optional();\n// JSON Schema consumers do not share JavaScript's Unicode-regexp flag.\n// Keep the native name rule at runtime without exporting a nonportable pattern.\nconst reportName = z.string().trim().min(2).max(120).refine(value => /^[\\p{L}\\p{N} _-]+$/u.test(value), 'Use letters, numbers, spaces, underscores or hyphens').describe('Unicode letters/numbers, spaces, underscores and hyphens.');\nexport const createAudience = z.object({ name: audienceName, description, subtype: z.enum(['WEB_EVENT', 'AD_ENGAGEMENT']), dataset_ids: ids.optional(), campaign_ids: ids.optional(), ad_set_ids: ids.optional(), included_events: z.array(z.string().min(1)).min(1).max(100).optional(), excluded_events: z.array(z.string().min(1)).max(100).optional(), lookback_days: z.union([z.literal(30), z.literal(60), z.literal(90), z.literal(180)]), exposure_type: z.enum(['IMPRESSIONS', 'CLICKS']).optional() }).strict().superRefine((value, ctx) => {\n if (value.subtype === 'WEB_EVENT' && (!value.dataset_ids || !value.included_events || value.campaign_ids || value.ad_set_ids || value.exposure_type)) ctx.addIssue({ code: 'custom', message: 'Web-event audiences require datasets and included events, without engagement fields' });\n if (value.subtype === 'AD_ENGAGEMENT' && (Boolean(value.campaign_ids) === Boolean(value.ad_set_ids) || !value.exposure_type || value.dataset_ids || value.included_events || value.excluded_events)) ctx.addIssue({ code: 'custom', message: 'Engagement audiences require campaign_ids or ad_set_ids plus exposure_type, without web-event fields' });\n});\nexport const createLookalike = z.object({ name: audienceName, description, seed_audience_id: spotifyId });\nexport const updateAudience = z.object({ audience_id: spotifyId, name: audienceName.optional(), description }).refine(v => v.name !== undefined || v.description !== undefined, 'Provide an audience field');\nexport const deleteAudience = z.object({ audience_id: spotifyId });\nexport const createReport = z.object({ name: reportName, granularity: z.enum(['LIFETIME', 'DAY']), dimensions: nativeFields, metrics: nativeFields, statuses: nativeFields.optional(), campaign_ids: ids.optional(), report_start: z.iso.datetime().optional(), report_end: z.iso.datetime().optional(), insight_dimension: insightDimension.optional(), attribution_window: z.enum(['IMPRESSION_30_DAY', 'IMPRESSION_7_DAY']).optional() }).superRefine((value, ctx) => {\n if (value.granularity === 'DAY' && (!value.report_start || !value.report_end)) ctx.addIssue({ code: 'custom', message: 'Daily exports require report_start and report_end' });\n if (value.insight_dimension && (value.granularity !== 'LIFETIME' || value.report_start || value.report_end)) ctx.addIssue({ code: 'custom', message: 'Insight exports require LIFETIME without report dates' });\n if (value.report_start && value.report_end && (Date.parse(value.report_end) < Date.parse(value.report_start) || Date.parse(value.report_end) - Date.parse(value.report_start) > 365 * 86_400_000)) ctx.addIssue({ code: 'custom', message: 'Report dates must be ordered and within365 days' });\n if ([value.report_start, value.report_end].some(v => v && !/T00:00:00Z$/.test(v))) ctx.addIssue({ code: 'custom', message: 'Use UTC midnight report dates' });\n});\nexport const managementWriteNames = new Set(['spotify_create_audience', 'spotify_create_lookalike_audience', 'spotify_update_audience', 'spotify_delete_audience', 'spotify_create_report']);\n\nexport function spotifyManagementTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\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: 'spotify', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove') => guardedWriteTool({ name, namespace: 'spotify', provider: 'spotify', description, payload, kind });\n return [\n read('spotify_audiences', 'Read existing account-owned custom/lookalike audiences with native filters and pagination. Does not upload customer records.', z.object({ ...account, audience_ids: ids.optional(), audience_types: z.array(z.enum(['CUSTOM', 'LOOKALIKE'])).optional(), q: z.string().optional(), ...page }), input => provider.management.audiences(input)),\n read('spotify_get_audience', 'Read one account-owned custom/lookalike audience and its processing status.', z.object({ ...account, audience_id: spotifyId }), input => provider.management.audience(input.account_id, input.audience_id)),\n read('spotify_audience_datasets', 'Read eligible account datasets and available web events for audience creation. Returns native pagination limits.', z.object({ ...account, q: z.string().optional(), limit: z.number().int().positive().max(50).default(50) }), input => provider.management.eligibleDatasets(input)),\n read('spotify_insight_report', 'Read native lifetime insights for exactly one verified published ad set, as required by the live endpoint. Missing/suppressed conversion fields remain unavailable.', z.object({ ...account, ad_set_id: spotifyId, insight_dimension: insightDimension, fields: nativeFields, statuses: nativeFields.optional() }), input => provider.management.insights(input)),\n read('spotify_change_history', 'Read account change history within Spotify’s rolling180-day window. Actor details and billing rows depend on the caller’s role.', z.object({ ...account, entity_type: z.enum(['CAMPAIGN', 'AD_SET', 'AD_ACCOUNT', 'BUSINESS', 'CREATIVE']).optional(), entity_ids: ids.optional(), entity_name: z.string().optional(), created_gte: z.iso.datetime().optional(), created_lte: z.iso.datetime().optional(), change_category: z.enum(['STATUS', 'BUDGET', 'TARGETING', 'CREATIVE', 'SCHEDULING', 'SETTINGS', 'BILLING']).optional(), sort_direction: z.enum(['ASC', 'DESC']).default('DESC'), ...page }), input => provider.management.read(input, 'change_history')),\n read('spotify_report_status', 'Read a previously submitted account export’s status and native CSV URL. Does not fetch arbitrary URLs or create a public share.', z.object({ ...account, report_id: spotifyId }), input => provider.management.read({ account_id: input.account_id }, `async_reports/${input.report_id}`)),\n write('spotify_create_audience', 'Create a web-event or ad-engagement audience from existing account-owned resources. Does not upload customer records or attach targeting to ads.', createAudience, 'create'),\n write('spotify_create_lookalike_audience', 'Create a lookalike from an existing account-owned seed audience. Does not upload customer records or change ad targeting.', createLookalike, 'create'),\n write('spotify_update_audience', 'Rename or edit the description of an account-owned audience, preserving its native type and source rules.', updateAudience, 'update'),\n write('spotify_delete_audience', 'Delete an account-owned audience through the normal preview/apply gate. Review dependencies before applying.', deleteAudience, 'remove'),\n write('spotify_create_report', 'Submit a native asynchronous CSV export job. No ad or delivery changes. Native field names are server-validated; use spotify_report_status for completion.', createReport, 'create'),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type ResourceSecretStore, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport { spotifyId } from './schemas.js';\nimport { capiSchema, createdReceipt, createCapi, createDataset, createMobile, createPixel, datasetSchema, datasetSharing, diagnosticSchema, mobileSchema, mobileSharing, paging, pixelId, pixelSchema, removeIntegration, updateCapi, updateDataset, updateMobile, updatePixel } from './measurement-schemas.js';\nimport { SpotifyCapiCredentials, capiCredentialWrites } from './capi-credentials.js';\n\ntype Row = Record<string, unknown>;\ntype Scope = { account_id: string; business_id: string };\ntype Dataset = z.infer<typeof datasetSchema>;\ntype Mobile = z.infer<typeof mobileSchema>;\ntype Receipt = z.infer<typeof createdReceipt>;\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<WriteResult> }\nconst RECEIPT_TTL = 7 * 24 * 60 * 60;\nconst commonNotes = ['Local preview only. Measurement resource management does not install website code, send conversion events, issue CAPI credentials or change ad delivery or budgets.', 'Native permissions and configuration remain authoritative. No automatic write retry; use the returned IDs and signed receipt to reconcile partial creation.'];\nconst canonical = (value: unknown): string => JSON.stringify(value, (key, item) => {\n if (Array.isArray(item) && ['aam_fields', 'auto_capture_fields', 'shared_ad_accounts'].includes(key)) return item.map(v => v && typeof v === 'object' && 'id' in v ? { id: v.id } : v).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));\n return item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).filter(([k]) => !['events', 'events_received', 'historical_events', 'created_at', 'updated_at', 'ad_set_count', 'is_receiving_events', 'is_receiving_lead_events'].includes(k)).sort(([a], [b]) => a.localeCompare(b))) : item;\n});\nconst digest = (scope: Scope, kind: string, value: unknown) => createHash('sha256').update(canonical({ ...scope, kind, configuration: value })).digest('hex');\nconst same = (a: unknown, b: unknown) => canonical(a) === canonical(b);\nconst members = (dataset: Dataset) => [dataset.pixel, dataset.capi_integration].filter((v): v is NonNullable<typeof v> => Boolean(v));\nconst contains = (dataset: Dataset, integration: string) => members(dataset).some(v => v.integration_id === integration);\nfunction params(input: Row) { const p = new URLSearchParams();for (const [k, v] of Object.entries(input)) if (v !== undefined) { if (Array.isArray(v)) for (const value of v) p.append(k, String(value)); else p.set(k, String(v)); } return p; }\nfunction ensure(value: unknown, message: string): asserts value { if (!value) throw new AdportError('PROVIDER_ERROR', `spotify: ${message}`); }\n\n/** Current official v3 OpenAPI, fetched 2026-11-05; signed recovery follows approved native creations only. */\nexport class SpotifyMeasurementService {\n readonly credentials: SpotifyCapiCredentials;\n constructor(private readonly client: SpotifyAdsClient, secrets?: ResourceSecretStore) { this.credentials = new SpotifyCapiCredentials(client, input => this.credentialScope(input), secrets); }\n private async credentialScope(input: { account_id: string; dataset_id: string }) {\n const scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id);\n this.exclusive(scope, dataset);\n ensure(dataset.shared_ad_accounts?.some(account => account.id === scope.account_id), 'CAPI credentials require sharing with this selected account');\n ensure(dataset.capi_integration, 'dataset has no verified CAPI integration');\n const integration = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);\n this.verifyIntegrationBinding(dataset, 'capi', integration.capi_connection_id, integration.dataset_id);\n return { ...scope, dataset_id: dataset.id, capi_connection_id: integration.capi_connection_id, configuration_hash: digest(scope, 'capi', integration), dataset_configuration_hash: digest(scope, 'dataset', dataset) };\n }\n private base(scope: Scope) { return `businesses/${scope.business_id}`; }\n private async scope(account: string): Promise<Scope> {\n const id = spotifyId.parse(account), data = await this.client.get(`ad_accounts/${id}`, z.object({ id: spotifyId, business_id: spotifyId }));\n ensure(data.id === id, 'measurement account identity mismatch');\n return { account_id: id, business_id: data.business_id };\n }\n private proof(account: string, value?: string, purpose: Receipt['purpose'] = 'creation'): Receipt | undefined {\n if (!value) return undefined;\n const parsed = createdReceipt.safeParse(this.client.verifyMeasurementReceipt(value)), now = Math.floor(Date.now() / 1000);\n if (!parsed.success || parsed.data.purpose !== purpose || parsed.data.account_id !== account || parsed.data.issued_at > now + 60 || parsed.data.expires_at <= now || parsed.data.expires_at <= parsed.data.issued_at || parsed.data.expires_at - parsed.data.issued_at > RECEIPT_TTL) throw new AdportError('INVALID_INPUT', 'spotify: expired or mismatched measurement resource receipt');\n return parsed.data;\n }\n private bind(scope: Scope, kind: Receipt['kind'], id: string, datasetId?: string, purpose: Receipt['purpose'] = 'creation'): string {\n const now = Math.floor(Date.now() / 1000);\n return this.client.measurementReceipt(createdReceipt.parse({ version: 1, purpose, ...scope, kind, id, ...(datasetId ? { dataset_id: datasetId } : {}), issued_at: now, expires_at: now + RECEIPT_TTL }));\n }\n private checkProof(scope: Scope, proof?: Receipt) { if (proof && proof.business_id !== scope.business_id) throw new AdportError('INVALID_INPUT', 'spotify: the account business changed; measurement receipt no longer matches'); }\n private async rawDataset(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/datasets/${spotifyId.parse(id)}`, datasetSchema);ensure(data.id === id, 'dataset identity mismatch');return data;\n }\n private async rawMobile(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/mobile_apps/${spotifyId.parse(id)}`, mobileSchema);ensure(data.id === id, 'mobile-app identity mismatch');return data;\n }\n private async rawPixel(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/pixels/${id}`, pixelSchema);ensure(data.id === id, 'Pixel identity mismatch');return data;\n }\n private async rawCapi(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/capi/${spotifyId.parse(id)}`, capiSchema);ensure(data.capi_connection_id === id, 'CAPI integration identity mismatch');return data;\n }\n private datasetContainsResource(dataset: Dataset, kind: Receipt['kind'], id: string) {\n return kind === 'pixel' ? dataset.pixel?.id === id : kind === 'capi' ? dataset.capi_integration?.capi_connection_id === id : false;\n }\n private verifyIntegrationBinding(dataset: Dataset, kind: 'pixel' | 'capi', id: string, observed: string | null | undefined) {\n ensure(this.datasetContainsResource(dataset, kind, id) && (observed == null || observed === dataset.id), `${kind === 'pixel' ? 'Pixel' : 'CAPI'} dataset binding mismatch`);\n }\n private async receiptNative(scope: Scope, proof: Receipt) {\n this.checkProof(scope, proof);\n const resource = proof.kind === 'pixel' ? await this.rawPixel(scope, proof.id) : proof.kind === 'capi' ? await this.rawCapi(scope, proof.id) : proof.kind === 'mobile_app' ? await this.rawMobile(scope, proof.id) : await this.rawDataset(scope, proof.id);\n const datasetId = proof.kind === 'dataset' ? proof.id : 'dataset_id' in resource && typeof resource.dataset_id === 'string' ? resource.dataset_id : undefined;\n let expectedDataset: Dataset | undefined, verifiedDatasetId = datasetId;\n let parentVerificationError: { code: string; http_status?: number } | undefined;\n // Null is missing evidence, not a conflicting edge. Inspect only the parent locked by the native creation receipt.\n if (!datasetId && proof.dataset_id && ['pixel', 'capi'].includes(proof.kind)) {\n try {\n expectedDataset = await this.rawDataset(scope, proof.dataset_id);\n if (this.datasetContainsResource(expectedDataset, proof.kind, proof.id)) verifiedDatasetId = expectedDataset.id;\n } catch (error) {\n if (!(error instanceof AdportError)) throw error;\n const status = error.details && typeof error.details === 'object' && 'http_status' in error.details ? error.details.http_status : undefined;\n parentVerificationError = { code: error.code, ...(typeof status === 'number' ? { http_status: status } : {}) };\n }\n }\n return { resource, datasetId, verifiedDatasetId, expectedDataset, parentVerificationError };\n }\n private async createdNative(scope: Scope, proof: Receipt) {\n const { resource, verifiedDatasetId } = await this.receiptNative(scope, proof);\n ensure(!proof.dataset_id || verifiedDatasetId === proof.dataset_id, 'created resource dataset binding changed; reconcile the original IDs');\n return { resource, datasetId: verifiedDatasetId };\n }\n private sharing(scope: Scope, row: { shared_ad_accounts?: Array<{ id: string; name?: string | null }> | null }) {\n return { shared_ad_accounts: row.shared_ad_accounts === null ? null : row.shared_ad_accounts?.filter(a => a.id === scope.account_id), other_shared_account_count: row.shared_ad_accounts ? row.shared_ad_accounts.filter(a => a.id !== scope.account_id).length : null };\n }\n private publicDataset(scope: Scope, row: Dataset, snapshot = true) { return { ...row, ...this.sharing(scope, row), ...(snapshot ? { configuration_hash: digest(scope, 'dataset', row) } : {}) }; }\n private publicMobile(scope: Scope, row: Mobile, snapshot = true) { return { ...row, ...this.sharing(scope, row), ...(snapshot ? { configuration_hash: digest(scope, 'mobile_app', row) } : {}) }; }\n private async selectedDatasets(scope: Scope) {\n // This endpoint has no documented limit/offset query; never invent paging parameters.\n const data = await this.client.get(`${this.base(scope)}/ad_accounts/${scope.account_id}/datasets`, z.object({ datasets: z.array(datasetSchema), paging: paging.nullish() }));\n ensure(new Set(data.datasets.map(d => d.id)).size === data.datasets.length, 'dataset inventory repeated an ID');\n ensure(!data.paging || data.paging.offset === 0 && data.paging.total_results >= data.datasets.length, 'dataset inventory pagination is inconsistent');\n for (const row of data.datasets) ensure(!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id === scope.account_id), 'dataset inventory contains an unshared account resource');\n return { ...data, complete: data.paging ? data.paging.total_results === data.datasets.length : null, truncated: !data.paging || data.paging.total_results !== data.datasets.length };\n }\n private recoverableDataset(scope: Scope, row: Dataset, proof: Receipt, nativeDatasetId?: string) {\n if (nativeDatasetId !== row.id) return false;\n if (proof.dataset_id === row.id || proof.kind === 'dataset' && proof.id === row.id) return true;\n // An initially unbound creation cannot be used to pivot into an unrelated shared parent.\n if (!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id !== scope.account_id)) return false;\n return proof.kind === 'pixel' ? row.pixel?.id === proof.id && !row.capi_integration : proof.kind === 'capi' ? row.capi_integration?.capi_connection_id === proof.id && !row.pixel : false;\n }\n private async dataset(scope: Scope, id: string, proof?: Receipt) {\n this.checkProof(scope, proof);\n const row = await this.rawDataset(scope, id);\n if (row.shared_ad_accounts?.some(a => a.id === scope.account_id)) return row;\n if (proof && this.recoverableDataset(scope, row, proof, (await this.createdNative(scope, proof)).datasetId)) return row;\n if (!row.shared_ad_accounts) {\n const selected = (await this.selectedDatasets(scope)).datasets.find(d => d.id === id);\n if (selected) return { ...row, ...(selected.shared_ad_accounts ? { shared_ad_accounts: selected.shared_ad_accounts } : {}) };\n }\n throw new AdportError('INVALID_INPUT', 'spotify: dataset is not shared with the selected account; an unshared creation requires its signed resource receipt');\n }\n private async mobile(scope: Scope, id: string, proof?: Receipt) {\n this.checkProof(scope, proof);const row = await this.rawMobile(scope, id);\n if (row.shared_ad_accounts?.some(a => a.id === scope.account_id) || proof?.kind === 'mobile_app' && proof.id === id) return row;\n if (!row.shared_ad_accounts) {\n const seen = new Set<string>();\n for (let offset = 0, page = 0; page < 1000; page++) {\n const data = await this.mobilePage(scope, { limit: 50, offset });\n for (const item of data.mobile_apps) { ensure(!seen.has(item.id), 'mobile-app inventory repeated a page');seen.add(item.id); }\n const selected = data.mobile_apps.find(a => a.id === id);\n if (selected) return { ...row, ...(selected.shared_ad_accounts ? { shared_ad_accounts: selected.shared_ad_accounts } : {}) };\n if (!data.truncated) break;offset = data.next_offset!;\n }\n }\n throw new AdportError('INVALID_INPUT', 'spotify: mobile app is not shared with the selected account or bound to its approved creation receipt');\n }\n private exclusive(scope: Scope, row: { shared_ad_accounts?: Array<{ id: string }> | null }) {\n if (!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id !== scope.account_id)) throw new AdportError('INVALID_INPUT', 'spotify: business-wide configuration changes require verified sharing restricted to this selected account');\n }\n private expected(scope: Scope, kind: string, value: unknown, hash: string) { if (digest(scope, kind, value) !== hash) throw new AdportError('INVALID_INPUT', 'spotify: measurement configuration changed; obtain a fresh snapshot before a new preview'); }\n private result(ids: string[], details: Row = {}): WriteResult { return { applied: true, resourceIds: [...new Set(ids)], ...(Object.keys(details).length ? { details } : {}) }; }\n private uncertain(ids: string[], receipt?: string): never { throw new AdportError('PROVIDER_ERROR', 'spotify: measurement write/readback unconfirmed; reconcile the original IDs before another mutation. No write was replayed.', { resource_ids: ids, ...(receipt ? { resource_receipt: receipt } : {}) }); }\n private review(scope: Scope, title: string, kind: WriteOperation['kind'], body: Row, current?: Row, notices = commonNotes): Omit<Plan, 'execute'> {\n const fields = Object.entries(body).map(([key, value]) => ({ label: key.replaceAll('_', ' '), ...(current?.[key] === undefined ? {} : { before: current[key] }), after: value }));\n return { summary: title, changes: [`${kind}: ${JSON.stringify(body)}`], notes: notices, coercions: [], budgetDeltas: [], review: { provider: 'spotify', accountId: scope.account_id, kind, title, fields, notices } };\n }\n\n async datasets(account: string) { const scope = await this.scope(account), data = await this.selectedDatasets(scope);return { ...scope, ...data, datasets: data.datasets.map(d => this.publicDataset(scope, d, false)) }; }\n private async mobilePage(scope: Scope, input: { limit: number; offset: number }) {\n const data = await this.client.get(`${this.base(scope)}/ad_accounts/${scope.account_id}/mobile_apps`, z.object({ mobile_apps: z.array(mobileSchema), paging }), params({ limit: input.limit, offset: input.offset }));\n ensure(data.paging.offset === input.offset && data.mobile_apps.length <= input.limit && (!data.mobile_apps.length || data.paging.total_results >= input.offset + data.mobile_apps.length), 'mobile-app pagination is inconsistent');\n ensure(new Set(data.mobile_apps.map(a => a.id)).size === data.mobile_apps.length, 'mobile-app page repeated an ID');\n for (const row of data.mobile_apps) ensure(!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id === scope.account_id), 'mobile-app inventory contains an unshared resource');\n const next = input.offset + data.mobile_apps.length, truncated = next < data.paging.total_results;ensure(!truncated || data.mobile_apps.length > 0, 'mobile-app pagination stalled');\n return { ...data, truncated, ...(truncated ? { next_offset: next } : {}) };\n }\n async mobileApps(input: { account_id: string; limit: number; offset: number }) { const scope = await this.scope(input.account_id), data = await this.mobilePage(scope, input);return { ...scope, ...data, mobile_apps: data.mobile_apps.map(a => this.publicMobile(scope, a, false)) }; }\n async context(account: string) { const scope = await this.scope(account), data = await this.selectedDatasets(scope);return { ...scope, ...data, datasets: data.datasets.map(d => this.publicDataset(scope, d, false)), notes: ['Only datasets shared with this selected account are inventoried. Business-wide resources and other account identities are excluded. Read an individual resource for its full mutation snapshot.', 'Pixel creation may create a dataset; CAPI can join that dataset. No tracking code, tokens or events are created by these reads.'] }; }\n async getDataset(input: { account_id: string; dataset_id: string; resource_receipt?: string }) { const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);return { ...scope, dataset: this.publicDataset(scope, await this.dataset(scope, input.dataset_id, proof)) }; }\n async getPixel(input: { account_id: string; dataset_id: string; resource_receipt?: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id, proof);ensure(dataset.pixel, 'dataset has no verified Pixel');\n const pixel = await this.rawPixel(scope, dataset.pixel.id);this.verifyIntegrationBinding(dataset, 'pixel', pixel.id, pixel.dataset_id);return { ...scope, pixel: { ...pixel, configuration_hash: digest(scope, 'pixel', pixel) }, dataset_binding: { observed_dataset_id: pixel.dataset_id ?? null, verified_dataset_id: dataset.id, verification_source: pixel.dataset_id ? 'resource' : 'dataset' } };\n }\n async getCapi(input: { account_id: string; dataset_id: string; resource_receipt?: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id, proof);ensure(dataset.capi_integration, 'dataset has no verified CAPI integration');\n const integration = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);this.verifyIntegrationBinding(dataset, 'capi', integration.capi_connection_id, integration.dataset_id);return { ...scope, capi_integration: { ...integration, configuration_hash: digest(scope, 'capi', integration) }, dataset_binding: { observed_dataset_id: integration.dataset_id ?? null, verified_dataset_id: dataset.id, verification_source: integration.dataset_id ? 'resource' : 'dataset' } };\n }\n async getMobile(input: { account_id: string; mobile_app_id: string; resource_receipt?: string }) { const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);return { ...scope, mobile_app: this.publicMobile(scope, await this.mobile(scope, input.mobile_app_id, proof)) }; }\n async diagnostics(input: { account_id: string; dataset_id: string; granularities: Array<'DAILY' | 'HOURLY'>; datasource_ids?: string[]; resource_receipt?: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);await this.dataset(scope, input.dataset_id, proof);\n const data = await this.client.get(`${this.base(scope)}/datasets/${input.dataset_id}/diagnostics`, diagnosticSchema, params({ granularities: input.granularities, datasource_ids: input.datasource_ids }));\n ensure(data.dataset_id === input.dataset_id && data.datasources.every(d => input.granularities.includes(d.granularity) && (!input.datasource_ids || input.datasource_ids.includes(d.datasource_id))), 'measurement diagnostic identity/filter mismatch');\n return { ...scope, ...data, notes: ['Diagnostics can lag implementation by at least 20 minutes. Received activity is not proof of campaign attribution, optimization or delivery. Missing or suppressed values remain native; this read sends no events.'] };\n }\n async created(input: { account_id: string; resource_receipt: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt)!, scope = await this.scope(input.account_id), native = await this.receiptNative(scope, proof);\n const matches = proof.dataset_id ? native.datasetId === proof.dataset_id : null;\n const verified = !proof.dataset_id || native.verifiedDatasetId === proof.dataset_id;\n const candidate = verified && native.verifiedDatasetId ? native.expectedDataset ?? await this.rawDataset(scope, native.verifiedDatasetId) : undefined;\n const dataset = candidate && (candidate.shared_ad_accounts?.some(a => a.id === scope.account_id) || this.recoverableDataset(scope, candidate, proof, native.verifiedDatasetId)) ? candidate : undefined;\n const key = proof.kind === 'capi' ? 'capi_integration' : proof.kind;\n const resource = proof.kind === 'mobile_app' ? this.publicMobile(scope, native.resource as Mobile) : proof.kind === 'dataset' ? this.publicDataset(scope, native.resource as Dataset) : { ...native.resource, configuration_hash: digest(scope, proof.kind, native.resource) };\n return { ...scope, kind: proof.kind, [key]: resource, dataset: dataset ? this.publicDataset(scope, dataset) : null,\n dataset_binding: { expected_dataset_id: proof.dataset_id ?? null, observed_dataset_id: native.datasetId ?? null, matches_receipt: matches, verified_dataset_id: dataset?.id ?? null, verification_source: dataset ? native.datasetId ? 'resource' : 'dataset' : null, ...(native.parentVerificationError ? { parent_verification_error: native.parentVerificationError } : {}) },\n needs_dataset_sharing: dataset?.shared_ad_accounts ? !dataset.shared_ad_accounts.some(a => a.id === scope.account_id) : null, resource_receipt: input.resource_receipt,\n notes: ['Read-only reconciliation of an approved creation. No creation, share, update or event request was replayed.', ...(matches === false ? [dataset ? 'The native child omits its dataset binding. The exact receipt-bound parent independently confirms the resource relationship; the native null value is preserved.' : 'The resource relationship is unverified. No unexpected dataset contents were followed. Sharing remains unverified and mutation checks remain strict.'] : [])] };\n }\n async sharingStatus(input: { account_id: string; resource_receipt: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt, 'sharing')!, scope = await this.scope(input.account_id);this.checkProof(scope, proof);\n if (!['dataset', 'mobile_app'].includes(proof.kind)) throw new AdportError('INVALID_INPUT', 'spotify: receipt does not identify a sharing operation');\n const row = proof.kind === 'dataset' ? await this.rawDataset(scope, proof.id) : await this.rawMobile(scope, proof.id);\n ensure(row.shared_ad_accounts, 'native sharing state is unavailable');\n return { ...scope, kind: proof.kind, resource_id: proof.id, shared_with_selected_account: row.shared_ad_accounts.some(a => a.id === scope.account_id), other_shared_account_count: row.shared_ad_accounts.filter(a => a.id !== scope.account_id).length, notes: ['Read-only reconciliation of the selected account’s sharing state. A sharing receipt does not grant resource-content access after unsharing.'] };\n }\n\n private async shareCreatedDataset(scope: Scope, id: string) {\n const current = await this.rawDataset(scope, id);this.exclusive(scope, current);\n if (!current.shared_ad_accounts!.some(a => a.id === scope.account_id)) await this.client.mutate(`${this.base(scope)}/datasets/${id}/ad_accounts/${scope.account_id}`, 'POST', undefined, z.undefined());\n const actual = await this.rawDataset(scope, id);this.exclusive(scope, actual);ensure(actual.shared_ad_accounts!.some(a => a.id === scope.account_id), 'created dataset sharing readback unconfirmed');return actual;\n }\n private async planCreate(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n const kind: Receipt['kind'] = op.tool === 'spotify_create_pixel' ? 'pixel' : op.tool === 'spotify_create_capi_integration' ? 'capi' : 'mobile_app';\n let body: Row, requestedDataset: string | undefined;\n if (kind === 'mobile_app') body = createMobile.parse(op.payload);\n else {\n const input = kind === 'pixel' ? createPixel.parse(op.payload) : createCapi.parse(op.payload);\n const { expected_dataset_configuration_hash, resource_receipt: _receipt, ...native } = input;\n if (input.dataset_id) {\n const dataset = await this.dataset(scope, input.dataset_id, proof);this.exclusive(scope, dataset);this.expected(scope, 'dataset', dataset, expected_dataset_configuration_hash!);\n if (kind === 'pixel' ? dataset.pixel : dataset.capi_integration) throw new AdportError('INVALID_INPUT', `spotify: dataset already has a ${kind} integration; reuse it instead of duplicating the source`);\n }\n const { acknowledge_advanced_matching: _ack, ...fields } = native as Row;\n body = fields;requestedDataset = input.dataset_id;\n }\n const path = `${this.base(scope)}/${kind === 'pixel' ? 'pixels' : kind === 'capi' ? 'capi' : 'mobile_apps'}`;\n const notices = [...commonNotes, kind === 'mobile_app' ? 'The new mobile-app record will be shared only with this selected ad account. Registration does not install or configure an MMP SDK.' : 'The new integration will use its verified dataset, which will be shared only with this selected ad account. A new native dataset is created when dataset_id is omitted.', ...(kind === 'pixel' ? ['Advanced matching is disabled by default. Native cookie and automatic-capture settings are returned for review before any website installation.'] : [])];\n return { ...this.review(scope, `Create Spotify ${kind.replaceAll('_', ' ')} \"${body.name}\"`, 'create', body, undefined, notices), execute: async () => {\n let id: string, nativeDataset: string | undefined;\n try {\n if (kind === 'pixel') { const row = await this.client.mutate(path, 'POST', body, z.object({ id: pixelId, dataset_id: z.unknown().optional() }));id = row.id;const dataset = spotifyId.safeParse(row.dataset_id);nativeDataset = dataset.success ? dataset.data : undefined; }\n else if (kind === 'capi') { const row = await this.client.mutate(path, 'POST', body, z.object({ capi_connection_id: spotifyId, dataset_id: z.unknown().optional() }));id = row.capi_connection_id;const dataset = spotifyId.safeParse(row.dataset_id);nativeDataset = dataset.success ? dataset.data : undefined; }\n else { const row = await this.client.mutate(path, 'POST', { mobile_app: body }, z.object({ id: spotifyId, dataset_id: z.unknown().optional() }));id = row.id;const dataset = spotifyId.safeParse(row.dataset_id);nativeDataset = dataset.success ? dataset.data : undefined; }\n } catch (error) { if (error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([]); }\n let receipt = this.bind(scope, kind, id, requestedDataset ?? nativeDataset), knownDataset = requestedDataset ?? nativeDataset;\n try {\n const bound = this.proof(scope.account_id, receipt)!, { resource, datasetId } = await this.createdNative(scope, bound);\n const observed = resource as Row;\n // Spotify returns null for unused matching fields; only verified AAM-off makes them ineffective.\n ensure(Object.entries(body).every(([key, value]) => key === 'dataset_id' && requestedDataset !== undefined && datasetId === requestedDataset\n || kind === 'pixel' && key === 'aam_fields' && Array.isArray(value) && !value.length && observed.aam_opt_in === false && observed[key] == null\n || same({ [key]: observed[key] }, { [key]: value })), 'created measurement fields differ from the request');\n ensure(!requestedDataset || datasetId === requestedDataset, 'created integration has a different dataset');\n if (kind === 'mobile_app') {\n const mobile = resource as Mobile;this.exclusive(scope, mobile);\n if (!mobile.shared_ad_accounts!.some(a => a.id === scope.account_id)) await this.client.mutate(`${path}/${id}/ad_accounts/${scope.account_id}`, 'POST', undefined, z.undefined());\n const actual = await this.rawMobile(scope, id);this.exclusive(scope, actual);ensure(actual.shared_ad_accounts!.some(a => a.id === scope.account_id), 'created mobile-app sharing readback unconfirmed');\n receipt = this.bind(scope, kind, id, datasetId);return this.result([id, ...(datasetId ? [datasetId] : [])], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', mobile_app_id: id, ...(datasetId ? { dataset_id: datasetId } : {}) });\n }\n ensure(datasetId, 'created integration has no verified dataset ID');knownDataset = datasetId;receipt = this.bind(scope, kind, id, datasetId);\n const dataset = await this.rawDataset(scope, datasetId);\n ensure(kind === 'pixel' ? dataset.pixel?.id === id : dataset.capi_integration?.capi_connection_id === id, 'created dataset does not bind the returned integration');\n await this.shareCreatedDataset(scope, datasetId);\n return this.result([id, datasetId], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', dataset_id: datasetId });\n } catch { return this.uncertain([id, ...(knownDataset ? [knownDataset] : [])], receipt); }\n } };\n }\n private async planUpdate(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n let current: Row, body: Row, path: string, kind: string, id: string, readback: () => Promise<Row>;\n if (op.tool === 'spotify_update_mobile_app') {\n const input = updateMobile.parse(op.payload), row = await this.mobile(scope, input.mobile_app_id, proof);this.exclusive(scope, row);this.expected(scope, 'mobile_app', row, input.expected_configuration_hash);\n const { mobile_app_id: _id, resource_receipt: _receipt, expected_configuration_hash: _hash, ...fields } = input;\n current = row;body = fields;kind = 'mobile_app';id = row.id;path = `${this.base(scope)}/mobile_apps/${id}`;readback = () => this.rawMobile(scope, id);\n } else {\n const input = op.tool === 'spotify_update_pixel' ? updatePixel.parse(op.payload) : op.tool === 'spotify_update_capi_integration' ? updateCapi.parse(op.payload) : op.tool === 'spotify_update_dataset' ? updateDataset.parse(op.payload) : undefined;\n if (!input) throw new AdportError('INVALID_INPUT', 'spotify: unsupported measurement update');\n const dataset = await this.dataset(scope, input.dataset_id, proof);this.exclusive(scope, dataset);\n const { dataset_id: _id, resource_receipt: _receipt, expected_configuration_hash: _hash, ...fields } = input;body = fields;\n if (op.tool === 'spotify_update_pixel') {\n ensure(dataset.pixel, 'dataset has no verified Pixel');const pixel = await this.rawPixel(scope, dataset.pixel.id);this.verifyIntegrationBinding(dataset, 'pixel', pixel.id, pixel.dataset_id);\n current = pixel;kind = 'pixel';id = pixel.id;path = `${this.base(scope)}/pixels/${id}`;readback = () => this.rawPixel(scope, id);\n } else if (op.tool === 'spotify_update_capi_integration') {\n ensure(dataset.capi_integration, 'dataset has no verified CAPI integration');const capi = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);this.verifyIntegrationBinding(dataset, 'capi', capi.capi_connection_id, capi.dataset_id);\n current = capi;kind = 'capi';id = capi.capi_connection_id;path = `${this.base(scope)}/capi/${id}`;readback = () => this.rawCapi(scope, id);\n } else { current = dataset;kind = 'dataset';id = dataset.id;path = `${this.base(scope)}/datasets/${id}`;readback = () => this.rawDataset(scope, id); }\n this.expected(scope, kind, current, input.expected_configuration_hash);\n }\n const expected = { ...current, ...body };\n return { ...this.review(scope, `Update Spotify ${kind.replaceAll('_', ' ')} \"${current.name}\"`, 'update', body, current), execute: async () => {\n let accepted = false;\n try { await this.client.mutate(path, 'PATCH', body, z.object({}));accepted = true;const actual = await readback();ensure(digest(scope, kind, actual) === digest(scope, kind, expected), 'measurement update readback differs'); }\n catch (error) { if (!accepted && error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([id]); }\n return this.result([id]);\n } };\n }\n private async planSharing(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n const mobile = op.tool === 'spotify_set_mobile_app_sharing', input = mobile ? mobileSharing.parse(op.payload) : datasetSharing.parse(op.payload);\n const id = 'mobile_app_id' in input ? input.mobile_app_id : input.dataset_id, kind = mobile ? 'mobile_app' as const : 'dataset' as const;\n const current = mobile ? await this.mobile(scope, id, proof) : await this.dataset(scope, id, proof);ensure(current.shared_ad_accounts, 'native sharing dependencies are unavailable');\n this.expected(scope, kind, current, input.expected_configuration_hash);\n const shared = current.shared_ad_accounts.some(a => a.id === scope.account_id), path = `${this.base(scope)}/${mobile ? 'mobile_apps' : 'datasets'}/${id}/ad_accounts/${scope.account_id}`;\n const targetShares = [...current.shared_ad_accounts.filter(a => a.id !== scope.account_id), ...(input.shared ? [{ id: scope.account_id }] : [])], expected = { ...current, shared_ad_accounts: targetShares };\n return { ...this.review(scope, `${input.shared ? 'Share' : 'Unshare'} Spotify ${kind.replaceAll('_', ' ')} with the selected account`, 'update', { shared: input.shared }, { shared }, [...commonNotes, `Only account ${scope.account_id} changes. Other account shares are preserved. Unsharing can stop this account using the measurement source.`]), execute: async () => {\n if (shared === input.shared) return this.result([id], { changed: false, shared_with_selected_account: shared });\n const receipt = this.bind(scope, kind, id, undefined, 'sharing');let accepted = false;\n try {\n await this.client.mutate(path, input.shared ? 'POST' : 'DELETE', undefined, z.undefined());accepted = true;\n const actual = mobile ? await this.rawMobile(scope, id) : await this.rawDataset(scope, id);ensure(digest(scope, kind, actual) === digest(scope, kind, expected), 'native sharing readback differs');\n } catch (error) { if (!accepted && error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([id], receipt); }\n return this.result([id], { resource_receipt: receipt, next_tool: 'spotify_measurement_sharing_status', shared_with_selected_account: input.shared });\n } };\n }\n private async planDataset(op: WriteOperation, scope: Scope): Promise<Plan> {\n const input = createDataset.parse(op.payload), selected: Array<{ dataset: Dataset; integration_id: string; kind: 'pixel' | 'capi'; id: string }> = [];\n for (const source of input.sources) {\n const proof = this.proof(scope.account_id, source.resource_receipt), dataset = await this.dataset(scope, source.dataset_id, proof);this.exclusive(scope, dataset);this.expected(scope, 'dataset', dataset, source.expected_configuration_hash);\n if (dataset.pixel?.integration_id === source.integration_id) { const pixel = await this.rawPixel(scope, dataset.pixel.id);this.verifyIntegrationBinding(dataset, 'pixel', pixel.id, pixel.dataset_id);selected.push({ dataset, integration_id: source.integration_id, kind: 'pixel', id: pixel.id }); }\n else if (dataset.capi_integration?.integration_id === source.integration_id) { const capi = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);this.verifyIntegrationBinding(dataset, 'capi', capi.capi_connection_id, capi.dataset_id);selected.push({ dataset, integration_id: source.integration_id, kind: 'capi', id: capi.capi_connection_id }); }\n else throw new AdportError('INVALID_INPUT', 'spotify: integration is not present in its approved source dataset');\n }\n const body = { name: input.name, integration_ids: selected.map(s => s.integration_id) };\n return { ...this.review(scope, `Create Spotify dataset \"${input.name}\" from existing integrations`, 'create', body, undefined, [...commonNotes, 'This can reroute existing integrations and affect their measurement. Prefer creating Pixel first and adding CAPI with that dataset_id; native integration regrouping can leave inconsistent source routing, which readback must reject.', 'The new dataset is shared only with the selected ad account.']), execute: async () => {\n let id: string;\n try { id = (await this.client.mutate(`${this.base(scope)}/datasets`, 'POST', body, z.object({ id: spotifyId }))).id; }\n catch (error) { if (error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([]); }\n const receipt = this.bind(scope, 'dataset', id, id);\n try {\n ensure(!selected.some(s => s.dataset.id === id), 'dataset creation returned an existing source ID');\n const actual = await this.rawDataset(scope, id);ensure(actual.name === input.name && selected.every(s => contains(actual, s.integration_id)), 'created dataset membership mismatch');\n const previous = new Map<string, Dataset>();\n for (const source of selected) {\n if (!previous.has(source.dataset.id)) previous.set(source.dataset.id, await this.rawDataset(scope, source.dataset.id));\n ensure(!contains(previous.get(source.dataset.id)!, source.integration_id), 'native regrouping retained the integration in its source dataset');\n if (source.kind === 'pixel') { const resource = await this.rawPixel(scope, source.id);this.verifyIntegrationBinding(actual, 'pixel', resource.id, resource.dataset_id); }\n else { const resource = await this.rawCapi(scope, source.id);this.verifyIntegrationBinding(actual, 'capi', resource.capi_connection_id, resource.dataset_id); }\n }\n await this.shareCreatedDataset(scope, id);\n } catch { return this.uncertain([id], receipt); }\n return this.result([id], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', dataset_id: id });\n } };\n }\n private async planRemove(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n const input = removeIntegration.parse(op.payload), current = await this.dataset(scope, input.dataset_id, proof);this.exclusive(scope, current);this.expected(scope, 'dataset', current, input.expected_configuration_hash);\n ensure(contains(current, input.integration_id), 'integration is not present in the selected dataset');\n return { ...this.review(scope, 'Remove Spotify dataset integration into a new native dataset', 'remove', { dataset_id: current.id, integration_id: input.integration_id }, undefined, [...commonNotes, 'Native removal creates another dataset for the integration. It does not delete the integration or stop website code. Ads using the old dataset can lose measurement.']), execute: async () => {\n let created: { id: string };\n try { created = await this.client.mutate(`${this.base(scope)}/datasets/${current.id}/integrations/${input.integration_id}`, 'DELETE', undefined, z.object({ id: spotifyId })); }\n catch (error) { if (error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([current.id]); }\n if (created.id === current.id) return this.uncertain([current.id]);\n const receipt = this.bind(scope, 'dataset', created.id, created.id);\n try {\n const next = await this.rawDataset(scope, created.id), previous = await this.rawDataset(scope, current.id);ensure(contains(next, input.integration_id) && !contains(previous, input.integration_id), 'integration removal readback is inconsistent');\n if (next.pixel?.integration_id === input.integration_id) { const resource = await this.rawPixel(scope, next.pixel.id);this.verifyIntegrationBinding(next, 'pixel', resource.id, resource.dataset_id); }\n if (next.capi_integration?.integration_id === input.integration_id) { const resource = await this.rawCapi(scope, next.capi_integration.capi_connection_id);this.verifyIntegrationBinding(next, 'capi', resource.capi_connection_id, resource.dataset_id); }\n } catch { return this.uncertain([current.id, created.id], receipt); }\n return this.result([current.id, created.id], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', dataset_id: created.id });\n } };\n }\n\n async plan(op: WriteOperation): Promise<Plan> {\n if (capiCredentialWrites.has(op.tool)) return this.credentials.plan(op);\n if (op.tool === 'spotify_create_dataset') for (const source of createDataset.parse(op.payload).sources) this.proof(op.accountId, source.resource_receipt);\n const proof = this.proof(op.accountId, typeof op.payload.resource_receipt === 'string' ? op.payload.resource_receipt : undefined), scope = await this.scope(op.accountId);this.checkProof(scope, proof);\n if (op.tool === 'spotify_create_pixel' || op.tool === 'spotify_create_capi_integration' || op.tool === 'spotify_create_mobile_app') return this.planCreate(op, scope, proof);\n if (op.tool === 'spotify_create_dataset') return this.planDataset(op, scope);\n if (op.tool === 'spotify_remove_dataset_integration') return this.planRemove(op, scope, proof);\n if (op.tool === 'spotify_set_dataset_sharing' || op.tool === 'spotify_set_mobile_app_sharing') return this.planSharing(op, scope, proof);\n return this.planUpdate(op, scope, proof);\n }\n}\n","import { z } from 'zod';\nimport { spotifyId } from './schemas.js';\n\nexport const pixelId = z.string().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/);\nexport const receiptInput = z.string().min(1).max(4096);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), name = z.string().trim().min(1);\nexport const domain = z.string().url().refine(value => { const u = new URL(value);return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without credentials');\nexport const aamField = z.enum(['EMAIL', 'PHONE', 'FIRST_NAME', 'LAST_NAME', 'DATE_OF_BIRTH', 'GENDER', 'CITY', 'STATE', 'ZIP', 'COUNTRY', 'EXTERNAL_ID']);\nconst datasetCreation = { dataset_id: spotifyId.optional(), expected_dataset_configuration_hash: hash.optional(), resource_receipt: receiptInput.optional() };\nexport const datasetTarget = { dataset_id: spotifyId, resource_receipt: receiptInput.optional() };\nexport const mobileTarget = { mobile_app_id: spotifyId, resource_receipt: receiptInput.optional() };\nconst pairing = (v: { dataset_id?: string; expected_dataset_configuration_hash?: string }) => Boolean(v.dataset_id) === Boolean(v.expected_dataset_configuration_hash);\nexport const createPixel = z.object({ ...datasetCreation, name, domain, aam_opt_in: z.boolean().default(false), aam_fields: z.array(aamField).max(11).default([]), acknowledge_advanced_matching: z.boolean().optional() }).strict()\n .refine(pairing, 'An existing dataset requires its current configuration hash')\n .refine(v => new Set(v.aam_fields).size === v.aam_fields.length, 'Matching fields must be unique')\n .refine(v => v.aam_opt_in ? v.acknowledge_advanced_matching === true && v.aam_fields.length > 0 : v.aam_fields.length === 0, 'Advanced matching needs explicit acknowledgement and fields; disabled matching has no fields');\nexport const updatePixel = z.object({ ...datasetTarget, expected_configuration_hash: hash, name: name.optional(), domain: domain.optional() }).strict().refine(v => v.name !== undefined || v.domain !== undefined, 'Provide a name or domain');\nexport const createCapi = z.object({ ...datasetCreation, name }).strict().refine(pairing, 'An existing dataset requires its current configuration hash');\nexport const updateCapi = z.object({ ...datasetTarget, expected_configuration_hash: hash, name }).strict();\nexport const createDataset = z.object({ name, sources: z.array(z.object({ dataset_id: spotifyId, integration_id: spotifyId, expected_configuration_hash: hash, resource_receipt: receiptInput.optional() }).strict()).min(1).max(100), acknowledge_measurement_effects: z.literal(true) }).strict().refine(v => new Set(v.sources.map(s => s.integration_id)).size === v.sources.length, 'Integration IDs must be unique');\nexport const updateDataset = z.object({ ...datasetTarget, expected_configuration_hash: hash, name }).strict();\nexport const removeIntegration = z.object({ ...datasetTarget, expected_configuration_hash: hash, integration_id: spotifyId, acknowledge_measurement_effects: z.literal(true) }).strict();\nexport const datasetSharing = z.object({ ...datasetTarget, expected_configuration_hash: hash, shared: z.boolean(), acknowledge_measurement_effects: z.boolean().optional() }).strict().refine(v => v.shared || v.acknowledge_measurement_effects === true, 'Unsharing requires acknowledgement of measurement effects');\nconst mobileFields = { name: z.string().trim().min(2).max(50), platform: z.enum(['IOS', 'ANDROID']).optional(), platform_app_id: z.string().min(2).max(120).optional(), ad_type: z.enum(['VIEW_THROUGH', 'STORE_KIT']).optional(), mobile_measurement_partner: z.enum(['KOCHAVA', 'APPS_FLYER', 'ADJUST', 'BRANCH', 'SINGULAR']).optional() };\nexport const createMobile = z.object(mobileFields).strict();\nexport const updateMobile = z.object({ ...mobileTarget, expected_configuration_hash: hash, ...mobileFields }).strict();\nexport const mobileSharing = z.object({ ...mobileTarget, expected_configuration_hash: hash, shared: z.boolean(), acknowledge_measurement_effects: z.boolean().optional() }).strict().refine(v => v.shared || v.acknowledge_measurement_effects === true, 'Unsharing requires acknowledgement of measurement effects');\n\nconst eventTime = z.object({ event_type: z.string().nullish(), first_event_time: z.string().nullish() });\nexport const pixelSchema = z.object({ id: pixelId, name: z.string().nullish(), domain: z.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), aam_opt_in: z.boolean().nullish(), aam_fields: z.array(aamField).nullish(), cookie_opt_in: z.boolean().nullish(), auto_capture_opt_in: z.boolean().nullish(), auto_capture_fields: z.array(z.string()).nullish(), events_received: z.array(eventTime).nullish() });\nexport const capiSchema = z.object({ capi_connection_id: spotifyId, name: z.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), events_received: z.array(eventTime).nullish() });\nconst shares = z.array(z.object({ id: spotifyId, name: z.string().nullish() })).refine(v => new Set(v.map(s => s.id)).size === v.length, 'Repeated account sharing IDs');\nexport const datasetSchema = z.object({ id: spotifyId, name: z.string().nullish(), pixel: pixelSchema.nullish(), capi_integration: capiSchema.nullish(), shared_ad_accounts: shares.nullish(), ad_set_count: z.number().int().nonnegative().nullish(), is_archived: z.boolean().nullish(), is_receiving_events: z.boolean().nullish(), is_receiving_lead_events: z.boolean().nullish() });\n// Native MobileApp includes link_token. It is deliberately absent from this projection.\nexport const mobileSchema = z.object({ id: spotifyId, name: z.string().nullish(), platform: z.string().nullish(), platform_app_id: z.string().nullish(), ad_type: z.string().nullish(), mobile_measurement_partner: z.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), ad_set_count: z.number().int().nonnegative().nullish(), is_skad_network: z.boolean().nullish(), shared_ad_accounts: shares.nullish() });\nexport const paging = z.object({ offset: z.number().int().nonnegative(), total_results: z.number().int().nonnegative(), page_size: z.number().int().nonnegative().nullish() });\nexport const diagnosticSchema = z.object({ dataset_id: spotifyId, datasources: z.array(z.object({ datasource_type: z.enum(['PIXEL', 'CAPI', 'MOBILE_APP']), datasource_id: z.string(), granularity: z.enum(['DAILY', 'HOURLY']), timeseries: z.array(z.object({ total: z.number().nullish(), timestamp: z.number().nullish(), event_counts: z.array(z.object({ name: z.string(), event_count: z.number(), last_activity_ms: z.number().nullish() })).nullish() })) })) });\nexport const createdReceipt = z.object({ version: z.literal(1), purpose: z.enum(['creation', 'sharing']), account_id: spotifyId, business_id: spotifyId, kind: z.enum(['pixel', 'capi', 'mobile_app', 'dataset']), id: pixelId, dataset_id: spotifyId.optional(), issued_at: z.number().int().positive().safe(), expires_at: z.number().int().positive().safe() }).strict().refine(v => v.kind === 'pixel' || spotifyId.safeParse(v.id).success, 'Invalid resource ID');\n","import { createHash } from 'node:crypto';\nimport { AdportError, type ResourceSecretScope, type ResourceSecretStore, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport { spotifyId } from './schemas.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const capiCredentialTarget = z.object({ dataset_id: spotifyId }).strict();\nconst snapshot = { dataset_id: spotifyId, expected_configuration_hash: hash, expected_dataset_configuration_hash: hash, expected_token_inventory_hash: hash };\nexport const createCapiCredential = z.object({ ...snapshot, acknowledge_credential_access: z.literal(true) }).strict();\nexport const storeCapiCredential = createCapiCredential.extend({ capi_auth_token_id: spotifyId });\nexport const revokeCapiCredential = z.object({ ...snapshot, capi_auth_token_id: spotifyId, acknowledge_ingestion_effects: z.literal(true) }).strict();\nexport const capiCredentialWrites = new Set(['spotify_create_capi_credential', 'spotify_store_capi_credential', 'spotify_revoke_capi_credential']);\n\n// GET returns secret values too. These private response objects never leave this service.\nconst nativeToken = z.object({ capi_auth_token_id: spotifyId, created_at: z.iso.datetime({ offset: true }).nullish(), capi_auth_token: z.string().min(1).max(65536).optional() });\nconst tokenList = z.object({ data: z.array(nativeToken).max(1000), paging: z.unknown().optional() }).refine(v => v.paging == null && new Set(v.data.map(t => t.capi_auth_token_id)).size === v.data.length, 'Invalid native credential inventory');\nconst createdToken = z.object({ data: nativeToken.extend({ capi_auth_token: z.string().min(1).max(65536) }) });\ntype NativeToken = z.infer<typeof nativeToken>;\nexport interface AuthorizedCapiCredentialScope {\n account_id: string;\n business_id: string;\n dataset_id: string;\n capi_connection_id: string;\n configuration_hash: string;\n dataset_configuration_hash: string;\n}\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<WriteResult> }\nconst notes = ['CAPI credentials grant ongoing event-ingestion access to this integration. The native endpoint provides no configurable expiry. No token value is returned to agents, widgets or audit logs.', 'No conversion events, tracking installation, ad delivery or budget changes. Native failures are never replayed automatically.'];\nconst previewNotes = ['Local preview only; Spotify has no native validation endpoint for credentials.', ...notes];\n\nexport class SpotifyCapiCredentials {\n constructor(private readonly client: SpotifyAdsClient, private readonly authorize: (input: { account_id: string; dataset_id: string }) => Promise<AuthorizedCapiCredentialScope>, private readonly secrets?: ResourceSecretStore) {}\n private path(scope: AuthorizedCapiCredentialScope) { return `businesses/${scope.business_id}/capi/${scope.capi_connection_id}/tokens`; }\n private key(scope: AuthorizedCapiCredentialScope, id: string): ResourceSecretScope { return { provider: 'spotify', accountId: scope.account_id, businessId: scope.business_id, resourceId: scope.capi_connection_id, credentialId: id }; }\n private metadata(tokens: NativeToken[]) { return tokens.map(t => ({ capi_auth_token_id: t.capi_auth_token_id, created_at: t.created_at ?? null })).sort((a, b) => a.capi_auth_token_id.localeCompare(b.capi_auth_token_id)); }\n private inventoryHash(scope: AuthorizedCapiCredentialScope, tokens: NativeToken[]) { return createHash('sha256').update(JSON.stringify({ ...scope, tokens: this.metadata(tokens) })).digest('hex'); }\n private async safe<T>(call: () => Promise<T>, operation: string): Promise<T> {\n try { return await call(); }\n catch (error) {\n const status = error instanceof AdportError && error.details && typeof error.details === 'object' && 'http_status' in error.details ? error.details.http_status : undefined;\n // Native errors may echo a CAPI secret that is unrelated to the OAuth token redactor.\n throw new AdportError('PROVIDER_ERROR', `spotify: CAPI credential ${operation} failed; inspect credential metadata before any new mutation. No request was replayed.`, typeof status === 'number' ? { http_status: status } : undefined);\n }\n }\n private async tokens(scope: AuthorizedCapiCredentialScope) { return (await this.safe(() => this.client.get(this.path(scope), tokenList), 'inventory read')).data; }\n private vault() { if (!this.secrets) throw new AdportError('INVALID_INPUT', 'spotify: a private resource credential store must be configured before managing CAPI credentials.');return this.secrets; }\n async list(input: { account_id: string; dataset_id: string }) {\n const scope = await this.authorize(input), tokens = await this.tokens(scope);\n return { ...scope, credential_inventory_hash: this.inventoryHash(scope, tokens), vault_configured: !!this.secrets,\n credentials: await Promise.all(this.metadata(tokens).map(async token => ({ ...token, stored_in_adport: this.secrets ? await this.safe(() => this.secrets!.has(this.key(scope, token.capi_auth_token_id)), 'storage metadata read') : null }))), notes };\n }\n private uncertain(scope: AuthorizedCapiCredentialScope, id: string | undefined, before: NativeToken[], operation: string): never {\n throw new AdportError('PROVIDER_ERROR', `spotify: CAPI credential ${operation} is unconfirmed. Do not repeat it; read spotify_capi_credentials and reconcile the selected credential.`, { business_id: scope.business_id, dataset_id: scope.dataset_id, capi_connection_id: scope.capi_connection_id, ...(id ? { capi_auth_token_id: id, resource_ids: [id] } : {}), previous_credential_ids: this.metadata(before).map(t => t.capi_auth_token_id) });\n }\n private async save(scope: AuthorizedCapiCredentialScope, token: NativeToken & { capi_auth_token: string }) {\n const store = this.vault(), key = this.key(scope, token.capi_auth_token_id);\n await store.putIfAbsent(key, token.capi_auth_token);\n if (await store.get(key) !== token.capi_auth_token) throw new Error('Stored credential does not match native credential.');\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const creating = op.tool === 'spotify_create_capi_credential', storing = op.tool === 'spotify_store_capi_credential';\n if (!capiCredentialWrites.has(op.tool)) throw new AdportError('UNKNOWN_TOOL', 'spotify: unknown CAPI credential mutation');\n const input = creating ? createCapiCredential.parse(op.payload) : storing ? storeCapiCredential.parse(op.payload) : revokeCapiCredential.parse(op.payload);\n const vault = this.vault(), scope = await this.authorize({ account_id: op.accountId, dataset_id: input.dataset_id }), before = await this.tokens(scope);\n if (scope.configuration_hash !== input.expected_configuration_hash || scope.dataset_configuration_hash !== input.expected_dataset_configuration_hash || this.inventoryHash(scope, before) !== input.expected_token_inventory_hash) throw new AdportError('PENDING_MISMATCH', 'spotify: CAPI configuration, sharing or credential inventory changed; read spotify_capi_credentials for a new preview.');\n const id = 'capi_auth_token_id' in input ? input.capi_auth_token_id : undefined;\n const selected = before.find(t => t.capi_auth_token_id === id);\n const stored = id ? await this.safe(() => vault.has(this.key(scope, id)), 'storage metadata read') : false;\n if (storing && !selected?.capi_auth_token) throw new AdportError('INVALID_INPUT', 'spotify: the selected active credential has no available native secret to store.');\n if (!creating && !selected && !stored) throw new AdportError('INVALID_INPUT', 'spotify: the selected credential is neither active in this integration nor stored in this Adport scope.');\n const title = creating ? 'Create CAPI credential' : storing ? 'Store existing CAPI credential' : selected ? 'Revoke CAPI credential' : 'Remove inactive CAPI credential copy';\n return { summary: `${title} for Spotify integration ${scope.capi_connection_id}`, changes: [creating ? '+ One native long-lived credential, saved privately in Adport.' : storing ? `+ Store only the selected active credential ${id}; do not create a native token.` : selected ? `- Revoke native credential ${id} and remove its Adport copy after confirmed native revocation.` : `- Remove only the private Adport copy of inactive credential ${id}; no native deletion request.`, 'No events are sent.'], coercions: [], budgetDeltas: [], notes: previewNotes,\n review: { provider: 'spotify', accountId: scope.account_id, kind: creating || storing ? 'create' : 'remove', title, fields: [{ label: 'Dataset', after: scope.dataset_id }, { label: 'CAPI integration', after: scope.capi_connection_id }, ...(id ? [{ label: 'Credential', after: id }, { label: 'Stored in Adport', before: stored, after: storing }] : []), { label: 'Active credentials', before: before.length, after: before.length + (creating ? 1 : !storing && selected ? -1 : 0) }], notices: previewNotes },\n execute: async () => {\n let createdId: string | undefined, nativeAcknowledged = false;\n try {\n if (creating) {\n const token = (await this.safe(() => this.client.mutate(this.path(scope), 'POST', undefined, createdToken), 'creation')).data;\n nativeAcknowledged = true;\n createdId = token.capi_auth_token_id;\n if (before.some(t => t.capi_auth_token_id === createdId)) throw new Error('Creation returned an existing credential ID.');\n await this.save(scope, token);\n const after = await this.tokens(scope);\n const actual = after.find(t => t.capi_auth_token_id === createdId);\n if (!actual || actual.capi_auth_token !== undefined && actual.capi_auth_token !== token.capi_auth_token) throw new Error('Credential readback mismatch.');\n return { applied: true, resourceIds: [createdId], details: { capi_auth_token_id: createdId, stored_in_adport: true, created_at: token.created_at ?? null, next_tool: 'spotify_capi_credentials' } };\n }\n if (storing) {\n await this.save(scope, selected as NativeToken & { capi_auth_token: string });\n return { applied: true, resourceIds: [id!], details: { capi_auth_token_id: id, stored_in_adport: true, native_credential_created: false } };\n }\n if (selected) { await this.safe(() => this.client.mutate(`${this.path(scope)}/${id}`, 'DELETE', undefined, z.undefined()), 'revocation');nativeAcknowledged = true; }\n if ((await this.tokens(scope)).some(t => t.capi_auth_token_id === id)) throw new Error('Credential remains active.');\n await vault.delete(this.key(scope, id!));\n return { applied: true, resourceIds: [id!], details: { capi_auth_token_id: id, native_active: false, stored_in_adport: false } };\n } catch (error) {\n // No raw native response, secret value, storage exception or stack is exposed.\n if (!nativeAcknowledged && error instanceof AdportError && error.details && typeof error.details === 'object' && 'http_status' in error.details && [400, 401, 403, 404, 409, 422].includes(Number(error.details.http_status))) throw error;\n return this.uncertain(scope, createdId ?? id, before, creating ? 'creation/storage' : storing ? 'storage' : 'revocation/cleanup');\n }\n } };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { spotifyId } from './schemas.js';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { createCapi, createDataset, createMobile, createPixel, datasetSharing, datasetTarget, mobileSharing, mobileTarget, receiptInput, removeIntegration, updateCapi, updateDataset, updateMobile, updatePixel } from './measurement-schemas.js';\nimport { capiCredentialTarget, capiCredentialWrites, createCapiCredential, revokeCapiCredential, storeCapiCredential } from './capi-credentials.js';\n\nexport const measurementWriteNames = new Set([...capiCredentialWrites, 'spotify_create_pixel', 'spotify_update_pixel', 'spotify_create_capi_integration', 'spotify_update_capi_integration', 'spotify_create_dataset', 'spotify_update_dataset', 'spotify_remove_dataset_integration', 'spotify_set_dataset_sharing', 'spotify_create_mobile_app', 'spotify_update_mobile_app', 'spotify_set_mobile_app_sharing']);\nexport function spotifyMeasurementTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'measurement', exposure: 'specialist' } as const;\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: 'spotify', description, input, catalog, presentation: 'records', annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove', destructive = false) => guardedWriteTool({ name, namespace: 'spotify', provider: 'spotify', description, payload, catalog, kind, destructive });\n const account = { account_id: spotifyId }, dataset = z.object({ ...account, ...datasetTarget });\n return [\n read('spotify_capi_credentials', 'List active CAPI credential IDs, creation times and private storage status for an integration shared only with this selected account. Returns snapshot hashes for mutations; never returns token values or sends events.', capiCredentialTarget.extend(account), v => provider.measurement.credentials.list(v)),\n write('spotify_create_capi_credential', 'Create one long-lived CAPI credential and store it privately in Adport. Requires current hashes from spotify_capi_credentials and explicit access acknowledgement. No secret is returned; no events are sent. Never repeat an unconfirmed creation.', createCapiCredential, 'create'),\n write('spotify_store_capi_credential', 'Store one selected active native CAPI credential privately in Adport without creating another token. Requires fresh credential/context hashes and explicit access acknowledgement. The token is fetched server-side and never returned.', storeCapiCredential, 'create'),\n write('spotify_revoke_capi_credential', 'Revoke one selected CAPI credential and remove its Adport copy after native confirmation. May stop existing event publishers. Fresh hashes and explicit acknowledgement required. Also reconciles a stored copy when native revocation already completed. No automatic native retries.', revokeCapiCredential, 'remove', true),\n read('spotify_measurement_context', 'Read the selected account’s verified business and shared dataset topology. Read an individual resource before a mutation to obtain its full configuration_hash. Other account identities and business-wide inventory are excluded; no tracking or credentials are created.', z.object(account), v => provider.measurement.context(v.account_id)),\n read('spotify_datasets', 'List only datasets shared with this account. The native endpoint has no limit/offset query; returns explicit completeness rather than inventing pagination.', z.object(account), v => provider.measurement.datasets(v.account_id)),\n read('spotify_get_dataset', 'Read one shared dataset and its configuration_hash. An unshared approved creation requires its signed resource_receipt. Other account identities are omitted.', dataset, v => provider.measurement.getDataset(v)),\n read('spotify_get_pixel', 'Read the Pixel bound to an authorized dataset, including matching settings and configuration_hash. Native Pixel IDs alone do not authorize business-wide reads.', dataset, v => provider.measurement.getPixel(v)),\n read('spotify_get_capi_integration', 'Read a CAPI connection bound to an authorized dataset. Returns configuration_hash and metadata only, never active credentials.', dataset, v => provider.measurement.getCapi(v)),\n read('spotify_mobile_apps', 'Read mobile measurement apps shared with this account using native pagination. Link tokens and other account identities are omitted.', z.object({ ...account, limit: z.number().int().positive().max(50).default(50), offset: z.number().int().nonnegative().default(0) }), v => provider.measurement.mobileApps(v)),\n read('spotify_get_mobile_app', 'Read one account-shared or approved-created mobile app with its configuration_hash. Native MMP link tokens are omitted.', z.object({ ...account, ...mobileTarget }), v => provider.measurement.getMobile(v)),\n read('spotify_dataset_diagnostics', 'Read native DAILY/HOURLY source activity for an authorized dataset. Diagnostics can lag 20 minutes; activity does not prove campaign attribution. Sends no conversion events.', z.object({ ...account, ...datasetTarget, granularities: z.array(z.enum(['DAILY', 'HOURLY'])).min(1).max(2).refine(v => new Set(v).size === v.length, 'Granularities must be unique').default(['DAILY']), datasource_ids: z.array(z.string().min(1)).min(1).max(100).optional() }), v => provider.measurement.diagnostics(v)),\n read('spotify_created_measurement', 'Reconcile the exact created resource and receipt-bound parent with current account/business access. A missing child binding requires the locked parent to independently name this exact resource. Explicit conflicts never follow another parent. Read-only; never replays a write.', z.object({ ...account, resource_receipt: receiptInput }), v => provider.measurement.created(v)),\n read('spotify_measurement_sharing_status', 'Reconcile sharing with the signed receipt from an approved share/unshare operation. Returns only selected-account sharing state; a status receipt does not grant content access after unsharing.', z.object({ ...account, resource_receipt: receiptInput }), v => provider.measurement.sharingStatus(v)),\n write('spotify_create_pixel', 'Create a Pixel and verify its native dataset, then share only with the selected account. AAM defaults off; opt-in requires explicit acknowledgement. Supports existing dataset_id with its current hash. No website install or event sending.', createPixel, 'create'),\n write('spotify_update_pixel', 'Update a verified Pixel name/domain with its current configuration_hash. Native update cannot change AAM. Preserves matching, routing and other configuration; rejects stale or cross-account-shared configuration and independently reads back the result.', updatePixel, 'update'),\n write('spotify_create_capi_integration', 'Create a CAPI connection in a new or verified existing dataset, then verify sharing with the selected account. Does not issue tokens or send events. Returns a signed receipt for partial creation recovery; never retries automatically.', createCapi, 'create'),\n write('spotify_update_capi_integration', 'Rename an authorized CAPI connection with its current configuration_hash. Preserves dataset routing and independently verifies native readback; does not touch credentials or events.', updateCapi, 'update'),\n write('spotify_create_dataset', 'Create a dataset from explicit account-owned integrations and source snapshots, acknowledging measurement rerouting. Independently checks each native integration’s new dataset binding and selected-account sharing. Prefer Pixel-first plus CAPI dataset_id for a shared topology.', createDataset, 'create', true),\n write('spotify_update_dataset', 'Rename an authorized dataset with its current configuration_hash, preserving sources and sharing. Business-wide edits are rejected when another account shares the dataset or dependencies are unknown.', updateDataset, 'update'),\n write('spotify_remove_dataset_integration', 'Remove one verified integration from a dataset. Spotify moves it to a newly created dataset; this does not delete the source or remove website code. Requires current snapshot and explicit acknowledgement; returns signed recovery context.', removeIntegration, 'remove', true),\n write('spotify_set_dataset_sharing', 'Share/unshare a verified dataset only with the selected account, preserving all other shares. Requires current configuration_hash; unsharing needs measurement-effect acknowledgement. An unshared creation requires its receipt. Native readback and signed status reconciliation prevent unsafe replay.', datasetSharing, 'update', true),\n write('spotify_create_mobile_app', 'Register native mobile measurement metadata and share the new app only with this account. Supports current MMP enums including SINGULAR. Does not install a partner SDK; link tokens are not returned.', createMobile, 'create'),\n write('spotify_update_mobile_app', 'Update account-owned mobile app metadata using its current configuration_hash. Sends the required native name, preserves omitted fields and independently verifies native readback. Link tokens cannot be edited or disclosed.', updateMobile, 'update'),\n write('spotify_set_mobile_app_sharing', 'Share/unshare only this account’s mobile-app association using the current hash. Unsharing needs explicit measurement-effect acknowledgement; other shares are preserved and the result is independently verified.', mobileSharing, 'update', true),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createDraftSchema, setBudgetSchema, setDeliverySchema, setStatusSchema, spotifyId } from './schemas.js';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { spotifyCreativeTools } from './creative-tools.js';\nimport { spotifyManagementTools } from './management-tools.js';\nimport { spotifyMeasurementTools } from './measurement-tools.js';\n\nexport function spotifyTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\n return [\n ...spotifyCreativeTools(provider),\n ...spotifyManagementTools(provider),\n ...spotifyMeasurementTools(provider),\n defineTool({ name: 'spotify_list_campaigns', namespace: 'spotify', description: 'List published Spotify Ads campaigns in the selected account.',\n input: z.object({ account_id: spotifyId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'spotify_get_ad_set', namespace: 'spotify', description: 'Read a Spotify ad set, including its budget and delivery setting.',\n input: z.object({ account_id: spotifyId, ad_set_id: spotifyId }), annotations: { readOnly: true }, handler: input => provider.getAdSet(input.account_id, input.ad_set_id) }),\n guardedWriteTool({ name: 'spotify_create_campaign_draft', namespace: 'spotify', provider: 'spotify', kind: 'create',\n description: 'Create an unpublished Spotify campaign draft, paused by policy. Does not publish or launch ads. Preview is local.', payload: createDraftSchema }),\n guardedWriteTool({ name: 'spotify_set_campaign_status', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Pause or activate an existing Spotify Ads campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'spotify_set_budget', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Change a Spotify ad-set budget in integer micros, preserving its current DAILY or LIFETIME type.', payload: setBudgetSchema }),\n guardedWriteTool({ name: 'spotify_set_ad_set_delivery', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Turn an existing Spotify ad set delivery OFF or ON.', payload: setDeliverySchema }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { assetFormat, assetType, bidStrategy, createAd, createAsset, createGroup, deliveryGoal, draftEntity, draftMutation, frequencyCaps, publishDraft, targets, updateAd, updateCampaign, updateGroup, uploadAsset } from './creative-schemas.js';\nimport { budgetSchema, spotifyId } from './schemas.js';\n\nconst page = { limit: z.number().int().positive().max(50).default(50), offset: z.number().int().nonnegative().default(0) };\nconst account = { account_id: spotifyId };\nconst strings = z.array(z.string().min(1)).min(1).max(1000);\nconst estimate = { asset_format: assetFormat, bid_strategy: bidStrategy, targets: targets.refine(v => Boolean(v.placements?.length), 'Estimates require placements'), delivery_goal: deliveryGoal.optional(), frequency_caps: frequencyCaps.optional(), category: z.string().regex(/^ADV_\\d+_\\d+$/).optional() };\n\nexport function spotifyCreativeTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\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: 'spotify', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove' = 'update') => guardedWriteTool({ name, namespace: 'spotify', provider: 'spotify', description, payload, kind });\n return [\n read('spotify_drafts', 'List unpublished campaign, ad-set or ad drafts, with native pagination and hierarchy versions. This does not publish.', z.object({ ...account, entity: draftEntity, campaign_ids: z.array(spotifyId).optional(), ad_set_ids: z.array(spotifyId).optional(), ...page }).refine(v => !(v.campaign_ids && v.entity !== 'ad_sets') && !(v.ad_set_ids && v.entity !== 'ads'), 'Use campaign_ids for ad_sets or ad_set_ids for ads'), input => provider.creatives.drafts(input)),\n read('spotify_get_draft', 'Read an account-owned draft and verify its parent hierarchy. Use the campaign draft version for validation/publication.', z.object({ ...account, entity: draftEntity, draft_id: spotifyId }), input => provider.creatives.get(input.account_id, input.entity, input.draft_id)),\n read('spotify_ad_sets', 'Read published ad-set targeting, bidding, budgets and delivery, with pagination.', z.object({ ...account, campaign_ids: z.array(spotifyId).optional(), ...page }), input => provider.creatives.page(input, 'ad_sets', 'ad_sets', { campaign_ids: input.campaign_ids })),\n defineTool({ name: 'spotify_ads', namespace: 'spotify', description: 'View published or draft ad copy and image/video/audio assets. Drafts include guarded copy-edit actions; publication remains separate.', input: z.object({ ...account, draft: z.boolean().default(false), ad_set_ids: z.array(spotifyId).optional(), ...page }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'offset', cursorOutput: 'next_offset' }, annotations: { readOnly: true }, handler: input => provider.creatives.ads(input) }),\n defineTool({ name: 'spotify_assets', namespace: 'spotify', description: 'View Spotify account image/video/audio assets and processing status with pagination.', input: z.object({ ...account, asset_types: z.array(assetType).optional(), asset_statuses: z.array(z.enum(['ERROR', 'PROCESSING', 'READY', 'WAITING_UPLOAD'])).optional(), name: z.string().optional(), ...page }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'offset', cursorOutput: 'next_offset' }, annotations: { readOnly: true }, handler: input => provider.creatives.assets(input) }),\n read('spotify_get_asset', 'Read an account-owned asset and processing status. No ad delivery changes.', z.object({ ...account, asset_id: spotifyId }), input => provider.creatives.asset(input.account_id, input.asset_id)),\n read('spotify_ad_categories', 'Search Spotify’s live advertiser-category codes for draft ad sets.', z.object({ ...account, q: z.string().optional() }), input => provider.creatives.categories(input.q)),\n read('spotify_targeting_options', 'Search native Spotify artist, genre, interest, language, playlist or podcast topic targeting.', z.object({ ...account, kind: z.enum(['artists', 'genres', 'interests', 'languages', 'playlists', 'episode_topics', 'sensitive_topics']), ids: strings.optional(), q: z.string().optional() }), input => provider.creatives.targeting(input)),\n read('spotify_geo_targets', 'Search native geographical targeting IDs with country/type filters and pagination.', z.object({ ...account, country_code: z.string().regex(/^[A-Z]{2}$/).optional(), ids: strings.optional(), types: strings.optional(), q: z.string().optional(), language: z.string().regex(/^[a-z]{2}$/).optional(), limit: z.number().int().positive().max(1000).default(50), offset: z.number().int().nonnegative().default(0) }), input => provider.creatives.targeting({ ...input, kind: 'geos' })),\n read('spotify_audience_estimate', 'Get a non-binding audience/delivery estimate using a read-only POST. Native micro amounts and explicit placements are required; no audience or ad is created.', z.object({ ...account, ...estimate, start_date: z.iso.datetime(), end_date: z.iso.datetime().optional(), bid_micro_amount: z.number().int().nonnegative().safe(), budget: budgetSchema.extend({ currency: z.string().regex(/^[A-Z]{3}$/) }) }).refine(v => !v.end_date || v.end_date > v.start_date, 'End date must follow start date'), input => provider.creatives.estimate('audience', input)),\n read('spotify_bid_estimate', 'Get a non-binding native bid estimate with explicit targeting/placements. No bids or delivery settings are changed.', z.object({ ...account, ...estimate, currency: z.string().regex(/^[A-Z]{3}$/) }), input => provider.creatives.estimate('bid', input)),\n read('spotify_validate_draft', 'Validate a specific campaign draft hierarchy version server-side without publishing. Returns native validation errors.', z.object({ ...account, ...publishDraft.shape }), input => provider.creatives.validate(input.account_id, input.draft_campaign_id, input.draft_hierarchy_version)),\n write('spotify_create_draft_ad_set', 'Stage an unpublished ad set under a verified draft campaign. Monetary values are integer micros. Partial drafts are allowed; targeting requires placements and lifetime budgets require end_time.', createGroup, 'create'),\n write('spotify_create_draft_ad', 'Stage unpublished ad copy and existing account-owned asset IDs under a verified draft ad set. Does not publish or enable delivery.', createAd, 'create'),\n write('spotify_update_draft_campaign', 'Patch only supplied draft campaign fields. Publication is separate; status changes here affect only the draft.', updateCampaign),\n write('spotify_update_draft_ad_set', 'Patch draft ad-set targeting, schedule, budget or bids. Preserves omitted nested targeting; arrays replace supplied dimensions. Amounts use micros.', updateGroup),\n write('spotify_update_draft_ad', 'Patch unpublished ad copy/assets/CTA. Omitted assets and CTA fields are preserved; supplied tracking arrays replace the full array.', updateAd),\n write('spotify_create_draft_from_published', 'Stage a copy of an account-owned published campaign/ad set/ad without changing delivery. Refuses to overwrite an existing draft.', draftMutation, 'create'),\n write('spotify_delete_draft', 'Delete only an unpublished draft. Delete child ad drafts first: parent deletion is refused while ads remain to prevent provider orphan records. Published entities remain unchanged.', draftMutation, 'remove'),\n ...(['ads', 'ad_sets'] as const).map(entity => write(`spotify_delete_draft_${entity}`, 'Atomically delete account-owned drafts through the native batch endpoint. Delete child ads before ad sets to prevent provider orphan records. Published entities remain unchanged.', z.object({ draft_ids: z.array(spotifyId).min(1).max(entity === 'ads' ? 100 : 40).refine(ids => new Set(ids).size === ids.length, 'IDs must be unique') }), 'remove')),\n write('spotify_publish_draft', 'Spotify publishes ACTIVE even from a PAUSED draft. Blocked while paused_creation policy is enabled. Otherwise requires explicit acknowledge_active_publication=true, exact hierarchy version, budget checks and server validation.', publishDraft, 'create'),\n write('spotify_create_asset', 'Create account-owned asset metadata for a later checksum-bound upload. No creative is attached to an ad.', createAsset, 'create'),\n write('spotify_upload_asset', 'Upload SHA-256-approved image/video/audio to a new WAITING_UPLOAD asset. Uses native chunking above20MB; Adport cap100MiB, hosted staging50MiB. Existing assets cannot be overwritten.', uploadAsset, 'create'),\n write('spotify_rename_asset', 'Rename account-owned asset metadata without replacing media or changing delivery.', z.object({ asset_id: spotifyId, name: z.string().trim().min(2).max(120) })),\n ];\n}\n"],"mappings":";AAAA,SAAS,+BAA0E;;;ACAnF,SAAS,mBAAmB;AAC5B,SAAS,YAAY,uBAAuB;AAC5C,SAAS,SAAS;AAEX,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAOjC,IAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAAG,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EACjE,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAC5C,CAAC;AAEM,SAAS,oBAAoB,UAAkB,aAAqB,OAAuB;AAEhG,SAAO,2CAA2C,IAAI,gBAAgB;AAAA,IACpE,WAAW;AAAA,IAAU,eAAe;AAAA,IAAQ,cAAc;AAAA,IAAa;AAAA,EACzE,CAAC,CAAC;AACJ;AAEA,eAAe,aAAa,aAAoE,MAAuB,WAAyB;AAC9I,QAAM,WAAW,MAAM,UAAU,mBAAmB;AAAA,IAClD,QAAQ;AAAA,IAAQ,SAAS;AAAA,MACvB,eAAe,SAAS,OAAO,KAAK,GAAG,YAAY,QAAQ,IAAI,YAAY,YAAY,EAAE,EAAE,SAAS,QAAQ,CAAC;AAAA,MAC7G,gBAAgB;AAAA,IAClB;AAAA,IAAG;AAAA,IAAM,UAAU;AAAA,IAAS,QAAQ,YAAY,QAAQ,GAAM;AAAA,EAChE,CAAC;AACD,MAAI,CAAC,SAAS,GAAI,OAAM,IAAI,YAAY,kBAAkB,kBAAkB,KAAK,IAAI,YAA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AACnD;","names":["params","url","parsed","z","AdportError","AdportError","z","z","z","z","z","account","params","AdportError","page","ids","url","name","AdportError","z","z","z","name","description","object","z","query","params","account","AdportError","createHash","AdportError","z","z","z","paging","AdportError","z","hash","z","AdportError","createHash","AdportError","account","z","snapshot","paging","page","hash","ids","defineTool","guardedWriteTool","z","name","description","defineTool","guardedWriteTool","account","z","z","account","page","AdportError","query","params","z","defineTool","guardedWriteTool","defineTool","guardedWriteTool","z","page","z","account","strings","name","description","defineTool","guardedWriteTool","ids","defineTool","z","guardedWriteTool"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/provider.ts","../src/creatives.ts","../src/creative-schemas.ts","../src/schemas.ts","../src/management.ts","../src/management-tools.ts","../src/measurement.ts","../src/measurement-schemas.ts","../src/capi-credentials.ts","../src/measurement-tools.ts","../src/tools.ts","../src/creative-tools.ts"],"sourcesContent":["import { FileResourceSecretStore, type CredentialStore, type ProviderModule } from '@adport/core';\nimport { SpotifyAdsClient, type SpotifyCredentials } from './client.js';\nimport { SpotifyAdsProvider } from './provider.js';\nimport { spotifyTools } from './tools.js';\nexport { SpotifyAdsClient, SPOTIFY_API_BASE, SPOTIFY_TOKEN_URL, buildSpotifyAuthUrl, exchangeSpotifyCode, type SpotifyCredentials } from './client.js';\nexport { SpotifyAdsProvider } from './provider.js';\nexport { spotifyTools } from './tools.js';\nexport { accountSchema, campaignSchema, draftSchema, adSetSchema, reportSchema } from './schemas.js';\n\nexport async function resolveSpotifyCredentials(store: CredentialStore): Promise<SpotifyCredentials | undefined> {\n const data = (await store.get('spotify'))?.data;\n if (data?.client_id && data.client_secret && data.refresh_token) return {\n clientId: data.client_id, clientSecret: data.client_secret, refreshToken: data.refresh_token,\n onRefreshToken: async refreshToken => {\n const latest = await store.get('spotify');\n if (latest) await store.set({ provider: 'spotify', source: latest.source, data: { ...latest.data, refresh_token: refreshToken } });\n },\n };\n if (process.env.SPOTIFY_CLIENT_ID && process.env.SPOTIFY_CLIENT_SECRET && process.env.SPOTIFY_REFRESH_TOKEN) return {\n clientId: process.env.SPOTIFY_CLIENT_ID, clientSecret: process.env.SPOTIFY_CLIENT_SECRET, refreshToken: process.env.SPOTIFY_REFRESH_TOKEN,\n };\n return undefined;\n}\n\nexport async function createSpotifyModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveSpotifyCredentials(store);\n if (!credentials) return undefined;\n const provider = new SpotifyAdsProvider(new SpotifyAdsClient(credentials), undefined, { resourceSecrets: new FileResourceSecretStore() });\n return { provider, tools: spotifyTools(provider) };\n}\n","import { AdportError } from '@adport/core';\nimport { createHmac, timingSafeEqual } from 'node:crypto';\nimport { z } from 'zod';\n\nexport const SPOTIFY_API_BASE = 'https://api-partner.spotify.com/ads/v3/';\nexport const SPOTIFY_TOKEN_URL = 'https://accounts.spotify.com/api/token';\nexport interface SpotifyCredentials {\n clientId: string;\n clientSecret: string;\n refreshToken: string;\n onRefreshToken?: (refreshToken: string) => Promise<void>;\n}\nconst tokenSchema = z.object({\n access_token: z.string().min(1), expires_in: z.number().positive(),\n refresh_token: z.string().min(1).optional(),\n});\n\nexport function buildSpotifyAuthUrl(clientId: string, redirectUri: string, state: string): string {\n // Ads API access is granted to the app, not through Web API music scopes.\n return `https://accounts.spotify.com/authorize/?${new URLSearchParams({\n client_id: clientId, response_type: 'code', redirect_uri: redirectUri, state,\n })}`;\n}\n\nasync function tokenRequest(credentials: Pick<SpotifyCredentials, 'clientId' | 'clientSecret'>, body: URLSearchParams, fetchImpl: typeof fetch) {\n const response = await fetchImpl(SPOTIFY_TOKEN_URL, {\n method: 'POST', headers: {\n authorization: `Basic ${Buffer.from(`${credentials.clientId}:${credentials.clientSecret}`).toString('base64')}`,\n 'content-type': 'application/x-www-form-urlencoded',\n }, body, redirect: 'error', signal: AbortSignal.timeout(30_000),\n });\n if (!response.ok) throw new AdportError('PROVIDER_ERROR', `spotify: OAuth ${body.get('grant_type')} failed (HTTP ${response.status})`);\n const parsed = tokenSchema.safeParse(await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed OAuth response');\n return parsed.data;\n}\n\nexport async function exchangeSpotifyCode(input: { clientId: string; clientSecret: string; code: string; redirectUri: string }, fetchImpl: typeof fetch = fetch): Promise<string> {\n const token = await tokenRequest(input, new URLSearchParams({ grant_type: 'authorization_code', code: input.code, redirect_uri: input.redirectUri }), fetchImpl);\n if (!token.refresh_token) throw new AdportError('PROVIDER_ERROR', 'spotify: OAuth exchange did not return a refresh token');\n return token.refresh_token;\n}\n\nexport class SpotifyAdsClient {\n private token?: { value: string; expiresAt: number };\n private refreshToken: string;\n private refreshing?: Promise<string>;\n constructor(private readonly credentials: SpotifyCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n this.refreshToken = credentials.refreshToken;\n }\n\n measurementReceipt(value: Record<string, unknown>): string {\n const payload = Buffer.from(JSON.stringify(value)).toString('base64url');\n return `${payload}.${createHmac('sha256', this.measurementReceiptKey()).update(payload).digest('base64url')}`;\n }\n verifyMeasurementReceipt(receipt: string): unknown {\n const invalid = () => new AdportError('INVALID_INPUT', 'spotify: invalid measurement resource receipt');\n if (receipt.length > 4096 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();\n const [payload, signature] = receipt.split('.'), supplied = Buffer.from(signature!, 'base64url');\n const expected = createHmac('sha256', this.measurementReceiptKey()).update(payload!).digest();\n if (Buffer.from(payload!, 'base64url').toString('base64url') !== payload || supplied.toString('base64url') !== signature || supplied.length !== expected.length || !timingSafeEqual(supplied, expected)) throw invalid();\n try { return JSON.parse(Buffer.from(payload!, 'base64url').toString('utf8')); } catch { throw invalid(); }\n }\n private measurementReceiptKey(): Buffer {\n // Stable across OAuth refresh rotation; every use also rechecks native account/business access.\n return createHmac('sha256', this.credentials.clientSecret).update(`adport:spotify:measurement:v1:${this.credentials.clientId}`).digest();\n }\n\n async get<T>(path: string, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, 'GET', schema, undefined, params);\n }\n async mutate<T>(path: string, method: 'POST' | 'PATCH' | 'DELETE', body: unknown, schema: z.ZodType<T>, params = new URLSearchParams()): Promise<T> {\n return this.request(path, method, schema, body, params);\n }\n async upload<T>(path: string, body: FormData, schema: z.ZodType<T>): Promise<T> {\n return this.request(path, 'POST', schema, body);\n }\n\n private async request<T>(path: string, method: 'GET' | 'POST' | 'PATCH' | 'DELETE', schema: z.ZodType<T>, body?: unknown, params = new URLSearchParams(), retry = true): Promise<T> {\n // Resource paths are built from schema-checked IDs. Reject foreign URLs,\n // absolute paths, queries and dot segments before sending any credentials.\n if (!/^[a-z_]+(?:\\/[a-zA-Z0-9_-]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'spotify: invalid API resource path');\n const url = new URL(path, SPOTIFY_API_BASE);\n url.search = params.toString();\n const token = await this.accessToken();\n const response = await this.fetchImpl(url.href, {\n method, headers: { authorization: `Bearer ${token}`, ...(body !== undefined && !(body instanceof FormData) ? { 'content-type': 'application/json' } : {}) },\n ...(body !== undefined ? { body: body instanceof FormData ? body : JSON.stringify(body) } : {}), redirect: 'error', signal: AbortSignal.timeout(60_000),\n });\n if (response.status === 401 && method === 'GET' && retry) {\n if (this.token?.value === token) this.token = undefined;\n return this.request(path, method, schema, body, params, false);\n }\n if (!response.ok) {\n const advice = response.status === 403 ? ' Check Ads API terms/allowlisting and ad-account permissions; reauthorization alone may not help.' : '';\n const details: Record<string, unknown> = { http_status: response.status };\n if ([400, 404, 409, 422].includes(response.status)) {\n const errors = z.object({ messages: z.array(z.string().max(2000)).max(30).optional(), sp_trace_id: z.uuid().optional(), error_codes: z.array(z.object({ code: z.string().max(200), definition: z.string().max(2000).optional() })).max(30).optional() });\n const parsed = errors.safeParse(await response.json().catch(() => undefined));\n if (parsed.success) {\n const redact = (value: string) => [this.credentials.clientId, this.credentials.clientSecret, this.credentials.refreshToken, this.refreshToken, token].reduce((text, secret) => secret ? text.replaceAll(secret, '[redacted]') : text, value);\n if (parsed.data.messages) details.messages = parsed.data.messages.map(redact);\n if (parsed.data.sp_trace_id) details.sp_trace_id = parsed.data.sp_trace_id;\n if (parsed.data.error_codes) details.error_codes = parsed.data.error_codes.map(error => ({ code: redact(error.code), ...(error.definition ? { definition: redact(error.definition) } : {}) }));\n }\n }\n const messages = Array.isArray(details.messages) ? ` ${details.messages.join('; ')}` : '';\n throw new AdportError('PROVIDER_ERROR', `spotify: HTTP ${response.status}.${advice}${messages}`, details);\n }\n const parsed = schema.safeParse(response.status === 204 ? undefined : await response.json());\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed API response', { api_path: path, response_issues: parsed.error.issues.map(issue => ({ path: issue.path, code: issue.code })) });\n return parsed.data;\n }\n\n private async accessToken(): Promise<string> {\n if (this.token && this.token.expiresAt > Date.now() + 60_000) return this.token.value;\n if (!this.refreshing) this.refreshing = this.refresh().finally(() => { this.refreshing = undefined; });\n return this.refreshing;\n }\n private async refresh(): Promise<string> {\n const token = await tokenRequest(this.credentials, new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.refreshToken }), this.fetchImpl);\n if (token.refresh_token && token.refresh_token !== this.refreshToken) {\n this.refreshToken = token.refresh_token;\n await this.credentials.onRefreshToken?.(token.refresh_token);\n }\n this.token = { value: token.access_token, expiresAt: Date.now() + token.expires_in * 1000 };\n return token.access_token;\n }\n}\n","import { z } from 'zod';\nimport {\n AdportError, LocalMediaResolver, resolveDateRange, type Account, type AdProvider, type MediaResolver, type MetricName,\n type NormalizedQuery, type Report, type ReportRow, type StandardActions,\n type WriteGuard, type WriteOperation, type WritePreview, type WriteResult, type ResourceSecretStore,\n} from '@adport/core';\nimport { SpotifyAdsClient } from './client.js';\nimport { SpotifyCreativeService } from './creatives.js';\nimport { SpotifyManagementService } from './management.js';\nimport { managementWriteNames } from './management-tools.js';\nimport { SpotifyMeasurementService } from './measurement.js';\nimport { measurementWriteNames } from './measurement-tools.js';\nimport {\n accountSchema, adSetSchema, businessSchema, campaignSchema, createDraftSchema,\n draftSchema, pagingSchema, reportSchema, setBudgetSchema, setDeliverySchema,\n setStatusSchema, spotifyId,\n} from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[] | WriteResult> }\nconst LEVEL = { account: 'AD_ACCOUNT', campaign: 'CAMPAIGN', ad_group: 'AD_SET', ad: 'AD' } as const;\nconst FIELDS = { spend: 'SPEND', impressions: 'IMPRESSIONS', clicks: 'CLICKS', conversions: 'PURCHASES', conversion_value: 'REVENUE' } as const;\nconst DERIVED = {\n ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000],\n cpa: ['spend', 'conversions', 1], roas: ['conversion_value', 'spend', 1],\n} as const;\n\nexport class SpotifyAdsProvider implements AdProvider {\n readonly id = 'spotify';\n readonly creatives: SpotifyCreativeService;\n readonly management: SpotifyManagementService;\n readonly measurement: SpotifyMeasurementService;\n constructor(private readonly client: SpotifyAdsClient, media: MediaResolver = new LocalMediaResolver(), options: { resourceSecrets?: ResourceSecretStore } = {}) { this.creatives = new SpotifyCreativeService(client, media); this.management = new SpotifyManagementService(client, this.creatives); this.measurement = new SpotifyMeasurementService(client, options.resourceSecrets); }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions {\n return { pauseCampaign: (accountId, campaignId) => ({ tool: 'spotify_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) };\n }\n\n async listAccounts(): Promise<Account[]> {\n const { businesses } = await this.client.get('businesses', z.object({ businesses: z.array(businessSchema) }));\n const accounts = new Map<string, Account>();\n for (const business of businesses) {\n const { ad_accounts } = await this.client.get(`businesses/${business.id}/ad_accounts`, z.object({ ad_accounts: z.array(accountSchema) }));\n for (const account of ad_accounts) accounts.set(account.id, { provider: this.id, id: account.id, name: account.name, currency: account.currency_code, status: account.status });\n }\n return [...accounts.values()];\n }\n\n async listCampaigns(accountId: string) {\n const path = `ad_accounts/${spotifyId.parse(accountId)}/campaigns`;\n const schema = z.object({ paging: pagingSchema, campaigns: z.array(campaignSchema) });\n const rows: z.infer<typeof campaignSchema>[] = [];\n const seen = new Set<string>();\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.client.get(path, schema, new URLSearchParams({ limit: '50', offset: String(offset), sort_field: 'ID', sort_direction: 'ASC' }));\n if (data.paging.offset !== offset) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination changed offset');\n for (const campaign of data.campaigns) {\n if (seen.has(campaign.id)) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination repeated an entity');\n seen.add(campaign.id);\n rows.push(campaign);\n }\n offset += data.campaigns.length;\n if (offset >= data.paging.total_results) return rows;\n if (!data.campaigns.length) break;\n }\n throw new AdportError('PROVIDER_ERROR', 'spotify: campaign pagination did not terminate; refusing incomplete results');\n }\n\n async getAdSet(accountId: string, adSetId: string) {\n const data = await this.client.get(`ad_accounts/${spotifyId.parse(accountId)}/ad_sets/${spotifyId.parse(adSetId)}`, adSetSchema);\n if (data.id !== adSetId) throw new AdportError('PROVIDER_ERROR', 'spotify: ad set response ID mismatch');\n return data;\n }\n\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n const start = z.iso.date().parse(range.start), end = z.iso.date().parse(range.end);\n const days = (Date.parse(end) - Date.parse(start)) / 86_400_000;\n if (days < 0 || days > 90) throw new AdportError('INVALID_INPUT', 'spotify: report end must be on/after start and within 90 days');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'spotify: report limit must be a positive integer');\n const fields = new Set<string>();\n for (const metric of query.metrics) {\n if (metric in FIELDS) fields.add(FIELDS[metric as keyof typeof FIELDS]);\n else if (metric in DERIVED) for (const dependency of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) fields.add(FIELDS[dependency as keyof typeof FIELDS]);\n }\n if (!fields.size) throw new AdportError('INVALID_INPUT', 'spotify: report requires at least one supported metric');\n const accountIds = [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))];\n const rows: ReportRow[] = [];\n for (const id of accountIds) {\n const accountId = spotifyId.parse(id);\n let params = new URLSearchParams({ entity_type: LEVEL[query.level], report_start: `${start}T00:00:00Z`, report_end: `${end}T00:00:00Z`, granularity: 'LIFETIME', limit: '50' });\n for (const field of fields) params.append('fields', field);\n const tokens = new Set<string>();\n const entities = new Set<string>();\n while (true) {\n const data = await this.client.get(`ad_accounts/${accountId}/aggregate_reports`, reportSchema, params);\n if (data.granularity !== 'LIFETIME') throw new AdportError('PROVIDER_ERROR', 'spotify: unexpected report granularity');\n for (const row of data.rows) {\n if (row.entity_type !== LEVEL[query.level] || (query.level === 'account' && row.entity_id !== accountId) || entities.has(row.entity_id)) {\n throw new AdportError('PROVIDER_ERROR', 'spotify: incorrectly scoped or duplicate report row');\n }\n entities.add(row.entity_id);\n rows.push({ provider: this.id, accountId, entity: { level: query.level, id: row.entity_id, name: row.entity_name, status: row.entity_status }, metrics: normalize(row.stats, query.metrics) });\n if (rows.length > limit) return { rows: rows.slice(0, limit), truncated: true };\n }\n if (!data.continuation_token) break;\n if (tokens.has(data.continuation_token) || tokens.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'spotify: report pagination did not terminate');\n tokens.add(data.continuation_token);\n // Other parameters are ignored by Spotify when a continuation is supplied.\n params = new URLSearchParams({ continuation_token: data.continuation_token });\n }\n }\n return { rows };\n }\n\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.plan(op, guard);\n return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const result = await (await this.plan(op, guard)).execute();\n return Array.isArray(result) ? { applied: true, resourceIds: result } : result;\n }\n\n private async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const accountId = spotifyId.parse(op.accountId);\n const base = `ad_accounts/${accountId}`;\n if (op.provider !== this.id) throw new AdportError('INVALID_INPUT', 'spotify: provider mismatch');\n if (measurementWriteNames.has(op.tool)) return this.measurement.plan(op);\n if (op.tool === 'spotify_create_campaign_draft' && op.kind === 'create') {\n const input = createDraftSchema.parse(op.payload);\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const body = { ...input, status };\n return {\n summary: `Create Spotify campaign draft \"${input.name}\" (not published)`, changes: [`+ ${JSON.stringify(body)}`],\n coercions: input.status !== status ? ['status coerced to PAUSED by policy (paused_creation)'] : [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.mutate(`${base}/drafts/campaigns`, 'POST', body, draftSchema);\n if (result.ad_account_id !== accountId || result.status !== status) throw new AdportError('PROVIDER_ERROR', 'spotify: created draft response violated account/status expectations; inspect the draft before retrying');\n return [result.id];\n },\n };\n }\n if (op.tool === 'spotify_set_campaign_status' && op.kind === 'update') {\n const input = setStatusSchema.parse(op.payload);\n const path = `${base}/campaigns/${input.campaign_id}`;\n const current = await this.client.get(path, campaignSchema);\n if (current.id !== input.campaign_id) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign response ID mismatch');\n return {\n summary: `Change Spotify campaign \"${current.name}\" status`, changes: [`~ ${current.id} status: ${current.status} → ${input.status}`], coercions: [], budgetDeltas: [],\n execute: async () => {\n const result = await this.client.mutate(path, 'PATCH', { status: input.status }, campaignSchema);\n if (result.id !== current.id || result.status !== input.status) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign update response mismatch; inspect before retrying');\n return [result.id];\n },\n };\n }\n if (op.kind === 'update' && ['spotify_set_budget', 'spotify_set_ad_set_delivery'].includes(op.tool)) {\n const input = op.tool === 'spotify_set_budget' ? setBudgetSchema.parse(op.payload) : setDeliverySchema.parse(op.payload);\n const current = await this.getAdSet(accountId, input.ad_set_id);\n const budget = 'budget_micros' in input ? { micro_amount: input.budget_micros, type: current.budget.type } : undefined;\n // Delivery must be the sole field in an ad-set PATCH. Budget changes keep\n // the existing budget type so DAILY/LIFETIME deltas stay comparable.\n const body = budget ? { budget } : { delivery: 'delivery' in input ? input.delivery : current.delivery };\n return {\n summary: `Change Spotify ad set \"${current.name}\" ${budget ? 'budget' : 'delivery'}`,\n changes: [budget ? `~ ${current.id} ${budget.type} budget micros: ${current.budget.micro_amount} → ${budget.micro_amount}` : `~ ${current.id} delivery: ${current.delivery} → ${body.delivery}`],\n coercions: [], budgetDeltas: budget ? [{ target: `ad set ${current.id} ${budget.type} budget`, fromMicros: current.budget.micro_amount, toMicros: budget.micro_amount }] : [],\n execute: async () => {\n const result = await this.client.mutate(`${base}/ad_sets/${current.id}`, 'PATCH', body, adSetSchema);\n if (result.id !== current.id || result.campaign_id !== current.campaign_id\n || (budget && (result.budget.type !== budget.type || result.budget.micro_amount !== budget.micro_amount))\n || (!budget && result.delivery !== body.delivery)) {\n throw new AdportError('PROVIDER_ERROR', 'spotify: ad set update response mismatch; inspect before retrying');\n }\n return [result.id];\n },\n };\n }\n return managementWriteNames.has(op.tool) ? this.management.plan(op) : this.creatives.plan(op, guard);\n }\n}\n\nfunction normalize(stats: Array<{ field_type: string; field_value: number }>, requested: MetricName[]) {\n const raw = new Map<string, number>();\n for (const stat of stats) {\n if (raw.has(stat.field_type)) throw new AdportError('PROVIDER_ERROR', 'spotify: duplicate report metric');\n raw.set(stat.field_type, stat.field_value);\n }\n const mapped: Partial<Record<MetricName, number>> = {};\n for (const [metric, field] of Object.entries(FIELDS)) {\n const value = raw.get(field);\n // Suppressed conversion counts (-5) and missing metrics are not zero.\n if (value !== undefined && value >= 0) mapped[metric as MetricName] = value;\n }\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) {\n if (mapped[numerator] !== undefined && mapped[denominator] !== undefined) mapped[metric as MetricName] = mapped[denominator] ? mapped[numerator]! / mapped[denominator]! * factor : 0;\n }\n return Object.fromEntries(requested.filter(metric => mapped[metric] !== undefined).map(metric => [metric, mapped[metric]]));\n}\n","import { AdportError, type Creative, type MediaResolver, type MediaSource, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport { assetResponse, createAd, createAsset, createGroup, draftMutation, draftResponse, publishDraft, updateAd, updateCampaign, updateGroup, uploadAsset } from './creative-schemas.js';\nimport { budgetSchema, spotifyId } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Entity = 'campaigns' | 'ad_sets' | 'ads';\ninterface Page { account_id: string; limit: number; offset: number }\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst object = z.record(z.string(), z.unknown());\nconst paging = z.looseObject({ offset: z.number().int().nonnegative(), total_results: z.number().int().nonnegative() });\nconst keys = { campaigns: 'campaign_drafts', ad_sets: 'ad_set_drafts', ads: 'ad_drafts' } as const;\n\n/** Spotify's live v3 OpenAPI is the wire authority, including native draft versions. */\nexport class SpotifyCreativeService {\n constructor(private readonly client: SpotifyAdsClient, private readonly media: MediaResolver) {}\n private base(account: string) { return `ad_accounts/${spotifyId.parse(account)}`; }\n\n async page(input: Page, path: string, key: string, params: Row = {}): Promise<Row & { truncated: boolean; next_offset?: number }> {\n const data = await this.client.get(`${this.base(input.account_id)}/${path}`, z.looseObject({ paging }), query({ limit: input.limit, offset: input.offset, ...params }));\n if (data.paging.offset !== input.offset) throw new AdportError('PROVIDER_ERROR', 'spotify: pagination offset mismatch');\n const rows = z.array(draftResponse).parse(data[key]);\n for (const row of rows) this.checkAccount(input.account_id, row);\n const next = input.offset + rows.length, truncated = next < data.paging.total_results;\n if (truncated && !rows.length) throw new AdportError('PROVIDER_ERROR', 'spotify: pagination stalled');\n return { ...data, truncated, ...(truncated ? { next_offset: next } : {}) };\n }\n\n async drafts(input: Page & { entity: Entity; campaign_ids?: string[]; ad_set_ids?: string[] }) {\n return this.page(input, `drafts/${input.entity}`, keys[input.entity], { campaign_ids: input.campaign_ids, ad_set_ids: input.ad_set_ids });\n }\n\n async get(account: string, entity: Entity, id: string, draft = true) {\n const row = await this.getOwned(account, entity, id, draft);\n if (entity === 'ad_sets') await this.get(account, 'campaigns', spotifyId.parse(row.campaign_id), draft);\n else if (entity === 'ads') await this.get(account, 'ad_sets', spotifyId.parse(row.ad_set_id), draft);\n return row;\n }\n\n private async getOwned(account: string, entity: Entity, id: string, draft = true) {\n const row = await this.client.get(`${this.base(account)}/${draft ? 'drafts/' : ''}${entity}/${spotifyId.parse(id)}`, draftResponse);\n if (row.id !== id) throw new AdportError('PROVIDER_ERROR', 'spotify: response ID mismatch');\n this.checkAccount(account, row);\n if (entity === 'campaigns') {\n if (draft && row.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'spotify: campaign account mismatch');\n if (!draft && row.ad_account_id == null) await this.verifyPublishedCampaign(account, id);\n }\n return row;\n }\n\n private checkAccount(account: string, row: Row) {\n if (row.ad_account_id != null && row.ad_account_id !== account) throw new AdportError('PROVIDER_ERROR', 'spotify: resource belongs to another account');\n }\n\n private async verifyPublishedCampaign(account: string, id: string) {\n // Live campaign GET/list responses can have ad_account_id:null. Prove\n // membership in the selected account's paged collection instead.\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.page({ account_id: account, limit: 50, offset }, 'campaigns', 'campaigns', { sort_field: 'ID', sort_direction: 'ASC' });\n if ((data.campaigns as Row[]).some(campaign => campaign.id === id)) return;\n if (!data.truncated) break;\n offset = data.next_offset!;\n }\n throw new AdportError('INVALID_INPUT', 'spotify: campaign is not present in the selected account’s published campaign list');\n }\n\n async assets(input: Page & { asset_types?: string[]; asset_statuses?: string[]; name?: string }) {\n const data = await this.client.get(`${this.base(input.account_id)}/assets`, z.looseObject({ paging, assets: z.array(assetResponse) }), query({ limit: input.limit, offset: input.offset, asset_types: input.asset_types, asset_statuses: input.asset_statuses, name: input.name }));\n if (data.paging.offset !== input.offset) throw new AdportError('PROVIDER_ERROR', 'spotify: asset pagination offset mismatch');\n for (const asset of data.assets) this.checkAccount(input.account_id, asset);\n const next = input.offset + data.assets.length, truncated = next < data.paging.total_results;\n if (truncated && !data.assets.length) throw new AdportError('PROVIDER_ERROR', 'spotify: asset pagination stalled');\n const creatives: Creative[] = data.assets.map(asset => ({ id: asset.id, provider: 'spotify', account_id: input.account_id, name: asset.name, type: asset.asset_type, status: asset.status, headlines: [], descriptions: [], landing_urls: [], media: mediaFor(asset), actions: [] }));\n return { ...data, creatives, truncated, ...(truncated ? { next_offset: next } : {}) };\n }\n\n async asset(account: string, id: string) {\n const asset = await this.client.get(`${this.base(account)}/assets/${spotifyId.parse(id)}`, assetResponse);\n if (asset.id !== id) throw new AdportError('PROVIDER_ERROR', 'spotify: asset response ID mismatch');\n this.checkAccount(account, asset);\n return asset;\n }\n\n async ads(input: Page & { draft: boolean; ad_set_ids?: string[] }) {\n const data = await this.page(input, `${input.draft ? 'drafts/' : ''}ads`, input.draft ? 'ad_drafts' : 'ads', { ad_set_ids: input.ad_set_ids });\n const rows = data[input.draft ? 'ad_drafts' : 'ads'] as Row[];\n const cache = new Map<string, Awaited<ReturnType<typeof this.asset>>>();\n const creatives: Creative[] = [];\n for (const ad of rows) {\n const assets = record(ad.assets), media: Creative['media'] = [];\n for (const id of new Set(Object.values(assets).filter((value): value is string => typeof value === 'string' && spotifyId.safeParse(value).success))) {\n if (!cache.has(id)) cache.set(id, await this.asset(input.account_id, id));\n media.push(...mediaFor(cache.get(id)!));\n }\n const args = { account_id: input.account_id, draft_id: ad.id };\n creatives.push({ id: String(ad.id), provider: 'spotify', account_id: input.account_id, name: String(ad.name ?? ad.id), type: input.draft ? 'DRAFT_AD' : 'AD', ...(typeof ad.status === 'string' ? { status: ad.status } : {}), ...(typeof ad.ad_set_id === 'string' ? { ad_group_id: ad.ad_set_id } : {}),\n headlines: typeof ad.advertiser_name === 'string' ? [ad.advertiser_name] : [], descriptions: typeof ad.tagline === 'string' ? [ad.tagline] : [], landing_urls: safeUrl(record(ad.call_to_action).clickthrough_url), media,\n actions: input.draft ? [{ label: 'Edit draft copy', tool: 'spotify_update_draft_ad', arguments: args, fields: [{ key: 'name', label: 'Ad name', type: 'text', value: String(ad.name ?? ''), max_length: 200 }, ...(typeof ad.tagline === 'string' ? [{ key: 'tagline', label: 'Tagline', type: 'text' as const, value: ad.tagline, max_length: 200 }] : [])] }] : [{ label: 'Stage a draft for editing', tool: 'spotify_create_draft_from_published', arguments: { account_id: input.account_id, entity: 'ads', draft_id: ad.id }, fields: [] }],\n });\n }\n return { ...data, creatives };\n }\n\n async read(account: string, path: string, params: Row = {}) { return this.client.get(`${this.base(account)}/${path}`, object, query(params)); }\n async targeting(input: { account_id: string; kind: string } & Row) {\n const { account_id, kind, ...params } = input;\n return this.client.get(`targets/${kind}`, object, query({ ...params, ...(kind === 'languages' ? { ad_account_id: account_id } : {}) }));\n }\n async categories(q?: string) { return this.client.get('ad_categories', object, query({ q })); }\n async estimate(kind: 'audience' | 'bid', input: { account_id: string } & Row) {\n const { account_id, ...body } = input;\n return this.client.mutate(`estimates/${kind}`, 'POST', { ...body, ...(kind === 'audience' ? { ad_account_id: account_id } : {}) }, object);\n }\n async validate(account: string, id: string, version: number) {\n const campaign = await this.get(account, 'campaigns', id);\n this.version(campaign, version);\n return this.client.mutate(`${this.base(account)}/drafts/campaigns/${id}`, 'POST', { action: 'VALIDATE', draft_hierarchy_version: version }, object);\n }\n private version(campaign: Row, version: number) {\n if (campaign.draft_hierarchy_version !== version) throw new AdportError('PENDING_MISMATCH', 'spotify: draft hierarchy changed. Read its current version and prepare a new preview.');\n }\n private async allDrafts(account: string, entity: Entity, campaign: string) {\n const rows: Row[] = [], seen = new Set<string>();\n for (let page = 0, offset = 0; page < 1000; page++) {\n const data = await this.drafts({ account_id: account, entity, campaign_ids: [campaign], limit: 50, offset });\n const nextRows = data[keys[entity]] as Row[];\n for (const row of nextRows) { if (seen.has(String(row.id))) throw new AdportError('PROVIDER_ERROR', 'spotify: repeated draft resource'); seen.add(String(row.id)); rows.push(row); }\n if (!data.truncated) return rows;\n offset = data.next_offset!;\n }\n throw new AdportError('PROVIDER_ERROR', 'spotify: draft hierarchy pagination did not terminate');\n }\n\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const base = this.base(op.accountId), coercions: string[] = [], budgetDeltas: WritePreview['budgetDeltas'] = [];\n let path: string, body: Row, method: 'POST' | 'PATCH' = 'PATCH', expectedId: string | undefined;\n const payload = op.payload;\n switch (op.tool) {\n case 'spotify_create_draft_ad_set': {\n const input = createGroup.parse(payload);\n await this.get(op.accountId, 'campaigns', input.campaign_id);\n body = input; path = `${base}/drafts/ad_sets`; method = 'POST';\n checkGroup(body);\n monetaryDeltas(body, {}, `draft ad set ${input.name}`, budgetDeltas);\n break;\n }\n case 'spotify_create_draft_ad': {\n const input = createAd.parse(payload);\n await this.get(op.accountId, 'ad_sets', input.ad_set_id);\n await this.verifyAssets(op.accountId, input.assets);\n body = input; path = `${base}/drafts/ads`; method = 'POST'; break;\n }\n case 'spotify_update_draft_campaign':\n case 'spotify_update_draft_ad_set':\n case 'spotify_update_draft_ad': {\n const entity = op.tool === 'spotify_update_draft_campaign' ? 'campaigns' : op.tool === 'spotify_update_draft_ad_set' ? 'ad_sets' : 'ads';\n const input = (entity === 'campaigns' ? updateCampaign : entity === 'ad_sets' ? updateGroup : updateAd).parse(payload);\n const { draft_id, ...fields } = input;\n const current = await this.get(op.accountId, entity, draft_id);\n body = { ...fields }; expectedId = draft_id;\n if (body.targets !== undefined) body.targets = { ...record(current.targets), ...record(body.targets) };\n for (const key of ['assets', 'call_to_action']) if (body[key] !== undefined) {\n const writable = key === 'assets' ? ['asset_id', 'logo_asset_id', 'companion_asset_id', 'canvas_asset_id'] : ['key', 'language', 'clickthrough_url'];\n body[key] = { ...Object.fromEntries(Object.entries(record(current[key])).filter(([field, value]) => writable.includes(field) && value !== null)), ...record(body[key]) };\n }\n if (entity === 'ad_sets') { checkGroup({ ...current, ...body }); monetaryDeltas(body, current, `draft ad set ${draft_id}`, budgetDeltas); }\n if (entity === 'ads') await this.verifyAssets(op.accountId, body.assets);\n path = `${base}/drafts/${entity}/${draft_id}`; break;\n }\n case 'spotify_create_draft_from_published': {\n const input = draftMutation.parse(payload);\n await this.get(op.accountId, input.entity, input.draft_id, false);\n try {\n await this.get(op.accountId, input.entity, input.draft_id);\n throw new AdportError('INVALID_INPUT', 'spotify: a draft already exists. Read and edit it instead of overwriting pending changes.');\n } catch (error) { if (!isNotFound(error)) throw error; }\n path = `${base}/${input.entity}/${input.draft_id}/drafts`; method = 'POST'; expectedId = input.draft_id; body = {}; break;\n }\n case 'spotify_delete_draft': {\n const input = draftMutation.parse(payload);\n // Spotify can retain orphan ad drafts after deleting a parent campaign.\n // The account-scoped resource read still proves ownership for cleanup.\n const current = await this.getOwned(op.accountId, input.entity, input.draft_id);\n if (input.entity === 'campaigns') {\n const groups = await this.allDrafts(op.accountId, 'ad_sets', input.draft_id);\n for (const group of groups) await this.ensureNoAdDrafts(op.accountId, String(group.id));\n } else if (input.entity === 'ad_sets') await this.ensureNoAdDrafts(op.accountId, input.draft_id);\n return { summary: `Delete Spotify draft ${input.entity}/${input.draft_id}`, changes: [`- ${current.name ?? current.id}; draft children may also be deleted. Published entities remain unchanged.`], coercions, budgetDeltas, execute: async () => { await this.client.mutate(`${base}/drafts/${input.entity}/${input.draft_id}`, 'DELETE', undefined, z.undefined()); return [input.draft_id]; } };\n }\n case 'spotify_delete_draft_ads':\n case 'spotify_delete_draft_ad_sets': {\n const ads = op.tool === 'spotify_delete_draft_ads', entity = ads ? 'ads' : 'ad_sets';\n const input = z.object({ draft_ids: z.array(spotifyId).min(1).max(ads ? 100 : 40).refine(ids => new Set(ids).size === ids.length, 'IDs must be unique') }).parse(payload);\n for (const id of input.draft_ids) { await this.getOwned(op.accountId, entity, id); if (!ads) await this.ensureNoAdDrafts(op.accountId, id); }\n return { summary: `Delete ${input.draft_ids.length} Spotify ${entity} drafts`, changes: input.draft_ids.map(id => `- draft ${id}${ads ? '' : ' and child ad drafts'}; published entities remain unchanged`), coercions, budgetDeltas, execute: async () => { await this.client.mutate(`${base}/drafts/${entity}`, 'DELETE', undefined, z.undefined(), query({ [ads ? 'ad_draft_ids' : 'ad_set_draft_ids']: input.draft_ids })); return input.draft_ids; } };\n }\n case 'spotify_publish_draft': return this.publish(op, guard);\n case 'spotify_create_asset': {\n const input = createAsset.parse(payload);\n return { summary: `Create Spotify ${input.asset_type} asset metadata`, changes: [`+ ${JSON.stringify(input)}; file upload is a separate approved operation`], coercions, budgetDeltas, execute: async () => { const asset = await this.client.mutate(`${base}/assets`, 'POST', input, assetResponse); this.checkAccount(op.accountId, asset); if (asset.asset_type !== input.asset_type) throw new AdportError('PROVIDER_ERROR', 'spotify: created asset type mismatch; inspect before retrying'); return [asset.id]; } };\n }\n case 'spotify_rename_asset': {\n const input = z.object({ asset_id: spotifyId, name: z.string().trim().min(2).max(120) }).parse(payload);\n const current = await this.asset(op.accountId, input.asset_id);\n return { summary: 'Rename Spotify asset', changes: [`~ ${current.id} name: ${current.name} → ${input.name}`], coercions, budgetDeltas, execute: async () => { const result = await this.client.mutate(`${base}/assets/${current.id}`, 'PATCH', { asset_type: current.asset_type, name: input.name }, assetResponse); if (result.id !== current.id || result.name !== input.name) throw new AdportError('PROVIDER_ERROR', 'spotify: asset update response mismatch'); return [current.id]; } };\n }\n case 'spotify_upload_asset': return this.upload(op);\n default: throw new AdportError('INVALID_INPUT', `spotify: unsupported write ${op.tool}`);\n }\n const parent = body.campaign_id ?? body.ad_set_id;\n return { summary: `Spotify ${op.tool.replace(/^spotify_/, '').replaceAll('_', ' ')}`, changes: [`${method} /${path} ${JSON.stringify(body)}`], coercions, budgetDeltas, execute: async () => {\n const result = await this.client.mutate(path, method, op.tool === 'spotify_create_draft_from_published' ? undefined : body, draftResponse);\n this.checkAccount(op.accountId, result);\n if ((expectedId && result.id !== expectedId) || (parent && parent !== (result.campaign_id ?? result.ad_set_id))) throw new AdportError('PROVIDER_ERROR', 'spotify: draft mutation response mismatch; inspect before retrying');\n return [result.id];\n } };\n }\n\n private async verifyAssets(account: string, assets: unknown) {\n for (const value of Object.values(record(assets))) await this.asset(account, spotifyId.parse(value));\n }\n\n private async ensureNoAdDrafts(account: string, group: string) {\n const data = await this.drafts({ account_id: account, entity: 'ads', ad_set_ids: [group], limit: 1, offset: 0 });\n if ((data.ad_drafts as Row[]).length || data.truncated) throw new AdportError('INVALID_INPUT', 'spotify: delete draft ads before deleting their parent. Spotify can otherwise leave undeletable orphan ad drafts.');\n }\n\n private async publish(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n if (guard.forcePausedCreation) throw new AdportError('POLICY_VIOLATION', 'spotify: publication is blocked by paused_creation. The live PUBLISH endpoint activates even a PAUSED draft; Spotify cannot guarantee paused publication. Keep this hierarchy as a draft.');\n const input = publishDraft.parse(op.payload), account = op.accountId;\n if (!input.acknowledge_active_publication) throw new AdportError('INVALID_INPUT', 'spotify: publishing activates the campaign. Explicit acknowledge_active_publication=true is required.');\n const campaign = await this.get(account, 'campaigns', input.draft_campaign_id);\n this.version(campaign, input.draft_hierarchy_version);\n const groups = await this.allDrafts(account, 'ad_sets', campaign.id);\n const budgetDeltas: WritePreview['budgetDeltas'] = [];\n for (const group of groups) {\n if (group.campaign_id !== campaign.id) throw new AdportError('PROVIDER_ERROR', 'spotify: draft ad set belongs to another campaign');\n let current: Row = {};\n try { current = await this.get(account, 'ad_sets', String(group.id), false); } catch (error) { if (!isNotFound(error)) throw error; }\n monetaryDeltas(group, current, `publish ad set ${group.id}`, budgetDeltas);\n }\n return { summary: `Publish Spotify campaign ${campaign.name ?? campaign.id} as ACTIVE`, changes: [`PUBLISH hierarchy version ${input.draft_hierarchy_version}; ${groups.length} draft ad sets. Spotify changes campaign status ${campaign.status} → ACTIVE, regardless of the draft's paused state.`], coercions: [], budgetDeltas, execute: async () => {\n const validation = await this.validate(account, campaign.id, input.draft_hierarchy_version);\n assertValidation(validation);\n const result = await this.client.mutate(`${this.base(account)}/drafts/campaigns/${campaign.id}`, 'POST', { action: 'PUBLISH', draft_hierarchy_version: input.draft_hierarchy_version }, object);\n assertValidation(result);\n const published = record(result.campaign);\n if (published.id !== campaign.id || (published.ad_account_id != null && published.ad_account_id !== account) || published.status !== 'ACTIVE') throw new AdportError('PROVIDER_ERROR', 'spotify: publish receipt does not confirm the expected campaign/account/status. Inspect before retrying.', { resource_ids: spotifyId.safeParse(published.id).success ? [published.id] : [], observed_status: published.status });\n if (published.ad_account_id == null) await this.verifyPublishedCampaign(account, campaign.id);\n return [campaign.id];\n } };\n }\n\n private async upload(op: WriteOperation): Promise<Plan> {\n const input = uploadAsset.parse(op.payload), current = await this.asset(op.accountId, input.asset_id);\n if (current.status !== 'WAITING_UPLOAD') throw new AdportError('INVALID_INPUT', 'spotify: upload only to a new WAITING_UPLOAD asset. Create a separate asset instead of replacing media used by ads.');\n const types = { IMAGE: ['image/png', 'image/jpeg'], AUDIO: ['audio/mpeg', 'audio/wav', 'audio/ogg'], VIDEO: ['video/mp4', 'video/quicktime'] };\n const file = await this.media.read(input as MediaSource, { maxBytes: 100 * 1024 * 1024, contentTypes: types[current.asset_type] });\n const path = `${this.base(op.accountId)}/assets/${current.id}`;\n return { summary: `Upload Spotify ${current.asset_type} asset ${current.name}`, changes: [`+ ${file.name}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}; existing ads are unchanged`], coercions: [], budgetDeltas: [], execute: async () => {\n let result: z.infer<typeof assetResponse>;\n if (file.bytes.byteLength <= 20_000_000) {\n result = await this.client.upload(`${path}/upload`, form(file.bytes, file.name, file.contentType, { asset_type: current.asset_type }), assetResponse);\n } else {\n const session = await this.client.mutate(`${path}/chunked_upload/start`, 'POST', undefined, z.object({ upload_session_id: spotifyId, max_chunk_size_mb: z.number().int().positive().max(100) }));\n const size = session.max_chunk_size_mb * 1_000_000, sections = Math.ceil(file.bytes.byteLength / size);\n if (sections > 1000) throw new AdportError('PROVIDER_ERROR', 'spotify: upload requires too many chunks');\n for (let index = 0; index < sections; index++) {\n const reply = await this.client.upload(`${path}/chunked_upload/transfer`, form(file.bytes.slice(index * size, (index + 1) * size), file.name, file.contentType, { asset_type: current.asset_type, upload_session_id: session.upload_session_id, upload_section: String(index + 1) }), z.object({ success: z.boolean() }));\n if (!reply.success) throw new AdportError('PROVIDER_ERROR', `spotify: upload section ${index + 1} failed. Inspect the asset before retrying.`);\n }\n result = await this.client.mutate(`${path}/chunked_upload/complete`, 'POST', { asset_type: current.asset_type, upload_session_id: session.upload_session_id, number_of_sections: sections }, assetResponse);\n }\n if (result.id !== current.id || result.asset_type !== current.asset_type || result.status === 'ERROR') throw new AdportError('PROVIDER_ERROR', 'spotify: uploaded asset response mismatch/error; inspect before retrying');\n return [current.id];\n } };\n }\n}\n\nfunction record(value: unknown): Row { return value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Row : {}; }\nfunction query(input: Row) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(input)) if (value !== undefined) { if (Array.isArray(value)) for (const item of value) params.append(key, String(item)); else params.set(key, String(value)); } return params; }\nfunction safeUrl(value: unknown): string[] { if (typeof value !== 'string') return []; try { const url = new URL(value); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password ? [value] : []; } catch { return []; } }\nfunction mediaFor(asset: z.infer<typeof assetResponse>): Creative['media'] { return safeUrl(asset.url).filter(url => url.startsWith('https:')).map(url => ({ type: asset.asset_type === 'IMAGE' ? 'image' : asset.asset_type === 'VIDEO' ? 'video' : 'audio', url })); }\nfunction isNotFound(error: unknown) { return error instanceof AdportError && record(error.details).http_status === 404; }\nfunction form(bytes: Uint8Array<ArrayBuffer>, name: string, type: string, fields: Record<string, string>) { const data = new FormData(); for (const [key, value] of Object.entries(fields)) data.set(key, value); data.set('media', new Blob([bytes], { type }), name); return data; }\nfunction checkGroup(row: Row) {\n const target = record(row.targets), budget = record(row.budget);\n if (row.targets !== undefined && (!Array.isArray(target.placements) || !target.placements.length)) throw new AdportError('INVALID_INPUT', 'spotify: supplied targeting must include placements');\n if (budget.type === 'LIFETIME' && !row.end_time) throw new AdportError('INVALID_INPUT', 'spotify: lifetime budget requires end_time');\n if (row.start_time && row.end_time && String(row.end_time) <= String(row.start_time)) throw new AdportError('INVALID_INPUT', 'spotify: end_time must be after start_time');\n}\nfunction monetaryDeltas(next: Row, current: Row, target: string, deltas: WritePreview['budgetDeltas']) {\n if (next.budget !== undefined) {\n const budget = budgetSchema.parse(next.budget), old = current.budget === undefined ? undefined : budgetSchema.parse(current.budget);\n if (old && old.type !== budget.type) throw new AdportError('INVALID_INPUT', 'spotify: budget type changes require a separate ad set');\n deltas.push({ target: `${target} ${budget.type} budget`, ...(old ? { fromMicros: old.micro_amount } : {}), toMicros: budget.micro_amount });\n }\n if (next.bid_micro_amount !== undefined) {\n const amount = z.number().int().nonnegative().safe().parse(next.bid_micro_amount);\n const old = current.bid_micro_amount === undefined ? undefined : z.number().int().nonnegative().safe().parse(current.bid_micro_amount);\n deltas.push({ target: `${target} bid`, ...(old !== undefined ? { fromMicros: old } : {}), toMicros: amount });\n }\n}\nfunction assertValidation(result: Row) {\n if (result.validation_errors !== undefined && result.validation_errors !== null && !Array.isArray(result.validation_errors)) throw new AdportError('PROVIDER_ERROR', 'spotify: malformed draft validation result');\n if (Array.isArray(result.validation_errors) && result.validation_errors.length) throw new AdportError('PROVIDER_ERROR', 'spotify: draft hierarchy failed validation; nothing was published', { validation_errors: result.validation_errors });\n}\n","import { mediaSourceFields } from '@adport/core';\nimport { z } from 'zod';\nimport { budgetSchema, spotifyId } from './schemas.js';\n\nconst strings = z.array(z.string().min(1)).max(1000);\nconst money = z.number().int().nonnegative().safe();\nconst url = z.string().url().refine(value => { const u = new URL(value); return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) destination without embedded credentials');\nexport const assetType = z.enum(['AUDIO', 'IMAGE', 'VIDEO']);\nexport const assetFormat = z.enum(['AUDIO', 'IMAGE', 'VIDEO', 'MULTI', 'CATALOG']);\nconst adLanguage = z.enum(['ARABIC', 'ARABIC_EGYPT', 'BULGARIAN', 'CHINESE', 'CHINESE_HK', 'CHINESE_TAIWAN', 'CROATIAN', 'CZECH', 'DANISH', 'DUTCH', 'ENGLISH', 'FINNISH', 'FRENCH', 'FRENCH_CANADA', 'GERMAN', 'GREEK', 'HEBREW', 'HUNGARIAN', 'INDONESIAN', 'ITALIAN', 'JAPANESE', 'KOREAN', 'NORWEGIAN', 'POLISH', 'PORTUGUESE', 'PORTUGUESE_PORTUGAL', 'ROMANIAN', 'RUSSIAN', 'SLOVAK', 'SPANISH', 'SPANISH_ARGENTINA', 'SPANISH_LATAM_CARIBBEAN', 'SPANISH_MEXICO', 'SWEDISH', 'THAI', 'TURKISH', 'UKRAINIAN', 'VIETNAMESE']);\nexport const deliveryGoal = z.enum(['UNSET', 'IMPRESSIONS', 'REACH', 'VIDEO_VIEWS', 'CLICKS', 'PAGE_VIEWS', 'APP_INSTALLS', 'STREAMS', 'LEADS']);\nexport const bidStrategy = z.enum(['COST_PER_RESULT', 'MAX_BID', 'AUTOBID', 'UNSET']);\nexport const frequencyCaps = z.array(z.object({ frequency_unit: z.enum(['DAY', 'WEEK', 'MONTH']), frequency_period: z.number().int().positive(), max_impressions: z.number().int().positive() }).strict()).max(6);\nexport const targets = z.object({\n age_ranges: z.array(z.object({ min: z.number().int().min(13).max(99), max: z.number().int().min(13).max(99) }).refine(v => v.max >= v.min)).optional(),\n artist_ids: strings.optional(), genre_ids: strings.optional(), interest_ids: z.array(spotifyId).optional(),\n geo_targets: z.object({ country_code: z.string().regex(/^[A-Z]{2}$/).optional(), city_ids: strings.optional(), postal_code_ids: strings.optional(), region_ids: strings.optional() }).strict().optional(),\n genders: z.array(z.enum(['MALE', 'FEMALE', 'NON_BINARY'])).optional(), platforms: z.array(z.enum(['ANDROID', 'DESKTOP', 'IOS'])).optional(),\n podcast_episode_topic_ids: strings.optional(), language: z.string().regex(/^[a-z]{2}$/).optional(), playlist_ids: strings.optional(),\n placements: z.array(z.enum(['MUSIC', 'PODCAST', 'PODCAST_SAI', 'PODCAST_DAI'])).min(1).optional(),\n audience_ids: z.array(spotifyId).optional(), audience_ids_exclusions: z.array(spotifyId).optional(),\n sensitive_topic_exclusions: z.object({ topics: z.array(z.object({ id: z.string().min(1), filter_option: z.enum(['STANDARD', 'LIMITED', 'PARTIAL', 'RESTRICTED']) }).strict()).optional(), filter_option: z.enum(['STANDARD', 'LIMITED', 'PARTIAL', 'RESTRICTED']).optional() }).strict().refine(v => Boolean(v.topics) !== Boolean(v.filter_option), 'Choose topics or a global filter').optional(),\n user_day_parts: z.array(z.object({ day_of_week: z.array(z.enum(['SUNDAY', 'MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY'])), hour_of_day: z.array(z.object({ min: z.number().int().min(0).max(23), max: z.number().int().min(0).max(23) }).refine(v => v.max >= v.min)) }).strict()).optional(),\n}).strict();\nexport const campaignPatch = z.object({ name: z.string().trim().min(2).max(200).optional(), purchase_order: z.string().min(2).max(45).optional(), delivery_goal_group: z.enum(['AWARENESS', 'WEBSITE_TRAFFIC', 'APP_PROMOTION', 'ENGAGEMENT_ON_SPOTIFY', 'LEAD_GEN', 'VIDEO_VIEWS']).optional(), status: z.enum(['PAUSED', 'ACTIVE', 'ARCHIVED']).optional() }).strict();\nexport const groupPatch = z.object({\n name: z.string().trim().min(2).max(200).optional(), start_time: z.iso.datetime().optional(), end_time: z.iso.datetime().optional(),\n budget: budgetSchema.optional(), bid_micro_amount: money.optional(), bid_strategy: bidStrategy.optional(), targets: targets.optional(),\n category: z.string().regex(/^ADV_\\d+_\\d+$/).optional(), asset_format: assetFormat.optional(), delivery_goal: deliveryGoal.optional(),\n pacing: z.enum(['PACING_ASAP', 'PACING_EVEN']).optional(), frequency_caps: frequencyCaps.optional(), dataset_id: spotifyId.optional(), mobile_app_id: spotifyId.optional(),\n}).strict();\nexport const adPatch = z.object({\n name: z.string().trim().min(2).max(200).optional(), advertiser_name: z.string().min(1).max(200).optional(), tagline: z.string().min(1).max(200).optional(),\n assets: z.object({ asset_id: spotifyId.optional(), logo_asset_id: spotifyId.optional(), companion_asset_id: spotifyId.optional(), canvas_asset_id: spotifyId.optional() }).strict().optional(),\n asset_format: assetFormat.optional(), call_to_action: z.object({ key: z.enum(['APPLY_NOW', 'BOOK_NOW', 'BUY_NOW', 'BUY_TICKETS', 'CLICK_NOW', 'DOWNLOAD', 'FIND_STORES', 'GET_COUPON', 'GET_INFO', 'INSTALL_NOW', 'LEARN_MORE', 'LISTEN_NOW', 'MORE_INFO', 'ORDER_NOW', 'PRE_SAVE', 'SAVE_NOW', 'SHARE', 'SHOP_NOW', 'SIGN_UP', 'VISIT_PROFILE', 'VISIT_SITE', 'WATCH_NOW']).optional(), language: adLanguage.optional(), clickthrough_url: url.optional() }).strict().optional(),\n third_party_tracking: z.array(z.object({ measurement_partner: z.enum(['IAS', 'DCM', 'UNSET']), url }).strict()).max(11).optional(),\n weight: z.number().int().min(1).max(100).optional(),\n}).strict();\nexport const createGroup = groupPatch.extend({ campaign_id: spotifyId, name: z.string().trim().min(2).max(200) });\nexport const createAd = adPatch.extend({ ad_set_id: spotifyId, name: z.string().trim().min(2).max(200) });\nexport const draftEntity = z.enum(['campaigns', 'ad_sets', 'ads']);\nexport const draftMutation = z.object({ entity: draftEntity, draft_id: spotifyId });\nexport const updateCampaign = campaignPatch.extend({ draft_id: spotifyId }).refine(v => Object.keys(v).length > 1, 'Provide a change');\nexport const updateGroup = groupPatch.extend({ draft_id: spotifyId }).refine(v => Object.keys(v).length > 1, 'Provide a change');\nexport const updateAd = adPatch.extend({ draft_id: spotifyId }).refine(v => Object.keys(v).length > 1, 'Provide a change');\nexport const publishDraft = z.object({ draft_campaign_id: spotifyId, draft_hierarchy_version: z.number().int().positive(), acknowledge_active_publication: z.literal(true).optional().describe('Required for publication when policy permits active creation. Spotify publishes ACTIVE even when the draft is PAUSED.') });\nexport const createAsset = z.object({ name: z.string().trim().min(2).max(120), asset_type: assetType, asset_subtype: z.enum(['BACKGROUND_MUSIC', 'USER_UPLOADED_AUDIO']).optional() }).refine(v => !v.asset_subtype || v.asset_type === 'AUDIO', 'Asset subtype is audio-only');\nexport const uploadAsset = z.object({ asset_id: spotifyId, ...mediaSourceFields }).refine(v => Number(Boolean(v.media_id)) + Number(Boolean(v.file_path)) === 1, 'Choose media_id or file_path');\nexport const assetResponse = z.looseObject({ id: spotifyId, name: z.string(), asset_type: assetType, status: z.string(), url: z.string().optional() });\nexport const draftResponse = z.looseObject({ id: spotifyId, name: z.string().nullable().optional(), ad_account_id: spotifyId.nullable().optional(), campaign_id: spotifyId.optional(), ad_set_id: spotifyId.optional(), status: z.string().nullable().optional(), draft_hierarchy_version: z.number().int().positive().nullable().optional() });\n","import { z } from 'zod';\n\n// Spotify Ads v3 reference contracts, reviewed 2026-08-31.\n// Response objects remain forward-compatible; fields consumed for policy and\n// reporting are validated instead of interpreting malformed data as empty data.\nexport const spotifyId = z.uuid();\nexport const businessSchema = z.looseObject({ id: spotifyId, name: z.string() });\nexport const accountSchema = z.looseObject({\n id: spotifyId, name: z.string(), currency_code: z.string(), status: z.string(),\n business_id: spotifyId.optional(), test_account_type: z.string().optional(),\n});\nexport const campaignSchema = z.looseObject({ id: spotifyId, name: z.string(), status: z.string() });\nexport const draftSchema = campaignSchema.extend({ ad_account_id: spotifyId });\nexport const budgetSchema = z.object({ micro_amount: z.number().int().nonnegative().safe(), type: z.enum(['DAILY', 'LIFETIME']) });\nexport const adSetSchema = z.looseObject({\n id: spotifyId, campaign_id: spotifyId, name: z.string(), budget: budgetSchema, delivery: z.enum(['ON', 'OFF']),\n});\nexport const pagingSchema = z.object({\n page_size: z.number().int().nonnegative(), total_results: z.number().int().nonnegative(),\n offset: z.number().int().nonnegative(), current_page: z.number().int().nonnegative(),\n});\nexport const reportRowSchema = z.looseObject({\n entity_type: z.enum(['AD_ACCOUNT', 'CAMPAIGN', 'AD_SET', 'AD']),\n entity_id: spotifyId, entity_name: z.string(), entity_status: z.string(),\n stats: z.array(z.object({ field_type: z.string(), field_value: z.number() })),\n});\nexport const reportSchema = z.looseObject({\n continuation_token: z.string().nullable().optional(),\n granularity: z.enum(['LIFETIME', 'DAY', 'HOUR']), rows: z.array(reportRowSchema),\n});\nexport const createDraftSchema = z.object({\n name: z.string().trim().min(2).max(200),\n purchase_order: z.string().min(2).max(45).optional(),\n delivery_goal_group: z.enum(['AWARENESS', 'WEBSITE_TRAFFIC', 'APP_PROMOTION', 'ENGAGEMENT_ON_SPOTIFY', 'LEAD_GEN', 'VIDEO_VIEWS']),\n status: z.enum(['PAUSED', 'ACTIVE']).default('PAUSED'),\n});\nexport const setStatusSchema = z.object({ campaign_id: spotifyId, status: z.enum(['PAUSED', 'ACTIVE']) });\nexport const setBudgetSchema = z.object({ ad_set_id: spotifyId, budget_micros: z.number().int().positive().safe() });\nexport const setDeliverySchema = z.object({ ad_set_id: spotifyId, delivery: z.enum(['OFF', 'ON']) });\n","import { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport type { SpotifyCreativeService } from './creatives.js';\nimport { createAudience, createLookalike, createReport, deleteAudience, updateAudience } from './management-tools.js';\nimport { spotifyId } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\nconst object = z.record(z.string(), z.unknown());\nconst audienceSchema = z.looseObject({ id: spotifyId, type: z.enum(['CUSTOM', 'LOOKALIKE']), name: z.string() });\nfunction query(input: Row) { const params = new URLSearchParams(); for (const [key, value] of Object.entries(input)) if (value !== undefined) { if (Array.isArray(value)) value.forEach(item => params.append(key, String(item))); else params.set(key, String(value)); } return params; }\n\nexport class SpotifyManagementService {\n constructor(private readonly client: SpotifyAdsClient, private readonly creatives: SpotifyCreativeService) {}\n private base(account: string) { return `ad_accounts/${spotifyId.parse(account)}`; }\n async read(input: { account_id: string } & Row, path: string) { const { account_id, ...params } = input; return this.client.get(`${this.base(account_id)}/${path}`, object, query(params)); }\n async audiences(input: { account_id: string; limit: number; offset: number } & Row) { const { account_id: _account, limit: _limit, offset: _offset, ...params } = input; return this.creatives.page(input, 'audiences', 'audiences', params); }\n async insights(input: { account_id: string; ad_set_id: string } & Row) {\n const { ad_set_id, ...params } = input;\n await this.creatives.get(input.account_id, 'ad_sets', ad_set_id, false);\n return this.read({ ...params, entity_ids: [ad_set_id], entity_ids_type: 'AD_SET' }, 'insight_reports');\n }\n async audience(account: string, id: string) {\n const result = await this.client.get(`${this.base(account)}/audiences/${spotifyId.parse(id)}`, audienceSchema);\n if (result.id !== id || (result.ad_account_id !== undefined && result.ad_account_id !== account)) throw new AdportError('PROVIDER_ERROR', 'spotify: audience account/ID mismatch');\n return result;\n }\n async eligibleDatasets(input: { account_id: string; limit: number; q?: string }) {\n const result = await this.read(input, 'audiences/datasets');\n const data = z.looseObject({ datasets: z.array(z.looseObject({ id: spotifyId })), paging: z.looseObject({ total_results: z.number().int().nonnegative(), offset: z.number().int().nonnegative() }).optional() }).parse(result);\n return { ...data, truncated: data.paging ? data.paging.offset + data.datasets.length < data.paging.total_results : data.datasets.length === input.limit };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const base = this.base(op.accountId);\n let path: string, method: 'POST' | 'PATCH' = 'POST', body: Row, expected: string | undefined;\n switch (op.tool) {\n case 'spotify_create_report': {\n const input = createReport.parse(op.payload);\n for (const id of input.campaign_ids ?? []) await this.creatives.get(op.accountId, 'campaigns', id, false);\n return { summary: `Submit Spotify CSV export ${input.name}`, changes: [`+ export job ${JSON.stringify(input)}; no ad delivery changes`], coercions: [], budgetDeltas: [], execute: async () => { const result = await this.client.mutate(`${base}/async_reports`, 'POST', input, z.object({ id: spotifyId })); return [result.id]; } };\n }\n case 'spotify_create_audience': {\n const input = createAudience.parse(op.payload);\n if (input.subtype === 'WEB_EVENT') {\n const data = await this.eligibleDatasets({ account_id: op.accountId, limit: 50 });\n if (input.dataset_ids!.some(id => !data.datasets.some(dataset => dataset.id === id))) throw new AdportError('INVALID_INPUT', 'spotify: dataset is not present in the selected account’s eligible audience datasets.');\n }\n for (const id of input.campaign_ids ?? []) await this.creatives.get(op.accountId, 'campaigns', id, false);\n for (const id of input.ad_set_ids ?? []) await this.creatives.get(op.accountId, 'ad_sets', id, false);\n body = { ...input, audience_type: 'CUSTOM' }; path = `${base}/audiences`; break;\n }\n case 'spotify_create_lookalike_audience': {\n const input = createLookalike.parse(op.payload); await this.audience(op.accountId, input.seed_audience_id);\n body = { ...input, audience_type: 'LOOKALIKE' }; path = `${base}/audiences`; break;\n }\n case 'spotify_update_audience': {\n const input = updateAudience.parse(op.payload), current = await this.audience(op.accountId, input.audience_id);\n const { audience_id, ...patch } = input; expected = audience_id; body = { ...patch, audience_type: current.type }; path = `${base}/audiences/${audience_id}`; method = 'PATCH'; break;\n }\n case 'spotify_delete_audience': {\n const input = deleteAudience.parse(op.payload), current = await this.audience(op.accountId, input.audience_id);\n return { summary: `Delete Spotify audience ${current.name}`, changes: [`- account-owned audience ${current.id}; targeting dependencies may be affected`], coercions: [], budgetDeltas: [], execute: async () => { const result = await this.client.mutate(`${base}/audiences/${current.id}`, 'DELETE', undefined, z.object({ deletion_count: z.number().int().nonnegative() })); if (result.deletion_count !== 1) throw new AdportError('PROVIDER_ERROR', 'spotify: audience deletion did not confirm one removed record; inspect before retrying'); return [current.id]; } };\n }\n default: throw new AdportError('INVALID_INPUT', `spotify: unsupported write ${op.tool}`);\n }\n return { summary: `Spotify ${op.tool.replace(/^spotify_/, '').replaceAll('_', ' ')}`, changes: [`${method} /${path} ${JSON.stringify(body)}`], coercions: [], budgetDeltas: [], execute: async () => {\n const result = await this.client.mutate(path, method, body, audienceSchema);\n if ((expected && result.id !== expected) || result.type !== body.audience_type || (result.ad_account_id !== undefined && result.ad_account_id !== op.accountId)) throw new AdportError('PROVIDER_ERROR', 'spotify: audience mutation receipt mismatch; inspect before retrying');\n return [result.id];\n } };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { spotifyId } from './schemas.js';\n\nconst account = { account_id: spotifyId };\nconst page = { limit: z.number().int().positive().max(50).default(50), offset: z.number().int().nonnegative().default(0) };\nconst ids = z.array(spotifyId).min(1).max(100);\nconst nativeFields = z.array(z.string().regex(/^[A-Z][A-Z0-9_]*$/)).min(1).max(100);\nconst insightDimension = z.enum(['ACT_AND_SET', 'AGE', 'AUDIENCE', 'CITY', 'COUNTRY', 'DEVICE_TYPE', 'FORMAT', 'GENDER', 'GENRE', 'INTERESTS', 'METRO', 'PLACEMENT', 'PLACEMENT_TYPE', 'PLATFORM', 'PODCAST_EPISODE_TOPIC', 'REGION', 'TONE']);\nconst audienceName = z.string().trim().min(2).max(80);\nconst description = z.string().max(80).optional();\n// JSON Schema consumers do not share JavaScript's Unicode-regexp flag.\n// Keep the native name rule at runtime without exporting a nonportable pattern.\nconst reportName = z.string().trim().min(2).max(120).refine(value => /^[\\p{L}\\p{N} _-]+$/u.test(value), 'Use letters, numbers, spaces, underscores or hyphens').describe('Unicode letters/numbers, spaces, underscores and hyphens.');\nexport const createAudience = z.object({ name: audienceName, description, subtype: z.enum(['WEB_EVENT', 'AD_ENGAGEMENT']), dataset_ids: ids.optional(), campaign_ids: ids.optional(), ad_set_ids: ids.optional(), included_events: z.array(z.string().min(1)).min(1).max(100).optional(), excluded_events: z.array(z.string().min(1)).max(100).optional(), lookback_days: z.union([z.literal(30), z.literal(60), z.literal(90), z.literal(180)]), exposure_type: z.enum(['IMPRESSIONS', 'CLICKS']).optional() }).strict().superRefine((value, ctx) => {\n if (value.subtype === 'WEB_EVENT' && (!value.dataset_ids || !value.included_events || value.campaign_ids || value.ad_set_ids || value.exposure_type)) ctx.addIssue({ code: 'custom', message: 'Web-event audiences require datasets and included events, without engagement fields' });\n if (value.subtype === 'AD_ENGAGEMENT' && (Boolean(value.campaign_ids) === Boolean(value.ad_set_ids) || !value.exposure_type || value.dataset_ids || value.included_events || value.excluded_events)) ctx.addIssue({ code: 'custom', message: 'Engagement audiences require campaign_ids or ad_set_ids plus exposure_type, without web-event fields' });\n});\nexport const createLookalike = z.object({ name: audienceName, description, seed_audience_id: spotifyId });\nexport const updateAudience = z.object({ audience_id: spotifyId, name: audienceName.optional(), description }).refine(v => v.name !== undefined || v.description !== undefined, 'Provide an audience field');\nexport const deleteAudience = z.object({ audience_id: spotifyId });\nexport const createReport = z.object({ name: reportName, granularity: z.enum(['LIFETIME', 'DAY']), dimensions: nativeFields, metrics: nativeFields, statuses: nativeFields.optional(), campaign_ids: ids.optional(), report_start: z.iso.datetime().optional(), report_end: z.iso.datetime().optional(), insight_dimension: insightDimension.optional(), attribution_window: z.enum(['IMPRESSION_30_DAY', 'IMPRESSION_7_DAY']).optional() }).superRefine((value, ctx) => {\n if (value.granularity === 'DAY' && (!value.report_start || !value.report_end)) ctx.addIssue({ code: 'custom', message: 'Daily exports require report_start and report_end' });\n if (value.insight_dimension && (value.granularity !== 'LIFETIME' || value.report_start || value.report_end)) ctx.addIssue({ code: 'custom', message: 'Insight exports require LIFETIME without report dates' });\n if (value.report_start && value.report_end && (Date.parse(value.report_end) < Date.parse(value.report_start) || Date.parse(value.report_end) - Date.parse(value.report_start) > 365 * 86_400_000)) ctx.addIssue({ code: 'custom', message: 'Report dates must be ordered and within365 days' });\n if ([value.report_start, value.report_end].some(v => v && !/T00:00:00Z$/.test(v))) ctx.addIssue({ code: 'custom', message: 'Use UTC midnight report dates' });\n});\nexport const managementWriteNames = new Set(['spotify_create_audience', 'spotify_create_lookalike_audience', 'spotify_update_audience', 'spotify_delete_audience', 'spotify_create_report']);\n\nexport function spotifyManagementTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\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: 'spotify', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove') => guardedWriteTool({ name, namespace: 'spotify', provider: 'spotify', description, payload, kind });\n return [\n read('spotify_audiences', 'Read existing account-owned custom/lookalike audiences with native filters and pagination. Does not upload customer records.', z.object({ ...account, audience_ids: ids.optional(), audience_types: z.array(z.enum(['CUSTOM', 'LOOKALIKE'])).optional(), q: z.string().optional(), ...page }), input => provider.management.audiences(input)),\n read('spotify_get_audience', 'Read one account-owned custom/lookalike audience and its processing status.', z.object({ ...account, audience_id: spotifyId }), input => provider.management.audience(input.account_id, input.audience_id)),\n read('spotify_audience_datasets', 'Read eligible account datasets and available web events for audience creation. Returns native pagination limits.', z.object({ ...account, q: z.string().optional(), limit: z.number().int().positive().max(50).default(50) }), input => provider.management.eligibleDatasets(input)),\n read('spotify_insight_report', 'Read native lifetime insights for exactly one verified published ad set, as required by the live endpoint. Missing/suppressed conversion fields remain unavailable.', z.object({ ...account, ad_set_id: spotifyId, insight_dimension: insightDimension, fields: nativeFields, statuses: nativeFields.optional() }), input => provider.management.insights(input)),\n read('spotify_change_history', 'Read account change history within Spotify’s rolling180-day window. Actor details and billing rows depend on the caller’s role.', z.object({ ...account, entity_type: z.enum(['CAMPAIGN', 'AD_SET', 'AD_ACCOUNT', 'BUSINESS', 'CREATIVE']).optional(), entity_ids: ids.optional(), entity_name: z.string().optional(), created_gte: z.iso.datetime().optional(), created_lte: z.iso.datetime().optional(), change_category: z.enum(['STATUS', 'BUDGET', 'TARGETING', 'CREATIVE', 'SCHEDULING', 'SETTINGS', 'BILLING']).optional(), sort_direction: z.enum(['ASC', 'DESC']).default('DESC'), ...page }), input => provider.management.read(input, 'change_history')),\n read('spotify_report_status', 'Read a previously submitted account export’s status and native CSV URL. Does not fetch arbitrary URLs or create a public share.', z.object({ ...account, report_id: spotifyId }), input => provider.management.read({ account_id: input.account_id }, `async_reports/${input.report_id}`)),\n write('spotify_create_audience', 'Create a web-event or ad-engagement audience from existing account-owned resources. Does not upload customer records or attach targeting to ads.', createAudience, 'create'),\n write('spotify_create_lookalike_audience', 'Create a lookalike from an existing account-owned seed audience. Does not upload customer records or change ad targeting.', createLookalike, 'create'),\n write('spotify_update_audience', 'Rename or edit the description of an account-owned audience, preserving its native type and source rules.', updateAudience, 'update'),\n write('spotify_delete_audience', 'Delete an account-owned audience through the normal preview/apply gate. Review dependencies before applying.', deleteAudience, 'remove'),\n write('spotify_create_report', 'Submit a native asynchronous CSV export job. No ad or delivery changes. Native field names are server-validated; use spotify_report_status for completion.', createReport, 'create'),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type ResourceSecretStore, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport { spotifyId } from './schemas.js';\nimport { capiSchema, createdReceipt, createCapi, createDataset, createMobile, createPixel, datasetSchema, datasetSharing, diagnosticSchema, mobileSchema, mobileSharing, paging, pixelId, pixelSchema, removeIntegration, updateCapi, updateDataset, updateMobile, updatePixel } from './measurement-schemas.js';\nimport { SpotifyCapiCredentials, capiCredentialWrites } from './capi-credentials.js';\n\ntype Row = Record<string, unknown>;\ntype Scope = { account_id: string; business_id: string };\ntype Dataset = z.infer<typeof datasetSchema>;\ntype Mobile = z.infer<typeof mobileSchema>;\ntype Receipt = z.infer<typeof createdReceipt>;\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<WriteResult> }\nconst RECEIPT_TTL = 7 * 24 * 60 * 60;\nconst commonNotes = ['Local preview only. Measurement resource management does not install website code, send conversion events, issue CAPI credentials or change ad delivery or budgets.', 'Native permissions and configuration remain authoritative. No automatic write retry; use the returned IDs and signed receipt to reconcile partial creation.'];\nconst canonical = (value: unknown): string => JSON.stringify(value, (key, item) => {\n if (Array.isArray(item) && ['aam_fields', 'auto_capture_fields', 'shared_ad_accounts'].includes(key)) return item.map(v => v && typeof v === 'object' && 'id' in v ? { id: v.id } : v).sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b)));\n return item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).filter(([k]) => !['events', 'events_received', 'historical_events', 'created_at', 'updated_at', 'ad_set_count', 'is_receiving_events', 'is_receiving_lead_events'].includes(k)).sort(([a], [b]) => a.localeCompare(b))) : item;\n});\nconst digest = (scope: Scope, kind: string, value: unknown) => createHash('sha256').update(canonical({ ...scope, kind, configuration: value })).digest('hex');\nconst same = (a: unknown, b: unknown) => canonical(a) === canonical(b);\nconst members = (dataset: Dataset) => [dataset.pixel, dataset.capi_integration].filter((v): v is NonNullable<typeof v> => Boolean(v));\nconst contains = (dataset: Dataset, integration: string) => members(dataset).some(v => v.integration_id === integration);\nfunction params(input: Row) { const p = new URLSearchParams();for (const [k, v] of Object.entries(input)) if (v !== undefined) { if (Array.isArray(v)) for (const value of v) p.append(k, String(value)); else p.set(k, String(v)); } return p; }\nfunction ensure(value: unknown, message: string): asserts value { if (!value) throw new AdportError('PROVIDER_ERROR', `spotify: ${message}`); }\n\n/** Current official v3 OpenAPI, fetched 2026-11-05; signed recovery follows approved native creations only. */\nexport class SpotifyMeasurementService {\n readonly credentials: SpotifyCapiCredentials;\n constructor(private readonly client: SpotifyAdsClient, secrets?: ResourceSecretStore) { this.credentials = new SpotifyCapiCredentials(client, input => this.credentialScope(input), secrets); }\n private async credentialScope(input: { account_id: string; dataset_id: string }) {\n const scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id);\n this.exclusive(scope, dataset);\n ensure(dataset.shared_ad_accounts?.some(account => account.id === scope.account_id), 'CAPI credentials require sharing with this selected account');\n ensure(dataset.capi_integration, 'dataset has no verified CAPI integration');\n const integration = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);\n this.verifyIntegrationBinding(dataset, 'capi', integration.capi_connection_id, integration.dataset_id);\n return { ...scope, dataset_id: dataset.id, capi_connection_id: integration.capi_connection_id, configuration_hash: digest(scope, 'capi', integration), dataset_configuration_hash: digest(scope, 'dataset', dataset) };\n }\n private base(scope: Scope) { return `businesses/${scope.business_id}`; }\n private async scope(account: string): Promise<Scope> {\n const id = spotifyId.parse(account), data = await this.client.get(`ad_accounts/${id}`, z.object({ id: spotifyId, business_id: spotifyId }));\n ensure(data.id === id, 'measurement account identity mismatch');\n return { account_id: id, business_id: data.business_id };\n }\n private proof(account: string, value?: string, purpose: Receipt['purpose'] = 'creation'): Receipt | undefined {\n if (!value) return undefined;\n const parsed = createdReceipt.safeParse(this.client.verifyMeasurementReceipt(value)), now = Math.floor(Date.now() / 1000);\n if (!parsed.success || parsed.data.purpose !== purpose || parsed.data.account_id !== account || parsed.data.issued_at > now + 60 || parsed.data.expires_at <= now || parsed.data.expires_at <= parsed.data.issued_at || parsed.data.expires_at - parsed.data.issued_at > RECEIPT_TTL) throw new AdportError('INVALID_INPUT', 'spotify: expired or mismatched measurement resource receipt');\n return parsed.data;\n }\n private bind(scope: Scope, kind: Receipt['kind'], id: string, datasetId?: string, purpose: Receipt['purpose'] = 'creation'): string {\n const now = Math.floor(Date.now() / 1000);\n return this.client.measurementReceipt(createdReceipt.parse({ version: 1, purpose, ...scope, kind, id, ...(datasetId ? { dataset_id: datasetId } : {}), issued_at: now, expires_at: now + RECEIPT_TTL }));\n }\n private checkProof(scope: Scope, proof?: Receipt) { if (proof && proof.business_id !== scope.business_id) throw new AdportError('INVALID_INPUT', 'spotify: the account business changed; measurement receipt no longer matches'); }\n private async rawDataset(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/datasets/${spotifyId.parse(id)}`, datasetSchema);ensure(data.id === id, 'dataset identity mismatch');return data;\n }\n private async rawMobile(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/mobile_apps/${spotifyId.parse(id)}`, mobileSchema);ensure(data.id === id, 'mobile-app identity mismatch');return data;\n }\n private async rawPixel(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/pixels/${id}`, pixelSchema);ensure(data.id === id, 'Pixel identity mismatch');return data;\n }\n private async rawCapi(scope: Scope, id: string) {\n const data = await this.client.get(`${this.base(scope)}/capi/${spotifyId.parse(id)}`, capiSchema);ensure(data.capi_connection_id === id, 'CAPI integration identity mismatch');return data;\n }\n private datasetContainsResource(dataset: Dataset, kind: Receipt['kind'], id: string) {\n return kind === 'pixel' ? dataset.pixel?.id === id : kind === 'capi' ? dataset.capi_integration?.capi_connection_id === id : false;\n }\n private verifyIntegrationBinding(dataset: Dataset, kind: 'pixel' | 'capi', id: string, observed: string | null | undefined) {\n ensure(this.datasetContainsResource(dataset, kind, id) && (observed == null || observed === dataset.id), `${kind === 'pixel' ? 'Pixel' : 'CAPI'} dataset binding mismatch`);\n }\n private async receiptNative(scope: Scope, proof: Receipt) {\n this.checkProof(scope, proof);\n const resource = proof.kind === 'pixel' ? await this.rawPixel(scope, proof.id) : proof.kind === 'capi' ? await this.rawCapi(scope, proof.id) : proof.kind === 'mobile_app' ? await this.rawMobile(scope, proof.id) : await this.rawDataset(scope, proof.id);\n const datasetId = proof.kind === 'dataset' ? proof.id : 'dataset_id' in resource && typeof resource.dataset_id === 'string' ? resource.dataset_id : undefined;\n let expectedDataset: Dataset | undefined, verifiedDatasetId = datasetId;\n let parentVerificationError: { code: string; http_status?: number } | undefined;\n // Null is missing evidence, not a conflicting edge. Inspect only the parent locked by the native creation receipt.\n if (!datasetId && proof.dataset_id && ['pixel', 'capi'].includes(proof.kind)) {\n try {\n expectedDataset = await this.rawDataset(scope, proof.dataset_id);\n if (this.datasetContainsResource(expectedDataset, proof.kind, proof.id)) verifiedDatasetId = expectedDataset.id;\n } catch (error) {\n if (!(error instanceof AdportError)) throw error;\n const status = error.details && typeof error.details === 'object' && 'http_status' in error.details ? error.details.http_status : undefined;\n parentVerificationError = { code: error.code, ...(typeof status === 'number' ? { http_status: status } : {}) };\n }\n }\n return { resource, datasetId, verifiedDatasetId, expectedDataset, parentVerificationError };\n }\n private async createdNative(scope: Scope, proof: Receipt) {\n const { resource, verifiedDatasetId } = await this.receiptNative(scope, proof);\n ensure(!proof.dataset_id || verifiedDatasetId === proof.dataset_id, 'created resource dataset binding changed; reconcile the original IDs');\n return { resource, datasetId: verifiedDatasetId };\n }\n private sharing(scope: Scope, row: { shared_ad_accounts?: Array<{ id: string; name?: string | null }> | null }) {\n return { shared_ad_accounts: row.shared_ad_accounts === null ? null : row.shared_ad_accounts?.filter(a => a.id === scope.account_id), other_shared_account_count: row.shared_ad_accounts ? row.shared_ad_accounts.filter(a => a.id !== scope.account_id).length : null };\n }\n private publicDataset(scope: Scope, row: Dataset, snapshot = true) { return { ...row, ...this.sharing(scope, row), ...(snapshot ? { configuration_hash: digest(scope, 'dataset', row) } : {}) }; }\n private publicMobile(scope: Scope, row: Mobile, snapshot = true) { return { ...row, ...this.sharing(scope, row), ...(snapshot ? { configuration_hash: digest(scope, 'mobile_app', row) } : {}) }; }\n private async selectedDatasets(scope: Scope) {\n // This endpoint has no documented limit/offset query; never invent paging parameters.\n const data = await this.client.get(`${this.base(scope)}/ad_accounts/${scope.account_id}/datasets`, z.object({ datasets: z.array(datasetSchema), paging: paging.nullish() }));\n ensure(new Set(data.datasets.map(d => d.id)).size === data.datasets.length, 'dataset inventory repeated an ID');\n ensure(!data.paging || data.paging.offset === 0 && data.paging.total_results >= data.datasets.length, 'dataset inventory pagination is inconsistent');\n for (const row of data.datasets) ensure(!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id === scope.account_id), 'dataset inventory contains an unshared account resource');\n return { ...data, complete: data.paging ? data.paging.total_results === data.datasets.length : null, truncated: !data.paging || data.paging.total_results !== data.datasets.length };\n }\n private recoverableDataset(scope: Scope, row: Dataset, proof: Receipt, nativeDatasetId?: string) {\n if (nativeDatasetId !== row.id) return false;\n if (proof.dataset_id === row.id || proof.kind === 'dataset' && proof.id === row.id) return true;\n // An initially unbound creation cannot be used to pivot into an unrelated shared parent.\n if (!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id !== scope.account_id)) return false;\n return proof.kind === 'pixel' ? row.pixel?.id === proof.id && !row.capi_integration : proof.kind === 'capi' ? row.capi_integration?.capi_connection_id === proof.id && !row.pixel : false;\n }\n private async dataset(scope: Scope, id: string, proof?: Receipt) {\n this.checkProof(scope, proof);\n const row = await this.rawDataset(scope, id);\n if (row.shared_ad_accounts?.some(a => a.id === scope.account_id)) return row;\n if (proof && this.recoverableDataset(scope, row, proof, (await this.createdNative(scope, proof)).datasetId)) return row;\n if (!row.shared_ad_accounts) {\n const selected = (await this.selectedDatasets(scope)).datasets.find(d => d.id === id);\n if (selected) return { ...row, ...(selected.shared_ad_accounts ? { shared_ad_accounts: selected.shared_ad_accounts } : {}) };\n }\n throw new AdportError('INVALID_INPUT', 'spotify: dataset is not shared with the selected account; an unshared creation requires its signed resource receipt');\n }\n private async mobile(scope: Scope, id: string, proof?: Receipt) {\n this.checkProof(scope, proof);const row = await this.rawMobile(scope, id);\n if (row.shared_ad_accounts?.some(a => a.id === scope.account_id) || proof?.kind === 'mobile_app' && proof.id === id) return row;\n if (!row.shared_ad_accounts) {\n const seen = new Set<string>();\n for (let offset = 0, page = 0; page < 1000; page++) {\n const data = await this.mobilePage(scope, { limit: 50, offset });\n for (const item of data.mobile_apps) { ensure(!seen.has(item.id), 'mobile-app inventory repeated a page');seen.add(item.id); }\n const selected = data.mobile_apps.find(a => a.id === id);\n if (selected) return { ...row, ...(selected.shared_ad_accounts ? { shared_ad_accounts: selected.shared_ad_accounts } : {}) };\n if (!data.truncated) break;offset = data.next_offset!;\n }\n }\n throw new AdportError('INVALID_INPUT', 'spotify: mobile app is not shared with the selected account or bound to its approved creation receipt');\n }\n private exclusive(scope: Scope, row: { shared_ad_accounts?: Array<{ id: string }> | null }) {\n if (!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id !== scope.account_id)) throw new AdportError('INVALID_INPUT', 'spotify: business-wide configuration changes require verified sharing restricted to this selected account');\n }\n private expected(scope: Scope, kind: string, value: unknown, hash: string) { if (digest(scope, kind, value) !== hash) throw new AdportError('INVALID_INPUT', 'spotify: measurement configuration changed; obtain a fresh snapshot before a new preview'); }\n private result(ids: string[], details: Row = {}): WriteResult { return { applied: true, resourceIds: [...new Set(ids)], ...(Object.keys(details).length ? { details } : {}) }; }\n private uncertain(ids: string[], receipt?: string): never { throw new AdportError('PROVIDER_ERROR', 'spotify: measurement write/readback unconfirmed; reconcile the original IDs before another mutation. No write was replayed.', { resource_ids: ids, ...(receipt ? { resource_receipt: receipt } : {}) }); }\n private review(scope: Scope, title: string, kind: WriteOperation['kind'], body: Row, current?: Row, notices = commonNotes): Omit<Plan, 'execute'> {\n const fields = Object.entries(body).map(([key, value]) => ({ label: key.replaceAll('_', ' '), ...(current?.[key] === undefined ? {} : { before: current[key] }), after: value }));\n return { summary: title, changes: [`${kind}: ${JSON.stringify(body)}`], notes: notices, coercions: [], budgetDeltas: [], review: { provider: 'spotify', accountId: scope.account_id, kind, title, fields, notices } };\n }\n\n async datasets(account: string) { const scope = await this.scope(account), data = await this.selectedDatasets(scope);return { ...scope, ...data, datasets: data.datasets.map(d => this.publicDataset(scope, d, false)) }; }\n private async mobilePage(scope: Scope, input: { limit: number; offset: number }) {\n const data = await this.client.get(`${this.base(scope)}/ad_accounts/${scope.account_id}/mobile_apps`, z.object({ mobile_apps: z.array(mobileSchema), paging }), params({ limit: input.limit, offset: input.offset }));\n ensure(data.paging.offset === input.offset && data.mobile_apps.length <= input.limit && (!data.mobile_apps.length || data.paging.total_results >= input.offset + data.mobile_apps.length), 'mobile-app pagination is inconsistent');\n ensure(new Set(data.mobile_apps.map(a => a.id)).size === data.mobile_apps.length, 'mobile-app page repeated an ID');\n for (const row of data.mobile_apps) ensure(!row.shared_ad_accounts || row.shared_ad_accounts.some(a => a.id === scope.account_id), 'mobile-app inventory contains an unshared resource');\n const next = input.offset + data.mobile_apps.length, truncated = next < data.paging.total_results;ensure(!truncated || data.mobile_apps.length > 0, 'mobile-app pagination stalled');\n return { ...data, truncated, ...(truncated ? { next_offset: next } : {}) };\n }\n async mobileApps(input: { account_id: string; limit: number; offset: number }) { const scope = await this.scope(input.account_id), data = await this.mobilePage(scope, input);return { ...scope, ...data, mobile_apps: data.mobile_apps.map(a => this.publicMobile(scope, a, false)) }; }\n async context(account: string) { const scope = await this.scope(account), data = await this.selectedDatasets(scope);return { ...scope, ...data, datasets: data.datasets.map(d => this.publicDataset(scope, d, false)), notes: ['Only datasets shared with this selected account are inventoried. Business-wide resources and other account identities are excluded. Read an individual resource for its full mutation snapshot.', 'Pixel creation may create a dataset; CAPI can join that dataset. No tracking code, tokens or events are created by these reads.'] }; }\n async getDataset(input: { account_id: string; dataset_id: string; resource_receipt?: string }) { const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);return { ...scope, dataset: this.publicDataset(scope, await this.dataset(scope, input.dataset_id, proof)) }; }\n async getPixel(input: { account_id: string; dataset_id: string; resource_receipt?: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id, proof);ensure(dataset.pixel, 'dataset has no verified Pixel');\n const pixel = await this.rawPixel(scope, dataset.pixel.id);this.verifyIntegrationBinding(dataset, 'pixel', pixel.id, pixel.dataset_id);return { ...scope, pixel: { ...pixel, configuration_hash: digest(scope, 'pixel', pixel) }, dataset_binding: { observed_dataset_id: pixel.dataset_id ?? null, verified_dataset_id: dataset.id, verification_source: pixel.dataset_id ? 'resource' : 'dataset' } };\n }\n async getCapi(input: { account_id: string; dataset_id: string; resource_receipt?: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id), dataset = await this.dataset(scope, input.dataset_id, proof);ensure(dataset.capi_integration, 'dataset has no verified CAPI integration');\n const integration = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);this.verifyIntegrationBinding(dataset, 'capi', integration.capi_connection_id, integration.dataset_id);return { ...scope, capi_integration: { ...integration, configuration_hash: digest(scope, 'capi', integration) }, dataset_binding: { observed_dataset_id: integration.dataset_id ?? null, verified_dataset_id: dataset.id, verification_source: integration.dataset_id ? 'resource' : 'dataset' } };\n }\n async getMobile(input: { account_id: string; mobile_app_id: string; resource_receipt?: string }) { const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);return { ...scope, mobile_app: this.publicMobile(scope, await this.mobile(scope, input.mobile_app_id, proof)) }; }\n async diagnostics(input: { account_id: string; dataset_id: string; granularities: Array<'DAILY' | 'HOURLY'>; datasource_ids?: string[]; resource_receipt?: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt), scope = await this.scope(input.account_id);await this.dataset(scope, input.dataset_id, proof);\n const data = await this.client.get(`${this.base(scope)}/datasets/${input.dataset_id}/diagnostics`, diagnosticSchema, params({ granularities: input.granularities, datasource_ids: input.datasource_ids }));\n ensure(data.dataset_id === input.dataset_id && data.datasources.every(d => input.granularities.includes(d.granularity) && (!input.datasource_ids || input.datasource_ids.includes(d.datasource_id))), 'measurement diagnostic identity/filter mismatch');\n return { ...scope, ...data, notes: ['Diagnostics can lag implementation by at least 20 minutes. Received activity is not proof of campaign attribution, optimization or delivery. Missing or suppressed values remain native; this read sends no events.'] };\n }\n async created(input: { account_id: string; resource_receipt: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt)!, scope = await this.scope(input.account_id), native = await this.receiptNative(scope, proof);\n const matches = proof.dataset_id ? native.datasetId === proof.dataset_id : null;\n const verified = !proof.dataset_id || native.verifiedDatasetId === proof.dataset_id;\n const candidate = verified && native.verifiedDatasetId ? native.expectedDataset ?? await this.rawDataset(scope, native.verifiedDatasetId) : undefined;\n const dataset = candidate && (candidate.shared_ad_accounts?.some(a => a.id === scope.account_id) || this.recoverableDataset(scope, candidate, proof, native.verifiedDatasetId)) ? candidate : undefined;\n const key = proof.kind === 'capi' ? 'capi_integration' : proof.kind;\n const resource = proof.kind === 'mobile_app' ? this.publicMobile(scope, native.resource as Mobile) : proof.kind === 'dataset' ? this.publicDataset(scope, native.resource as Dataset) : { ...native.resource, configuration_hash: digest(scope, proof.kind, native.resource) };\n return { ...scope, kind: proof.kind, [key]: resource, dataset: dataset ? this.publicDataset(scope, dataset) : null,\n dataset_binding: { expected_dataset_id: proof.dataset_id ?? null, observed_dataset_id: native.datasetId ?? null, matches_receipt: matches, verified_dataset_id: dataset?.id ?? null, verification_source: dataset ? native.datasetId ? 'resource' : 'dataset' : null, ...(native.parentVerificationError ? { parent_verification_error: native.parentVerificationError } : {}) },\n needs_dataset_sharing: dataset?.shared_ad_accounts ? !dataset.shared_ad_accounts.some(a => a.id === scope.account_id) : null, resource_receipt: input.resource_receipt,\n notes: ['Read-only reconciliation of an approved creation. No creation, share, update or event request was replayed.', ...(matches === false ? [dataset ? 'The native child omits its dataset binding. The exact receipt-bound parent independently confirms the resource relationship; the native null value is preserved.' : 'The resource relationship is unverified. No unexpected dataset contents were followed. Sharing remains unverified and mutation checks remain strict.'] : [])] };\n }\n async sharingStatus(input: { account_id: string; resource_receipt: string }) {\n const proof = this.proof(input.account_id, input.resource_receipt, 'sharing')!, scope = await this.scope(input.account_id);this.checkProof(scope, proof);\n if (!['dataset', 'mobile_app'].includes(proof.kind)) throw new AdportError('INVALID_INPUT', 'spotify: receipt does not identify a sharing operation');\n const row = proof.kind === 'dataset' ? await this.rawDataset(scope, proof.id) : await this.rawMobile(scope, proof.id);\n ensure(row.shared_ad_accounts, 'native sharing state is unavailable');\n return { ...scope, kind: proof.kind, resource_id: proof.id, shared_with_selected_account: row.shared_ad_accounts.some(a => a.id === scope.account_id), other_shared_account_count: row.shared_ad_accounts.filter(a => a.id !== scope.account_id).length, notes: ['Read-only reconciliation of the selected account’s sharing state. A sharing receipt does not grant resource-content access after unsharing.'] };\n }\n\n private async shareCreatedDataset(scope: Scope, id: string) {\n const current = await this.rawDataset(scope, id);this.exclusive(scope, current);\n if (!current.shared_ad_accounts!.some(a => a.id === scope.account_id)) await this.client.mutate(`${this.base(scope)}/datasets/${id}/ad_accounts/${scope.account_id}`, 'POST', undefined, z.undefined());\n const actual = await this.rawDataset(scope, id);this.exclusive(scope, actual);ensure(actual.shared_ad_accounts!.some(a => a.id === scope.account_id), 'created dataset sharing readback unconfirmed');return actual;\n }\n private async planCreate(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n const kind: Receipt['kind'] = op.tool === 'spotify_create_pixel' ? 'pixel' : op.tool === 'spotify_create_capi_integration' ? 'capi' : 'mobile_app';\n let body: Row, requestedDataset: string | undefined;\n if (kind === 'mobile_app') body = createMobile.parse(op.payload);\n else {\n const input = kind === 'pixel' ? createPixel.parse(op.payload) : createCapi.parse(op.payload);\n const { expected_dataset_configuration_hash, resource_receipt: _receipt, ...native } = input;\n if (input.dataset_id) {\n const dataset = await this.dataset(scope, input.dataset_id, proof);this.exclusive(scope, dataset);this.expected(scope, 'dataset', dataset, expected_dataset_configuration_hash!);\n if (kind === 'pixel' ? dataset.pixel : dataset.capi_integration) throw new AdportError('INVALID_INPUT', `spotify: dataset already has a ${kind} integration; reuse it instead of duplicating the source`);\n }\n const { acknowledge_advanced_matching: _ack, ...fields } = native as Row;\n body = fields;requestedDataset = input.dataset_id;\n }\n const path = `${this.base(scope)}/${kind === 'pixel' ? 'pixels' : kind === 'capi' ? 'capi' : 'mobile_apps'}`;\n const notices = [...commonNotes, kind === 'mobile_app' ? 'The new mobile-app record will be shared only with this selected ad account. Registration does not install or configure an MMP SDK.' : 'The new integration will use its verified dataset, which will be shared only with this selected ad account. A new native dataset is created when dataset_id is omitted.', ...(kind === 'pixel' ? ['Advanced matching is disabled by default. Native cookie and automatic-capture settings are returned for review before any website installation.'] : [])];\n return { ...this.review(scope, `Create Spotify ${kind.replaceAll('_', ' ')} \"${body.name}\"`, 'create', body, undefined, notices), execute: async () => {\n let id: string, nativeDataset: string | undefined;\n try {\n if (kind === 'pixel') { const row = await this.client.mutate(path, 'POST', body, z.object({ id: pixelId, dataset_id: z.unknown().optional() }));id = row.id;const dataset = spotifyId.safeParse(row.dataset_id);nativeDataset = dataset.success ? dataset.data : undefined; }\n else if (kind === 'capi') { const row = await this.client.mutate(path, 'POST', body, z.object({ capi_connection_id: spotifyId, dataset_id: z.unknown().optional() }));id = row.capi_connection_id;const dataset = spotifyId.safeParse(row.dataset_id);nativeDataset = dataset.success ? dataset.data : undefined; }\n else { const row = await this.client.mutate(path, 'POST', { mobile_app: body }, z.object({ id: spotifyId, dataset_id: z.unknown().optional() }));id = row.id;const dataset = spotifyId.safeParse(row.dataset_id);nativeDataset = dataset.success ? dataset.data : undefined; }\n } catch (error) { if (error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([]); }\n let receipt = this.bind(scope, kind, id, requestedDataset ?? nativeDataset), knownDataset = requestedDataset ?? nativeDataset;\n try {\n const bound = this.proof(scope.account_id, receipt)!, { resource, datasetId } = await this.createdNative(scope, bound);\n const observed = resource as Row;\n // Spotify returns null for unused matching fields; only verified AAM-off makes them ineffective.\n ensure(Object.entries(body).every(([key, value]) => key === 'dataset_id' && requestedDataset !== undefined && datasetId === requestedDataset\n || kind === 'pixel' && key === 'aam_fields' && Array.isArray(value) && !value.length && observed.aam_opt_in === false && observed[key] == null\n || same({ [key]: observed[key] }, { [key]: value })), 'created measurement fields differ from the request');\n ensure(!requestedDataset || datasetId === requestedDataset, 'created integration has a different dataset');\n if (kind === 'mobile_app') {\n const mobile = resource as Mobile;this.exclusive(scope, mobile);\n if (!mobile.shared_ad_accounts!.some(a => a.id === scope.account_id)) await this.client.mutate(`${path}/${id}/ad_accounts/${scope.account_id}`, 'POST', undefined, z.undefined());\n const actual = await this.rawMobile(scope, id);this.exclusive(scope, actual);ensure(actual.shared_ad_accounts!.some(a => a.id === scope.account_id), 'created mobile-app sharing readback unconfirmed');\n receipt = this.bind(scope, kind, id, datasetId);return this.result([id, ...(datasetId ? [datasetId] : [])], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', mobile_app_id: id, ...(datasetId ? { dataset_id: datasetId } : {}) });\n }\n ensure(datasetId, 'created integration has no verified dataset ID');knownDataset = datasetId;receipt = this.bind(scope, kind, id, datasetId);\n const dataset = await this.rawDataset(scope, datasetId);\n ensure(kind === 'pixel' ? dataset.pixel?.id === id : dataset.capi_integration?.capi_connection_id === id, 'created dataset does not bind the returned integration');\n await this.shareCreatedDataset(scope, datasetId);\n return this.result([id, datasetId], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', dataset_id: datasetId });\n } catch { return this.uncertain([id, ...(knownDataset ? [knownDataset] : [])], receipt); }\n } };\n }\n private async planUpdate(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n let current: Row, body: Row, path: string, kind: string, id: string, readback: () => Promise<Row>;\n if (op.tool === 'spotify_update_mobile_app') {\n const input = updateMobile.parse(op.payload), row = await this.mobile(scope, input.mobile_app_id, proof);this.exclusive(scope, row);this.expected(scope, 'mobile_app', row, input.expected_configuration_hash);\n const { mobile_app_id: _id, resource_receipt: _receipt, expected_configuration_hash: _hash, ...fields } = input;\n current = row;body = fields;kind = 'mobile_app';id = row.id;path = `${this.base(scope)}/mobile_apps/${id}`;readback = () => this.rawMobile(scope, id);\n } else {\n const input = op.tool === 'spotify_update_pixel' ? updatePixel.parse(op.payload) : op.tool === 'spotify_update_capi_integration' ? updateCapi.parse(op.payload) : op.tool === 'spotify_update_dataset' ? updateDataset.parse(op.payload) : undefined;\n if (!input) throw new AdportError('INVALID_INPUT', 'spotify: unsupported measurement update');\n const dataset = await this.dataset(scope, input.dataset_id, proof);this.exclusive(scope, dataset);\n const { dataset_id: _id, resource_receipt: _receipt, expected_configuration_hash: _hash, ...fields } = input;body = fields;\n if (op.tool === 'spotify_update_pixel') {\n ensure(dataset.pixel, 'dataset has no verified Pixel');const pixel = await this.rawPixel(scope, dataset.pixel.id);this.verifyIntegrationBinding(dataset, 'pixel', pixel.id, pixel.dataset_id);\n current = pixel;kind = 'pixel';id = pixel.id;path = `${this.base(scope)}/pixels/${id}`;readback = () => this.rawPixel(scope, id);\n } else if (op.tool === 'spotify_update_capi_integration') {\n ensure(dataset.capi_integration, 'dataset has no verified CAPI integration');const capi = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);this.verifyIntegrationBinding(dataset, 'capi', capi.capi_connection_id, capi.dataset_id);\n current = capi;kind = 'capi';id = capi.capi_connection_id;path = `${this.base(scope)}/capi/${id}`;readback = () => this.rawCapi(scope, id);\n } else { current = dataset;kind = 'dataset';id = dataset.id;path = `${this.base(scope)}/datasets/${id}`;readback = () => this.rawDataset(scope, id); }\n this.expected(scope, kind, current, input.expected_configuration_hash);\n }\n const expected = { ...current, ...body };\n return { ...this.review(scope, `Update Spotify ${kind.replaceAll('_', ' ')} \"${current.name}\"`, 'update', body, current), execute: async () => {\n let accepted = false;\n try { await this.client.mutate(path, 'PATCH', body, z.object({}));accepted = true;const actual = await readback();ensure(digest(scope, kind, actual) === digest(scope, kind, expected), 'measurement update readback differs'); }\n catch (error) { if (!accepted && error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([id]); }\n return this.result([id]);\n } };\n }\n private async planSharing(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n const mobile = op.tool === 'spotify_set_mobile_app_sharing', input = mobile ? mobileSharing.parse(op.payload) : datasetSharing.parse(op.payload);\n const id = 'mobile_app_id' in input ? input.mobile_app_id : input.dataset_id, kind = mobile ? 'mobile_app' as const : 'dataset' as const;\n const current = mobile ? await this.mobile(scope, id, proof) : await this.dataset(scope, id, proof);ensure(current.shared_ad_accounts, 'native sharing dependencies are unavailable');\n this.expected(scope, kind, current, input.expected_configuration_hash);\n const shared = current.shared_ad_accounts.some(a => a.id === scope.account_id), path = `${this.base(scope)}/${mobile ? 'mobile_apps' : 'datasets'}/${id}/ad_accounts/${scope.account_id}`;\n const targetShares = [...current.shared_ad_accounts.filter(a => a.id !== scope.account_id), ...(input.shared ? [{ id: scope.account_id }] : [])], expected = { ...current, shared_ad_accounts: targetShares };\n return { ...this.review(scope, `${input.shared ? 'Share' : 'Unshare'} Spotify ${kind.replaceAll('_', ' ')} with the selected account`, 'update', { shared: input.shared }, { shared }, [...commonNotes, `Only account ${scope.account_id} changes. Other account shares are preserved. Unsharing can stop this account using the measurement source.`]), execute: async () => {\n if (shared === input.shared) return this.result([id], { changed: false, shared_with_selected_account: shared });\n const receipt = this.bind(scope, kind, id, undefined, 'sharing');let accepted = false;\n try {\n await this.client.mutate(path, input.shared ? 'POST' : 'DELETE', undefined, z.undefined());accepted = true;\n const actual = mobile ? await this.rawMobile(scope, id) : await this.rawDataset(scope, id);ensure(digest(scope, kind, actual) === digest(scope, kind, expected), 'native sharing readback differs');\n } catch (error) { if (!accepted && error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([id], receipt); }\n return this.result([id], { resource_receipt: receipt, next_tool: 'spotify_measurement_sharing_status', shared_with_selected_account: input.shared });\n } };\n }\n private async planDataset(op: WriteOperation, scope: Scope): Promise<Plan> {\n const input = createDataset.parse(op.payload), selected: Array<{ dataset: Dataset; integration_id: string; kind: 'pixel' | 'capi'; id: string }> = [];\n for (const source of input.sources) {\n const proof = this.proof(scope.account_id, source.resource_receipt), dataset = await this.dataset(scope, source.dataset_id, proof);this.exclusive(scope, dataset);this.expected(scope, 'dataset', dataset, source.expected_configuration_hash);\n if (dataset.pixel?.integration_id === source.integration_id) { const pixel = await this.rawPixel(scope, dataset.pixel.id);this.verifyIntegrationBinding(dataset, 'pixel', pixel.id, pixel.dataset_id);selected.push({ dataset, integration_id: source.integration_id, kind: 'pixel', id: pixel.id }); }\n else if (dataset.capi_integration?.integration_id === source.integration_id) { const capi = await this.rawCapi(scope, dataset.capi_integration.capi_connection_id);this.verifyIntegrationBinding(dataset, 'capi', capi.capi_connection_id, capi.dataset_id);selected.push({ dataset, integration_id: source.integration_id, kind: 'capi', id: capi.capi_connection_id }); }\n else throw new AdportError('INVALID_INPUT', 'spotify: integration is not present in its approved source dataset');\n }\n const body = { name: input.name, integration_ids: selected.map(s => s.integration_id) };\n return { ...this.review(scope, `Create Spotify dataset \"${input.name}\" from existing integrations`, 'create', body, undefined, [...commonNotes, 'This can reroute existing integrations and affect their measurement. Prefer creating Pixel first and adding CAPI with that dataset_id; native integration regrouping can leave inconsistent source routing, which readback must reject.', 'The new dataset is shared only with the selected ad account.']), execute: async () => {\n let id: string;\n try { id = (await this.client.mutate(`${this.base(scope)}/datasets`, 'POST', body, z.object({ id: spotifyId }))).id; }\n catch (error) { if (error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([]); }\n const receipt = this.bind(scope, 'dataset', id, id);\n try {\n ensure(!selected.some(s => s.dataset.id === id), 'dataset creation returned an existing source ID');\n const actual = await this.rawDataset(scope, id);ensure(actual.name === input.name && selected.every(s => contains(actual, s.integration_id)), 'created dataset membership mismatch');\n const previous = new Map<string, Dataset>();\n for (const source of selected) {\n if (!previous.has(source.dataset.id)) previous.set(source.dataset.id, await this.rawDataset(scope, source.dataset.id));\n ensure(!contains(previous.get(source.dataset.id)!, source.integration_id), 'native regrouping retained the integration in its source dataset');\n if (source.kind === 'pixel') { const resource = await this.rawPixel(scope, source.id);this.verifyIntegrationBinding(actual, 'pixel', resource.id, resource.dataset_id); }\n else { const resource = await this.rawCapi(scope, source.id);this.verifyIntegrationBinding(actual, 'capi', resource.capi_connection_id, resource.dataset_id); }\n }\n await this.shareCreatedDataset(scope, id);\n } catch { return this.uncertain([id], receipt); }\n return this.result([id], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', dataset_id: id });\n } };\n }\n private async planRemove(op: WriteOperation, scope: Scope, proof?: Receipt): Promise<Plan> {\n const input = removeIntegration.parse(op.payload), current = await this.dataset(scope, input.dataset_id, proof);this.exclusive(scope, current);this.expected(scope, 'dataset', current, input.expected_configuration_hash);\n ensure(contains(current, input.integration_id), 'integration is not present in the selected dataset');\n return { ...this.review(scope, 'Remove Spotify dataset integration into a new native dataset', 'remove', { dataset_id: current.id, integration_id: input.integration_id }, undefined, [...commonNotes, 'Native removal creates another dataset for the integration. It does not delete the integration or stop website code. Ads using the old dataset can lose measurement.']), execute: async () => {\n let created: { id: string };\n try { created = await this.client.mutate(`${this.base(scope)}/datasets/${current.id}/integrations/${input.integration_id}`, 'DELETE', undefined, z.object({ id: spotifyId })); }\n catch (error) { if (error instanceof AdportError && /HTTP (400|401|403|404|409|422)\\b/.test(error.message)) throw error;return this.uncertain([current.id]); }\n if (created.id === current.id) return this.uncertain([current.id]);\n const receipt = this.bind(scope, 'dataset', created.id, created.id);\n try {\n const next = await this.rawDataset(scope, created.id), previous = await this.rawDataset(scope, current.id);ensure(contains(next, input.integration_id) && !contains(previous, input.integration_id), 'integration removal readback is inconsistent');\n if (next.pixel?.integration_id === input.integration_id) { const resource = await this.rawPixel(scope, next.pixel.id);this.verifyIntegrationBinding(next, 'pixel', resource.id, resource.dataset_id); }\n if (next.capi_integration?.integration_id === input.integration_id) { const resource = await this.rawCapi(scope, next.capi_integration.capi_connection_id);this.verifyIntegrationBinding(next, 'capi', resource.capi_connection_id, resource.dataset_id); }\n } catch { return this.uncertain([current.id, created.id], receipt); }\n return this.result([current.id, created.id], { resource_receipt: receipt, next_tool: 'spotify_created_measurement', dataset_id: created.id });\n } };\n }\n\n async plan(op: WriteOperation): Promise<Plan> {\n if (capiCredentialWrites.has(op.tool)) return this.credentials.plan(op);\n if (op.tool === 'spotify_create_dataset') for (const source of createDataset.parse(op.payload).sources) this.proof(op.accountId, source.resource_receipt);\n const proof = this.proof(op.accountId, typeof op.payload.resource_receipt === 'string' ? op.payload.resource_receipt : undefined), scope = await this.scope(op.accountId);this.checkProof(scope, proof);\n if (op.tool === 'spotify_create_pixel' || op.tool === 'spotify_create_capi_integration' || op.tool === 'spotify_create_mobile_app') return this.planCreate(op, scope, proof);\n if (op.tool === 'spotify_create_dataset') return this.planDataset(op, scope);\n if (op.tool === 'spotify_remove_dataset_integration') return this.planRemove(op, scope, proof);\n if (op.tool === 'spotify_set_dataset_sharing' || op.tool === 'spotify_set_mobile_app_sharing') return this.planSharing(op, scope, proof);\n return this.planUpdate(op, scope, proof);\n }\n}\n","import { z } from 'zod';\nimport { spotifyId } from './schemas.js';\n\nexport const pixelId = z.string().min(1).max(200).regex(/^[A-Za-z0-9_-]+$/);\nexport const receiptInput = z.string().min(1).max(4096);\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), name = z.string().trim().min(1);\nexport const domain = z.string().url().refine(value => { const u = new URL(value);return ['https:', 'http:'].includes(u.protocol) && !u.username && !u.password; }, 'Use an HTTP(S) URL without credentials');\nexport const aamField = z.enum(['EMAIL', 'PHONE', 'FIRST_NAME', 'LAST_NAME', 'DATE_OF_BIRTH', 'GENDER', 'CITY', 'STATE', 'ZIP', 'COUNTRY', 'EXTERNAL_ID']);\nconst datasetCreation = { dataset_id: spotifyId.optional(), expected_dataset_configuration_hash: hash.optional(), resource_receipt: receiptInput.optional() };\nexport const datasetTarget = { dataset_id: spotifyId, resource_receipt: receiptInput.optional() };\nexport const mobileTarget = { mobile_app_id: spotifyId, resource_receipt: receiptInput.optional() };\nconst pairing = (v: { dataset_id?: string; expected_dataset_configuration_hash?: string }) => Boolean(v.dataset_id) === Boolean(v.expected_dataset_configuration_hash);\nexport const createPixel = z.object({ ...datasetCreation, name, domain, aam_opt_in: z.boolean().default(false), aam_fields: z.array(aamField).max(11).default([]), acknowledge_advanced_matching: z.boolean().optional() }).strict()\n .refine(pairing, 'An existing dataset requires its current configuration hash')\n .refine(v => new Set(v.aam_fields).size === v.aam_fields.length, 'Matching fields must be unique')\n .refine(v => v.aam_opt_in ? v.acknowledge_advanced_matching === true && v.aam_fields.length > 0 : v.aam_fields.length === 0, 'Advanced matching needs explicit acknowledgement and fields; disabled matching has no fields');\nexport const updatePixel = z.object({ ...datasetTarget, expected_configuration_hash: hash, name: name.optional(), domain: domain.optional() }).strict().refine(v => v.name !== undefined || v.domain !== undefined, 'Provide a name or domain');\nexport const createCapi = z.object({ ...datasetCreation, name }).strict().refine(pairing, 'An existing dataset requires its current configuration hash');\nexport const updateCapi = z.object({ ...datasetTarget, expected_configuration_hash: hash, name }).strict();\nexport const createDataset = z.object({ name, sources: z.array(z.object({ dataset_id: spotifyId, integration_id: spotifyId, expected_configuration_hash: hash, resource_receipt: receiptInput.optional() }).strict()).min(1).max(100), acknowledge_measurement_effects: z.literal(true) }).strict().refine(v => new Set(v.sources.map(s => s.integration_id)).size === v.sources.length, 'Integration IDs must be unique');\nexport const updateDataset = z.object({ ...datasetTarget, expected_configuration_hash: hash, name }).strict();\nexport const removeIntegration = z.object({ ...datasetTarget, expected_configuration_hash: hash, integration_id: spotifyId, acknowledge_measurement_effects: z.literal(true) }).strict();\nexport const datasetSharing = z.object({ ...datasetTarget, expected_configuration_hash: hash, shared: z.boolean(), acknowledge_measurement_effects: z.boolean().optional() }).strict().refine(v => v.shared || v.acknowledge_measurement_effects === true, 'Unsharing requires acknowledgement of measurement effects');\nconst mobileFields = { name: z.string().trim().min(2).max(50), platform: z.enum(['IOS', 'ANDROID']).optional(), platform_app_id: z.string().min(2).max(120).optional(), ad_type: z.enum(['VIEW_THROUGH', 'STORE_KIT']).optional(), mobile_measurement_partner: z.enum(['KOCHAVA', 'APPS_FLYER', 'ADJUST', 'BRANCH', 'SINGULAR']).optional() };\nexport const createMobile = z.object(mobileFields).strict();\nexport const updateMobile = z.object({ ...mobileTarget, expected_configuration_hash: hash, ...mobileFields }).strict();\nexport const mobileSharing = z.object({ ...mobileTarget, expected_configuration_hash: hash, shared: z.boolean(), acknowledge_measurement_effects: z.boolean().optional() }).strict().refine(v => v.shared || v.acknowledge_measurement_effects === true, 'Unsharing requires acknowledgement of measurement effects');\n\nconst eventTime = z.object({ event_type: z.string().nullish(), first_event_time: z.string().nullish() });\nexport const pixelSchema = z.object({ id: pixelId, name: z.string().nullish(), domain: z.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), aam_opt_in: z.boolean().nullish(), aam_fields: z.array(aamField).nullish(), cookie_opt_in: z.boolean().nullish(), auto_capture_opt_in: z.boolean().nullish(), auto_capture_fields: z.array(z.string()).nullish(), events_received: z.array(eventTime).nullish() });\nexport const capiSchema = z.object({ capi_connection_id: spotifyId, name: z.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), events_received: z.array(eventTime).nullish() });\nconst shares = z.array(z.object({ id: spotifyId, name: z.string().nullish() })).refine(v => new Set(v.map(s => s.id)).size === v.length, 'Repeated account sharing IDs');\nexport const datasetSchema = z.object({ id: spotifyId, name: z.string().nullish(), pixel: pixelSchema.nullish(), capi_integration: capiSchema.nullish(), shared_ad_accounts: shares.nullish(), ad_set_count: z.number().int().nonnegative().nullish(), is_archived: z.boolean().nullish(), is_receiving_events: z.boolean().nullish(), is_receiving_lead_events: z.boolean().nullish() });\n// Native MobileApp includes link_token. It is deliberately absent from this projection.\nexport const mobileSchema = z.object({ id: spotifyId, name: z.string().nullish(), platform: z.string().nullish(), platform_app_id: z.string().nullish(), ad_type: z.string().nullish(), mobile_measurement_partner: z.string().nullish(), dataset_id: spotifyId.nullish(), integration_id: spotifyId.nullish(), ad_set_count: z.number().int().nonnegative().nullish(), is_skad_network: z.boolean().nullish(), shared_ad_accounts: shares.nullish() });\nexport const paging = z.object({ offset: z.number().int().nonnegative(), total_results: z.number().int().nonnegative(), page_size: z.number().int().nonnegative().nullish() });\nexport const diagnosticSchema = z.object({ dataset_id: spotifyId, datasources: z.array(z.object({ datasource_type: z.enum(['PIXEL', 'CAPI', 'MOBILE_APP']), datasource_id: z.string(), granularity: z.enum(['DAILY', 'HOURLY']), timeseries: z.array(z.object({ total: z.number().nullish(), timestamp: z.number().nullish(), event_counts: z.array(z.object({ name: z.string(), event_count: z.number(), last_activity_ms: z.number().nullish() })).nullish() })) })) });\nexport const createdReceipt = z.object({ version: z.literal(1), purpose: z.enum(['creation', 'sharing']), account_id: spotifyId, business_id: spotifyId, kind: z.enum(['pixel', 'capi', 'mobile_app', 'dataset']), id: pixelId, dataset_id: spotifyId.optional(), issued_at: z.number().int().positive().safe(), expires_at: z.number().int().positive().safe() }).strict().refine(v => v.kind === 'pixel' || spotifyId.safeParse(v.id).success, 'Invalid resource ID');\n","import { createHash } from 'node:crypto';\nimport { AdportError, type ResourceSecretScope, type ResourceSecretStore, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsClient } from './client.js';\nimport { spotifyId } from './schemas.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const capiCredentialTarget = z.object({ dataset_id: spotifyId }).strict();\nconst snapshot = { dataset_id: spotifyId, expected_configuration_hash: hash, expected_dataset_configuration_hash: hash, expected_token_inventory_hash: hash };\nexport const createCapiCredential = z.object({ ...snapshot, acknowledge_credential_access: z.literal(true) }).strict();\nexport const storeCapiCredential = createCapiCredential.extend({ capi_auth_token_id: spotifyId });\nexport const revokeCapiCredential = z.object({ ...snapshot, capi_auth_token_id: spotifyId, acknowledge_ingestion_effects: z.literal(true) }).strict();\nexport const capiCredentialWrites = new Set(['spotify_create_capi_credential', 'spotify_store_capi_credential', 'spotify_revoke_capi_credential']);\n\n// GET returns secret values too. These private response objects never leave this service.\nconst nativeToken = z.object({ capi_auth_token_id: spotifyId, created_at: z.iso.datetime({ offset: true }).nullish(), capi_auth_token: z.string().min(1).max(65536).optional() });\nconst tokenList = z.object({ data: z.array(nativeToken).max(1000), paging: z.unknown().optional() }).refine(v => v.paging == null && new Set(v.data.map(t => t.capi_auth_token_id)).size === v.data.length, 'Invalid native credential inventory');\nconst createdToken = z.object({ data: nativeToken.extend({ capi_auth_token: z.string().min(1).max(65536) }) });\ntype NativeToken = z.infer<typeof nativeToken>;\nexport interface AuthorizedCapiCredentialScope {\n account_id: string;\n business_id: string;\n dataset_id: string;\n capi_connection_id: string;\n configuration_hash: string;\n dataset_configuration_hash: string;\n}\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<WriteResult> }\nconst notes = ['CAPI credentials grant ongoing event-ingestion access to this integration. The native endpoint provides no configurable expiry. No token value is returned to agents, widgets or audit logs.', 'No conversion events, tracking installation, ad delivery or budget changes. Native failures are never replayed automatically.'];\nconst previewNotes = ['Local preview only; Spotify has no native validation endpoint for credentials.', ...notes];\n\nexport class SpotifyCapiCredentials {\n constructor(private readonly client: SpotifyAdsClient, private readonly authorize: (input: { account_id: string; dataset_id: string }) => Promise<AuthorizedCapiCredentialScope>, private readonly secrets?: ResourceSecretStore) {}\n private path(scope: AuthorizedCapiCredentialScope) { return `businesses/${scope.business_id}/capi/${scope.capi_connection_id}/tokens`; }\n private key(scope: AuthorizedCapiCredentialScope, id: string): ResourceSecretScope { return { provider: 'spotify', accountId: scope.account_id, businessId: scope.business_id, resourceId: scope.capi_connection_id, credentialId: id }; }\n private metadata(tokens: NativeToken[]) { return tokens.map(t => ({ capi_auth_token_id: t.capi_auth_token_id, created_at: t.created_at ?? null })).sort((a, b) => a.capi_auth_token_id.localeCompare(b.capi_auth_token_id)); }\n private inventoryHash(scope: AuthorizedCapiCredentialScope, tokens: NativeToken[]) { return createHash('sha256').update(JSON.stringify({ ...scope, tokens: this.metadata(tokens) })).digest('hex'); }\n private async safe<T>(call: () => Promise<T>, operation: string): Promise<T> {\n try { return await call(); }\n catch (error) {\n const status = error instanceof AdportError && error.details && typeof error.details === 'object' && 'http_status' in error.details ? error.details.http_status : undefined;\n // Native errors may echo a CAPI secret that is unrelated to the OAuth token redactor.\n throw new AdportError('PROVIDER_ERROR', `spotify: CAPI credential ${operation} failed; inspect credential metadata before any new mutation. No request was replayed.`, typeof status === 'number' ? { http_status: status } : undefined);\n }\n }\n private async tokens(scope: AuthorizedCapiCredentialScope) { return (await this.safe(() => this.client.get(this.path(scope), tokenList), 'inventory read')).data; }\n private vault() { if (!this.secrets) throw new AdportError('INVALID_INPUT', 'spotify: a private resource credential store must be configured before managing CAPI credentials.');return this.secrets; }\n async list(input: { account_id: string; dataset_id: string }) {\n const scope = await this.authorize(input), tokens = await this.tokens(scope);\n return { ...scope, credential_inventory_hash: this.inventoryHash(scope, tokens), vault_configured: !!this.secrets,\n credentials: await Promise.all(this.metadata(tokens).map(async token => ({ ...token, stored_in_adport: this.secrets ? await this.safe(() => this.secrets!.has(this.key(scope, token.capi_auth_token_id)), 'storage metadata read') : null }))), notes };\n }\n private uncertain(scope: AuthorizedCapiCredentialScope, id: string | undefined, before: NativeToken[], operation: string): never {\n throw new AdportError('PROVIDER_ERROR', `spotify: CAPI credential ${operation} is unconfirmed. Do not repeat it; read spotify_capi_credentials and reconcile the selected credential.`, { business_id: scope.business_id, dataset_id: scope.dataset_id, capi_connection_id: scope.capi_connection_id, ...(id ? { capi_auth_token_id: id, resource_ids: [id] } : {}), previous_credential_ids: this.metadata(before).map(t => t.capi_auth_token_id) });\n }\n private async save(scope: AuthorizedCapiCredentialScope, token: NativeToken & { capi_auth_token: string }) {\n const store = this.vault(), key = this.key(scope, token.capi_auth_token_id);\n await store.putIfAbsent(key, token.capi_auth_token);\n if (await store.get(key) !== token.capi_auth_token) throw new Error('Stored credential does not match native credential.');\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const creating = op.tool === 'spotify_create_capi_credential', storing = op.tool === 'spotify_store_capi_credential';\n if (!capiCredentialWrites.has(op.tool)) throw new AdportError('UNKNOWN_TOOL', 'spotify: unknown CAPI credential mutation');\n const input = creating ? createCapiCredential.parse(op.payload) : storing ? storeCapiCredential.parse(op.payload) : revokeCapiCredential.parse(op.payload);\n const vault = this.vault(), scope = await this.authorize({ account_id: op.accountId, dataset_id: input.dataset_id }), before = await this.tokens(scope);\n if (scope.configuration_hash !== input.expected_configuration_hash || scope.dataset_configuration_hash !== input.expected_dataset_configuration_hash || this.inventoryHash(scope, before) !== input.expected_token_inventory_hash) throw new AdportError('PENDING_MISMATCH', 'spotify: CAPI configuration, sharing or credential inventory changed; read spotify_capi_credentials for a new preview.');\n const id = 'capi_auth_token_id' in input ? input.capi_auth_token_id : undefined;\n const selected = before.find(t => t.capi_auth_token_id === id);\n const stored = id ? await this.safe(() => vault.has(this.key(scope, id)), 'storage metadata read') : false;\n if (storing && !selected?.capi_auth_token) throw new AdportError('INVALID_INPUT', 'spotify: the selected active credential has no available native secret to store.');\n if (!creating && !selected && !stored) throw new AdportError('INVALID_INPUT', 'spotify: the selected credential is neither active in this integration nor stored in this Adport scope.');\n const title = creating ? 'Create CAPI credential' : storing ? 'Store existing CAPI credential' : selected ? 'Revoke CAPI credential' : 'Remove inactive CAPI credential copy';\n return { summary: `${title} for Spotify integration ${scope.capi_connection_id}`, changes: [creating ? '+ One native long-lived credential, saved privately in Adport.' : storing ? `+ Store only the selected active credential ${id}; do not create a native token.` : selected ? `- Revoke native credential ${id} and remove its Adport copy after confirmed native revocation.` : `- Remove only the private Adport copy of inactive credential ${id}; no native deletion request.`, 'No events are sent.'], coercions: [], budgetDeltas: [], notes: previewNotes,\n review: { provider: 'spotify', accountId: scope.account_id, kind: creating || storing ? 'create' : 'remove', title, fields: [{ label: 'Dataset', after: scope.dataset_id }, { label: 'CAPI integration', after: scope.capi_connection_id }, ...(id ? [{ label: 'Credential', after: id }, { label: 'Stored in Adport', before: stored, after: storing }] : []), { label: 'Active credentials', before: before.length, after: before.length + (creating ? 1 : !storing && selected ? -1 : 0) }], notices: previewNotes },\n execute: async () => {\n let createdId: string | undefined, nativeAcknowledged = false;\n try {\n if (creating) {\n const token = (await this.safe(() => this.client.mutate(this.path(scope), 'POST', undefined, createdToken), 'creation')).data;\n nativeAcknowledged = true;\n createdId = token.capi_auth_token_id;\n if (before.some(t => t.capi_auth_token_id === createdId)) throw new Error('Creation returned an existing credential ID.');\n await this.save(scope, token);\n const after = await this.tokens(scope);\n const actual = after.find(t => t.capi_auth_token_id === createdId);\n if (!actual || actual.capi_auth_token !== undefined && actual.capi_auth_token !== token.capi_auth_token) throw new Error('Credential readback mismatch.');\n return { applied: true, resourceIds: [createdId], details: { capi_auth_token_id: createdId, stored_in_adport: true, created_at: token.created_at ?? null, next_tool: 'spotify_capi_credentials' } };\n }\n if (storing) {\n await this.save(scope, selected as NativeToken & { capi_auth_token: string });\n return { applied: true, resourceIds: [id!], details: { capi_auth_token_id: id, stored_in_adport: true, native_credential_created: false } };\n }\n if (selected) { await this.safe(() => this.client.mutate(`${this.path(scope)}/${id}`, 'DELETE', undefined, z.undefined()), 'revocation');nativeAcknowledged = true; }\n if ((await this.tokens(scope)).some(t => t.capi_auth_token_id === id)) throw new Error('Credential remains active.');\n await vault.delete(this.key(scope, id!));\n return { applied: true, resourceIds: [id!], details: { capi_auth_token_id: id, native_active: false, stored_in_adport: false } };\n } catch (error) {\n // No raw native response, secret value, storage exception or stack is exposed.\n if (!nativeAcknowledged && error instanceof AdportError && error.details && typeof error.details === 'object' && 'http_status' in error.details && [400, 401, 403, 404, 409, 422].includes(Number(error.details.http_status))) throw error;\n return this.uncertain(scope, createdId ?? id, before, creating ? 'creation/storage' : storing ? 'storage' : 'revocation/cleanup');\n }\n } };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport { spotifyId } from './schemas.js';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { createCapi, createDataset, createMobile, createPixel, datasetSharing, datasetTarget, mobileSharing, mobileTarget, receiptInput, removeIntegration, updateCapi, updateDataset, updateMobile, updatePixel } from './measurement-schemas.js';\nimport { capiCredentialTarget, capiCredentialWrites, createCapiCredential, revokeCapiCredential, storeCapiCredential } from './capi-credentials.js';\n\nexport const measurementWriteNames = new Set([...capiCredentialWrites, 'spotify_create_pixel', 'spotify_update_pixel', 'spotify_create_capi_integration', 'spotify_update_capi_integration', 'spotify_create_dataset', 'spotify_update_dataset', 'spotify_remove_dataset_integration', 'spotify_set_dataset_sharing', 'spotify_create_mobile_app', 'spotify_update_mobile_app', 'spotify_set_mobile_app_sharing']);\nexport function spotifyMeasurementTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'measurement', exposure: 'specialist' } as const;\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: 'spotify', description, input, catalog, presentation: 'records', annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove', destructive = false) => guardedWriteTool({ name, namespace: 'spotify', provider: 'spotify', description, payload, catalog, kind, destructive });\n const account = { account_id: spotifyId }, dataset = z.object({ ...account, ...datasetTarget });\n return [\n read('spotify_capi_credentials', 'List active CAPI credential IDs, creation times and private storage status for an integration shared only with this selected account. Returns snapshot hashes for mutations; never returns token values or sends events.', capiCredentialTarget.extend(account), v => provider.measurement.credentials.list(v)),\n write('spotify_create_capi_credential', 'Create one long-lived CAPI credential and store it privately in Adport. Requires current hashes from spotify_capi_credentials and explicit access acknowledgement. No secret is returned; no events are sent. Never repeat an unconfirmed creation.', createCapiCredential, 'create'),\n write('spotify_store_capi_credential', 'Store one selected active native CAPI credential privately in Adport without creating another token. Requires fresh credential/context hashes and explicit access acknowledgement. The token is fetched server-side and never returned.', storeCapiCredential, 'create'),\n write('spotify_revoke_capi_credential', 'Revoke one selected CAPI credential and remove its Adport copy after native confirmation. May stop existing event publishers. Fresh hashes and explicit acknowledgement required. Also reconciles a stored copy when native revocation already completed. No automatic native retries.', revokeCapiCredential, 'remove', true),\n read('spotify_measurement_context', 'Read the selected account’s verified business and shared dataset topology. Read an individual resource before a mutation to obtain its full configuration_hash. Other account identities and business-wide inventory are excluded; no tracking or credentials are created.', z.object(account), v => provider.measurement.context(v.account_id)),\n read('spotify_datasets', 'List only datasets shared with this account. The native endpoint has no limit/offset query; returns explicit completeness rather than inventing pagination.', z.object(account), v => provider.measurement.datasets(v.account_id)),\n read('spotify_get_dataset', 'Read one shared dataset and its configuration_hash. An unshared approved creation requires its signed resource_receipt. Other account identities are omitted.', dataset, v => provider.measurement.getDataset(v)),\n read('spotify_get_pixel', 'Read the Pixel bound to an authorized dataset, including matching settings and configuration_hash. Native Pixel IDs alone do not authorize business-wide reads.', dataset, v => provider.measurement.getPixel(v)),\n read('spotify_get_capi_integration', 'Read a CAPI connection bound to an authorized dataset. Returns configuration_hash and metadata only, never active credentials.', dataset, v => provider.measurement.getCapi(v)),\n read('spotify_mobile_apps', 'Read mobile measurement apps shared with this account using native pagination. Link tokens and other account identities are omitted.', z.object({ ...account, limit: z.number().int().positive().max(50).default(50), offset: z.number().int().nonnegative().default(0) }), v => provider.measurement.mobileApps(v)),\n read('spotify_get_mobile_app', 'Read one account-shared or approved-created mobile app with its configuration_hash. Native MMP link tokens are omitted.', z.object({ ...account, ...mobileTarget }), v => provider.measurement.getMobile(v)),\n read('spotify_dataset_diagnostics', 'Read native DAILY/HOURLY source activity for an authorized dataset. Diagnostics can lag 20 minutes; activity does not prove campaign attribution. Sends no conversion events.', z.object({ ...account, ...datasetTarget, granularities: z.array(z.enum(['DAILY', 'HOURLY'])).min(1).max(2).refine(v => new Set(v).size === v.length, 'Granularities must be unique').default(['DAILY']), datasource_ids: z.array(z.string().min(1)).min(1).max(100).optional() }), v => provider.measurement.diagnostics(v)),\n read('spotify_created_measurement', 'Reconcile the exact created resource and receipt-bound parent with current account/business access. A missing child binding requires the locked parent to independently name this exact resource. Explicit conflicts never follow another parent. Read-only; never replays a write.', z.object({ ...account, resource_receipt: receiptInput }), v => provider.measurement.created(v)),\n read('spotify_measurement_sharing_status', 'Reconcile sharing with the signed receipt from an approved share/unshare operation. Returns only selected-account sharing state; a status receipt does not grant content access after unsharing.', z.object({ ...account, resource_receipt: receiptInput }), v => provider.measurement.sharingStatus(v)),\n write('spotify_create_pixel', 'Create a Pixel and verify its native dataset, then share only with the selected account. AAM defaults off; opt-in requires explicit acknowledgement. Supports existing dataset_id with its current hash. No website install or event sending.', createPixel, 'create'),\n write('spotify_update_pixel', 'Replace the supplied name or domain on an account-owned Pixel using its current configuration_hash. Preserves matching, routing and other settings. Rejects stale or shared configuration and verifies the result by readback.', updatePixel, 'update', true),\n write('spotify_create_capi_integration', 'Create a CAPI connection in a new or verified existing dataset, then verify sharing with the selected account. Does not issue tokens or send events. Returns a signed receipt for partial creation recovery; never retries automatically.', createCapi, 'create'),\n write('spotify_update_capi_integration', 'Replace the name of an authorized CAPI connection using its current configuration_hash. Preserves dataset routing, credentials and events. Verifies the result by readback.', updateCapi, 'update', true),\n write('spotify_create_dataset', 'Create a dataset from explicit account-owned integrations and source snapshots, acknowledging measurement rerouting. Independently checks each native integration’s new dataset binding and selected-account sharing. Prefer Pixel-first plus CAPI dataset_id for a shared topology.', createDataset, 'create', true),\n write('spotify_update_dataset', 'Replace the name of an authorized dataset using its current configuration_hash. Preserves sources and sharing. Rejects edits when another account shares the dataset or dependencies are unknown.', updateDataset, 'update', true),\n write('spotify_remove_dataset_integration', 'Remove one verified integration from a dataset. Spotify moves it to a newly created dataset; this does not delete the source or remove website code. Requires current snapshot and explicit acknowledgement; returns signed recovery context.', removeIntegration, 'remove', true),\n write('spotify_set_dataset_sharing', 'Share/unshare a verified dataset only with the selected account, preserving all other shares. Requires current configuration_hash; unsharing needs measurement-effect acknowledgement. An unshared creation requires its receipt. Native readback and signed status reconciliation prevent unsafe replay.', datasetSharing, 'update', true),\n write('spotify_create_mobile_app', 'Register native mobile measurement metadata and share the new app only with this account. Supports current MMP enums including SINGULAR. Does not install a partner SDK; link tokens are not returned.', createMobile, 'create'),\n write('spotify_update_mobile_app', 'Replace the name and supplied attribution settings of an account-owned mobile app using its current configuration_hash. Preserves omitted fields and verifies the result by readback. Link tokens stay private and unchanged.', updateMobile, 'update', true),\n write('spotify_set_mobile_app_sharing', 'Share/unshare only this account’s mobile-app association using the current hash. Unsharing needs explicit measurement-effect acknowledgement; other shares are preserved and the result is independently verified.', mobileSharing, 'update', true),\n ];\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { createDraftSchema, setBudgetSchema, setDeliverySchema, setStatusSchema, spotifyId } from './schemas.js';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { spotifyCreativeTools } from './creative-tools.js';\nimport { spotifyManagementTools } from './management-tools.js';\nimport { spotifyMeasurementTools } from './measurement-tools.js';\n\nexport function spotifyTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\n return [\n ...spotifyCreativeTools(provider),\n ...spotifyManagementTools(provider),\n ...spotifyMeasurementTools(provider),\n defineTool({ name: 'spotify_list_campaigns', namespace: 'spotify', description: 'List published Spotify Ads campaigns in the selected account.',\n input: z.object({ account_id: spotifyId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'spotify_get_ad_set', namespace: 'spotify', description: 'Read a Spotify ad set, including its budget and delivery setting.',\n input: z.object({ account_id: spotifyId, ad_set_id: spotifyId }), annotations: { readOnly: true }, handler: input => provider.getAdSet(input.account_id, input.ad_set_id) }),\n guardedWriteTool({ name: 'spotify_create_campaign_draft', namespace: 'spotify', provider: 'spotify', kind: 'create',\n description: 'Create an unpublished Spotify campaign draft, paused by policy. Does not publish or launch ads. Preview is local.', payload: createDraftSchema }),\n guardedWriteTool({ name: 'spotify_set_campaign_status', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Pause or activate an existing Spotify Ads campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'spotify_set_budget', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Change a Spotify ad-set budget in integer micros, preserving its current DAILY or LIFETIME type.', payload: setBudgetSchema }),\n guardedWriteTool({ name: 'spotify_set_ad_set_delivery', namespace: 'spotify', provider: 'spotify', kind: 'update',\n description: 'Turn an existing Spotify ad set delivery OFF or ON.', payload: setDeliverySchema }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { SpotifyAdsProvider } from './provider.js';\nimport { assetFormat, assetType, bidStrategy, createAd, createAsset, createGroup, deliveryGoal, draftEntity, draftMutation, frequencyCaps, publishDraft, targets, updateAd, updateCampaign, updateGroup, uploadAsset } from './creative-schemas.js';\nimport { budgetSchema, spotifyId } from './schemas.js';\n\nconst page = { limit: z.number().int().positive().max(50).default(50), offset: z.number().int().nonnegative().default(0) };\nconst account = { account_id: spotifyId };\nconst strings = z.array(z.string().min(1)).min(1).max(1000);\nconst estimate = { asset_format: assetFormat, bid_strategy: bidStrategy, targets: targets.refine(v => Boolean(v.placements?.length), 'Estimates require placements'), delivery_goal: deliveryGoal.optional(), frequency_caps: frequencyCaps.optional(), category: z.string().regex(/^ADV_\\d+_\\d+$/).optional() };\n\nexport function spotifyCreativeTools(provider: SpotifyAdsProvider): AnyToolDefinition[] {\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: 'spotify', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove' = 'update') => guardedWriteTool({ name, namespace: 'spotify', provider: 'spotify', description, payload, kind });\n return [\n read('spotify_drafts', 'List unpublished campaign, ad-set or ad drafts, with native pagination and hierarchy versions. This does not publish.', z.object({ ...account, entity: draftEntity, campaign_ids: z.array(spotifyId).optional(), ad_set_ids: z.array(spotifyId).optional(), ...page }).refine(v => !(v.campaign_ids && v.entity !== 'ad_sets') && !(v.ad_set_ids && v.entity !== 'ads'), 'Use campaign_ids for ad_sets or ad_set_ids for ads'), input => provider.creatives.drafts(input)),\n read('spotify_get_draft', 'Read an account-owned draft and verify its parent hierarchy. Use the campaign draft version for validation/publication.', z.object({ ...account, entity: draftEntity, draft_id: spotifyId }), input => provider.creatives.get(input.account_id, input.entity, input.draft_id)),\n read('spotify_ad_sets', 'Read published ad-set targeting, bidding, budgets and delivery, with pagination.', z.object({ ...account, campaign_ids: z.array(spotifyId).optional(), ...page }), input => provider.creatives.page(input, 'ad_sets', 'ad_sets', { campaign_ids: input.campaign_ids })),\n defineTool({ name: 'spotify_ads', namespace: 'spotify', description: 'View published or draft ad copy and image/video/audio assets. Drafts include guarded copy-edit actions; publication remains separate.', input: z.object({ ...account, draft: z.boolean().default(false), ad_set_ids: z.array(spotifyId).optional(), ...page }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'offset', cursorOutput: 'next_offset' }, annotations: { readOnly: true }, handler: input => provider.creatives.ads(input) }),\n defineTool({ name: 'spotify_assets', namespace: 'spotify', description: 'View Spotify account image/video/audio assets and processing status with pagination.', input: z.object({ ...account, asset_types: z.array(assetType).optional(), asset_statuses: z.array(z.enum(['ERROR', 'PROCESSING', 'READY', 'WAITING_UPLOAD'])).optional(), name: z.string().optional(), ...page }), output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'offset', cursorOutput: 'next_offset' }, annotations: { readOnly: true }, handler: input => provider.creatives.assets(input) }),\n read('spotify_get_asset', 'Read an account-owned asset and processing status. No ad delivery changes.', z.object({ ...account, asset_id: spotifyId }), input => provider.creatives.asset(input.account_id, input.asset_id)),\n read('spotify_ad_categories', 'Search Spotify’s live advertiser-category codes for draft ad sets.', z.object({ ...account, q: z.string().optional() }), input => provider.creatives.categories(input.q)),\n read('spotify_targeting_options', 'Search native Spotify artist, genre, interest, language, playlist or podcast topic targeting.', z.object({ ...account, kind: z.enum(['artists', 'genres', 'interests', 'languages', 'playlists', 'episode_topics', 'sensitive_topics']), ids: strings.optional(), q: z.string().optional() }), input => provider.creatives.targeting(input)),\n read('spotify_geo_targets', 'Search native geographical targeting IDs with country/type filters and pagination.', z.object({ ...account, country_code: z.string().regex(/^[A-Z]{2}$/).optional(), ids: strings.optional(), types: strings.optional(), q: z.string().optional(), language: z.string().regex(/^[a-z]{2}$/).optional(), limit: z.number().int().positive().max(1000).default(50), offset: z.number().int().nonnegative().default(0) }), input => provider.creatives.targeting({ ...input, kind: 'geos' })),\n read('spotify_audience_estimate', 'Get a non-binding audience/delivery estimate using a read-only POST. Native micro amounts and explicit placements are required; no audience or ad is created.', z.object({ ...account, ...estimate, start_date: z.iso.datetime(), end_date: z.iso.datetime().optional(), bid_micro_amount: z.number().int().nonnegative().safe(), budget: budgetSchema.extend({ currency: z.string().regex(/^[A-Z]{3}$/) }) }).refine(v => !v.end_date || v.end_date > v.start_date, 'End date must follow start date'), input => provider.creatives.estimate('audience', input)),\n read('spotify_bid_estimate', 'Get a non-binding native bid estimate with explicit targeting/placements. No bids or delivery settings are changed.', z.object({ ...account, ...estimate, currency: z.string().regex(/^[A-Z]{3}$/) }), input => provider.creatives.estimate('bid', input)),\n read('spotify_validate_draft', 'Validate a specific campaign draft hierarchy version server-side without publishing. Returns native validation errors.', z.object({ ...account, ...publishDraft.shape }), input => provider.creatives.validate(input.account_id, input.draft_campaign_id, input.draft_hierarchy_version)),\n write('spotify_create_draft_ad_set', 'Stage an unpublished ad set under a verified draft campaign. Monetary values are integer micros. Partial drafts are allowed; targeting requires placements and lifetime budgets require end_time.', createGroup, 'create'),\n write('spotify_create_draft_ad', 'Stage unpublished ad copy and existing account-owned asset IDs under a verified draft ad set. Does not publish or enable delivery.', createAd, 'create'),\n write('spotify_update_draft_campaign', 'Patch only supplied draft campaign fields. Publication is separate; status changes here affect only the draft.', updateCampaign),\n write('spotify_update_draft_ad_set', 'Patch draft ad-set targeting, schedule, budget or bids. Preserves omitted nested targeting; arrays replace supplied dimensions. Amounts use micros.', updateGroup),\n write('spotify_update_draft_ad', 'Patch unpublished ad copy/assets/CTA. Omitted assets and CTA fields are preserved; supplied tracking arrays replace the full array.', updateAd),\n write('spotify_create_draft_from_published', 'Stage a copy of an account-owned published campaign/ad set/ad without changing delivery. Refuses to overwrite an existing draft.', draftMutation, 'create'),\n write('spotify_delete_draft', 'Delete only an unpublished draft. Delete child ad drafts first: parent deletion is refused while ads remain to prevent provider orphan records. Published entities remain unchanged.', draftMutation, 'remove'),\n ...(['ads', 'ad_sets'] as const).map(entity => write(`spotify_delete_draft_${entity}`, 'Atomically delete account-owned drafts through the native batch endpoint. Delete child ads before ad sets to prevent provider orphan records. Published entities remain unchanged.', z.object({ draft_ids: z.array(spotifyId).min(1).max(entity === 'ads' ? 100 : 40).refine(ids => new Set(ids).size === ids.length, 'IDs must be unique') }), 'remove')),\n write('spotify_publish_draft', 'Spotify publishes ACTIVE even from a PAUSED draft. Blocked while paused_creation policy is enabled. Otherwise requires explicit acknowledge_active_publication=true, exact hierarchy version, budget checks and server validation.', publishDraft, 'create'),\n write('spotify_create_asset', 'Create account-owned asset metadata for a later checksum-bound upload. No creative is attached to an ad.', createAsset, 'create'),\n write('spotify_upload_asset', 'Upload SHA-256-approved image/video/audio to a new WAITING_UPLOAD asset. Uses native chunking above20MB; Adport cap100MiB, hosted staging50MiB. Existing assets cannot be overwritten.', uploadAsset, 'create'),\n write('spotify_rename_asset', 'Rename account-owned asset metadata without replacing media or changing delivery.', z.object({ asset_id: spotifyId, name: z.string().trim().min(2).max(120) })),\n ];\n}\n"],"mappings":";AAAA,SAAS,+BAA0E;;;ACAnF,SAAS,mBAAmB;AAC5B,SAAS,YAAY,uBAAuB;AAC5C,SAAS,SAAS;AAEX,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAOjC,IAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAAG,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EACjE,eAAe,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAC5C,CAAC;AAEM,SAAS,oBAAoB,UAAkB,aAAqB,OAAuB;AAEhG,SAAO,2CAA2C,IAAI,gBAAgB;AAAA,IACpE,WAAW;AAAA,IAAU,eAAe;AAAA,IAAQ,cAAc;AAAA,IAAa;AAAA,EACzE,CAAC,CAAC;AACJ;AAEA,eAAe,aAAa,aAAoE,MAAuB,WAAyB;AAC9I,QAAM,WAAW,MAAM,UAAU,mBAAmB;AAAA,IAClD,QAAQ;AAAA,IAAQ,SAAS;AAAA,MACvB,eAAe,SAAS,OAAO,KAAK,GAAG,YAAY,QAAQ,IAAI,YAAY,YAAY,EAAE,EAAE,SAAS,QAAQ,CAAC;AAAA,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,cAAc,MAAM,0BAA0B,KAAK;AACzD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,mBAAmB,IAAI,iBAAiB,WAAW,GAAG,QAAW,EAAE,iBAAiB,IAAI,wBAAwB,EAAE,CAAC;AACxI,SAAO,EAAE,UAAU,OAAO,aAAa,QAAQ,EAAE;AACnD;","names":["params","url","parsed","z","AdportError","AdportError","z","z","z","z","z","account","params","AdportError","page","ids","url","name","AdportError","z","z","z","name","description","object","z","query","params","account","AdportError","createHash","AdportError","z","z","z","paging","AdportError","z","hash","z","AdportError","createHash","AdportError","account","z","snapshot","paging","page","hash","ids","defineTool","guardedWriteTool","z","name","description","defineTool","guardedWriteTool","account","z","z","account","page","AdportError","query","params","z","defineTool","guardedWriteTool","defineTool","guardedWriteTool","z","page","z","account","strings","name","description","defineTool","guardedWriteTool","ids","defineTool","z","guardedWriteTool"]}