@adport/provider-x 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2500 -6
- package/dist/index.js +3088 -101
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client.ts","../src/entities.ts","../src/schemas.ts","../src/provider.ts","../src/analytics.ts","../src/writes.ts","../src/tools.ts","../src/oauth.ts","../src/index.ts"],"sourcesContent":["import { createHmac, randomBytes } from 'node:crypto';\nimport OAuth from 'oauth-1.0a';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\n\nexport const X_ADS_API_BASE = 'https://ads-api.x.com/12/';\nexport interface XAdsCredentials {\n consumerKey: string;\n consumerSecret: string;\n accessToken: string;\n accessTokenSecret: string;\n}\nexport type XParams = Record<string, string | number | boolean>;\nexport type XMethod = 'GET' | 'POST' | 'PUT';\n\nexport function createXSigner(credentials: Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>): OAuth {\n const oauth = new OAuth({\n consumer: { key: credentials.consumerKey, secret: credentials.consumerSecret },\n signature_method: 'HMAC-SHA1',\n hash_function: (base, key) => createHmac('sha1', key).update(base).digest('base64'),\n });\n // The library's default nonce uses Math.random. Use cryptographic entropy.\n oauth.getNonce = () => randomBytes(24).toString('hex');\n return oauth;\n}\n\nexport class XAdsClient {\n private readonly signer: OAuth;\n private readonly token: OAuth.Token;\n constructor(credentials: XAdsCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n if (Object.values(credentials).some(value => typeof value !== 'string' || !value.trim()) ||\n !credentials.consumerKey || !credentials.consumerSecret || !credentials.accessToken || !credentials.accessTokenSecret) {\n throw new AdportError('INVALID_INPUT', 'x: all four OAuth 1.0a credentials are required');\n }\n this.signer = createXSigner(credentials);\n this.token = { key: credentials.accessToken, secret: credentials.accessTokenSecret };\n }\n\n async request<T>(method: XMethod, path: string, schema: z.ZodType<T>, params: XParams = {}): Promise<T> {\n if (!/^[a-z0-9_]+(?:\\/[a-z0-9_]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'x: invalid API resource path');\n const url = new URL(path, X_ADS_API_BASE);\n for (const [key, value] of Object.entries(params)) {\n if (!/^[a-z][a-z0-9_]*$/.test(key) || key.startsWith('oauth_') || (typeof value === 'number' && !Number.isFinite(value))) {\n throw new AdportError('INVALID_INPUT', 'x: invalid API parameter');\n }\n url.searchParams.set(key, String(value));\n }\n // oauth-1.0a decodes percent escapes but not form-style '+' spaces.\n // Serialize spaces as %20 so the signed values match X's query parser.\n url.search = url.search.replace(/\\+/g, '%20');\n // X's endpoint reference specifies query parameters for POST and PUT too.\n // Sign the final encoded URL, and send exactly that URL without a JSON body.\n const headers = this.signer.toHeader(this.signer.authorize({ url: url.href, method }, this.token));\n let response: Response;\n try {\n response = await this.fetchImpl(url.href, { method, headers: { ...headers, accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(30_000) });\n } catch {\n throw new AdportError('PROVIDER_ERROR', `x: transport failed${method === 'GET' ? '' : '; write outcome unknown, inspect the account before retrying'}`);\n }\n if (!response.ok) {\n const guidance = response.status === 403 ? 'Check Ads API app approval and this user’s ad-account permissions; reconnecting alone may not help.'\n : response.status === 401 ? 'Check OAuth 1.0a credentials, token permissions and the local clock. Regenerate user tokens after Ads API approval.'\n : response.status === 429 ? 'Rate limit reached; wait for the provider reset before retrying.' : 'Provider request failed.';\n throw new AdportError('PROVIDER_ERROR', `x: HTTP ${response.status}. ${guidance}${method === 'GET' ? '' : ' The write was not retried.'}`);\n }\n let body: unknown;\n try { body = await response.json(); } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid JSON response'); }\n if (body && typeof body === 'object' && 'errors' in body && Array.isArray(body.errors) && body.errors.length) {\n throw new AdportError('PROVIDER_ERROR', 'x: provider returned an error envelope');\n }\n const parsed = schema.safeParse(body);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'x: unexpected API response schema');\n return parsed.data;\n }\n\n async list<T extends { id: string }>(path: string, item: z.ZodType<T>, params: XParams = {}): Promise<T[]> {\n const schema = z.object({ data: z.array(item), next_cursor: z.string().nullable().optional() });\n const rows: T[] = [], ids = new Set<string>(), cursors = new Set<string>();\n let cursor: string | undefined;\n while (true) {\n const page = await this.request('GET', path, schema, { ...params, count: 200, ...(cursor ? { cursor } : {}) });\n for (const row of page.data) {\n if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: pagination repeated an entity');\n ids.add(row.id); rows.push(row);\n }\n if (!page.next_cursor) return rows;\n if (cursors.has(page.next_cursor) || cursors.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'x: cursor pagination did not terminate');\n cursors.add(page.next_cursor); cursor = page.next_cursor;\n }\n }\n}\n","import { z } from 'zod';\nimport { AdportError, type Account } from '@adport/core';\nimport { XAdsClient } from './client.js';\nimport { accountSchema, campaignSchema, fundingSchema, lineItemSchema, mediaCreativeSchema, promotedAccountSchema, promotedTweetSchema, xId } from './schemas.js';\n\nexport class XAdsEntities {\n constructor(readonly client: XAdsClient) {}\n async listAccounts(): Promise<Account[]> {\n // X's account response has no currency. It belongs to funding instruments\n // and campaigns; never infer USD or invent account currency here.\n return (await this.client.list('accounts', accountSchema)).map(a => ({ provider: 'x', id: a.id, name: a.name, status: a.approval_status }));\n }\n async getAccount(accountId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}`, z.object({ data: accountSchema }));\n if (data.id !== accountId) throw new AdportError('PROVIDER_ERROR', 'x: account ID mismatch');\n return data;\n }\n listCampaigns(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/campaigns`, campaignSchema, { with_deleted: true, with_draft: true });\n }\n async getCampaign(accountId: string, campaignId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/campaigns/${xId.parse(campaignId)}`, z.object({ data: campaignSchema }));\n if (data.id !== campaignId) throw new AdportError('PROVIDER_ERROR', 'x: campaign ID mismatch');\n return data;\n }\n async listFundingInstruments(accountId: string) {\n const data = await this.client.list(`accounts/${xId.parse(accountId)}/funding_instruments`, fundingSchema);\n if (data.some(f => f.account_id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'x: funding instrument account mismatch');\n return data;\n }\n async getFundingInstrument(accountId: string, fundingId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/funding_instruments/${xId.parse(fundingId)}`, z.object({ data: fundingSchema }));\n if (data.id !== fundingId || data.account_id !== accountId) throw new AdportError('PROVIDER_ERROR', 'x: funding instrument account/ID mismatch');\n return data;\n }\n listLineItems(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true });\n }\n listPromotedTweets(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/promoted_tweets`, promotedTweetSchema, { with_deleted: true });\n }\n listPromotedAccounts(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/promoted_accounts`, promotedAccountSchema, { with_deleted: true });\n }\n listMediaCreatives(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/media_creatives`, mediaCreativeSchema, { with_deleted: true });\n }\n}\n","import { z } from 'zod';\n\nexport const xId = z.string().regex(/^[a-z0-9]+$/).min(1).max(64);\nconst micros = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst currency = z.string().regex(/^[A-Z]{3}$/);\nexport const accountSchema = z.object({\n id: xId, name: z.string(), timezone: z.string(), timezone_switch_at: z.string().nullable().optional(),\n approval_status: z.string(), deleted: z.boolean(),\n});\nexport const fundingSchema = z.object({\n id: xId, account_id: xId, description: z.string(), currency, type: z.string(),\n entity_status: z.string(), able_to_fund: z.boolean(), deleted: z.boolean(),\n});\nexport const campaignSchema = z.object({\n id: xId, name: z.string(), currency, funding_instrument_id: xId, entity_status: z.string(), deleted: z.boolean(),\n budget_optimization: z.string(), daily_budget_amount_local_micro: micros.nullable(), total_budget_amount_local_micro: micros.nullable(),\n});\nexport const lineItemSchema = z.object({\n id: xId, name: z.string(), campaign_id: xId, currency, entity_status: z.string(), deleted: z.boolean(),\n placements: z.array(z.string()), product_type: z.string(), objective: z.string(),\n});\nexport const promotedTweetSchema = z.object({\n id: xId, line_item_id: xId, tweet_id: z.string().regex(/^\\d+$/), entity_status: z.string(), deleted: z.boolean(),\n});\nexport const promotedAccountSchema = z.object({ id: xId, line_item_id: xId, user_id: z.string().regex(/^\\d+$/), entity_status: z.string(), deleted: z.boolean() });\nexport const mediaCreativeSchema = z.object({ id: xId, line_item_id: xId, account_media_id: xId, entity_status: z.string(), deleted: z.boolean() });\nexport const createCampaignSchema = z.object({\n name: z.string().min(1).max(255), funding_instrument_id: xId,\n daily_budget_micros: micros.positive(), total_budget_micros: micros.positive().optional(),\n status: z.enum(['ACTIVE', 'PAUSED']).default('PAUSED'),\n});\nexport const setStatusSchema = z.object({ campaign_id: xId, status: z.enum(['ACTIVE', 'PAUSED']) });\nexport const setBudgetSchema = z.object({ campaign_id: xId, budget_type: z.enum(['DAILY', 'TOTAL']), budget_micros: micros.positive() });\n","import { z } from 'zod';\nimport { AdportError, resolveDateRange, type AdProvider, type MetricName, type NormalizedQuery, type Report, type ReportRow, type StandardActions, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { XAdsClient } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { XAdsAnalytics, X_PLACEMENTS, xAccountMidnight } from './analytics.js';\nimport { planXWrite } from './writes.js';\n\ntype BaseMetric = 'spend' | 'impressions' | 'clicks';\ntype Metrics = Partial<Record<BaseMetric, number>>;\ninterface Entity { id: string; name: string; status: string; currency: string; type: string }\nconst DERIVED = { ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000] } as const;\nconst DAY = 86_400_000;\n\nexport class XAdsProvider extends XAdsEntities implements AdProvider {\n readonly id = 'x';\n private readonly analytics: XAdsAnalytics;\n constructor(client: XAdsClient, analytics?: XAdsAnalytics) { super(client); this.analytics = analytics ?? new XAdsAnalytics(client); }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions { return { pauseCampaign: (accountId, campaignId) => ({ tool: 'x_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) }; }\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await planXWrite(this, op, guard); return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n return { applied: true, resourceIds: await (await planXWrite(this, op, guard)).execute() };\n }\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n z.iso.date().parse(range.start); z.iso.date().parse(range.end);\n if (range.end < range.start) throw new AdportError('INVALID_INPUT', 'x: report end precedes start');\n const needed = new Set<BaseMetric>();\n for (const metric of query.metrics) {\n if (['spend', 'impressions', 'clicks'].includes(metric)) needed.add(metric as BaseMetric);\n else if (metric in DERIVED) for (const dep of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) needed.add(dep as BaseMetric);\n }\n if (!needed.size) throw new AdportError('INVALID_INPUT', 'x: supported normalized metrics are spend, impressions, link clicks, ctr, cpc and cpm; conversion normalization is not yet verified');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'x: report limit must be a positive integer');\n const groups = [...(needed.has('spend') ? ['BILLING'] : []), ...(needed.has('clicks') || needed.has('impressions') ? ['ENGAGEMENT'] : [])];\n const rows: ReportRow[] = [];\n const accounts = [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))];\n for (const accountId of accounts) {\n const account = await this.getAccount(accountId);\n const start = xAccountMidnight(range.start, account.timezone);\n const endDate = new Date(Date.parse(`${range.end}T00:00:00Z`) + DAY).toISOString().slice(0, 10);\n const end = xAccountMidnight(endDate, account.timezone);\n if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError('INVALID_INPUT', 'x: requested dates predate the account timezone switch; its previous reporting timezone is unknown');\n let entities = await this.reportEntities(accountId, query.level);\n if (query.level === 'account' && new Set(entities.map(e => e.currency)).size > 1) throw new AdportError('PROVIDER_ERROR', 'x: cannot aggregate campaigns with different currencies into one account total');\n const truncated = query.level !== 'account' && entities.length > limit - rows.length;\n if (query.level !== 'account') entities = entities.slice(0, Math.max(0, limit - rows.length));\n const totals = new Map<string, Metrics>();\n const entityKey = (entity: Entity) => `${entity.type}:${entity.id}`;\n for (const type of new Set(entities.map(e => e.type))) {\n const typed = entities.filter(e => e.type === type);\n for (let offset = 0; offset < typed.length; offset += 20) {\n const batch = typed.slice(offset, offset + 20);\n const accumulated = new Map(batch.map(e => [e.id, undefined as Metrics | undefined]));\n for (let from = start; from < end;) {\n const asynchronous = end - start > 7 * DAY || end < Date.now() - 7 * DAY || type === 'MEDIA_CREATIVE';\n const to = Math.min(end, from + (asynchronous ? 30 : 7) * DAY);\n for (const placement of X_PLACEMENTS) {\n const stats = await this.analytics.totals(accountId, { entity: type, entity_ids: batch.map(e => e.id).join(','), start_time: new Date(from).toISOString(), end_time: new Date(to).toISOString(), granularity: 'TOTAL', placement, metric_groups: groups.join(',') }, asynchronous);\n for (const row of stats.data) {\n const source = row.id_data[0]!.metrics, metrics: Metrics = {};\n for (const [key, field, divisor] of [['spend', 'billed_charge_local_micro', 1_000_000], ['impressions', 'impressions', 1], ['clicks', 'url_clicks', 1]] as const) {\n const value = source[field];\n if (value !== undefined && needed.has(key)) metrics[key] = (value?.[0] ?? 0) / divisor;\n }\n accumulated.set(row.id, add(accumulated.get(row.id), metrics));\n }\n }\n from = to;\n }\n for (const entity of batch) totals.set(entityKey(entity), accumulated.get(entity.id) ?? {});\n }\n }\n if (query.level === 'account') {\n if (entities.length) {\n let total: Metrics | undefined;\n for (const entity of entities) total = add(total, totals.get(entityKey(entity))!);\n rows.push({ provider: this.id, accountId, entity: { level: 'account', id: accountId, name: account.name, status: account.approval_status }, metrics: normalize(total ?? {}, query.metrics) });\n }\n } else for (const entity of entities) rows.push({ provider: this.id, accountId, entity: { level: query.level, id: query.level === 'ad' ? entityKey(entity) : entity.id, name: entity.name, status: entity.status }, metrics: normalize(totals.get(entityKey(entity))!, query.metrics) });\n if (truncated) return { rows, truncated: true };\n if (rows.length >= limit) {\n return { rows, ...(accounts.indexOf(accountId) < accounts.length - 1 ? { truncated: true } : {}) };\n }\n }\n return { rows };\n }\n private async reportEntities(accountId: string, level: NormalizedQuery['level']): Promise<Entity[]> {\n if (level === 'account' || level === 'campaign') return (await this.listCampaigns(accountId)).filter(c => c.entity_status !== 'DRAFT').map(c => ({ id: c.id, name: c.name, currency: c.currency, status: c.entity_status, type: 'CAMPAIGN' }));\n const allLines = await this.listLineItems(accountId);\n const lines = allLines.filter(l => l.entity_status !== 'DRAFT');\n if (level === 'ad_group') return lines.map(l => ({ id: l.id, name: l.name, currency: l.currency, status: l.entity_status, type: 'LINE_ITEM' }));\n const lookup = new Map(allLines.map(l => [l.id, l]));\n const tweets = await this.listPromotedTweets(accountId), media = await this.listMediaCreatives(accountId);\n const promoted = lines.some(l => l.product_type === 'PROMOTED_ACCOUNT') ? await this.listPromotedAccounts(accountId) : [];\n return [\n ...tweets.map(t => ({ ...t, type: 'PROMOTED_TWEET', name: `Promoted post ${t.tweet_id}` })),\n ...media.map(t => ({ ...t, type: 'MEDIA_CREATIVE', name: `Media creative ${t.account_media_id}` })),\n ...promoted.map(t => ({ ...t, type: 'PROMOTED_ACCOUNT', name: `Promoted account ${t.user_id}` })),\n ].filter(t => {\n if (!lookup.has(t.line_item_id)) throw new AdportError('PROVIDER_ERROR', 'x: ad references an unknown line item');\n return lookup.get(t.line_item_id)!.entity_status !== 'DRAFT';\n }).map(t => {\n const parent = lookup.get(t.line_item_id);\n if (!parent) throw new AdportError('PROVIDER_ERROR', 'x: ad references an unknown or draft line item');\n return { id: t.id, name: t.name, status: t.entity_status, currency: parent.currency, type: t.type };\n });\n }\n}\nfunction add(previous: Metrics | undefined, next: Metrics): Metrics {\n if (!previous) return { ...next };\n const sum: Metrics = {};\n for (const key of ['spend', 'impressions', 'clicks'] as const) if (previous[key] !== undefined && next[key] !== undefined) {\n const value = previous[key]! + next[key]!;\n if (!Number.isFinite(value) || value > Number.MAX_SAFE_INTEGER) throw new AdportError('PROVIDER_ERROR', 'x: report total exceeds safe numeric range');\n sum[key] = value;\n }\n return sum;\n}\nfunction normalize(values: Metrics, requested: MetricName[]) {\n const all: Partial<Record<MetricName, number>> = { ...values };\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (values[numerator] !== undefined && values[denominator] !== undefined) all[metric as MetricName] = values[denominator] ? values[numerator]! / values[denominator]! * factor : 0;\n return Object.fromEntries(requested.filter(m => all[m] !== undefined).map(m => [m, all[m]]));\n}\n","import { gunzipSync } from 'node:zlib';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\nimport { XAdsClient, type XParams } from './client.js';\nimport { xId } from './schemas.js';\n\nexport const X_PLACEMENTS = ['ALL_ON_TWITTER', 'SPOTLIGHT', 'TREND'] as const;\nconst scalar = z.array(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable()).length(1).nullable().optional();\nexport const statsSchema = z.object({\n data_type: z.literal('stats'), time_series_length: z.literal(1),\n data: z.array(z.object({ id: xId, id_data: z.array(z.object({ segment: z.null(), metrics: z.object({\n billed_charge_local_micro: scalar, impressions: scalar, url_clicks: scalar,\n }) })).length(1) })),\n request: z.object({ params: z.object({\n start_time: z.string(), end_time: z.string(), entity: z.string(), entity_ids: z.array(xId),\n placement: z.string(), granularity: z.literal('TOTAL'), metric_groups: z.array(z.string()),\n }) }),\n});\ntype Stats = z.infer<typeof statsSchema>;\nconst jobSchema = z.object({\n id_str: z.string().regex(/^\\d+$/), account_id: xId, status: z.enum(['PROCESSING', 'SUCCESS', 'FAILED']), url: z.string().nullable(),\n start_time: z.string(), end_time: z.string(), entity: z.string(), entity_ids: z.array(xId), placement: z.string(),\n granularity: z.literal('TOTAL'), metric_groups: z.array(z.string()),\n});\ntype Job = z.infer<typeof jobSchema>;\nconst MAX_FILE_BYTES = 20 * 1024 * 1024;\n\n/** Report jobs are read computations, not advertising mutations. */\nexport class XAdsAnalytics {\n private readonly jobs = new Map<string, Job>();\n private readonly inflight = new Map<string, Promise<Stats>>();\n constructor(private readonly client: XAdsClient, private readonly fetchImpl: typeof fetch = fetch, private readonly pause: (ms: number) => Promise<unknown> = delay) {}\n\n async totals(accountId: string, params: XParams, asynchronous: boolean): Promise<Stats> {\n const key = JSON.stringify([accountId, Object.entries(params).sort(), asynchronous]);\n const active = this.inflight.get(key);\n if (active) return active;\n const promise = this.load(accountId, params, asynchronous, key);\n this.inflight.set(key, promise);\n try { return await promise; } finally { this.inflight.delete(key); }\n }\n private async load(accountId: string, params: XParams, asynchronous: boolean, key: string): Promise<Stats> {\n xId.parse(accountId);\n if (!asynchronous) return validateStats(await this.client.request('GET', `stats/accounts/${accountId}`, statsSchema, params), params);\n const path = `stats/jobs/accounts/${accountId}`;\n let job: Job = this.jobs.get(key) ?? (await this.client.request('POST', path, z.object({ data: jobSchema }), params)).data;\n validateJob(job, accountId, params);\n this.jobs.set(key, job);\n for (let attempt = 0; attempt <= 15; attempt++) {\n if (job.status === 'FAILED') {\n this.jobs.delete(key);\n throw new AdportError('PROVIDER_ERROR', `x: analytics job ${job.id_str} failed`);\n }\n if (job.status === 'SUCCESS') {\n if (!job.url) throw new AdportError('PROVIDER_ERROR', 'x: successful analytics job has no download URL');\n const result = validateStats(await this.download(job.url, job.id_str), params);\n this.jobs.delete(key);\n return result;\n }\n if (attempt === 15) break;\n await this.pause(1000);\n const id = job.id_str;\n const response: { data: Job[] } = await this.client.request('GET', path, z.object({ data: z.array(jobSchema) }), { job_ids: id });\n const match = response.data.filter(row => row.id_str === id);\n if (match.length !== 1 || response.data.length !== 1) throw new AdportError('PROVIDER_ERROR', 'x: analytics polling returned a different or duplicate job');\n job = match[0]!; validateJob(job, accountId, params); this.jobs.set(key, job);\n }\n // Keep the handle: the next identical request on this client resumes it.\n throw new AdportError('PROVIDER_ERROR', `x: analytics job ${job.id_str} is still processing; retry this report to resume polling`);\n }\n private async download(raw: string, id: string): Promise<Stats> {\n let url: URL;\n try { url = new URL(raw); } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid analytics download URL'); }\n if (url.origin !== 'https://ton.twimg.com' || url.username || url.password || url.hash || url.pathname !== `/advertiser-api-async-analytics/stats_job_${id}.json.gz`) {\n throw new AdportError('PROVIDER_ERROR', 'x: untrusted analytics download URL');\n }\n let response: Response;\n try { response = await this.fetchImpl(url.href, { redirect: 'error', signal: AbortSignal.timeout(30_000) }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'x: analytics download transport failed'); }\n if (!response.ok || !response.body) throw new AdportError('PROVIDER_ERROR', 'x: analytics download failed');\n const reader = response.body.getReader(), chunks: Uint8Array[] = []; let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read(); if (done) break;\n size += value.byteLength;\n if (size > MAX_FILE_BYTES) { await reader.cancel(); throw new Error('size'); }\n chunks.push(value);\n }\n const compressed = Buffer.concat(chunks);\n // fetch may already decompress HTTP Content-Encoding, unlike a raw .gz file.\n const bytes = compressed[0] === 0x1f && compressed[1] === 0x8b ? gunzipSync(compressed, { maxOutputLength: MAX_FILE_BYTES }) : compressed;\n const parsed = statsSchema.safeParse(JSON.parse(bytes.toString('utf8')));\n if (!parsed.success) throw new Error('schema');\n return parsed.data;\n } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid or oversized analytics download'); }\n finally { reader.releaseLock(); }\n }\n}\nfunction matches(data: Stats['request']['params'], params: XParams): boolean {\n return Date.parse(data.start_time) === Date.parse(String(params.start_time)) && Date.parse(data.end_time) === Date.parse(String(params.end_time)) &&\n data.entity === params.entity && data.placement === params.placement && data.granularity === params.granularity &&\n [...data.entity_ids].sort().join(',') === String(params.entity_ids).split(',').sort().join(',') &&\n [...data.metric_groups].sort().join(',') === String(params.metric_groups).split(',').sort().join(',');\n}\nfunction validateJob(job: Job, accountId: string, params: XParams) {\n if (job.account_id !== accountId || !matches(job, params)) throw new AdportError('PROVIDER_ERROR', 'x: analytics job scope does not match the report');\n}\nfunction validateStats(data: Stats, params: XParams): Stats {\n const ids = String(params.entity_ids).split(','), returned = data.data.map(row => row.id);\n if (!matches(data.request.params, params) || new Set(returned).size !== returned.length || returned.some(id => !ids.includes(id)) || ids.some(id => !returned.includes(id))) {\n throw new AdportError('PROVIDER_ERROR', 'x: analytics returned incomplete, duplicate or incorrectly scoped data');\n }\n return data;\n}\n\nexport function xAccountMidnight(date: string, timezone: string): number {\n z.iso.date().parse(date);\n const target = Date.parse(`${date}T00:00:00Z`);\n let format: Intl.DateTimeFormat;\n try { format = new Intl.DateTimeFormat('en-GB', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid account timezone'); }\n let value = target;\n for (let i = 0; i < 5; i++) {\n const parts = Object.fromEntries(format.formatToParts(new Date(value)).map(p => [p.type, p.value]));\n const rendered = Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`);\n if (rendered === target) {\n if (value % 3_600_000 !== 0) throw new AdportError('INVALID_INPUT', 'x: account-local midnight is not a whole UTC hour; the API cannot represent this exact date boundary');\n return value;\n }\n value += target - rendered;\n }\n throw new AdportError('INVALID_INPUT', 'x: no midnight exists for this account-local report date');\n}\n","import { z } from 'zod';\nimport { AdportError, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { XParams } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { campaignSchema, createCampaignSchema, setBudgetSchema, setStatusSchema, xId } from './schemas.js';\n\nexport interface XWritePlan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\n\n/** Called by the provider on both policy preview and exact approved apply. */\nexport async function planXWrite(entities: XAdsEntities, op: WriteOperation, guard: WriteGuard): Promise<XWritePlan> {\n if (op.provider !== 'x') throw new AdportError('INVALID_INPUT', 'x: provider mismatch');\n const accountId = xId.parse(op.accountId), base = `accounts/${accountId}/campaigns`;\n if (op.kind === 'create' && op.tool === 'x_create_campaign') {\n const input = createCampaignSchema.parse(op.payload);\n if (input.total_budget_micros !== undefined && input.daily_budget_micros > input.total_budget_micros) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total budget');\n const funding = await entities.getFundingInstrument(accountId, input.funding_instrument_id);\n if (funding.deleted || !funding.able_to_fund || funding.entity_status !== 'ACTIVE') throw new AdportError('INVALID_INPUT', 'x: selected funding instrument cannot fund a campaign');\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const params: XParams = { name: input.name, funding_instrument_id: funding.id, budget_optimization: 'LINE_ITEM', entity_status: status, daily_budget_amount_local_micro: input.daily_budget_micros,\n ...(input.total_budget_micros !== undefined ? { total_budget_amount_local_micro: input.total_budget_micros } : {}) };\n return {\n summary: `Create X campaign \"${input.name}\"`, changes: [`+ ${JSON.stringify(params)} (${funding.currency})`, 'Campaign only; serving also requires line items, targeting and creatives.'],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [{ target: 'new campaign daily budget', toMicros: input.daily_budget_micros }, ...(input.total_budget_micros !== undefined ? [{ target: 'new campaign total budget', toMicros: input.total_budget_micros }] : [])],\n execute: async () => {\n const { data } = await entities.client.request('POST', base, z.object({ data: campaignSchema }), params);\n if (data.name !== input.name || data.funding_instrument_id !== funding.id || data.currency !== funding.currency || data.entity_status !== status || data.deleted || data.budget_optimization !== 'LINE_ITEM' || data.daily_budget_amount_local_micro !== input.daily_budget_micros || data.total_budget_amount_local_micro !== (input.total_budget_micros ?? null)) {\n throw new AdportError('PROVIDER_ERROR', 'x: created campaign response does not match the approved plan; inspect the account before retrying');\n }\n return [data.id];\n },\n };\n }\n if (op.kind === 'update' && ['x_set_campaign_status', 'x_set_budget'].includes(op.tool)) {\n const input = op.tool === 'x_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const current = await entities.getCampaign(accountId, input.campaign_id);\n if (current.deleted || current.entity_status === 'DRAFT') throw new AdportError('INVALID_INPUT', 'x: deleted and draft campaigns cannot be changed by this tool');\n let params: XParams;\n const budgetDeltas: XWritePlan['budgetDeltas'] = [];\n if ('budget_micros' in input) {\n const field = input.budget_type === 'DAILY' ? 'daily_budget_amount_local_micro' : 'total_budget_amount_local_micro';\n const from = current[field];\n if (from === null) throw new AdportError('INVALID_INPUT', 'x: no existing budget of this type; this tool does not change budget semantics');\n if (current.budget_optimization !== 'LINE_ITEM') throw new AdportError('INVALID_INPUT', 'x: unsupported campaign budget optimization');\n const daily = input.budget_type === 'DAILY' ? input.budget_micros : current.daily_budget_amount_local_micro;\n const total = input.budget_type === 'TOTAL' ? input.budget_micros : current.total_budget_amount_local_micro;\n if (daily !== null && total !== null && daily > total) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total budget');\n params = { [field]: input.budget_micros };\n budgetDeltas.push({ target: `campaign ${current.id} ${input.budget_type.toLowerCase()} budget`, fromMicros: from, toMicros: input.budget_micros });\n } else params = { entity_status: input.status };\n return {\n summary: `Update X campaign \"${current.name}\"`, changes: Object.entries(params).map(([key, value]) => `~ ${key}: ${current[key as keyof typeof current]} → ${value}`), coercions: [], budgetDeltas,\n execute: async () => {\n const { data } = await entities.client.request('PUT', `${base}/${current.id}`, z.object({ data: campaignSchema }), params);\n const expected = { ...current, ...params };\n for (const key of ['id', 'funding_instrument_id', 'currency', 'entity_status', 'deleted', 'budget_optimization', 'daily_budget_amount_local_micro', 'total_budget_amount_local_micro'] as const) {\n if (data[key] !== expected[key]) throw new AdportError('PROVIDER_ERROR', 'x: updated campaign response does not match the approved plan; inspect the account before retrying');\n }\n return [data.id];\n },\n };\n }\n throw new AdportError('INVALID_INPUT', `x: unsupported write ${op.tool}`);\n}\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { XAdsProvider } from './provider.js';\nimport { createCampaignSchema, setBudgetSchema, setStatusSchema, xId } from './schemas.js';\n\nexport function xTools(provider: XAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'x_list_campaigns', namespace: 'x', description: 'List X Ads campaigns including inactive, deleted and draft campaigns.', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'x_list_funding_instruments', namespace: 'x', description: 'List existing funding instruments for campaign creation; does not create or change billing.', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listFundingInstruments(input.account_id) }),\n defineTool({ name: 'x_list_line_items', namespace: 'x', description: 'List X Ads line items (ad groups).', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listLineItems(input.account_id) }),\n guardedWriteTool({ name: 'x_create_campaign', namespace: 'x', provider: 'x', kind: 'create', description: 'Create a paused X Ads campaign with an existing funding instrument and account-currency budgets in integer micros. Preview is local.', payload: createCampaignSchema }),\n guardedWriteTool({ name: 'x_set_campaign_status', namespace: 'x', provider: 'x', kind: 'update', description: 'Pause or activate an existing X Ads campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'x_set_budget', namespace: 'x', provider: 'x', kind: 'update', description: 'Change an existing X Ads daily or total campaign budget in integer micros, preserving the other cap.', payload: setBudgetSchema }),\n ];\n}\n","import { AdportError } from '@adport/core';\nimport { createXSigner, type XAdsCredentials } from './client.js';\n\ntype App = Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>;\nexport interface XUserTokens { accessToken: string; accessTokenSecret: string }\nexport interface XRequestTokens { requestToken: string; requestTokenSecret: string }\nconst REQUEST_TOKEN_URL = 'https://api.x.com/oauth/request_token';\nconst ACCESS_TOKEN_URL = 'https://api.x.com/oauth/access_token';\nconst INVALIDATE_TOKEN_URL = 'https://api.x.com/1.1/oauth/invalidate_token.json';\nconst LIMIT = 16 * 1024;\n\nfunction validToken(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= 4096 && !/[\\s\\x00-\\x1f\\x7f]/.test(value);\n}\nfunction requireValues(...values: unknown[]): void {\n if (!values.every(validToken)) throw new AdportError('INVALID_INPUT', 'x: OAuth credentials or verifier are missing or malformed');\n}\nfunction failure(message: string): AdportError { return new AdportError('PROVIDER_ERROR', `x: ${message}`); }\n\nasync function textBody(response: Response): Promise<string> {\n const reader = response.body?.getReader();\n if (!reader) throw failure('empty OAuth response');\n const chunks: Uint8Array[] = []; let length = 0;\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.byteLength;\n if (length > LIMIT) { await reader.cancel(); throw failure('OAuth response exceeded size limit'); }\n chunks.push(value);\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));\n } catch { throw failure('invalid or oversized OAuth response'); }\n finally { reader.releaseLock(); }\n}\n\nasync function signedPost(app: App, url: string, parameters: Record<string, string>, token: { key: string; secret: string } | undefined, fetchImpl: typeof fetch): Promise<Response> {\n requireValues(app.consumerKey, app.consumerSecret);\n const signer = createXSigner(app);\n // OAuth-specific parameters belong in the Authorization header. Include\n // them in the signature once, and send no query string or request body.\n const authorization = signer.authorize({ method: 'POST', url, data: parameters }, token);\n let response: Response;\n try {\n response = await fetchImpl(url, { method: 'POST', headers: { ...signer.toHeader({ ...authorization, ...parameters }) }, redirect: 'error', signal: AbortSignal.timeout(30_000) });\n } catch { throw failure('OAuth transport failed; restart authorization rather than replaying the exchange'); }\n if (response.status !== 200) throw failure(`OAuth request failed (HTTP ${response.status})`);\n return response;\n}\n\nasync function tokens(response: Response): Promise<URLSearchParams> {\n // The official examples return form-encoded tokens, not JSON, despite the\n // generic endpoint metadata saying JSON. Reject duplicate token fields.\n const values = new URLSearchParams(await textBody(response));\n for (const key of ['oauth_token', 'oauth_token_secret']) {\n if (values.getAll(key).length !== 1 || !validToken(values.get(key))) throw failure('malformed OAuth token response');\n }\n return values;\n}\n\nexport async function requestXToken(app: App, callback: string, fetchImpl: typeof fetch = fetch): Promise<XRequestTokens> {\n let url: URL;\n try { url = new URL(callback); } catch { throw new AdportError('INVALID_INPUT', 'x: an exact registered HTTPS callback is required'); }\n if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) throw new AdportError('INVALID_INPUT', 'x: an exact registered HTTPS callback without query or fragment is required');\n const values = await tokens(await signedPost(app, REQUEST_TOKEN_URL, { oauth_callback: url.href }, undefined, fetchImpl));\n if (values.getAll('oauth_callback_confirmed').length !== 1 || values.get('oauth_callback_confirmed') !== 'true') throw failure('OAuth callback was not confirmed');\n return { requestToken: values.get('oauth_token')!, requestTokenSecret: values.get('oauth_token_secret')! };\n}\n\nexport function buildXAuthorizationUrl(requestToken: string): string {\n requireValues(requestToken);\n return `https://api.x.com/oauth/authorize?${new URLSearchParams({ oauth_token: requestToken })}`;\n}\n\nexport async function exchangeXToken(app: App, request: XRequestTokens, verifier: string, fetchImpl: typeof fetch = fetch): Promise<XUserTokens> {\n requireValues(request.requestToken, request.requestTokenSecret, verifier);\n const values = await tokens(await signedPost(app, ACCESS_TOKEN_URL, { oauth_verifier: verifier }, { key: request.requestToken, secret: request.requestTokenSecret }, fetchImpl));\n return { accessToken: values.get('oauth_token')!, accessTokenSecret: values.get('oauth_token_secret')! };\n}\n\nexport async function revokeXToken(credentials: XAdsCredentials, fetchImpl: typeof fetch = fetch): Promise<void> {\n requireValues(credentials.accessToken, credentials.accessTokenSecret);\n const response = await signedPost(credentials, INVALIDATE_TOKEN_URL, {}, { key: credentials.accessToken, secret: credentials.accessTokenSecret }, fetchImpl);\n let value: unknown;\n try { value = JSON.parse(await textBody(response)); } catch { throw failure('invalid OAuth revocation response'); }\n if (!value || typeof value !== 'object' || !('access_token' in value) || value.access_token !== credentials.accessToken) throw failure('OAuth revocation was not confirmed for this token');\n}\n","export { XAdsClient, X_ADS_API_BASE, type XAdsCredentials, type XParams } from './client.js';\nexport { XAdsEntities } from './entities.js';\nexport { XAdsProvider } from './provider.js';\nexport { XAdsAnalytics } from './analytics.js';\nexport { xTools } from './tools.js';\nexport { requestXToken, buildXAuthorizationUrl, exchangeXToken, revokeXToken, type XRequestTokens, type XUserTokens } from './oauth.js';\n\nimport { type CredentialStore, type ProviderModule } from '@adport/core';\nimport { XAdsClient, type XAdsCredentials } from './client.js';\nimport { XAdsProvider } from './provider.js';\nimport { xTools } from './tools.js';\n\nexport function xCredentialsFromData(data: Record<string, string> | undefined): XAdsCredentials | undefined {\n if (!data?.consumer_key?.trim() || !data.consumer_secret?.trim() || !data.access_token?.trim() || !data.access_token_secret?.trim()) return undefined;\n return { consumerKey: data.consumer_key, consumerSecret: data.consumer_secret, accessToken: data.access_token, accessTokenSecret: data.access_token_secret };\n}\nexport function xEnvironmentData(): Record<string, string> {\n return { consumer_key: process.env.X_CONSUMER_KEY ?? '', consumer_secret: process.env.X_CONSUMER_SECRET ?? '', access_token: process.env.X_ACCESS_TOKEN ?? '', access_token_secret: process.env.X_ACCESS_TOKEN_SECRET ?? '' };\n}\nexport async function resolveXCredentials(store: CredentialStore): Promise<XAdsCredentials | undefined> {\n return xCredentialsFromData((await store.get('x'))?.data) ?? xCredentialsFromData(xEnvironmentData());\n}\nexport async function createXModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveXCredentials(store);\n if (!credentials) return undefined;\n const provider = new XAdsProvider(new XAdsClient(credentials));\n return { provider, tools: xTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,YAAY,mBAAmB;AACxC,OAAO,WAAW;AAClB,SAAS,SAAS;AAClB,SAAS,mBAAmB;AAErB,IAAM,iBAAiB;AAUvB,SAAS,cAAc,aAA6E;AACzG,QAAM,QAAQ,IAAI,MAAM;AAAA,IACtB,UAA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z","z","AdportError","AdportError"]}
|
|
1
|
+
{"version":3,"sources":["../src/client.ts","../src/entities.ts","../src/schemas.ts","../src/provider.ts","../src/analytics.ts","../src/writes.ts","../src/management.ts","../src/management-tools.ts","../src/targeting.ts","../src/targeting-tools.ts","../src/creatives.ts","../src/creative-tools.ts","../src/media.ts","../src/media-tools.ts","../src/cards.ts","../src/card-schemas.ts","../src/audiences.ts","../src/audience-tools.ts","../src/measurement.ts","../src/measurement-tools.ts","../src/posts.ts","../src/post-schemas.ts","../src/scheduled.ts","../src/scheduled-schemas.ts","../src/direct-media.ts","../src/direct-media-schemas.ts","../src/preroll-cta.ts","../src/preroll-cta-schemas.ts","../src/account-media.ts","../src/account-media-schemas.ts","../src/promoted-accounts.ts","../src/promoted-account-schemas.ts","../src/tools.ts","../src/card-tools.ts","../src/post-tools.ts","../src/scheduled-tools.ts","../src/direct-media-tools.ts","../src/preroll-cta-tools.ts","../src/account-media-tools.ts","../src/promoted-account-tools.ts","../src/oauth.ts","../src/index.ts"],"sourcesContent":["import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';\nimport OAuth from 'oauth-1.0a';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\n\nexport const X_ADS_API_BASE = 'https://ads-api.x.com/12/';\nexport interface XAdsCredentials {\n consumerKey: string;\n consumerSecret: string;\n accessToken: string;\n accessTokenSecret: string;\n}\nexport type XParams = Record<string, string | number | boolean>;\nexport type XMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';\n\nexport function createXSigner(credentials: Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>): OAuth {\n const oauth = new OAuth({\n consumer: { key: credentials.consumerKey, secret: credentials.consumerSecret },\n signature_method: 'HMAC-SHA1',\n hash_function: (base, key) => createHmac('sha1', key).update(base).digest('base64'),\n });\n // The library's default nonce uses Math.random. Use cryptographic entropy.\n oauth.getNonce = () => randomBytes(24).toString('hex');\n return oauth;\n}\n\nexport class XAdsClient {\n private readonly signer: OAuth;\n private readonly token: OAuth.Token;\n private readonly receiptKey: Buffer;\n constructor(credentials: XAdsCredentials, private readonly fetchImpl: typeof fetch = fetch) {\n if (Object.values(credentials).some(value => typeof value !== 'string' || !value.trim()) ||\n !credentials.consumerKey || !credentials.consumerSecret || !credentials.accessToken || !credentials.accessTokenSecret) {\n throw new AdportError('INVALID_INPUT', 'x: all four OAuth 1.0a credentials are required');\n }\n this.signer = createXSigner(credentials);\n this.token = { key: credentials.accessToken, secret: credentials.accessTokenSecret };\n this.receiptKey = createHmac('sha256', credentials.consumerSecret).update(`adport.x.media.v1.${credentials.accessTokenSecret}`).digest();\n }\n\n async request<T>(method: XMethod, path: string, schema: z.ZodType<T>, params: XParams = {}, jsonBody?: unknown): Promise<T> {\n if (!/^[a-z0-9_]+(?:\\/[a-z0-9_]+)*$/.test(path)) throw new AdportError('INVALID_INPUT', 'x: invalid API resource path');\n return this.send(method, new URL(path, X_ADS_API_BASE), schema, params, jsonBody);\n }\n\n async mediaRequest<T>(method: 'GET' | 'POST', path: string, schema: z.ZodType<T>, params: XParams = {}, jsonBody?: unknown): Promise<T> {\n if (!(method === 'GET' ? path === 'media/upload' : path === 'media/upload/initialize' || /^media\\/upload\\/[1-9]\\d{0,18}\\/(?:append|finalize)$/.test(path))) throw new AdportError('INVALID_INPUT', 'x: unsupported native media route');\n return this.send(method, new URL(path, 'https://api.x.com/2/'), schema, params, jsonBody);\n }\n\n resourceReceipt(value: Record<string, unknown>): string {\n const payload = Buffer.from(JSON.stringify(value)).toString('base64url');\n return `${payload}.${createHmac('sha256', this.receiptKey).update(payload).digest('base64url')}`;\n }\n verifyResourceReceipt(receipt: string): unknown {\n const invalid = () => new AdportError('INVALID_INPUT', 'x: invalid resource receipt; use the receipt from the approved upload');\n if (receipt.length > 2048 || !/^[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]{43}$/.test(receipt)) throw invalid();\n const [payload, signature] = receipt.split('.'), expected = createHmac('sha256', this.receiptKey).update(payload!).digest(), supplied = Buffer.from(signature!, 'base64url');\n if (supplied.toString('base64url') !== signature || expected.length !== supplied.length || !timingSafeEqual(expected, supplied)) throw invalid();\n try { return JSON.parse(Buffer.from(payload!, 'base64url').toString('utf8')); } catch { throw invalid(); }\n }\n\n private async send<T>(method: XMethod, url: URL, schema: z.ZodType<T>, params: XParams, jsonBody?: unknown): Promise<T> {\n const path = url.pathname.replace(/^\\/(?:12|2)\\//, '');\n for (const [key, value] of Object.entries(params)) {\n if (!/^[a-z][a-z0-9_]*$/.test(key) || key.startsWith('oauth_') || (typeof value === 'number' && !Number.isFinite(value))) {\n throw new AdportError('INVALID_INPUT', 'x: invalid API parameter');\n }\n url.searchParams.set(key, String(value));\n }\n // oauth-1.0a decodes percent escapes but not form-style '+' spaces.\n // Serialize spaces as %20 so the signed values match X's query parser.\n url.search = url.search.replace(/\\+/g, '%20');\n // Single-resource writes use query parameters; documented batches use JSON.\n // JSON is excluded from OAuth 1 form-parameter normalization.\n const headers = this.signer.toHeader(this.signer.authorize({ url: url.href, method }, this.token));\n let response: Response;\n try {\n response = await this.fetchImpl(url.href, { method, headers: { ...headers, accept: 'application/json', ...(jsonBody !== undefined ? { 'content-type': 'application/json' } : {}) }, ...(jsonBody !== undefined ? { body: JSON.stringify(jsonBody) } : {}), redirect: 'error', signal: AbortSignal.timeout(30_000) });\n } catch {\n throw new AdportError('PROVIDER_ERROR', `x: transport failed${method === 'GET' ? '' : '; write outcome unknown, inspect the account before retrying'}`);\n }\n if (!response.ok) {\n const guidance = response.status === 403 ? 'Check Ads API app approval and this user’s ad-account permissions; reconnecting alone may not help.'\n : response.status === 401 ? 'Check OAuth 1.0a credentials, token permissions and the local clock. Regenerate user tokens after Ads API approval.'\n : response.status === 429 ? 'Rate limit reached; wait for the provider reset before retrying.' : 'Provider request failed.';\n throw new AdportError('PROVIDER_ERROR', `x: HTTP ${response.status}. ${guidance}${method === 'GET' ? '' : ' The write was not retried.'}`, { http_status: response.status });\n }\n let body: unknown;\n try { body = await response.json(); } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid JSON response'); }\n const nonempty = (value: unknown) => Array.isArray(value) ? value.length > 0 : value && typeof value === 'object' ? Object.keys(value).length > 0 : typeof value === 'string' && value.length > 0;\n if (body && typeof body === 'object' && 'errors' in body && nonempty(body.errors)) {\n throw new AdportError('PROVIDER_ERROR', 'x: provider returned an error envelope', mutationReceipt(method, path, body));\n }\n if (body && typeof body === 'object' && 'operation_errors' in body && nonempty(body.operation_errors)) {\n const data = /^batch\\/accounts\\/[a-z0-9]+\\/(?:targeting_criteria|line_items)$/.test(path) && 'data' in body && Array.isArray(body.data) ? body.data : [];\n const ids = data.flatMap(row => row && typeof row === 'object' && typeof row.id === 'string' && /^[a-z0-9]{1,32}$/.test(row.id) ? [row.id] : []).slice(0, 500);\n throw new AdportError('PROVIDER_ERROR', 'x: provider rejected batch operations; inspect the account before retrying', { resource_ids: ids });\n }\n const parsed = schema.safeParse(body);\n if (!parsed.success) {\n throw new AdportError('PROVIDER_ERROR', `x: unexpected API response schema${method === 'GET' ? '' : '; write may have succeeded, reconcile before retrying'}`, mutationReceipt(method, path, body));\n }\n return parsed.data;\n }\n\n async list<T extends { id: string }>(path: string, item: z.ZodType<T>, params: XParams = {}): Promise<T[]> {\n const schema = z.object({ data: z.array(item), next_cursor: z.string().nullable().optional() });\n const rows: T[] = [], ids = new Set<string>(), cursors = new Set<string>();\n let cursor: string | undefined;\n while (true) {\n const page = await this.request('GET', path, schema, { ...params, count: 200, ...(cursor ? { cursor } : {}) });\n for (const row of page.data) {\n if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: pagination repeated an entity');\n ids.add(row.id); rows.push(row);\n }\n if (!page.next_cursor) return rows;\n if (cursors.has(page.next_cursor) || cursors.size >= 1000) throw new AdportError('PROVIDER_ERROR', 'x: cursor pagination did not terminate');\n cursors.add(page.next_cursor); cursor = page.next_cursor;\n }\n }\n}\n\nfunction mutationReceipt(method: XMethod, path: string, body: unknown) {\n const ids = mutationIds(method, path, body);\n const data = method === 'POST' && /^accounts\\/[a-z0-9]+\\/promoted_tweets$/.test(path) && body && typeof body === 'object' && 'data' in body ? body.data : undefined;\n const rows = Array.isArray(data) ? data : data && typeof data === 'object' ? [data] : [];\n const tweets = [...new Set(rows.flatMap(row => row && typeof row === 'object' && typeof row.tweet_id === 'string' && /^[1-9]\\d{0,24}$/.test(row.tweet_id) ? [row.tweet_id] : []))].slice(0, 500);\n return ids.length || tweets.length ? { ...(ids.length ? { resource_ids: ids } : {}), ...(tweets.length ? { reported_tweet_ids: tweets } : {}) } : undefined;\n}\n\nfunction mutationIds(method: XMethod, path: string, body: unknown): string[] {\n const data = method !== 'GET' && /^(?:accounts\\/[a-z0-9]+\\/(?:(?:cards|draft_tweets|scheduled_tweets|scheduled_promoted_tweets|media_library|account_media|media_creatives|preroll_call_to_actions|line_items|campaigns|tracking_tags|promoted_tweets|promoted_accounts)(?:\\/[a-z0-9_]+)?|tweet|tweets\\/[1-9]\\d{0,24}\\/name)|media\\/upload(?:\\/[a-z0-9]+){1,2})$/.test(path) && body && typeof body === 'object' && 'data' in body ? body.data : undefined;\n const rows = Array.isArray(data) ? data : data && typeof data === 'object' ? [data] : [];\n return [...new Set(rows.flatMap(row => row && typeof row === 'object' ? ['id_str', 'id', 'media_key'].flatMap(key => { const value = (row as Record<string, unknown>)[key];return typeof value === 'string' && /^(?:[a-z0-9]{1,32}|\\d{1,3}_[1-9]\\d{0,24})$/.test(value) ? [value] : []; }) : []))].slice(0, 500);\n}\n","import { z } from 'zod';\nimport { AdportError, type Account } from '@adport/core';\nimport { XAdsClient } from './client.js';\nimport { accountSchema, campaignSchema, fundingSchema, lineItemSchema, mediaCreativeSchema, promotedAccountSchema, promotedTweetSchema, xId } from './schemas.js';\n\nexport class XAdsEntities {\n constructor(readonly client: XAdsClient) {}\n async listAccounts(): Promise<Account[]> {\n // X's account response has no currency. It belongs to funding instruments\n // and campaigns; never infer USD or invent account currency here.\n return (await this.client.list('accounts', accountSchema)).map(a => ({ provider: 'x', id: a.id, name: a.name, status: a.approval_status }));\n }\n async getAccount(accountId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}`, z.object({ data: accountSchema }));\n if (data.id !== accountId) throw new AdportError('PROVIDER_ERROR', 'x: account ID mismatch');\n return data;\n }\n listCampaigns(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/campaigns`, campaignSchema, { with_deleted: true, with_draft: true });\n }\n async getCampaign(accountId: string, campaignId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/campaigns/${xId.parse(campaignId)}`, z.object({ data: campaignSchema }));\n if (data.id !== campaignId) throw new AdportError('PROVIDER_ERROR', 'x: campaign ID mismatch');\n return data;\n }\n async listFundingInstruments(accountId: string) {\n const data = await this.client.list(`accounts/${xId.parse(accountId)}/funding_instruments`, fundingSchema);\n if (data.some(f => f.account_id !== accountId)) throw new AdportError('PROVIDER_ERROR', 'x: funding instrument account mismatch');\n return data;\n }\n async getFundingInstrument(accountId: string, fundingId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/funding_instruments/${xId.parse(fundingId)}`, z.object({ data: fundingSchema }));\n if (data.id !== fundingId || data.account_id !== accountId) throw new AdportError('PROVIDER_ERROR', 'x: funding instrument account/ID mismatch');\n return data;\n }\n listLineItems(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true });\n }\n async getLineItem(accountId: string, resourceId: string) {\n const { data } = await this.client.request('GET', `accounts/${xId.parse(accountId)}/line_items/${xId.parse(resourceId)}`, z.object({ data: lineItemSchema }));\n if (data.id !== resourceId) throw new AdportError('PROVIDER_ERROR', 'x: line-item ID mismatch');\n const campaign = await this.getCampaign(accountId, data.campaign_id);\n if (campaign.currency !== data.currency) throw new AdportError('PROVIDER_ERROR', 'x: line-item currency differs from its campaign');\n return data;\n }\n lineItemPlacements() {\n return this.client.request('GET', 'line_items/placements', z.object({ data: z.array(z.object({ product_type: z.string(), placements: z.array(z.array(z.string())) })) }));\n }\n listPromotedTweets(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/promoted_tweets`, promotedTweetSchema, { with_deleted: true });\n }\n listPromotedAccounts(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/promoted_accounts`, promotedAccountSchema, { with_deleted: true });\n }\n listMediaCreatives(accountId: string) {\n return this.client.list(`accounts/${xId.parse(accountId)}/media_creatives`, mediaCreativeSchema, { with_deleted: true });\n }\n}\n","import { z } from 'zod';\n\nexport const xId = z.string().regex(/^[a-z0-9]+$/).min(1).max(64);\nconst micros = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);\nconst currency = z.string().regex(/^[A-Z]{3}$/);\nexport const accountSchema = z.object({\n id: xId, name: z.string(), timezone: z.string(), timezone_switch_at: z.string().nullable().optional(),\n approval_status: z.string(), deleted: z.boolean(),\n});\nexport const fundingSchema = z.object({\n id: xId, account_id: xId, description: z.string(), currency, type: z.string(),\n entity_status: z.string(), able_to_fund: z.boolean(), deleted: z.boolean(),\n});\nexport const campaignSchema = z.object({\n id: xId, name: z.string(), currency, funding_instrument_id: xId, entity_status: z.string(), deleted: z.boolean(),\n budget_optimization: z.string(), daily_budget_amount_local_micro: micros.nullable(), total_budget_amount_local_micro: micros.nullable(),\n});\nexport const lineItemSchema = z.looseObject({\n id: xId, name: z.string().nullable(), campaign_id: xId, currency, entity_status: z.string(), deleted: z.boolean(),\n placements: z.array(z.string()), product_type: z.string(), objective: z.string(),\n bid_strategy: z.string().optional(), bid_amount_local_micro: micros.nullable().optional(),\n daily_budget_amount_local_micro: micros.nullable().optional(), total_budget_amount_local_micro: micros.nullable().optional(),\n start_time: z.string().nullable().optional(), end_time: z.string().nullable().optional(),\n});\nexport const promotedTweetSchema = z.object({\n id: xId, line_item_id: xId, tweet_id: z.string().regex(/^\\d+$/), entity_status: z.string(), deleted: z.boolean(),\n});\nexport const promotedAccountSchema = z.object({ id: xId, line_item_id: xId, user_id: z.string().regex(/^\\d+$/), entity_status: z.string(), deleted: z.boolean() });\nexport const mediaCreativeSchema = z.object({ id: xId, line_item_id: xId, account_media_id: xId, entity_status: z.string(), deleted: z.boolean() });\nexport const createCampaignSchema = z.object({\n name: z.string().min(1).max(255), funding_instrument_id: xId,\n daily_budget_micros: micros.positive(), total_budget_micros: micros.positive().optional(),\n status: z.enum(['ACTIVE', 'PAUSED']).default('PAUSED'),\n});\nexport const setStatusSchema = z.object({ campaign_id: xId, status: z.enum(['ACTIVE', 'PAUSED']) });\nexport const setBudgetSchema = z.object({ campaign_id: xId, budget_type: z.enum(['DAILY', 'TOTAL']), budget_micros: micros.positive() });\n","import { z } from 'zod';\nimport { AdportError, resolveDateRange, type AdProvider, type MediaResolver, type MetricName, type NormalizedQuery, type Report, type ReportRow, type StandardActions, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { XAdsClient } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { XAdsAnalytics, X_PLACEMENTS, xAccountMidnight } from './analytics.js';\nimport { planXWrite } from './writes.js';\nimport { XManagementService } from './management.js';\nimport { XTargetingService } from './targeting.js';\nimport { XCreativeService } from './creatives.js';\nimport { XMediaService } from './media.js';\nimport { XCardService } from './cards.js';\nimport { cardWrites } from './card-schemas.js';\nimport { XAudienceService } from './audiences.js';\nimport { XMeasurementService } from './measurement.js';\nimport { XPostService } from './posts.js';\nimport { postWrites } from './post-schemas.js';\nimport { XScheduledService } from './scheduled.js';\nimport { scheduledWrites } from './scheduled-schemas.js';\nimport { XDirectMediaService } from './direct-media.js';\nimport { directMediaWrites } from './direct-media-schemas.js';\nimport { XPrerollCtaService } from './preroll-cta.js';\nimport { prerollCtaWrites } from './preroll-cta-schemas.js';\nimport { XAccountMediaService } from './account-media.js';\nimport { XPromotedAccountService } from './promoted-accounts.js';\nimport { promotedAccountWrites } from './promoted-account-schemas.js';\n\ntype BaseMetric = 'spend' | 'impressions' | 'clicks';\ntype Metrics = Partial<Record<BaseMetric, number>>;\ninterface Entity { id: string; name: string; status: string; currency: string; type: string }\nconst DERIVED = { ctr: ['clicks', 'impressions', 100], cpc: ['spend', 'clicks', 1], cpm: ['spend', 'impressions', 1000] } as const;\nconst DAY = 86_400_000;\n\nexport class XAdsProvider extends XAdsEntities implements AdProvider {\n readonly id = 'x';\n private readonly analytics: XAdsAnalytics;\n private readonly management: XManagementService;\n readonly targeting: XTargetingService;\n readonly creatives: XCreativeService;\n readonly mediaUploads: XMediaService;\n readonly cards: XCardService;\n readonly audiences: XAudienceService;\n readonly measurement: XMeasurementService;\n readonly posts: XPostService;\n readonly scheduled: XScheduledService;\n readonly directMedia: XDirectMediaService;\n readonly prerollCtas: XPrerollCtaService;\n readonly accountMedia: XAccountMediaService;\n readonly promotedAccounts: XPromotedAccountService;\n constructor(client: XAdsClient, analytics?: XAdsAnalytics, media?: MediaResolver) { super(client); this.analytics = analytics ?? new XAdsAnalytics(client); this.measurement = new XMeasurementService(this, this.analytics); this.management = new XManagementService(this, this.measurement); this.targeting = new XTargetingService(this); this.creatives = new XCreativeService(this); this.mediaUploads = new XMediaService(this, media); this.cards = new XCardService(this, this.creatives); this.audiences = new XAudienceService(this); this.posts = new XPostService(this, this.creatives); this.scheduled = new XScheduledService(this, this.creatives, this.posts); this.directMedia = new XDirectMediaService(this, this.posts); this.prerollCtas = new XPrerollCtaService(this, this.posts); this.accountMedia = new XAccountMediaService(this, this.directMedia); this.promotedAccounts = new XPromotedAccountService(this, this.creatives, this.posts); }\n capabilities() { return { serverDryRun: false }; }\n standardActions(): StandardActions { return { pauseCampaign: (accountId, campaignId) => ({ tool: 'x_set_campaign_status', input: { account_id: accountId, campaign_id: campaignId, status: 'PAUSED' } }) }; }\n async previewWrite(op: WriteOperation, guard: WriteGuard): Promise<WritePreview> {\n const { execute: _execute, ...preview } = await this.writePlan(op, guard); return { ...preview, serverValidated: false };\n }\n async applyWrite(op: WriteOperation, guard: WriteGuard): Promise<WriteResult> {\n const result = await (await this.writePlan(op, guard)).execute(); return Array.isArray(result) ? { applied: true, resourceIds: result } : result;\n }\n private writePlan(op: WriteOperation, guard: WriteGuard) { if (promotedAccountWrites.has(op.tool)) return this.promotedAccounts.plan(op, guard); if (op.tool === 'x_delete_account_media') return this.accountMedia.plan(op); if (prerollCtaWrites.has(op.tool)) return this.prerollCtas.plan(op, guard); if (directMediaWrites.has(op.tool)) return this.directMedia.plan(op, guard); if (scheduledWrites.has(op.tool)) return this.scheduled.plan(op, guard); if (postWrites.has(op.tool)) return this.posts.plan(op, guard); if (/^x_(?:create|update|delete)_tracking_tag$/.test(op.tool)) return this.measurement.plan(op); if (/^x_(?:create_custom_audience|update_custom_audience|update_custom_audience_users|delete_custom_audience)$/.test(op.tool)) return this.audiences.plan(op); if (cardWrites.has(op.tool)) return this.cards.plan(op); if (['x_upload_media', 'x_register_uploaded_media'].includes(op.tool)) return this.mediaUploads.plan(op); if (/^x_(?:create_draft_tweet|update_draft_tweet|delete_draft_tweet|update_media_library|delete_media_library_item)$/.test(op.tool)) return this.creatives.plan(op, guard); if (['x_add_targeting_criterion', 'x_remove_targeting_criterion', 'x_update_targeting'].includes(op.tool)) return this.targeting.plan(op, guard); return /^x_(?:create_line_item|update_line_item|set_line_item_(?:status|budget|bidding)|delete_line_item)$/.test(op.tool) ? this.management.plan(op, guard) : planXWrite(this, op, guard); }\n async report(query: NormalizedQuery): Promise<Report> {\n const range = resolveDateRange(query.dateRange);\n z.iso.date().parse(range.start); z.iso.date().parse(range.end);\n if (range.end < range.start) throw new AdportError('INVALID_INPUT', 'x: report end precedes start');\n const needed = new Set<BaseMetric>();\n for (const metric of query.metrics) {\n if (['spend', 'impressions', 'clicks'].includes(metric)) needed.add(metric as BaseMetric);\n else if (metric in DERIVED) for (const dep of DERIVED[metric as keyof typeof DERIVED].slice(0, 2)) needed.add(dep as BaseMetric);\n }\n if (!needed.size) throw new AdportError('INVALID_INPUT', 'x: supported normalized metrics are spend, impressions, link clicks, ctr, cpc and cpm; conversion normalization is not yet verified');\n const limit = query.limit ?? 1000;\n if (!Number.isSafeInteger(limit) || limit < 1) throw new AdportError('INVALID_INPUT', 'x: report limit must be a positive integer');\n const groups = [...(needed.has('spend') ? ['BILLING'] : []), ...(needed.has('clicks') || needed.has('impressions') ? ['ENGAGEMENT'] : [])];\n const rows: ReportRow[] = [];\n const accounts = [...new Set(query.accountIds ?? (await this.listAccounts()).map(a => a.id))];\n for (const accountId of accounts) {\n const account = await this.getAccount(accountId);\n const start = xAccountMidnight(range.start, account.timezone);\n const endDate = new Date(Date.parse(`${range.end}T00:00:00Z`) + DAY).toISOString().slice(0, 10);\n const end = xAccountMidnight(endDate, account.timezone);\n if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError('INVALID_INPUT', 'x: requested dates predate the account timezone switch; its previous reporting timezone is unknown');\n let entities = await this.reportEntities(accountId, query.level);\n if (query.level === 'account' && new Set(entities.map(e => e.currency)).size > 1) throw new AdportError('PROVIDER_ERROR', 'x: cannot aggregate campaigns with different currencies into one account total');\n const truncated = query.level !== 'account' && entities.length > limit - rows.length;\n if (query.level !== 'account') entities = entities.slice(0, Math.max(0, limit - rows.length));\n const totals = new Map<string, Metrics>();\n const entityKey = (entity: Entity) => `${entity.type}:${entity.id}`;\n for (const type of new Set(entities.map(e => e.type))) {\n const typed = entities.filter(e => e.type === type);\n for (let offset = 0; offset < typed.length; offset += 20) {\n const batch = typed.slice(offset, offset + 20);\n const accumulated = new Map(batch.map(e => [e.id, undefined as Metrics | undefined]));\n for (let from = start; from < end;) {\n const asynchronous = end - start > 7 * DAY || end < Date.now() - 7 * DAY || type === 'MEDIA_CREATIVE';\n const to = Math.min(end, from + (asynchronous ? 30 : 7) * DAY);\n for (const placement of X_PLACEMENTS) {\n const stats = await this.analytics.totals(accountId, { entity: type, entity_ids: batch.map(e => e.id).join(','), start_time: new Date(from).toISOString(), end_time: new Date(to).toISOString(), granularity: 'TOTAL', placement, metric_groups: groups.join(',') }, asynchronous);\n for (const row of stats.data) {\n const source = row.id_data[0]!.metrics, metrics: Metrics = {};\n for (const [key, field, divisor] of [['spend', 'billed_charge_local_micro', 1_000_000], ['impressions', 'impressions', 1], ['clicks', 'url_clicks', 1]] as const) {\n const value = source[field];\n if (value !== undefined && needed.has(key)) metrics[key] = (value?.[0] ?? 0) / divisor;\n }\n accumulated.set(row.id, add(accumulated.get(row.id), metrics));\n }\n }\n from = to;\n }\n for (const entity of batch) totals.set(entityKey(entity), accumulated.get(entity.id) ?? {});\n }\n }\n if (query.level === 'account') {\n if (entities.length) {\n let total: Metrics | undefined;\n for (const entity of entities) total = add(total, totals.get(entityKey(entity))!);\n rows.push({ provider: this.id, accountId, entity: { level: 'account', id: accountId, name: account.name, status: account.approval_status }, metrics: normalize(total ?? {}, query.metrics) });\n }\n } else for (const entity of entities) rows.push({ provider: this.id, accountId, entity: { level: query.level, id: query.level === 'ad' ? entityKey(entity) : entity.id, name: entity.name, status: entity.status }, metrics: normalize(totals.get(entityKey(entity))!, query.metrics) });\n if (truncated) return { rows, truncated: true };\n if (rows.length >= limit) {\n return { rows, ...(accounts.indexOf(accountId) < accounts.length - 1 ? { truncated: true } : {}) };\n }\n }\n return { rows };\n }\n private async reportEntities(accountId: string, level: NormalizedQuery['level']): Promise<Entity[]> {\n if (level === 'account' || level === 'campaign') return (await this.listCampaigns(accountId)).filter(c => c.entity_status !== 'DRAFT').map(c => ({ id: c.id, name: c.name, currency: c.currency, status: c.entity_status, type: 'CAMPAIGN' }));\n const allLines = await this.listLineItems(accountId);\n const lines = allLines.filter(l => l.entity_status !== 'DRAFT');\n if (level === 'ad_group') return lines.map(l => ({ id: l.id, name: l.name ?? l.id, currency: l.currency, status: l.entity_status, type: 'LINE_ITEM' }));\n const lookup = new Map(allLines.map(l => [l.id, l]));\n const tweets = await this.listPromotedTweets(accountId), media = await this.listMediaCreatives(accountId);\n const promoted = lines.some(l => l.product_type === 'PROMOTED_ACCOUNT') ? await this.listPromotedAccounts(accountId) : [];\n return [\n ...tweets.map(t => ({ ...t, type: 'PROMOTED_TWEET', name: `Promoted post ${t.tweet_id}` })),\n ...media.map(t => ({ ...t, type: 'MEDIA_CREATIVE', name: `Media creative ${t.account_media_id}` })),\n ...promoted.map(t => ({ ...t, type: 'PROMOTED_ACCOUNT', name: `Promoted account ${t.user_id}` })),\n ].filter(t => {\n if (!lookup.has(t.line_item_id)) throw new AdportError('PROVIDER_ERROR', 'x: ad references an unknown line item');\n return lookup.get(t.line_item_id)!.entity_status !== 'DRAFT';\n }).map(t => {\n const parent = lookup.get(t.line_item_id);\n if (!parent) throw new AdportError('PROVIDER_ERROR', 'x: ad references an unknown or draft line item');\n return { id: t.id, name: t.name, status: t.entity_status, currency: parent.currency, type: t.type };\n });\n }\n}\nfunction add(previous: Metrics | undefined, next: Metrics): Metrics {\n if (!previous) return { ...next };\n const sum: Metrics = {};\n for (const key of ['spend', 'impressions', 'clicks'] as const) if (previous[key] !== undefined && next[key] !== undefined) {\n const value = previous[key]! + next[key]!;\n if (!Number.isFinite(value) || value > Number.MAX_SAFE_INTEGER) throw new AdportError('PROVIDER_ERROR', 'x: report total exceeds safe numeric range');\n sum[key] = value;\n }\n return sum;\n}\nfunction normalize(values: Metrics, requested: MetricName[]) {\n const all: Partial<Record<MetricName, number>> = { ...values };\n for (const [metric, [numerator, denominator, factor]] of Object.entries(DERIVED)) if (values[numerator] !== undefined && values[denominator] !== undefined) all[metric as MetricName] = values[denominator] ? values[numerator]! / values[denominator]! * factor : 0;\n return Object.fromEntries(requested.filter(m => all[m] !== undefined).map(m => [m, all[m]]));\n}\n","import { gunzipSync } from 'node:zlib';\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { z } from 'zod';\nimport { AdportError } from '@adport/core';\nimport { XAdsClient, type XParams } from './client.js';\nimport { xId } from './schemas.js';\n\nexport const X_PLACEMENTS = ['ALL_ON_TWITTER', 'SPOTLIGHT', 'TREND'] as const;\nconst scalar = z.array(z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable()).length(1).nullable().optional();\nexport const statsSchema = z.object({\n data_type: z.literal('stats'), time_series_length: z.literal(1),\n data: z.array(z.object({ id: xId, id_data: z.array(z.object({ segment: z.null(), metrics: z.object({\n billed_charge_local_micro: scalar, impressions: scalar, url_clicks: scalar,\n }).catchall(z.json()) })).length(1) })),\n request: z.object({ params: z.object({\n account_id: xId.optional(),\n start_time: z.string(), end_time: z.string(), entity: z.string(), entity_ids: z.array(xId),\n placement: z.string(), granularity: z.literal('TOTAL'), metric_groups: z.array(z.string()),\n }) }),\n});\ntype Stats = z.infer<typeof statsSchema>;\nconst jobSchema = z.object({\n id_str: z.string().regex(/^\\d+$/), account_id: xId, status: z.enum(['PROCESSING', 'SUCCESS', 'FAILED']), url: z.string().nullable(),\n start_time: z.string(), end_time: z.string(), entity: z.string(), entity_ids: z.array(xId), placement: z.string(),\n granularity: z.literal('TOTAL'), metric_groups: z.array(z.string()),\n});\ntype Job = z.infer<typeof jobSchema>;\nconst MAX_FILE_BYTES = 20 * 1024 * 1024;\n\n/** Report jobs are read computations, not advertising mutations. */\nexport class XAdsAnalytics {\n private readonly jobs = new Map<string, Job>();\n private readonly inflight = new Map<string, Promise<Stats>>();\n constructor(private readonly client: XAdsClient, private readonly fetchImpl: typeof fetch = fetch, private readonly pause: (ms: number) => Promise<unknown> = delay) {}\n\n async totals(accountId: string, params: XParams, asynchronous: boolean): Promise<Stats> {\n const key = JSON.stringify([accountId, Object.entries(params).sort(), asynchronous]);\n const active = this.inflight.get(key);\n if (active) return active;\n const promise = this.load(accountId, params, asynchronous, key);\n this.inflight.set(key, promise);\n try { return await promise; } finally { this.inflight.delete(key); }\n }\n private async load(accountId: string, params: XParams, asynchronous: boolean, key: string): Promise<Stats> {\n xId.parse(accountId);\n if (!asynchronous) return validateStats(await this.client.request('GET', `stats/accounts/${accountId}`, statsSchema, params), params, accountId);\n const path = `stats/jobs/accounts/${accountId}`;\n let job: Job = this.jobs.get(key) ?? (await this.client.request('POST', path, z.object({ data: jobSchema }), params)).data;\n validateJob(job, accountId, params);\n this.jobs.set(key, job);\n for (let attempt = 0; attempt <= 15; attempt++) {\n if (job.status === 'FAILED') {\n this.jobs.delete(key);\n throw new AdportError('PROVIDER_ERROR', `x: analytics job ${job.id_str} failed`);\n }\n if (job.status === 'SUCCESS') {\n if (!job.url) throw new AdportError('PROVIDER_ERROR', 'x: successful analytics job has no download URL');\n const result = validateStats(await this.download(job.url, job.id_str), params, accountId);\n this.jobs.delete(key);\n return result;\n }\n if (attempt === 15) break;\n await this.pause(1000);\n const id = job.id_str;\n const response: { data: Job[] } = await this.client.request('GET', path, z.object({ data: z.array(jobSchema) }), { job_ids: id });\n const match = response.data.filter(row => row.id_str === id);\n if (match.length !== 1 || response.data.length !== 1) throw new AdportError('PROVIDER_ERROR', 'x: analytics polling returned a different or duplicate job');\n job = match[0]!; validateJob(job, accountId, params); this.jobs.set(key, job);\n }\n // Keep the handle: the next identical request on this client resumes it.\n throw new AdportError('PROVIDER_ERROR', `x: analytics job ${job.id_str} is still processing; retry this report to resume polling`);\n }\n private async download(raw: string, id: string): Promise<Stats> {\n let url: URL;\n try { url = new URL(raw); } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid analytics download URL'); }\n if (url.origin !== 'https://ton.twimg.com' || url.username || url.password || url.hash || url.pathname !== `/advertiser-api-async-analytics/stats_job_${id}.json.gz`) {\n throw new AdportError('PROVIDER_ERROR', 'x: untrusted analytics download URL');\n }\n let response: Response;\n try { response = await this.fetchImpl(url.href, { redirect: 'error', signal: AbortSignal.timeout(30_000) }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'x: analytics download transport failed'); }\n if (!response.ok || !response.body) throw new AdportError('PROVIDER_ERROR', 'x: analytics download failed');\n const reader = response.body.getReader(), chunks: Uint8Array[] = []; let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read(); if (done) break;\n size += value.byteLength;\n if (size > MAX_FILE_BYTES) { await reader.cancel(); throw new Error('size'); }\n chunks.push(value);\n }\n const compressed = Buffer.concat(chunks);\n // fetch may already decompress HTTP Content-Encoding, unlike a raw .gz file.\n const bytes = compressed[0] === 0x1f && compressed[1] === 0x8b ? gunzipSync(compressed, { maxOutputLength: MAX_FILE_BYTES }) : compressed;\n const parsed = statsSchema.safeParse(JSON.parse(bytes.toString('utf8')));\n if (!parsed.success) throw new Error('schema');\n return parsed.data;\n } catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid or oversized analytics download'); }\n finally { reader.releaseLock(); }\n }\n}\nfunction matches(data: Stats['request']['params'], params: XParams): boolean {\n return Date.parse(data.start_time) === Date.parse(String(params.start_time)) && Date.parse(data.end_time) === Date.parse(String(params.end_time)) &&\n data.entity === params.entity && data.placement === params.placement && data.granularity === params.granularity &&\n [...data.entity_ids].sort().join(',') === String(params.entity_ids).split(',').sort().join(',') &&\n [...data.metric_groups].sort().join(',') === String(params.metric_groups).split(',').sort().join(',');\n}\nfunction validateJob(job: Job, accountId: string, params: XParams) {\n if (job.account_id !== accountId || !matches(job, params)) throw new AdportError('PROVIDER_ERROR', 'x: analytics job scope does not match the report');\n}\nfunction validateStats(data: Stats, params: XParams, accountId: string): Stats {\n const ids = String(params.entity_ids).split(','), returned = data.data.map(row => row.id);\n if (data.request.params.account_id !== undefined && data.request.params.account_id !== accountId || !matches(data.request.params, params) || new Set(returned).size !== returned.length || returned.some(id => !ids.includes(id)) || ids.some(id => !returned.includes(id))) {\n throw new AdportError('PROVIDER_ERROR', 'x: analytics returned incomplete, duplicate or incorrectly scoped data');\n }\n return data;\n}\n\nexport function xAccountMidnight(date: string, timezone: string): number {\n z.iso.date().parse(date);\n const target = Date.parse(`${date}T00:00:00Z`);\n let format: Intl.DateTimeFormat;\n try { format = new Intl.DateTimeFormat('en-GB', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' }); }\n catch { throw new AdportError('PROVIDER_ERROR', 'x: invalid account timezone'); }\n let value = target;\n for (let i = 0; i < 5; i++) {\n const parts = Object.fromEntries(format.formatToParts(new Date(value)).map(p => [p.type, p.value]));\n const rendered = Date.parse(`${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}Z`);\n if (rendered === target) {\n if (value % 3_600_000 !== 0) throw new AdportError('INVALID_INPUT', 'x: account-local midnight is not a whole UTC hour; the API cannot represent this exact date boundary');\n return value;\n }\n value += target - rendered;\n }\n throw new AdportError('INVALID_INPUT', 'x: no midnight exists for this account-local report date');\n}\n","import { z } from 'zod';\nimport { AdportError, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport type { XParams } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { campaignSchema, createCampaignSchema, setBudgetSchema, setStatusSchema, xId } from './schemas.js';\n\nexport interface XWritePlan extends Omit<WritePreview, 'serverValidated'> { execute: () => Promise<string[]> }\n\n/** Called by the provider on both policy preview and exact approved apply. */\nexport async function planXWrite(entities: XAdsEntities, op: WriteOperation, guard: WriteGuard): Promise<XWritePlan> {\n if (op.provider !== 'x') throw new AdportError('INVALID_INPUT', 'x: provider mismatch');\n const accountId = xId.parse(op.accountId), base = `accounts/${accountId}/campaigns`;\n if (op.kind === 'create' && op.tool === 'x_create_campaign') {\n const input = createCampaignSchema.parse(op.payload);\n if (input.total_budget_micros !== undefined && input.daily_budget_micros > input.total_budget_micros) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total budget');\n const funding = await entities.getFundingInstrument(accountId, input.funding_instrument_id);\n if (funding.deleted || !funding.able_to_fund || funding.entity_status !== 'ACTIVE') throw new AdportError('INVALID_INPUT', 'x: selected funding instrument cannot fund a campaign');\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n const params: XParams = { name: input.name, funding_instrument_id: funding.id, budget_optimization: 'LINE_ITEM', entity_status: status, daily_budget_amount_local_micro: input.daily_budget_micros,\n ...(input.total_budget_micros !== undefined ? { total_budget_amount_local_micro: input.total_budget_micros } : {}) };\n return {\n summary: `Create X campaign \"${input.name}\"`, changes: [`+ ${JSON.stringify(params)} (${funding.currency})`, 'Campaign only; serving also requires line items, targeting and creatives.'],\n coercions: status !== input.status ? ['status coerced to PAUSED by policy (paused_creation)'] : [],\n budgetDeltas: [{ target: 'new campaign daily budget', toMicros: input.daily_budget_micros }, ...(input.total_budget_micros !== undefined ? [{ target: 'new campaign total budget', toMicros: input.total_budget_micros }] : [])],\n execute: async () => {\n const { data } = await entities.client.request('POST', base, z.object({ data: campaignSchema }), params);\n if (data.name !== input.name || data.funding_instrument_id !== funding.id || data.currency !== funding.currency || data.entity_status !== status || data.deleted || data.budget_optimization !== 'LINE_ITEM' || data.daily_budget_amount_local_micro !== input.daily_budget_micros || data.total_budget_amount_local_micro !== (input.total_budget_micros ?? null)) {\n throw new AdportError('PROVIDER_ERROR', 'x: created campaign response does not match the approved plan; inspect the account before retrying');\n }\n return [data.id];\n },\n };\n }\n if (op.kind === 'update' && ['x_set_campaign_status', 'x_set_budget'].includes(op.tool)) {\n const input = op.tool === 'x_set_budget' ? setBudgetSchema.parse(op.payload) : setStatusSchema.parse(op.payload);\n const current = await entities.getCampaign(accountId, input.campaign_id);\n if (current.deleted || current.entity_status === 'DRAFT') throw new AdportError('INVALID_INPUT', 'x: deleted and draft campaigns cannot be changed by this tool');\n let params: XParams;\n const budgetDeltas: XWritePlan['budgetDeltas'] = [];\n if ('budget_micros' in input) {\n const field = input.budget_type === 'DAILY' ? 'daily_budget_amount_local_micro' : 'total_budget_amount_local_micro';\n const from = current[field];\n if (from === null) throw new AdportError('INVALID_INPUT', 'x: no existing budget of this type; this tool does not change budget semantics');\n if (current.budget_optimization !== 'LINE_ITEM') throw new AdportError('INVALID_INPUT', 'x: unsupported campaign budget optimization');\n const daily = input.budget_type === 'DAILY' ? input.budget_micros : current.daily_budget_amount_local_micro;\n const total = input.budget_type === 'TOTAL' ? input.budget_micros : current.total_budget_amount_local_micro;\n if (daily !== null && total !== null && daily > total) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total budget');\n params = { [field]: input.budget_micros };\n budgetDeltas.push({ target: `campaign ${current.id} ${input.budget_type.toLowerCase()} budget`, fromMicros: from, toMicros: input.budget_micros });\n } else params = { entity_status: input.status };\n return {\n summary: `Update X campaign \"${current.name}\"`, changes: Object.entries(params).map(([key, value]) => `~ ${key}: ${current[key as keyof typeof current]} → ${value}`), coercions: [], budgetDeltas,\n execute: async () => {\n const { data } = await entities.client.request('PUT', `${base}/${current.id}`, z.object({ data: campaignSchema }), params);\n const expected = { ...current, ...params };\n for (const key of ['id', 'funding_instrument_id', 'currency', 'entity_status', 'deleted', 'budget_optimization', 'daily_budget_amount_local_micro', 'total_budget_amount_local_micro'] as const) {\n if (data[key] !== expected[key]) throw new AdportError('PROVIDER_ERROR', 'x: updated campaign response does not match the approved plan; inspect the account before retrying');\n }\n return [data.id];\n },\n };\n }\n throw new AdportError('INVALID_INPUT', `x: unsupported write ${op.tool}`);\n}\n","import { AdportError, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { createLine, micros, setLineBid, updateLine } from './management-tools.js';\nimport { lineItemSchema, xId as id } from './schemas.js';\nimport type { XWritePlan } from './writes.js';\nimport type { XMeasurementService } from './measurement.js';\n\ntype Line = z.infer<typeof lineItemSchema>;\nexport class XManagementService {\n constructor(private readonly entities: XAdsEntities, private readonly measurement: XMeasurementService) {}\n private bid(objective: string, strategy: string, amount: unknown, create: boolean) {\n if (strategy === 'AUTO' && amount !== undefined) throw new AdportError('INVALID_INPUT', 'x: AUTO ignores bid amounts; do not supply a purported monetary cap');\n if (strategy !== 'AUTO' && !micros.safeParse(amount).success) throw new AdportError('INVALID_INPUT', 'x: MAX/TARGET require a positive safe integer bid in micros');\n if (strategy === 'MAX' && ['REACH', 'FOLLOWERS'].includes(objective)) throw new AdportError('INVALID_INPUT', 'x: MAX is unavailable for REACH/FOLLOWERS');\n if (strategy === 'TARGET' && !(create ? ['REACH', 'FOLLOWERS', 'WEBSITE_CLICKS'] : ['REACH', 'WEBSITE_CLICKS']).includes(objective)) throw new AdportError('INVALID_INPUT', 'x: TARGET is not documented for this objective/operation');\n }\n private verify(data: Line, currency: string, expected: Record<string, unknown>) {\n const matches = (key: string, value: unknown) => value === null ? data[key] === null : ['placements', 'categories'].includes(key) ? Array.isArray(data[key]) && [...data[key]].sort().join(',') === String(value).split(',').sort().join(',') : ['start_time', 'end_time'].includes(key) ? Date.parse(String(data[key])) === Date.parse(String(value)) : data[key] === value;\n if (data.currency !== currency || Object.entries(expected).some(([key, value]) => !matches(key, value))) throw new AdportError('PROVIDER_ERROR', 'x: line-item receipt ID/parent/status/money mismatch; reconcile before retrying', { resource_ids: [data.id] });\n }\n private async receipt(method: 'POST' | 'PUT' | 'DELETE', path: string, params: XParams, currency: string, expected: Record<string, unknown>) {\n const { data } = await this.entities.client.request(method, path, z.object({ data: lineItemSchema }), params);\n this.verify(data, currency, expected);\n return [data.id];\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<XWritePlan> {\n const account = id.parse(op.accountId), create = op.tool === 'x_create_line_item', remove = op.tool === 'x_delete_line_item';\n if (op.provider !== 'x' || op.kind !== (create ? 'create' : remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'x: provider or line-item operation kind mismatch');\n const base = `accounts/${account}/line_items`, coercions: string[] = [], budgetDeltas: XWritePlan['budgetDeltas'] = [];\n let current: Line | undefined, params: XParams = {}, expected: Record<string, unknown>, path = base, method: 'POST' | 'PUT' | 'DELETE' = create ? 'POST' : 'PUT';\n if (create) {\n const input = createLine.parse(op.payload), campaign = await this.entities.getCampaign(account, input.campaign_id);\n if (campaign.deleted || campaign.entity_status === 'DRAFT' || campaign.budget_optimization !== 'LINE_ITEM') throw new AdportError('INVALID_INPUT', 'x: creation requires an existing non-deleted/non-draft LINE_ITEM-budget campaign');\n const choices = await this.entities.lineItemPlacements(), selected = [...input.placements].sort().join(',');\n if (!choices.data.some(value => value.product_type === input.product_type && value.placements.some(placements => [...placements].sort().join(',') === selected))) throw new AdportError('INVALID_INPUT', 'x: placement combination is unavailable for this product; inspect x_line_item_placements');\n const siblings = (await this.entities.listLineItems(account)).filter(value => value.campaign_id === input.campaign_id && !value.deleted);\n if (siblings.some(value => value.objective !== input.objective || value.product_type !== input.product_type)) throw new AdportError('INVALID_INPUT', 'x: all campaign line items must share product_type and objective');\n this.bid(input.objective, input.bid_strategy, input.bid_micros, true);\n if (['APP_INSTALLS', 'APP_ENGAGEMENTS'].includes(input.objective) && !input.android_app_store_identifier && !input.ios_app_store_identifier) throw new AdportError('INVALID_INPUT', 'x: app objectives need an explicit app-store identifier; native platform targeting is added automatically');\n if (input.placements.includes('PUBLISHER_NETWORK') && (!input.advertiser_domain || !input.categories?.length)) throw new AdportError('INVALID_INPUT', 'x: publisher placement needs advertiser_domain and IAB categories');\n if (input.goal === 'SITE_VISITS' && input.objective !== 'WEBSITE_CLICKS' || input.goal === 'APP_PURCHASES' && input.objective !== 'APP_INSTALLS' || ['APP_CLICKS', 'APP_INSTALLS'].includes(input.goal ?? '') && !['APP_INSTALLS', 'APP_ENGAGEMENTS'].includes(input.objective)) throw new AdportError('INVALID_INPUT', 'x: goal is not documented for the selected objective');\n const primary = input.primary_web_event_tag ? (await this.measurement.getWeb({ account_id: account, web_event_tag_id: input.primary_web_event_tag })).data : undefined;\n if (primary && primary.configuration_hash !== input.expected_web_event_tag_hash) throw new AdportError('INVALID_INPUT', 'x: primary web event tag configuration changed; read and preview it again');\n const status = guard.forcePausedCreation ? 'PAUSED' : input.status;\n if (status !== input.status) coercions.push('entity_status coerced to PAUSED by policy (paused_creation)');\n params = { campaign_id: input.campaign_id, name: input.name, objective: input.objective, product_type: input.product_type, placements: input.placements.join(','), start_time: input.start_time, end_time: input.end_time, entity_status: status, bid_strategy: input.bid_strategy, standard_delivery: input.standard_delivery };\n for (const key of ['android_app_store_identifier', 'ios_app_store_identifier', 'advertiser_domain', 'goal', 'primary_web_event_tag'] as const) if (input[key] !== undefined) params[key] = input[key];\n if (input.categories) params.categories = input.categories.join(',');\n for (const [source, target] of [['bid_micros', 'bid_amount_local_micro'], ['daily_budget_micros', 'daily_budget_amount_local_micro'], ['total_budget_micros', 'total_budget_amount_local_micro']] as const) if (input[source] !== undefined) { params[target] = input[source]; budgetDeltas.push({ target: `new line item ${target}`, toMicros: input[source] }); }\n expected = { ...params, deleted: false };\n const measurementNotes = ['Native objective/goal/account eligibility is checked by X on apply; this is a local preview.', 'No pixel code is installed and no conversion event is sent. Event status does not prove current measurement accuracy.'];\n return { summary: `Create X line item ${input.name}`, changes: [`Native POST ${base}: ${JSON.stringify(params)}; currency ${campaign.currency}. ${input.android_app_store_identifier || input.ios_app_store_identifier ? 'Native app-store parameters add platform targeting.' : ''}`], coercions, budgetDeltas,\n ...(input.goal || primary ? { notes: measurementNotes, review: { provider: 'x', accountId: account, kind: 'create' as const, title: 'Create ad group', subject: input.name, fields: [{ label: 'Campaign', after: campaign.name }, { label: 'Objective', after: input.objective }, { label: 'Goal', after: input.goal ?? 'Native default' }, { label: 'Status', after: status }, { label: 'Placements', after: input.placements.join(', ') }, { label: 'Start', after: input.start_time }, { label: 'End', after: input.end_time }, { label: 'Bid strategy', after: input.bid_strategy }, ...(primary ? [{ label: 'Primary event', after: `${primary.name} · ${primary.id}` }, { label: 'Event type', after: primary.type }, { label: 'Native event status', after: typeof primary.status === 'string' ? primary.status : 'Not reported' }] : []), ...budgetDeltas.map(value => ({ label: value.target.endsWith('bid_amount_local_micro') ? 'Bid' : value.target.endsWith('daily_budget_amount_local_micro') ? 'Daily budget' : 'Total budget', after: value.toMicros, format: 'money' as const, currency: campaign.currency }))], notices: measurementNotes } } : {}),\n execute: async () => {\n let created: string | undefined;\n try {\n const ids = await this.receipt('POST', base, params, campaign.currency, expected);created = ids[0];\n if (input.goal || primary) this.verify(await this.entities.getLineItem(account, created!), campaign.currency, { ...expected, id: created });\n return ids;\n } catch (error) {\n if (!created) throw error;\n throw new AdportError('PROVIDER_ERROR', 'x: created ad-group measurement configuration is unconfirmed; inspect the known ID before another create; do not replay automatically', { resource_ids: [created] });\n }\n } };\n }\n current = await this.entities.getLineItem(account, id.parse(op.payload.line_item_id));\n if (current.deleted || current.entity_status === 'DRAFT') throw new AdportError('INVALID_INPUT', 'x: deleted/draft line items are not editable through this workflow');\n const parent = await this.entities.getCampaign(account, current.campaign_id);\n if (!remove && (parent.deleted || parent.entity_status === 'DRAFT')) throw new AdportError('INVALID_INPUT', 'x: parent campaign is deleted or draft');\n path = `${base}/${current.id}`;\n if (remove) {\n if (!['PROMOTED_TWEETS', 'PROMOTED_ACCOUNT', 'MEDIA'].includes(current.product_type)) throw new AdportError('INVALID_INPUT', 'x: unsupported product type; child ownership cannot be proven for deletion');\n const [posts, media, users] = await Promise.all([current.product_type !== 'MEDIA' ? this.entities.listPromotedTweets(account) : [], current.product_type === 'MEDIA' ? this.entities.listMediaCreatives(account) : [], current.product_type === 'PROMOTED_ACCOUNT' ? this.entities.listPromotedAccounts(account) : []]);\n if ([...posts, ...media, ...users].some(value => value.line_item_id === current!.id && !value.deleted)) throw new AdportError('INVALID_INPUT', 'x: remove line-item promotions/media before deleting their parent');\n method = 'DELETE'; expected = { id: current.id, campaign_id: current.campaign_id, deleted: true };\n } else {\n switch (op.tool) {\n case 'x_update_line_item': { const { line_item_id: _id, ...input } = updateLine.parse(op.payload); params = input; const start = String(input.start_time ?? current.start_time ?? ''), end = String(input.end_time ?? current.end_time ?? ''); if (end && (!start || Date.parse(end) <= Date.parse(start))) throw new AdportError('INVALID_INPUT', 'x: merged end time must follow start'); break; }\n case 'x_set_line_item_status': params = { entity_status: z.enum(['ACTIVE', 'PAUSED']).parse(op.payload.status) }; break;\n case 'x_set_line_item_budget': {\n const key = z.enum(['DAILY', 'TOTAL']).parse(op.payload.budget_type) === 'DAILY' ? 'daily_budget_amount_local_micro' : 'total_budget_amount_local_micro', previous = current[key], target = micros.parse(op.payload.budget_micros);\n if (!Number.isSafeInteger(previous) || previous === null || previous === undefined) throw new AdportError('INVALID_INPUT', 'x: an existing budget of the same type is required');\n if (parent.budget_optimization !== 'LINE_ITEM') throw new AdportError('INVALID_INPUT', 'x: line-item budgets require LINE_ITEM parent budget optimization');\n const daily = key === 'daily_budget_amount_local_micro' ? target : current.daily_budget_amount_local_micro, total = key === 'total_budget_amount_local_micro' ? target : current.total_budget_amount_local_micro;\n if (daily !== null && daily !== undefined && total !== null && total !== undefined && daily > total) throw new AdportError('INVALID_INPUT', 'x: daily budget cannot exceed total');\n params = { [key]: target }; budgetDeltas.push({ target: `line item ${current.id} ${key}`, fromMicros: previous, toMicros: target }); break;\n }\n case 'x_set_line_item_bidding': {\n const input = setLineBid.parse(op.payload), strategy = input.bid_strategy ?? current.bid_strategy;\n if (!strategy || !['AUTO', 'MAX', 'TARGET'].includes(strategy)) throw new AdportError('INVALID_INPUT', 'x: current bidding strategy is unavailable');\n if (strategy === 'AUTO' && current.bid_strategy !== 'AUTO') throw new AdportError('INVALID_INPUT', 'x: removing a monetary bid cap via AUTO cannot be represented by current policy');\n const previous = current.bid_strategy === 'AUTO' ? undefined : current.bid_amount_local_micro, amount = input.bid_micros ?? previous;\n if (current.bid_strategy !== 'AUTO' && (previous === undefined || previous === null)) throw new AdportError('INVALID_INPUT', 'x: current monetary bid is unavailable');\n this.bid(current.objective, strategy, amount, false); params = { ...(input.bid_strategy ? { bid_strategy: strategy } : {}), ...(input.bid_micros !== undefined ? { bid_amount_local_micro: input.bid_micros } : {}) };\n if (input.bid_micros !== undefined) budgetDeltas.push({ target: `line item ${current.id} bid`, ...(previous !== undefined && previous !== null ? { fromMicros: previous } : {}), toMicros: input.bid_micros }); break;\n }\n default: throw new AdportError('INVALID_INPUT', `x: unsupported management write ${op.tool}`);\n }\n const preserved = Object.fromEntries(['id', 'campaign_id', 'deleted', 'entity_status', 'name', 'objective', 'product_type', 'placements', 'bid_strategy', 'bid_amount_local_micro', 'daily_budget_amount_local_micro', 'total_budget_amount_local_micro', 'start_time', 'end_time', 'standard_delivery'].filter(key => current![key] !== undefined).map(key => [key, current![key]]));\n expected = { ...preserved, ...params };\n }\n const value = current;\n return { summary: `${remove ? 'Delete' : 'Update'} X line item ${value.name ?? value.id}`, changes: [`Native ${method} ${path}: ${JSON.stringify(params)}`], coercions, budgetDeltas, execute: () => this.receipt(method, path, params, value.currency, expected) };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { xId as id } from './schemas.js';\n\nexport const micros = z.number().int().positive().safe(), objective = z.enum(['APP_ENGAGEMENTS', 'APP_INSTALLS', 'REACH', 'FOLLOWERS', 'ENGAGEMENTS', 'VIDEO_VIEWS', 'PREROLL_VIEWS', 'WEBSITE_CLICKS']);\nconst placement = z.enum(['ALL_ON_TWITTER', 'PUBLISHER_NETWORK', 'TAP_BANNER', 'TAP_FULL', 'TAP_FULL_LANDSCAPE', 'TAP_NATIVE', 'TAP_MRECT', 'TWITTER_PROFILE', 'TWITTER_REPLIES', 'TWITTER_SEARCH', 'TWITTER_TIMELINE']);\nconst time = z.iso.datetime({ offset: true }), name = z.string().min(1).max(255);\nconst goal = z.enum(['APP_CLICKS', 'APP_INSTALLS', 'APP_PURCHASES', 'ENGAGEMENT', 'FOLLOWERS', 'LINK_CLICKS', 'MAX_REACH', 'PREROLL', 'PREROLL_STARTS', 'REACH_WITH_ENGAGEMENT', 'SITE_VISITS', 'VIDEO_VIEW', 'VIEW_3S_100PCT', 'VIEW_6S', 'VIEW_15S', 'WEBSITE_CONVERSIONS']);\nexport const createLine = z.object({ campaign_id: id, name, objective, product_type: z.enum(['MEDIA', 'PROMOTED_ACCOUNT', 'PROMOTED_TWEETS']), placements: z.array(placement).min(1).max(10).refine(v => new Set(v).size === v.length, 'Use unique placements'), start_time: time, end_time: time, status: z.enum(['ACTIVE', 'PAUSED']).default('PAUSED'), bid_strategy: z.enum(['AUTO', 'MAX', 'TARGET']).default('AUTO'), bid_micros: micros.optional(), daily_budget_micros: micros.optional(), total_budget_micros: micros.optional(), android_app_store_identifier: z.string().min(1).optional(), ios_app_store_identifier: z.string().regex(/^\\d+$/).optional(), advertiser_domain: z.string().regex(/^(?![.-])[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$/).optional(), categories: z.array(z.string().min(1)).optional(), standard_delivery: z.boolean().default(true), goal: goal.optional(), primary_web_event_tag: id.optional(), expected_web_event_tag_hash: z.string().regex(/^[a-f0-9]{64}$/).optional() }).refine(v => Date.parse(v.end_time) > Date.parse(v.start_time), 'End must follow start').refine(v => v.daily_budget_micros === undefined || v.total_budget_micros === undefined || v.daily_budget_micros <= v.total_budget_micros, 'Daily budget cannot exceed total').refine(v => (v.primary_web_event_tag !== undefined) === (v.expected_web_event_tag_hash !== undefined), 'Provide both primary_web_event_tag and expected_web_event_tag_hash').refine(v => v.goal !== 'WEBSITE_CONVERSIONS' || v.primary_web_event_tag !== undefined, 'WEBSITE_CONVERSIONS requires a primary_web_event_tag and its current hash');\nexport const updateLine = z.object({ line_item_id: id, name: name.optional(), start_time: time.optional(), end_time: time.optional() }).refine(v => Object.keys(v).length > 1, 'Provide line-item changes');\nexport const setLineBid = z.object({ line_item_id: id, bid_strategy: z.enum(['AUTO', 'MAX', 'TARGET']).optional(), bid_micros: micros.optional() }).refine(v => v.bid_strategy !== undefined || v.bid_micros !== undefined, 'Provide bid settings');\n\nexport function xManagementTools(provider: XAdsProvider): AnyToolDefinition[] {\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove' = 'update') => guardedWriteTool({ name, namespace: 'x', provider: 'x', description, payload, kind });\n return [\n defineTool({ name: 'x_line_item_placements', namespace: 'x', description: 'Read current native placement combinations by product type after verifying access to the selected account.', input: z.object({ account_id: id }), annotations: { readOnly: true }, handler: async v => { await provider.getAccount(v.account_id); return provider.lineItemPlacements(); } }),\n write('x_create_line_item', 'Create a paused X ad group with explicit objective, product, placements and flight. Budgets/bids use micros; AUTO cannot claim a monetary bid cap. Parent currency and sibling format are checked. Optional native goal and primary conversion tag require a fresh tag hash; native eligibility remains authoritative.', createLine, 'create'),\n write('x_update_line_item', 'Edit supplied line-item name/start/end fields, preserving omitted schedule bounds and delivery status.', updateLine),\n write('x_set_line_item_status', 'Pause or activate a verified line item using native PUT. Draft/deleted line items are rejected.', z.object({ line_item_id: id, status: z.enum(['PAUSED', 'ACTIVE']) })),\n write('x_set_line_item_budget', 'Change an existing line-item daily or total cap in integer micros, preserving the other cap and using current values for policy checks.', z.object({ line_item_id: id, budget_type: z.enum(['DAILY', 'TOTAL']), budget_micros: micros })),\n write('x_set_line_item_bidding', 'Change native AUTO/MAX/TARGET bidding with current monetary values. Removing a bounded bid via AUTO is rejected because policy cannot represent an unbounded change.', setLineBid),\n write('x_delete_line_item', 'Delete a verified line item only after its promoted posts/accounts/media creatives are removed. Native receipt must confirm deletion.', z.object({ line_item_id: id }), 'remove'),\n ];\n}\n","import { AdportError, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport { XAdsEntities } from './entities.js';\nimport { addCriterion, criteriaInput, optionsInput, updateCriteria } from './targeting-tools.js';\nimport { xId as id } from './schemas.js';\nimport type { XWritePlan } from './writes.js';\n\ntype Row = Record<string, unknown>;\nconst rows = z.array(z.record(z.string(), z.unknown()));\nconst criterion = z.looseObject({ id, line_item_id: id, targeting_type: z.string(), targeting_value: z.string(), operator_type: z.string().optional(), deleted: z.boolean() });\nconst includedLocation = (value: { targeting_type: string; operator_type?: string }) => value.targeting_type === 'LOCATION' && value.operator_type !== 'NE';\nconst optionParams: Record<string, readonly string[]> = { app_store_categories: ['q', 'os_type'], conversations: ['conversation_type', 'count', 'cursor'], devices: ['count', 'q'], events: ['event_types', 'count', 'country_codes', 'cursor', 'end_time', 'start_time'], interests: ['count', 'cursor', 'q'], languages: ['count', 'cursor', 'q'], locations: ['count', 'country_code', 'cursor', 'location_type', 'q'], network_operators: ['count', 'country_code', 'cursor', 'q'], platform_versions: ['q'], platforms: ['count', 'q', 'lang'], tv_markets: [], tv_shows: ['locale', 'count', 'cursor', 'q'] };\ntype Collection = 'custom_audiences' | 'promotable_users' | 'app_lists';\nexport class XTargetingService {\n constructor(private readonly entities: XAdsEntities) {}\n async options(value: z.input<typeof optionsInput>) {\n const input = optionsInput.parse(value), allowed = optionParams[input.dimension]!;\n if (input.dimension === 'tv_shows' && (!input.locale || input.count > 50)) throw new AdportError('INVALID_INPUT', 'x: TV shows require locale and count <=50');\n const params: XParams = {};\n for (const [key, value] of Object.entries(input)) {\n if (['account_id', 'dimension'].includes(key) || value === undefined || (key === 'count' && !allowed.includes('count'))) continue;\n if (!allowed.includes(key)) throw new AdportError('INVALID_INPUT', `x: ${key} is not supported for targeting ${input.dimension}`);\n params[key] = Array.isArray(value) ? value.join(',') : value;\n }\n await this.entities.getAccount(input.account_id);\n const result = await this.entities.client.request('GET', `targeting_criteria/${input.dimension}`, z.object({ data: rows, next_cursor: z.string().nullable().optional() }), params), paged = allowed.includes('cursor'), next = paged ? result.next_cursor ?? undefined : undefined;\n if (next && next === input.cursor) throw new AdportError('PROVIDER_ERROR', 'x: targeting pagination repeated its cursor');\n if (paged && result.data.length > 1000) throw new AdportError('PROVIDER_ERROR', 'x: native targeting page exceeds its documented maximum');\n const limited = !paged && (result.data.length > input.count || Boolean(result.next_cursor) || (allowed.includes('count') && result.data.length >= input.count));\n return { items: paged ? result.data : result.data.slice(0, input.count), truncated: Boolean(next) || limited, ...(next ? { next_cursor: next } : {}), ...(limited ? { warning: 'Native endpoint has no documented usable continuation for this limit. Narrow the filter or increase count.' } : paged && result.data.length > input.count ? { warning: 'Native endpoint exceeded the requested count; the complete page is retained so continuation skips no choices.' } : {}) };\n }\n async criteria(value: z.input<typeof criteriaInput>) {\n const input = criteriaInput.parse(value), wanted = [...new Set(input.line_item_ids)]; let index = 0;\n await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => { while (index < wanted.length) await this.entities.getLineItem(input.account_id, wanted[index++]!); }));\n const page = await this.entities.client.request('GET', `accounts/${input.account_id}/targeting_criteria`, z.object({ data: z.array(criterion), next_cursor: z.string().nullable().optional() }), { line_item_ids: wanted.join(','), count: input.count, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}) });\n if (page.data.some(value => !wanted.includes(value.line_item_id) || (!input.with_deleted && value.deleted))) throw new AdportError('PROVIDER_ERROR', 'x: criteria list returned another line item or an excluded deleted row');\n if (new Set(page.data.map(value => value.id)).size !== page.data.length) throw new AdportError('PROVIDER_ERROR', 'x: criteria list repeated an entity');\n if (page.next_cursor && page.next_cursor === input.cursor) throw new AdportError('PROVIDER_ERROR', 'x: criteria pagination repeated its cursor');\n return { items: page.data, truncated: Boolean(page.next_cursor), ...(page.next_cursor ? { next_cursor: page.next_cursor } : {}) };\n }\n async owned(account: string, resource: string) {\n const { data } = await this.entities.client.request('GET', `accounts/${id.parse(account)}/targeting_criteria/${id.parse(resource)}`, z.object({ data: criterion }));\n if (data.id !== resource) throw new AdportError('PROVIDER_ERROR', 'x: criterion ID mismatch');\n await this.entities.getLineItem(account, data.line_item_id);\n return data;\n }\n private async current(account: string, line: string) {\n const items: Array<z.infer<typeof criterion>> = [], seen = new Set<string>(), ids = new Set<string>(); let cursor: string | undefined;\n while (true) {\n const page = await this.entities.client.request('GET', `accounts/${account}/targeting_criteria`, z.object({ data: z.array(criterion), next_cursor: z.string().nullable().optional() }), { line_item_ids: line, with_deleted: false, count: 1000, ...(cursor ? { cursor } : {}) });\n if (page.data.some(value => value.line_item_id !== line || value.deleted)) throw new AdportError('PROVIDER_ERROR', 'x: current criteria scope/deletion mismatch');\n if (page.data.length > 1000 || items.length + page.data.length > 5000) throw new AdportError('INVALID_INPUT', 'x: criteria context exceeds the safe mutation limit');\n for (const value of page.data) { if (ids.has(value.id)) throw new AdportError('PROVIDER_ERROR', 'x: criteria pagination repeated an entity'); ids.add(value.id); }\n items.push(...page.data);\n if (!page.next_cursor) return items;\n if (items.length >= 5000 || seen.has(page.next_cursor) || seen.size >= 25) throw new AdportError('INVALID_INPUT', 'x: criteria context exceeds the safe mutation limit or repeats pages');\n seen.add(page.next_cursor); cursor = page.next_cursor;\n }\n }\n private async available(account: string, collection: 'custom_audiences' | 'promotable_users' | 'app_lists', find: (row: Row) => boolean): Promise<Row> {\n const seen = new Set<string>(); let count = 0, cursor: string | undefined;\n while (true) {\n const page = await this.entities.client.request('GET', `accounts/${account}/${collection}`, z.object({ data: rows, next_cursor: z.string().nullable().optional() }), { count: 200, ...(cursor ? { cursor } : {}) });\n const found = page.data.find(find); if (found) return found;\n count += page.data.length;\n if (!page.next_cursor || count >= 5000 || seen.has(page.next_cursor) || seen.size >= 25) throw new AdportError('INVALID_INPUT', `x: reference is not in the account’s first 5,000 available ${collection}`);\n seen.add(page.next_cursor); cursor = page.next_cursor;\n }\n }\n private async source(account: string, input: z.infer<typeof addCriterion>, lookup: (collection: Collection, find: (row: Row) => boolean) => Promise<Row> = (collection, find) => this.available(account, collection, find)) {\n const type = input.targeting_type, value = input.targeting_value;\n if (type.startsWith('CUSTOM_AUDIENCE')) {\n const audience = await lookup('custom_audiences', row => row.id === value);\n if (audience.deleted !== false || audience.targetable !== true) throw new AdportError('INVALID_INPUT', 'x: audience is deleted or not targetable');\n } else if (type.startsWith('CAMPAIGN_ENGAGEMENT')) await this.entities.getCampaign(account, id.parse(value));\n else if (['USER_ENGAGEMENT', 'USER_ENGAGEMENT_LOOKALIKE', 'FOLLOWERS_OF_USER'].includes(type)) await lookup('promotable_users', row => row.user_id === value && row.promotable_user_type === 'FULL' && row.deleted === false);\n else if (type === 'APP_LIST') { if (input.operator_type !== 'NE') throw new AdportError('INVALID_INPUT', 'x: APP_LIST is exclusion-only (NE)'); const list = await lookup('app_lists', row => row.id === value); if (list.deleted === true) throw new AdportError('INVALID_INPUT', 'x: app list is deleted'); }\n else if (type === 'ENGAGEMENT_TYPE' && !['IMPRESSION', 'ENGAGEMENT'].includes(value)) throw new AdportError('INVALID_INPUT', 'x: ENGAGEMENT_TYPE must be IMPRESSION or ENGAGEMENT');\n }\n private finalState(values: Array<{ targeting_type: string; targeting_value: string; operator_type?: string }>) {\n const types = values.map(value => value.targeting_type), sources = ['CAMPAIGN_ENGAGEMENT', 'CAMPAIGN_ENGAGEMENT_LOOKALIKE', 'USER_ENGAGEMENT', 'USER_ENGAGEMENT_LOOKALIKE'];\n if (types.filter(type => type === 'AGE').length > 1) throw new AdportError('INVALID_INPUT', 'x: only one age bucket is allowed; use a batch replacement');\n if (types.includes('TV_SHOW') && !values.some(includedLocation)) throw new AdportError('INVALID_INPUT', 'x: TV shows require included location targeting; native provider also checks market compatibility');\n if (types.includes('ENGAGEMENT_TYPE') !== types.some(type => sources.includes(type))) throw new AdportError('INVALID_INPUT', 'x: engagement type and source must be configured together; use x_update_targeting for an atomic pair');\n const keys = values.map(value => JSON.stringify([value.targeting_type, value.operator_type ?? 'EQ', value.targeting_value]));\n if (new Set(keys).size !== keys.length) throw new AdportError('INVALID_INPUT', 'x: identical targeting criteria would be duplicated');\n }\n private async batch(op: WriteOperation): Promise<XWritePlan> {\n const account = id.parse(op.accountId), input = updateCriteria.parse(op.payload);\n if (op.provider !== 'x' || op.kind !== 'update') throw new AdportError('INVALID_INPUT', 'x: batch targeting operation kind/provider mismatch');\n const line = await this.entities.getLineItem(account, input.line_item_id);\n if (line.deleted || line.entity_status === 'DRAFT') throw new AdportError('INVALID_INPUT', 'x: deleted/draft line items cannot be changed');\n const current = await this.current(account, line.id), removed = input.remove.map(id => current.find(value => value.id === id));\n if (removed.some(value => !value)) throw new AdportError('INVALID_INPUT', 'x: every removed criterion must currently belong to the selected line item');\n const additions = input.add.map(value => ({ ...value, line_item_id: line.id })), final = [...current.filter(value => !input.remove.includes(value.id)), ...additions]; this.finalState(final);\n const books = new Map<Collection, Promise<Row[]>>(), lookup = async (collection: Collection, find: (row: Row) => boolean) => {\n let loaded = books.get(collection);\n if (!loaded) { loaded = (async () => { const all: Row[] = [], seen = new Set<string>(); let cursor: string | undefined; while (true) { const page = await this.entities.client.request('GET', `accounts/${account}/${collection}`, z.object({ data: rows, next_cursor: z.string().nullable().optional() }), { count: 200, ...(cursor ? { cursor } : {}) }); all.push(...page.data.slice(0, 5000 - all.length)); if (!page.next_cursor || all.length >= 5000) return all; if (seen.has(page.next_cursor) || seen.size >= 25) throw new AdportError('PROVIDER_ERROR', 'x: source availability pagination repeated'); seen.add(page.next_cursor); cursor = page.next_cursor; } })(); books.set(collection, loaded); }\n const found = (await loaded).find(find); if (!found) throw new AdportError('INVALID_INPUT', `x: reference is not in the account’s first 5,000 available ${collection}`); return found;\n };\n for (const value of additions) await this.source(account, value, lookup);\n const operations = [...input.remove.map(value => ({ operation_type: 'Delete', params: { targeting_criterion_id: value } })), ...additions.map(value => ({ operation_type: 'Create', params: value }))], expected = [...removed.map(value => ({ ...value!, deleted: true })), ...additions.map(value => ({ ...value, deleted: false }))];\n const lastLocation = current.some(includedLocation) && !final.some(includedLocation);\n return { summary: `Atomically update X targeting for ${line.id}`, changes: [`Remove existing criteria: ${JSON.stringify(removed.map(value => ({ id: value!.id, type: value!.targeting_type, value: value!.targeting_value, operator: value!.operator_type ?? 'unavailable' })))}`, `Native batch: ${input.remove.length} removals, ${additions.length} additions. Group status ${line.entity_status}. ${JSON.stringify(operations)}`, ...(lastLocation ? ['This removes the last LOCATION criterion and can broaden geographic delivery.'] : [])], coercions: [], budgetDeltas: [], execute: async () => {\n const response = await this.entities.client.request('POST', `batch/accounts/${account}/targeting_criteria`, z.object({ data: z.array(criterion) }), {}, operations), ids = response.data.map(value => value.id);\n if (response.data.length !== expected.length || new Set(ids).size !== ids.length || response.data.some((value, index) => { const wanted = expected[index]!; return value.line_item_id !== line.id || value.deleted !== wanted.deleted || value.targeting_type !== wanted.targeting_type || value.targeting_value !== wanted.targeting_value || ('id' in wanted && wanted.id !== value.id) || (!wanted.deleted && value.operator_type !== wanted.operator_type); })) throw new AdportError('PROVIDER_ERROR', 'x: ordered batch targeting receipts differ from the approved plan; reconcile before retrying', { resource_ids: ids });\n return ids;\n } };\n }\n async plan(op: WriteOperation, _guard: WriteGuard): Promise<XWritePlan> {\n if (op.tool === 'x_update_targeting') return this.batch(op);\n const account = id.parse(op.accountId), add = op.tool === 'x_add_targeting_criterion';\n if (op.provider !== 'x' || !['x_add_targeting_criterion', 'x_remove_targeting_criterion'].includes(op.tool) || op.kind !== (add ? 'create' : 'remove')) throw new AdportError('INVALID_INPUT', 'x: provider or targeting operation kind mismatch');\n const input = add ? addCriterion.parse(op.payload) : undefined, previous = add ? undefined : await this.owned(account, id.parse(op.payload.targeting_criterion_id)), line = await this.entities.getLineItem(account, input?.line_item_id ?? previous!.line_item_id);\n if (line.deleted || line.entity_status === 'DRAFT' || previous?.deleted) throw new AdportError('INVALID_INPUT', 'x: deleted/draft line items or deleted criteria cannot be changed');\n const current = await this.current(account, line.id);\n if (!add && !current.some(value => value.id === previous!.id)) throw new AdportError('INVALID_INPUT', 'x: criterion is no longer current on the selected line item');\n this.finalState(add ? [...current, input!] : current.filter(value => value.id !== previous!.id));\n if (input) {\n await this.source(account, input);\n if (current.some(value => value.targeting_type === input.targeting_type && value.targeting_value === input.targeting_value && (value.operator_type ?? 'EQ') === input.operator_type)) throw new AdportError('INVALID_INPUT', 'x: identical criterion already exists');\n }\n const item = input ?? previous!, lastLocation = !add && includedLocation(item) && current.filter(includedLocation).length === 1, changes = [`${add ? 'Add' : 'Remove'} ${JSON.stringify(item)}; line item ${line.id}, status ${line.entity_status}; ${current.length} current criteria. Active group audience can change immediately.`, ...(lastLocation ? ['This removes the last included LOCATION criterion and can broaden geographic delivery.'] : [])];\n return { summary: `${add ? 'Add' : 'Remove'} X targeting criterion`, changes, coercions: [], budgetDeltas: [], execute: async () => {\n const path = `accounts/${account}/targeting_criteria${add ? '' : `/${previous!.id}`}`, params: XParams = input ? { line_item_id: input.line_item_id, targeting_type: input.targeting_type, targeting_value: input.targeting_value, operator_type: input.operator_type } : {};\n const response = await this.entities.client.request(add ? 'POST' : 'DELETE', path, z.object({ data: criterion }), params), value = response.data;\n const expectedId = previous?.id ?? value.id;\n if (value.id !== expectedId || value.line_item_id !== line.id || value.targeting_type !== item.targeting_type || value.targeting_value !== item.targeting_value || value.deleted !== !add) throw new AdportError('PROVIDER_ERROR', 'x: criterion receipt differs from the approved plan; reconcile before retrying', { resource_ids: [value.id] });\n if (input) {\n let native = value;\n try { if (native.operator_type === undefined) native = (await this.entities.client.request('GET', `accounts/${account}/targeting_criteria/${value.id}`, z.object({ data: criterion }))).data; }\n catch { throw new AdportError('PROVIDER_ERROR', 'x: criterion operator readback failed; reconcile before retrying', { resource_ids: [value.id] }); }\n if (native.id !== value.id || native.line_item_id !== line.id || native.targeting_type !== input.targeting_type || native.targeting_value !== input.targeting_value || native.operator_type !== input.operator_type || native.deleted) throw new AdportError('PROVIDER_ERROR', 'x: criterion operator readback mismatch; reconcile before retrying', { resource_ids: [value.id] });\n }\n return [value.id];\n } };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { xId as id } from './schemas.js';\n\nexport const optionDimensions = z.enum(['app_store_categories', 'conversations', 'devices', 'events', 'interests', 'languages', 'locations', 'network_operators', 'platform_versions', 'platforms', 'tv_markets', 'tv_shows']);\nexport const optionsInput = z.object({ account_id: id, dimension: optionDimensions, count: z.number().int().min(1).max(1000).default(50), cursor: z.string().optional(), q: z.string().min(1).max(255).optional(), os_type: z.enum(['ANDROID', 'IOS']).optional(), country_code: z.string().regex(/^[A-Z]{2}$/).optional(), country_codes: z.array(z.string().regex(/^[A-Z]{2}$/)).min(1).max(100).optional(), location_type: z.enum(['COUNTRIES', 'REGIONS', 'METROS', 'CITIES', 'POSTAL_CODES']).optional(), conversation_type: z.string().regex(/^[A-Z_]+$/).optional(), event_types: z.array(z.enum(['CONFERENCE', 'HOLIDAY', 'MUSIC_AND_ENTERTAINMENT', 'OTHER', 'POLITICS', 'RECURRING', 'SPORTS'])).min(1).optional(), start_time: z.iso.datetime({ offset: true }).optional(), end_time: z.iso.datetime({ offset: true }).optional(), locale: z.string().regex(/^[a-z]{2}-[A-Z]{2}$/).optional(), lang: z.string().regex(/^[a-z]{2}$/).optional() });\nexport const criteriaInput = z.object({ account_id: id, line_item_ids: z.array(id).min(1).max(20), count: z.number().int().min(1).max(1000).default(100), cursor: z.string().optional(), with_deleted: z.boolean().default(false) });\nexport const addCriterion = z.object({ line_item_id: id, targeting_type: z.enum(['AGE', 'DEVICE', 'EVENT', 'CAMPAIGN_ENGAGEMENT', 'CAMPAIGN_ENGAGEMENT_LOOKALIKE', 'CONVERSATION', 'ENGAGEMENT_TYPE', 'FOLLOWERS_OF_USER', 'GENDER', 'INTEREST', 'LANGUAGE', 'LIVE_TV_EVENT', 'LOCATION', 'NETWORK_ACTIVATION_DURATION', 'NETWORK_OPERATOR', 'PLATFORM', 'PLATFORM_VERSION', 'SIMILAR_TO_FOLLOWERS_OF_USER', 'TV_SHOW', 'USER_ENGAGEMENT', 'USER_ENGAGEMENT_LOOKALIKE', 'WIFI_ONLY', 'BROAD_KEYWORD', 'EXACT_KEYWORD', 'PHRASE_KEYWORD', 'UNORDERED_KEYWORD', 'CUSTOM_AUDIENCE', 'CUSTOM_AUDIENCE_EXPANDED', 'APP_STORE_CATEGORY', 'APP_STORE_CATEGORY_LOOKALIKE', 'APP_LIST']), targeting_value: z.string().min(1).max(2000), operator_type: z.enum(['EQ', 'NE', 'GTE', 'LT']).default('EQ') });\nexport const updateCriteria = z.object({ line_item_id: id, add: z.array(addCriterion.omit({ line_item_id: true })).max(500).default([]), remove: z.array(id).max(500).default([]) }).refine(v => v.add.length + v.remove.length >= 1 && v.add.length + v.remove.length <= 500, 'Provide 1–500 combined operations').refine(v => new Set(v.remove).size === v.remove.length, 'Use unique removal IDs');\n\nexport function xTargetingTools(provider: XAdsProvider): AnyToolDefinition[] {\n return [\n defineTool({ name: 'x_targeting_options', namespace: 'x', description: 'Read current native targeting choices. Filters are checked per dimension. Unpaged dimensions use count as a local limit and report potential truncation.', input: optionsInput, annotations: { readOnly: true }, handler: v => provider.targeting.options(v) }),\n defineTool({ name: 'x_targeting_criteria', namespace: 'x', description: 'Read native criteria for selected verified line items, including type/value/operator and native cursor pagination.', input: criteriaInput, annotations: { readOnly: true }, handler: v => provider.targeting.criteria(v) }),\n defineTool({ name: 'x_get_targeting_criterion', namespace: 'x', description: 'Read one criterion and verify its line-item/campaign account hierarchy.', input: z.object({ account_id: id, targeting_criterion_id: id }), annotations: { readOnly: true }, handler: v => provider.targeting.owned(v.account_id, v.targeting_criterion_id) }),\n guardedWriteTool({ name: 'x_add_targeting_criterion', namespace: 'x', provider: 'x', kind: 'create', description: 'Add one native criterion without replacing other dimensions. Referenced audiences/campaigns/users/apps are verified. Can change an active group’s audience immediately.', payload: addCriterion }),\n guardedWriteTool({ name: 'x_remove_targeting_criterion', namespace: 'x', provider: 'x', kind: 'remove', description: 'Remove one verified native criterion. Preview identifies removal of the last location bound. Multi-step replacements should be reviewed with the group paused.', payload: z.object({ targeting_criterion_id: id }) }),\n guardedWriteTool({ name: 'x_update_targeting', namespace: 'x', provider: 'x', kind: 'update', description: 'Atomically add/remove 1–500 criteria on one verified line item through native JSON batch. Checks final targeting dependencies, source availability and each ordered receipt; other dimensions remain unchanged.', payload: updateCriteria }),\n ];\n}\n","import { AdportError, type Creative, type WriteGuard, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport { cardUri, createDraft, draftList, libraryList, mediaKey, snowflake, updateDraft, updateLibrary } from './creative-tools.js';\nimport type { XAdsEntities } from './entities.js';\nimport { xId } from './schemas.js';\nimport type { XWritePlan } from './writes.js';\n\nconst draftSchema = z.looseObject({ id: snowflake, user_id: snowflake, text: z.string(), name: z.string().nullable(), nullcast: z.boolean(), card_uri: cardUri.nullable(), media_keys: z.array(mediaKey), status: z.string().optional() });\nconst librarySchema = z.looseObject({ media_key: mediaKey, media_type: z.enum(['IMAGE', 'VIDEO', 'GIF']), media_status: z.string(), deleted: z.boolean() });\nconst userSchema = z.looseObject({ id: xId, user_id: snowflake, promotable_user_type: z.string(), deleted: z.boolean() });\nconst cardSchema = z.looseObject({ id: xId, card_uri: cardUri, deleted: z.boolean(), card_type: z.string() });\nconst cursor = { next_cursor: z.string().nullable().optional() };\nconst safeUrl = (value: unknown) => { if (typeof value !== 'string') return undefined; try { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password && ['pbs.twimg.com', 'video.twimg.com', 'ton.twimg.com'].includes(url.hostname) ? value : undefined; } catch { return undefined; } };\nconst same = (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right);\nconst fieldsMatch = (value: Record<string, unknown>, wanted: Record<string, unknown>) => Object.entries(wanted).every(([key, expected]) => same(value[key], expected));\ntype Media = z.infer<typeof librarySchema>;\ntype Draft = z.infer<typeof draftSchema>;\n\nexport class XCreativeService {\n constructor(private readonly entities: XAdsEntities) {}\n async users(account: string, requireComplete = false) {\n await this.entities.getAccount(account);\n const path = `accounts/${xId.parse(account)}/promotable_users`;\n if (!requireComplete) return this.entities.client.list(path, userSchema);\n const rows: z.infer<typeof userSchema>[] = [], ids = new Set<string>(), cursors = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.entities.client.request('GET', path, z.object({ data: z.array(userSchema).max(1000), next_cursor: z.string().nullable().optional() }), { count: 200, ...(cursor ? { cursor } : {}) });\n for (const row of result.data) { if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: promotable-user inventory repeated an ID');ids.add(row.id);rows.push(row); }\n if (result.next_cursor === null) return rows;\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('PROVIDER_ERROR', 'x: promotable-user inventory is incomplete; receiving-author uniqueness is unconfirmed');\n }\n async access(account: string) {\n await this.entities.getAccount(account);\n return (await this.entities.client.request('GET', `accounts/${xId.parse(account)}/authenticated_user_access`, z.object({ data: z.object({ user_id: snowflake, permissions: z.array(z.string()) }) }))).data;\n }\n async verifyComposer(account: string, user: string) {\n if (!(await this.users(account)).some(v => v.user_id === user && v.promotable_user_type === 'FULL' && !v.deleted)) throw new AdportError('INVALID_INPUT', 'x: author must be a current FULL promotable user on the selected account');\n const access = await this.access(account);\n if (access.user_id !== user && !access.permissions.includes('TWEET_COMPOSER')) throw new AdportError('INVALID_INPUT', 'x: authenticated actor needs TWEET_COMPOSER to author for another user');\n return access;\n }\n async draft(account: string, resource: string) {\n await this.entities.getAccount(account);\n const { data } = await this.entities.client.request('GET', `accounts/${xId.parse(account)}/draft_tweets/${snowflake.parse(resource)}`, z.object({ data: draftSchema }));\n if (data.id !== resource || (data.status !== undefined && data.status !== 'DRAFT')) throw new AdportError('PROVIDER_ERROR', 'x: draft ID/state mismatch');\n return data;\n }\n async media(account: string, resource: string) {\n await this.entities.getAccount(account);\n const { data } = await this.entities.client.request('GET', `accounts/${xId.parse(account)}/media_library/${mediaKey.parse(resource)}`, z.object({ data: librarySchema }));\n if (data.media_key !== resource) throw new AdportError('PROVIDER_ERROR', 'x: media key mismatch');\n return data;\n }\n async cards(account: string, values: string[], withDeleted = false) {\n const wanted = [...new Set(values.map(value => cardUri.parse(value)))];\n if (!wanted.length || wanted.length > 200) throw new AdportError('INVALID_INPUT', 'x: provide 1–200 card URIs');\n await this.entities.getAccount(account);\n const { data } = await this.entities.client.request('GET', `accounts/${xId.parse(account)}/cards/all`, z.object({ data: z.array(cardSchema) }), { card_uris: wanted.join(','), with_deleted: withDeleted });\n if (data.some(v => !wanted.includes(v.card_uri) || (!withDeleted && v.deleted)) || new Set(data.map(v => v.card_uri)).size !== data.length) throw new AdportError('PROVIDER_ERROR', 'x: card association/filter mismatch');\n return { items: data, missing: wanted.filter(value => !data.some(v => v.card_uri === value)) };\n }\n async verifyAttachments(account: string, keys: string[], card?: string | null) {\n const media = await Promise.all(keys.map(key => this.media(account, key)));\n if (media.some(value => value.deleted || value.media_status !== 'TRANSCODE_COMPLETED')) throw new AdportError('INVALID_INPUT', 'x: every media attachment must be ready and present in the selected account library');\n if (media.length > 4 || (media.some(value => value.media_type !== 'IMAGE') && media.length > 1)) throw new AdportError('INVALID_INPUT', 'x: use up to four images, one GIF or one video');\n const cards = card ? await this.cards(account, [card]) : { items: [], missing: [] };\n if (cards.missing.length) throw new AdportError('INVALID_INPUT', 'x: card is not available in the selected account');\n return { media, cards: cards.items };\n }\n private page(ids: string[], next: string | null | undefined, previous?: string) {\n if (new Set(ids).size !== ids.length || (next && next === previous)) throw new AdportError('PROVIDER_ERROR', 'x: creative pagination repeated an entity or cursor');\n return { truncated: Boolean(next), ...(next ? { next_cursor: next } : {}) };\n }\n visual(value: Media): Creative['media'] {\n const url = safeUrl(value.media_url), poster = safeUrl(value.poster_media_url);\n return [...(url ? [{ type: value.media_type === 'IMAGE' ? 'image' as const : 'video' as const, url, ...(value.media_type !== 'IMAGE' && poster ? { poster_url: poster } : {}) }] : []), ...(!url && poster ? [{ type: 'image' as const, url: poster, alt: 'Video poster' }] : [])];\n }\n async library(value: z.input<typeof libraryList>) {\n const input = libraryList.parse(value); await this.entities.getAccount(input.account_id);\n const params: XParams = { count: input.count, ...(input.cursor ? { cursor: input.cursor } : {}), ...(input.media_type ? { media_type: input.media_type } : {}), ...(input.q ? { q: input.q } : {}) };\n const result = await this.entities.client.request('GET', `accounts/${input.account_id}/media_library`, z.object({ data: z.array(librarySchema), ...cursor }), params);\n if (result.data.some(v => v.deleted || (input.media_type && v.media_type !== input.media_type))) throw new AdportError('PROVIDER_ERROR', 'x: media library filter/state mismatch');\n const creatives: Creative[] = result.data.map(v => ({ id: v.media_key, provider: 'x', account_id: input.account_id, name: String(v.name ?? v.file_name ?? v.media_key), type: `${v.media_type}_ASSET`, status: v.media_status, headlines: typeof v.title === 'string' && v.title ? [v.title] : [], descriptions: typeof v.description === 'string' && v.description ? [v.description] : [], landing_urls: [], media: this.visual(v), actions: [{ label: 'Rename library media', tool: 'x_update_media_library', arguments: { account_id: input.account_id, media_key: v.media_key }, fields: [{ key: 'name', label: 'Name', type: 'text', value: String(v.name ?? ''), max_length: 100 }] }] }));\n return { items: result.data, creatives, ...this.page(result.data.map(v => v.media_key), result.next_cursor, input.cursor) };\n }\n async drafts(value: z.input<typeof draftList>) {\n const input = draftList.parse(value); await this.entities.getAccount(input.account_id);\n const result = await this.entities.client.request('GET', `accounts/${input.account_id}/draft_tweets`, z.object({ data: z.array(draftSchema), ...cursor }), { count: input.count, ...(input.cursor ? { cursor: input.cursor } : {}), ...(input.user_id ? { user_id: input.user_id } : {}) });\n if (result.data.some(v => (v.status !== undefined && v.status !== 'DRAFT') || (input.user_id && v.user_id !== input.user_id))) throw new AdportError('PROVIDER_ERROR', 'x: draft author/state filter mismatch');\n const sources = new Map<string, Media>(), warnings: string[] = [], wanted = [...new Set(result.data.flatMap(v => v.media_keys))].slice(0, 100); let index = 0;\n if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => { while (index < wanted.length) { const key = wanted[index++]!; try { const value = await this.media(input.account_id, key); if (!value.deleted) sources.set(key, value); else warnings.push(`Media ${key} was deleted from the library.`); } catch { warnings.push(`Media ${key} could not be read from this account.`); } } }));\n if (input.include_media && new Set(result.data.flatMap(v => v.media_keys)).size > 100) warnings.push('Preview hydration is limited to 100 distinct media items; native references remain in items.');\n const creatives: Creative[] = result.data.map(v => ({ id: v.id, provider: 'x', account_id: input.account_id, name: v.name ?? `Draft ${v.id}`, type: v.nullcast ? 'PROMOTED_ONLY_DRAFT' : 'ORGANIC_DRAFT', status: 'DRAFT', headlines: [], descriptions: [v.text], landing_urls: [], media: input.include_media ? v.media_keys.flatMap(key => sources.has(key) ? this.visual(sources.get(key)!) : []) : [], actions: [{ label: 'Edit draft copy', tool: 'x_update_draft_tweet', arguments: { account_id: input.account_id, draft_tweet_id: v.id }, fields: [{ key: 'text', label: 'Post text', type: 'text', value: v.text }] }, { label: 'Rename draft', tool: 'x_update_draft_tweet', arguments: { account_id: input.account_id, draft_tweet_id: v.id }, fields: [{ key: 'name', label: 'Draft name', type: 'text', value: v.name ?? '', max_length: 80 }] }] }));\n return { items: result.data, creatives, warnings, ...this.page(result.data.map(v => v.id), result.next_cursor, input.cursor) };\n }\n async plan(op: WriteOperation, _guard: WriteGuard): Promise<XWritePlan> {\n const account = xId.parse(op.accountId), create = op.tool === 'x_create_draft_tweet', remove = ['x_delete_draft_tweet', 'x_delete_media_library_item'].includes(op.tool);\n if (op.provider !== 'x' || op.kind !== (create ? 'create' : remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'x: creative operation provider/kind mismatch');\n const plan = (summary: string, changes: string[], execute: () => Promise<string[]>): XWritePlan => ({ summary, changes, execute, coercions: [], budgetDeltas: [] });\n if (['x_update_media_library', 'x_delete_media_library_item'].includes(op.tool)) {\n const input = op.tool === 'x_update_media_library' ? updateLibrary.parse(op.payload) : { media_key: mediaKey.parse(op.payload.media_key) }, current = await this.media(account, input.media_key), { media_key: key, ...fields } = input;\n if (current.deleted) throw new AdportError('INVALID_INPUT', 'x: media library record is already deleted');\n if ('title' in fields || 'description' in fields || 'poster_media_key' in fields) {\n if (current.media_type === 'IMAGE') throw new AdportError('INVALID_INPUT', 'x: title/description/poster changes need video or GIF media');\n if ('poster_media_key' in fields) { if (current.media_type !== 'VIDEO') throw new AdportError('INVALID_INPUT', 'x: poster changes require VIDEO media'); const poster = await this.media(account, fields.poster_media_key!); if (poster.deleted || poster.media_type !== 'IMAGE' || poster.media_status !== 'TRANSCODE_COMPLETED') throw new AdportError('INVALID_INPUT', 'x: poster must be a ready account-owned image'); }\n }\n const expected = remove ? { deleted: true } : { ...fields, deleted: false }, preserved = remove ? {} : Object.fromEntries(['name', 'file_name', 'title', 'description', 'poster_media_key'].filter(key => !(key in fields) && key in current).map(key => [key, current[key]]));\n return plan(`${remove ? 'Delete' : 'Edit'} X media library ${key}`, [remove ? 'Delete the library record. Existing posts/ads may retain media. This neither pauses delivery nor proves underlying bytes were deleted.' : `Metadata can be shared by existing creatives. Change only ${JSON.stringify(fields)}; preserve other metadata.`], async () => {\n try {\n const { data } = await this.entities.client.request(remove ? 'DELETE' : 'PUT', `accounts/${account}/media_library/${key}`, z.object({ data: librarySchema.partial().required({ media_key: true }) }), fields);\n if (data.media_key !== key || (data.media_type !== undefined && data.media_type !== current.media_type) || !fieldsMatch(data, Object.fromEntries(Object.entries({ ...preserved, ...expected }).filter(([key]) => key in data))) || (remove && data.deleted !== true)) throw new AdportError('PROVIDER_ERROR', 'x: media-library receipt mismatch; reconcile before retrying', { resource_ids: [data.media_key, key] });\n if (!remove) { const observed = await this.media(account, key); if (observed.media_type !== current.media_type || !fieldsMatch(observed, { ...preserved, ...expected })) throw new Error('x: media-library readback mismatch; reconcile before retrying'); }\n return [key];\n } catch (error) { throw new AdportError('PROVIDER_ERROR', error instanceof Error ? error.message : 'x: media-library update failed; reconcile before retrying', { resource_ids: [key] }); }\n });\n }\n if (!['x_create_draft_tweet', 'x_update_draft_tweet', 'x_delete_draft_tweet'].includes(op.tool)) throw new AdportError('INVALID_INPUT', 'x: unsupported creative operation');\n const current: Draft | undefined = create ? undefined : await this.draft(account, snowflake.parse(op.payload.draft_tweet_id));\n if (remove) return plan(`Permanently delete X draft ${current!.id}`, [`Hard delete draft authored by ${current!.user_id}; this cannot be undone. Already published posts remain separate.`], async () => {\n const { data } = await this.entities.client.request('DELETE', `accounts/${account}/draft_tweets/${current!.id}`, z.object({ data: z.looseObject({ id: snowflake, user_id: snowflake.optional(), status: z.string() }) }));\n if (data.id !== current!.id || (data.user_id !== undefined && data.user_id !== current!.user_id) || data.status !== 'DELETED') throw new AdportError('PROVIDER_ERROR', 'x: draft-deletion receipt mismatch; reconcile before retrying', { resource_ids: [data.id] });\n return [data.id];\n });\n const input = create ? createDraft.parse(op.payload) : updateDraft.parse(op.payload), user = create ? createDraft.parse(input).as_user_id : current!.user_id;\n await this.verifyComposer(account, user);\n const expected = { text: input.text ?? current?.text ?? '', name: input.name ?? current?.name ?? null, media_keys: input.media_keys ?? current?.media_keys ?? [], card_uri: input.card_uri !== undefined ? input.card_uri : current?.card_uri ?? null, nullcast: create ? true : current!.nullcast, user_id: user };\n if (!expected.text.trim() && !expected.media_keys.length) throw new AdportError('INVALID_INPUT', 'x: final draft needs text or media');\n await this.verifyAttachments(account, input.media_keys ?? [], input.card_uri);\n const fields: XParams = { ...(create ? { as_user_id: user, nullcast: true } : {}), ...(input.text !== undefined ? { text: input.text } : {}), ...(input.name !== undefined ? { name: input.name } : {}), ...(input.media_keys !== undefined ? { media_keys: input.media_keys.join(',') } : {}), ...(input.card_uri !== undefined ? { card_uri: input.card_uri ?? '' } : {}) };\n return plan(`${create ? 'Create' : 'Edit'} X native draft`, [`Author ${user}; native draft only, no publication or ad association. ${JSON.stringify(expected)}`, 'Native weighted text length and content eligibility are checked by X only on apply; this local preview is not server validation.'], async () => {\n let data: Draft;\n try {\n if (create) ({ data } = await this.entities.client.request('POST', `accounts/${account}/draft_tweets`, z.object({ data: draftSchema }), fields));\n else {\n // Live text-only PUT omits name. GET returns its preserved value.\n const receipt = (await this.entities.client.request('PUT', `accounts/${account}/draft_tweets/${current!.id}`, z.object({ data: draftSchema.partial().required({ id: true }) }), fields)).data;\n if (receipt.id !== current!.id || !fieldsMatch(receipt, Object.fromEntries(Object.entries(expected).filter(([key]) => key in receipt)))) throw new AdportError('PROVIDER_ERROR', 'x: partial draft receipt mismatch; reconcile before retrying', { resource_ids: [receipt.id, current!.id] });\n data = await this.draft(account, current!.id);\n }\n }\n catch (error) { if (!create) throw new AdportError('PROVIDER_ERROR', error instanceof Error ? error.message : 'x: draft update failed; reconcile before retrying', { resource_ids: [current!.id] }); throw error; }\n if ((!create && data.id !== current!.id) || (data.status !== undefined && data.status !== 'DRAFT') || !fieldsMatch(data, expected)) throw new AdportError('PROVIDER_ERROR', 'x: draft receipt differs from the approved content; reconcile before retrying', { resource_ids: [data.id] });\n return [data.id];\n });\n }\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { xId } from './schemas.js';\n\nexport const snowflake = z.string().regex(/^[1-9]\\d{0,24}$/);\nexport const mediaKey = z.string().regex(/^\\d+_[1-9]\\d{0,24}$/);\nexport const cardUri = z.string().regex(/^card:\\/\\/[1-9]\\d{0,24}$/);\nconst text = z.string().max(10_000).describe('Native weighted-length/content validation happens on apply; local preview is not server validation.');\nconst mediaKeys = z.array(mediaKey).max(4).refine(v => new Set(v).size === v.length, 'Use unique media keys');\nconst draftFields = { text: text.optional(), name: z.string().min(1).max(80).optional(), media_keys: mediaKeys.optional(), card_uri: cardUri.nullable().optional() };\nexport const createDraft = z.object({ as_user_id: snowflake, ...draftFields });\nexport const updateDraft = z.object({ draft_tweet_id: snowflake, ...draftFields }).refine(v => Object.keys(v).length > 1, 'Provide draft changes');\nexport const updateLibrary = z.object({ media_key: mediaKey, name: z.string().min(1).max(100).optional(), file_name: z.string().min(1).max(255).optional(), title: z.string().max(70).optional(), description: z.string().max(200).optional(), poster_media_key: mediaKey.optional() }).refine(v => Object.keys(v).length > 1, 'Provide library changes');\nexport const draftList = z.object({ account_id: xId, count: z.number().int().min(1).max(200).default(20), cursor: z.string().optional(), user_id: snowflake.optional(), include_media: z.boolean().default(true) });\nexport const libraryList = z.object({ account_id: xId, count: z.number().int().min(1).max(50).default(20), cursor: z.string().optional(), media_type: z.enum(['IMAGE', 'GIF', 'VIDEO']).optional(), q: z.string().min(1).max(255).optional() });\n\nexport function xCreativeTools(provider: XAdsProvider): AnyToolDefinition[] {\n const read = <T extends z.ZodRawShape>(name: string, description: string, input: z.ZodObject<T>, handler: (value: z.output<z.ZodObject<T>>) => Promise<unknown>) => defineTool({ name, namespace: 'x', description, input, annotations: { readOnly: true }, handler });\n const write = (name: string, description: string, payload: z.ZodObject, kind: 'create' | 'update' | 'remove' = 'update') => guardedWriteTool({ name, namespace: 'x', provider: 'x', kind, description, payload });\n return [\n defineTool({ name: 'x_draft_tweets', namespace: 'x', description: 'View native account drafts with actual copy, media previews and guarded edit actions. Native draft state is separate from ad delivery.', input: draftList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: v => provider.creatives.drafts(v) }),\n read('x_get_draft_tweet', 'Read a native draft through the selected account, keeping snowflake IDs as strings.', z.object({ account_id: xId, draft_tweet_id: snowflake }), v => provider.creatives.draft(v.account_id, v.draft_tweet_id)),\n defineTool({ name: 'x_media_library', namespace: 'x', description: 'View native account media-library images, GIFs and videos, processing state and metadata edit actions.', input: libraryList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: v => provider.creatives.library(v) }),\n read('x_get_media_library_item', 'Read one account-scoped media-library item, including native processing readiness and preview URLs.', z.object({ account_id: xId, media_key: mediaKey }), v => provider.creatives.media(v.account_id, v.media_key)),\n read('x_promotable_users', 'Read account-associated users and FULL/RETWEETS_ONLY eligibility for creative authoring.', z.object({ account_id: xId }), v => provider.creatives.users(v.account_id)),\n read('x_authenticated_user_access', 'Read the authenticated actor and native account permissions, including TWEET_COMPOSER when granted.', z.object({ account_id: xId }), v => provider.creatives.access(v.account_id)),\n read('x_get_cards', 'Read exact native cards by account-associated card URI, including legacy card content.', z.object({ account_id: xId, card_uris: z.array(cardUri).min(1).max(200), with_deleted: z.boolean().default(false) }), v => provider.creatives.cards(v.account_id, v.card_uris, v.with_deleted)),\n write('x_create_draft_tweet', 'Create a promoted-only native draft; no post publication or ad association. Checks FULL advertiser/composer access and owned ready media/cards. Local preview is not native content validation.', createDraft, 'create'),\n write('x_update_draft_tweet', 'Edit supplied native draft copy/name/media/card fields, preserving omitted values and nullcast state. Empty media_keys clears media; null card_uri clears the card.', updateDraft),\n write('x_delete_draft_tweet', 'Permanently delete one verified native draft. This cannot be undone and does not delete an already published post.', z.object({ draft_tweet_id: snowflake }), 'remove'),\n write('x_update_media_library', 'Edit native media-library metadata or a video poster, preserving omitted fields. Metadata can be shared with existing creatives; library status is separate from ad delivery.', updateLibrary),\n write('x_delete_media_library_item', 'Delete a verified native media-library record. Existing posts/ads may retain media; this is not an ad pause or proof of underlying byte deletion.', z.object({ media_key: mediaKey }), 'remove'),\n ];\n}\n","import { AdportError, LocalMediaResolver, type MediaResolver, type WriteOperation, type WritePreview, type WriteResult, type WriteReview } from '@adport/core';\nimport { z } from 'zod';\nimport { mediaKey, snowflake } from './creative-tools.js';\nimport { registerMedia, uploadMedia } from './media-tools.js';\nimport type { XAdsProvider } from './provider.js';\nimport { xId } from './schemas.js';\n\ninterface MediaPlan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<WriteResult> }\nconst nativeId = snowflake.refine(v => v.length <= 19, 'Native media v2 ID exceeds 19 digits');\nconst processing = z.looseObject({ state: z.enum(['pending', 'in_progress', 'succeeded', 'failed']), check_after_secs: z.number().int().nonnegative().optional(), progress_percent: z.number().min(0).max(100).optional() });\nconst nativeMedia = z.looseObject({ id: nativeId, media_key: mediaKey.optional(), expires_after_secs: z.number().int().positive().optional(), size: z.number().int().nonnegative().safe().optional(), processing_info: processing.optional() });\nconst receiptSchema = z.object({ kind: z.literal('media_upload_v1'), account_id: xId, user_id: nativeId, media_id: nativeId, media_key: mediaKey.optional(), media_type: z.enum(['IMAGE', 'GIF', 'VIDEO']), sha256: z.string().regex(/^[a-f0-9]{64}$/), byte_length: z.number().int().positive().max(50 * 1024 * 1024), finalized: z.boolean(), expires_at: z.number().int().positive().safe() });\ntype Receipt = z.infer<typeof receiptSchema>;\n\nexport class XMediaService {\n constructor(private readonly provider: XAdsProvider, private readonly media: MediaResolver = new LocalMediaResolver()) {}\n private receipt(account: string, value: string) {\n const parsed = receiptSchema.safeParse(this.provider.client.verifyResourceReceipt(value)), now = Math.floor(Date.now() / 1000);\n if (!parsed.success || parsed.data.account_id !== xId.parse(account) || parsed.data.expires_at <= now || parsed.data.expires_at > now + 86_400 || (parsed.data.media_key && parsed.data.media_key.split('_')[1] !== parsed.data.media_id)) throw new AdportError('INVALID_INPUT', 'x: expired or mismatched account upload receipt');\n return parsed.data;\n }\n private async author(account: string, user: string, write: boolean) {\n if (!(await this.provider.creatives.users(account)).some(v => v.user_id === user && v.promotable_user_type === 'FULL' && !v.deleted)) throw new AdportError('INVALID_INPUT', 'x: upload author is not a current FULL promotable account user');\n if (write) { const access = await this.provider.creatives.access(account); if (access.user_id !== user && !access.permissions.includes('TWEET_COMPOSER')) throw new AdportError('INVALID_INPUT', 'x: upload author needs native composer access'); }\n }\n private checked(value: z.infer<typeof nativeMedia>, bound: Receipt) {\n if (value.id !== bound.media_id || (value.media_key && value.media_key.split('_')[1] !== value.id) || (bound.media_key && value.media_key && bound.media_key !== value.media_key) || (value.size !== undefined && value.size !== bound.byte_length)) throw new AdportError('PROVIDER_ERROR', 'x: upload processing ID/key/size mismatch');\n const updated = { ...bound, ...(value.media_key ? { media_key: value.media_key } : {}), ...(value.expires_after_secs ? { expires_at: Math.min(bound.expires_at, Math.floor(Date.now() / 1000) + value.expires_after_secs) } : {}) };\n return { native: value, bound: updated, state: value.processing_info?.state ?? 'succeeded', resource_receipt: this.provider.client.resourceReceipt(updated) };\n }\n private async nativeStatus(bound: Receipt) {\n const { data } = await this.provider.client.mediaRequest('GET', 'media/upload', z.object({ data: nativeMedia }), { media_id: bound.media_id, command: 'STATUS' });\n return this.checked(data, bound);\n }\n async status(account: string, value: string) {\n const bound = this.receipt(account, value); await this.author(account, bound.user_id, false);\n return this.nativeStatus(bound);\n }\n async plan(op: WriteOperation): Promise<MediaPlan> {\n const account = xId.parse(op.accountId);\n if (op.provider !== 'x' || op.kind !== 'create') throw new AdportError('INVALID_INPUT', 'x: media provider/kind mismatch');\n const plan = (summary: string, changes: string[], execute: () => Promise<WriteResult>, review: WriteReview): MediaPlan => ({ summary, changes, execute, review, coercions: [], budgetDeltas: [] });\n if (op.tool === 'x_upload_media') {\n const input = uploadMedia.parse(op.payload); nativeId.parse(input.as_user_id); await this.author(account, input.as_user_id, true);\n const file = await this.media.read(input, { maxBytes: 50 * 1024 * 1024, contentTypes: ['image/png', 'image/jpeg', 'image/gif', 'video/mp4'] }), kind = file.contentType === 'image/gif' ? 'GIF' : file.contentType.startsWith('image/') ? 'IMAGE' : 'VIDEO';\n if (file.bytes.byteLength > (kind === 'IMAGE' ? 5 : kind === 'GIF' ? 15 : 50) * 1024 * 1024) throw new AdportError('INVALID_INPUT', 'x: media exceeds the image5MiB/GIF15MiB/video50MiB application limit');\n const category = kind === 'IMAGE' ? 'tweet_image' : kind === 'GIF' ? 'tweet_gif' : 'amplify_video';\n return plan('Upload X native media bytes', [`${file.name}; ${file.contentType}; ${file.bytes.byteLength} bytes; SHA-256 ${file.sha256}. Author ${input.as_user_id}, category ${category}.`, 'Initialize, append 1MiB JSON/base64 chunks and finalize. Upload processing and library registration are separate. No post or ad is created; incomplete native uploads may remain until provider expiry.'], async () => {\n const init = (await this.provider.client.mediaRequest('POST', 'media/upload/initialize', z.object({ data: nativeMedia }), {}, { additional_owners: [input.as_user_id], media_category: category, media_type: file.contentType, total_bytes: file.bytes.byteLength })).data;\n let bound: Receipt = { kind: 'media_upload_v1', account_id: account, user_id: input.as_user_id, media_id: init.id, ...(init.media_key ? { media_key: init.media_key } : {}), media_type: kind, sha256: file.sha256, byte_length: file.bytes.byteLength, finalized: false, expires_at: Math.floor(Date.now() / 1000) + Math.min(init.expires_after_secs ?? 3600, 86_400) };\n try {\n this.checked(init, bound);\n for (let offset = 0, segment = 0; offset < file.bytes.byteLength; offset += 1024 * 1024, segment++) await this.provider.client.mediaRequest('POST', `media/upload/${init.id}/append`, z.object({ data: z.object({ expires_at: z.number().int().positive().safe().optional() }).optional() }), {}, { segment_index: segment, media: Buffer.from(file.bytes.subarray(offset, offset + 1024 * 1024)).toString('base64') });\n const final = (await this.provider.client.mediaRequest('POST', `media/upload/${init.id}/finalize`, z.object({ data: nativeMedia }))).data;\n const result = this.checked(final, { ...bound, finalized: true }); bound = result.bound;\n if (result.state === 'failed') throw new Error('x: native media processing failed');\n return { applied: true, resourceIds: [bound.media_key ?? bound.media_id], details: { upload_id: bound.media_id, ...(bound.media_key ? { media_key: bound.media_key } : {}), status: result.state, resource_receipt: result.resource_receipt, expires_at: new Date(bound.expires_at * 1000).toISOString(), next_tool: result.state === 'succeeded' ? 'x_register_uploaded_media' : 'x_media_upload_status', note: 'Upload finalized; this does not register a library entry, publish a post or prove ad eligibility.' } };\n } catch (error) { throw new AdportError('PROVIDER_ERROR', error instanceof Error ? error.message : 'x: upload failed; reconcile before retrying', { resource_ids: [bound.media_key ?? bound.media_id], resource_receipt: this.provider.client.resourceReceipt(bound), note: 'Upload was not replayed. Native incomplete bytes may remain until provider expiry.' }); }\n }, { provider: 'x', accountId: account, kind: 'create', title: `Upload ${kind.toLowerCase()}`, subject: file.name, fields: [{ label: 'Type', after: file.contentType }, { label: 'Size', after: `${file.bytes.byteLength.toLocaleString('en-US')} bytes` }, { label: 'Author', after: input.as_user_id }, { label: 'SHA-256', after: file.sha256 }], notices: ['X validates on apply. An incomplete upload may remain until it expires.', 'Publishing and library registration are separate actions.'] });\n }\n if (op.tool !== 'x_register_uploaded_media') throw new AdportError('INVALID_INPUT', 'x: unsupported media operation');\n const input = registerMedia.parse(op.payload), bound = this.receipt(account, input.resource_receipt); await this.author(account, bound.user_id, true);\n if (!bound.finalized) throw new AdportError('INVALID_INPUT', 'x: incomplete upload cannot be registered; create a new approved upload after reconciling the incomplete session');\n const status = await this.nativeStatus(bound), key = status.bound.media_key;\n if (status.state !== 'succeeded' || !key) throw new AdportError('INVALID_INPUT', 'x: upload is not processed or has no native media key; check x_media_upload_status');\n if (bound.media_type === 'IMAGE' && (input.title !== undefined || input.description !== undefined)) throw new AdportError('INVALID_INPUT', 'x: title/description require video or GIF media');\n try { const existing = await this.provider.creatives.media(account, key); if (!existing.deleted) throw new AdportError('INVALID_INPUT', 'x: media is already registered in this account'); }\n catch (error) { if (!(error instanceof AdportError) || !error.details || typeof error.details !== 'object' || !('http_status' in error.details) || error.details.http_status !== 404) throw error; }\n const fields = { media_key: key, name: input.name, ...(input.file_name !== undefined ? { file_name: input.file_name } : {}), ...(input.title !== undefined ? { title: input.title } : {}), ...(input.description !== undefined ? { description: input.description } : {}) };\n return plan(`Register X upload ${key}`, [`Associate this approved ${bound.media_type} upload with account ${account}; SHA-256 ${bound.sha256}. ${JSON.stringify(fields)}`, 'No post publication or ad association. Native library and processing eligibility remain separate from campaign approval.'], async () => {\n try {\n const { data } = await this.provider.client.request('POST', `accounts/${account}/media_library`, z.object({ data: z.looseObject({ media_key: mediaKey }) }), fields);\n if (data.media_key !== key) throw new Error('x: registered media key mismatch');\n const observed = await this.provider.creatives.media(account, key);\n if (observed.deleted || observed.media_type !== bound.media_type || Object.entries(fields).some(([field, value]) => observed[field] !== value)) throw new Error('x: registered media metadata readback mismatch');\n return { applied: true, resourceIds: [key], details: { status: observed.media_status, next_tool: 'x_get_media_library_item' } };\n } catch (error) { throw new AdportError('PROVIDER_ERROR', error instanceof Error ? error.message : 'x: library registration failed; reconcile before retrying', { resource_ids: [key], resource_receipt: input.resource_receipt }); }\n }, { provider: 'x', accountId: account, kind: 'create', title: 'Add media to X library', subject: input.name, fields: [{ label: 'Media', after: key }, ...(input.file_name === undefined ? [] : [{ label: 'File name', after: input.file_name }]), ...(input.title === undefined ? [] : [{ label: 'Title', after: input.title }]), ...(input.description === undefined ? [] : [{ label: 'Description', after: input.description }]), { label: 'SHA-256', after: bound.sha256 }], notices: ['Adds the approved upload to this account’s media library. Publishing is a separate action.'] });\n }\n}\n","import { defineTool, guardedWriteTool, mediaSourceFields, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { snowflake } from './creative-tools.js';\nimport { xId } from './schemas.js';\n\nexport const mediaReceipt = z.string().min(1).max(2048);\nexport const uploadMedia = z.object({ as_user_id: snowflake, ...mediaSourceFields }).refine(v => Boolean(v.media_id) !== Boolean(v.file_path), 'Choose project media_id or local file_path');\nexport const registerMedia = z.object({ resource_receipt: mediaReceipt, name: z.string().min(1).max(100), file_name: z.string().min(1).max(255).optional(), title: z.string().max(70).optional(), description: z.string().max(200).optional() });\nexport function xMediaTools(provider: XAdsProvider): AnyToolDefinition[] {\n return [\n guardedWriteTool({ name: 'x_upload_media', namespace: 'x', provider: 'x', kind: 'create', description: 'Upload SHA-256-bound image/GIF/video bytes through native v2 initialize/append/finalize with the existing OAuth1 grant. Returns a signed account/author-bound processing receipt; does not register, publish or attach an ad.', payload: uploadMedia }),\n defineTool({ name: 'x_media_upload_status', namespace: 'x', description: 'Read native upload processing only with the signed receipt from this account’s approved upload. Native IDs alone do not authorize account-less status reads.', input: z.object({ account_id: xId, resource_receipt: mediaReceipt }), annotations: { readOnly: true }, handler: v => provider.mediaUploads.status(v.account_id, v.resource_receipt) }),\n guardedWriteTool({ name: 'x_register_uploaded_media', namespace: 'x', provider: 'x', kind: 'create', description: 'Register an approved, processed upload in its account’s native media library. Requires its unexpired signed receipt, checks current author/processing, and preserves upload IDs on a partial failure. No post publication or ad association.', payload: registerMedia }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type ReviewField, type WriteOperation } from '@adport/core';\nimport { z } from 'zod';\nimport { cardButtonLabel, cardComponents, cardSlides, cardWrites, createCard, deleteCard, listCards, nativeCard, updateCard, type CardLayout, type NativeCard } from './card-schemas.js';\nimport type { XParams } from './client.js';\nimport { snowflake } from './creative-tools.js';\nimport type { XCreativeService } from './creatives.js';\nimport type { XAdsEntities } from './entities.js';\nimport { xId } from './schemas.js';\nimport type { XWritePlan } from './writes.js';\n\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, canonical(v)])) : value;\nconst equal = (a: unknown, b: unknown) => JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));\nconst layoutOf = (card: NativeCard) => ({ ...(card.components?.length ? { components: card.components } : {}), ...(card.slides?.length ? { slides: card.slides } : {}) });\nconst content = (card: NativeCard) => ({ id: card.id, card_uri: card.card_uri, name: card.name, card_type: card.card_type, deleted: card.deleted, ...layoutOf(card) });\nconst mutationNotice = 'Shared card edits or deletion can affect existing posts and ads. This operation does not publish a post, create an ad association or change delivery/budgets. Native content validation happens only on apply. No native write is retried automatically.';\ntype Media = Awaited<ReturnType<XCreativeService['media']>>;\n\nexport class XCardService {\n constructor(private readonly entities: XAdsEntities, private readonly creatives: XCreativeService) {}\n private hash(account: string, card: NativeCard) { return createHash('sha256').update(JSON.stringify(canonical({ account_id: account, card }))).digest('hex'); }\n private decorate(account: string, card: NativeCard) { return { ...card, configuration_hash: this.hash(account, card) }; }\n private async owned(account: string, id: string, withDeleted = false) {\n await this.entities.getAccount(account);\n const result = await this.entities.client.request('GET', `accounts/${xId.parse(account)}/cards/${snowflake.parse(id)}`, z.object({ data: z.array(nativeCard).max(1) }), { with_deleted: withDeleted });\n const card = result.data[0];\n if (!card || card.id !== id || !withDeleted && card.deleted || card.account_id !== undefined && card.account_id !== account) throw new AdportError('PROVIDER_ERROR', 'x: card ID, account or deletion state mismatch');\n return card;\n }\n async get(account: string, id: string, withDeleted = false) { return this.decorate(account, await this.owned(account, id, withDeleted)); }\n private keys(layout: CardLayout) { return [...new Set((layout.components ? [layout.components] : layout.slides ?? []).flatMap(row => row.flatMap(v => v.type === 'MEDIA' ? [v.media_key] : v.type === 'SWIPEABLE_MEDIA' ? v.media_keys : [])))]; }\n private supportedLayout(card: NativeCard): CardLayout {\n const value = layoutOf(card);\n if (!!value.components === !!value.slides) throw new AdportError('INVALID_INPUT', 'x: current card layout is not representable by this authoring tool; no fields were discarded');\n if (value.components) { const parsed = cardComponents.safeParse(value.components);if (parsed.success) return { components: parsed.data }; }\n if (value.slides) { const parsed = cardSlides.safeParse(value.slides);if (parsed.success) return { slides: parsed.data }; }\n throw new AdportError('INVALID_INPUT', 'x: current card contains unsupported component fields; replace the complete layout explicitly or change only its name');\n }\n private async mediaFor(account: string, layout: CardLayout) {\n const sources = new Map<string, Media>();\n for (const key of this.keys(layout)) {\n const value = await this.creatives.media(account, key);\n if (value.deleted || value.media_status !== 'TRANSCODE_COMPLETED' || !['IMAGE', 'VIDEO'].includes(value.media_type) || value.account_id !== undefined && value.account_id !== account) throw new AdportError('INVALID_INPUT', 'x: every card attachment must be a ready image or video in the selected account library');\n sources.set(key, value);\n }\n return sources;\n }\n private cardType(layout: CardLayout, media: Map<string, Media>) {\n const kinds = new Set([...media.values()].map(v => v.media_type)), kind = kinds.size > 1 ? 'MIXED_MEDIA' : [...kinds][0];\n if (layout.slides) return `${kind}_MULTI_DEST_CAROUSEL_WEBSITE`;\n const [asset, description] = layout.components!, destination = description!.type === 'DETAILS' ? 'WEBSITE' : 'APP';\n return asset!.type === 'MEDIA' ? `${kind}_${destination}` : `${kind}${kind === 'MIXED_MEDIA' ? '_SINGLE_DEST' : ''}_CAROUSEL_${destination}`;\n }\n private copyLayout(card: NativeCard, input: z.infer<typeof updateCard>) {\n const layout = this.supportedLayout(card);\n if (layout.slides && input.slide_index === undefined) throw new AdportError('INVALID_INPUT', 'x: select slide_index for a multi-destination copy edit');\n if (layout.components && input.slide_index !== undefined) throw new AdportError('INVALID_INPUT', 'x: slide_index is only valid for a multi-destination card');\n const row = layout.components ?? layout.slides?.[input.slide_index!];\n if (!row) throw new AdportError('INVALID_INPUT', 'x: selected slide is not present in this card');\n const description = row[1]!;\n if (input.title !== undefined || input.website_url !== undefined) {\n if (description.type !== 'DETAILS') throw new AdportError('INVALID_INPUT', 'x: title/website_url shortcuts require website DETAILS');\n if (input.title !== undefined) description.title = input.title;\n if (input.website_url !== undefined) description.destination.url = input.website_url;\n }\n if (input.button_label !== undefined) {\n if (description.type !== 'BUTTON') throw new AdportError('INVALID_INPUT', 'x: button_label requires an app BUTTON');\n description.label.value = input.button_label;\n }\n return layout;\n }\n private actions(account: string, card: NativeCard): Creative['actions'] {\n if (card.deleted || !snowflake.safeParse(card.id).success || !card.name) return [];\n const args = { account_id: account, card_id: card.id, expected_configuration_hash: this.hash(account, card), acknowledge_shared_creative_effects: true };\n const actions: Creative['actions'] = [{ label: 'Rename card', tool: 'x_update_card', arguments: args, fields: [{ key: 'name', label: 'Card name', type: 'text', value: card.name, max_length: 80 }] }];\n let layout: CardLayout;try { layout = this.supportedLayout(card); } catch { return actions; }\n for (const [index, row] of (layout.components ? [layout.components] : layout.slides!).entries()) {\n const description = row[1]!, bound = { ...args, ...(layout.slides ? { slide_index: index } : {}) };\n if (description.type === 'DETAILS') actions.push({ label: layout.slides ? `Edit slide ${index + 1} copy` : 'Edit card copy', tool: 'x_update_card', arguments: bound, fields: [{ key: 'title', label: 'Title', type: 'text', value: description.title }, { key: 'website_url', label: 'Website URL', type: 'text', value: description.destination.url }] });\n if (description.type === 'BUTTON') actions.push({ label: 'Edit app button', tool: 'x_update_card', arguments: bound, fields: [{ key: 'button_label', label: 'Button', type: 'select', value: description.label.value, options: cardButtonLabel.options.map(value => ({ label: value, value })) }] });\n }\n return actions;\n }\n async list(value: z.input<typeof listCards>) {\n const input = listCards.parse(value);await this.entities.getAccount(input.account_id);\n const params: XParams = { count: input.count, include_legacy_cards: input.include_legacy_cards, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}), ...(input.q ? { q: input.q } : {}), ...(input.card_types ? { card_types: input.card_types.join(',') } : {}), ...(input.card_ids ? { card_id: input.card_ids.join(',') } : {}), ...(input.card_uris ? { card_uris: input.card_uris.join(',') } : {}) };\n const result = await this.entities.client.request('GET', `accounts/${input.account_id}/cards`, z.object({ data: z.array(nativeCard).max(1000), next_cursor: z.string().max(4096).nullish() }), params);\n if (new Set(result.data.map(v => v.id)).size !== result.data.length || new Set(result.data.map(v => v.card_uri)).size !== result.data.length || result.next_cursor && result.next_cursor === input.cursor || result.data.some(v => !input.with_deleted && v.deleted || v.account_id !== undefined && v.account_id !== input.account_id || input.card_ids && !input.card_ids.includes(v.id) || input.card_uris && !input.card_uris.includes(v.card_uri) || input.card_types && !input.card_types.some(t => t === v.card_type))) throw new AdportError('PROVIDER_ERROR', 'x: card inventory repeated a resource/cursor or returned a conflicting account/filter');\n const warnings: string[] = [], media = new Map<string, Media>(), keys: string[] = [];\n for (const card of result.data) { try { keys.push(...this.keys(this.supportedLayout(card))); } catch { warnings.push(`Card ${card.id} has a layout that cannot be hydrated by this tool; native content is retained in items.`); } }\n const unique = [...new Set(keys)];let offset = 0;\n if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, unique.length, 100) }, async () => { while (offset < Math.min(unique.length, 100)) { const key = unique[offset++]!;try { const source = await this.creatives.media(input.account_id, key);if (!source.deleted && (source.account_id === undefined || source.account_id === input.account_id)) media.set(key, source);else warnings.push(`Media ${key} is deleted or unavailable in this account.`); } catch { warnings.push(`Media ${key} could not be read from this account.`); } } }));\n if (input.include_media && unique.length > 100) warnings.push('Preview hydration is limited to 100 distinct media; native card references are retained in items.');\n const creatives: Creative[] = result.data.map(card => {\n let layout: CardLayout | undefined;try { layout = this.supportedLayout(card); } catch {}\n const rows = layout?.components ? [layout.components] : layout?.slides ?? [], descriptions = rows.map(v => v[1]!), headlines = descriptions.flatMap(v => v.type === 'DETAILS' ? [v.title] : []), urls = descriptions.flatMap(v => v.type === 'DETAILS' ? [v.destination.url] : []);\n return { id: card.id, provider: 'x', account_id: input.account_id, name: card.name ?? card.id, type: card.card_type, status: card.deleted ? 'DELETED' : 'CARD', headlines, descriptions: descriptions.flatMap(v => v.type === 'BUTTON' ? [v.label.value] : []), landing_urls: urls, media: input.include_media && layout ? this.keys(layout).flatMap(key => media.has(key) ? this.creatives.visual(media.get(key)!) : []) : [], actions: this.actions(input.account_id, card) };\n });\n return { items: result.data.map(v => this.decorate(input.account_id, v)), creatives, warnings, truncated: Boolean(result.next_cursor), ...(result.next_cursor ? { next_cursor: result.next_cursor } : {}) };\n }\n private layoutFields(layout: CardLayout): Record<string, unknown> {\n const fields: Record<string, unknown> = { Media: this.keys(layout) };\n for (const [index, row] of (layout.components ? [layout.components] : layout.slides ?? []).entries()) {\n const prefix = layout.slides ? `Slide ${index + 1} ` : '', description = row[1]!;\n if (description.type === 'DETAILS') { fields[`${prefix}title`] = description.title;fields[`${prefix}website`] = description.destination.url; }\n if (description.type === 'BUTTON') { fields.Button = description.label.value;fields['App destination'] = description.destination; }\n }\n return fields;\n }\n async plan(op: WriteOperation): Promise<XWritePlan> {\n const creating = op.tool === 'x_create_card', removing = op.tool === 'x_delete_card', account = xId.parse(op.accountId);\n if (op.provider !== 'x' || !cardWrites.has(op.tool) || op.kind !== (creating ? 'create' : removing ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'x: card operation provider/kind mismatch');\n const input = creating ? createCard.parse(op.payload) : removing ? deleteCard.parse(op.payload) : updateCard.parse(op.payload);\n await this.entities.getAccount(account);\n const current = 'card_id' in input ? await this.owned(account, input.card_id) : undefined;\n if (current && 'expected_configuration_hash' in input && this.hash(account, current) !== input.expected_configuration_hash) throw new AdportError('PENDING_MISMATCH', 'x: card configuration changed; read x_get_card before requesting a new preview');\n let body: Record<string, unknown> = {}, expected: ReturnType<typeof content> | undefined, layout: CardLayout | undefined;\n if (!removing) {\n if (creating) { const v = createCard.parse(input);body = v;layout = v; }\n else {\n const v = updateCard.parse(input);body = { ...(v.name !== undefined ? { name: v.name } : {}) };\n layout = v.components ? { components: v.components } : v.slides ? { slides: v.slides } : v.title !== undefined || v.website_url !== undefined || v.button_label !== undefined ? this.copyLayout(current!, v) : undefined;\n if (layout) body = { ...body, ...layout };\n }\n const sources = layout ? await this.mediaFor(account, layout) : undefined;\n expected = { ...(current ? content(current) : { id: '', card_uri: '', deleted: false }), name: typeof body.name === 'string' ? body.name : current!.name, card_type: layout ? this.cardType(layout, sources!) : current!.card_type, ...(layout ?? layoutOf(current!)) };\n if (layout?.components) delete expected.slides;\n if (layout?.slides) delete expected.components;\n }\n const title = `${creating ? 'Create' : removing ? 'Delete' : 'Edit'} X card`, name = typeof body.name === 'string' ? body.name : current!.name ?? current!.id;\n const fields: ReviewField[] = [{ label: 'Card name', ...(current ? { before: current.name ?? current.id } : {}), after: removing ? null : name }, ...(current ? [{ label: 'Card ID', after: current.id }] : [])];\n if (removing) fields.push({ label: 'Deleted', before: false, after: true });\n if (layout) {\n let previous: Record<string, unknown> = {};try { if (current) previous = this.layoutFields(this.supportedLayout(current)); } catch {}\n const proposed = this.layoutFields(layout);\n fields.push({ label: 'Card type', ...(current ? { before: current.card_type } : {}), after: expected!.card_type });\n for (const key of new Set([...Object.keys(previous), ...Object.keys(proposed)])) if (!current || !equal(previous[key], proposed[key])) fields.push({ label: key, ...(current ? { before: previous[key] } : {}), after: proposed[key] ?? null });\n }\n return { summary: `${title} \"${name}\"`, changes: [removing ? `- Delete card ${current!.id} (${current!.card_uri}). No restore endpoint is established.` : `${creating ? '+' : '~'} ${JSON.stringify(body)}`, mutationNotice], notes: [creating ? 'Creates an unattached card only. No post is published and no ad association is created.' : mutationNotice], coercions: [], budgetDeltas: [],\n review: { provider: 'x', accountId: account, kind: creating ? 'create' : removing ? 'remove' : 'update', title, fields, notices: [mutationNotice] },\n execute: async () => {\n let knownId = current?.id;\n try {\n const base = `accounts/${account}/cards`;\n const receipt = creating\n ? (await this.entities.client.request('POST', base, z.object({ data: nativeCard }), {}, body)).data\n : (await this.entities.client.request(removing ? 'DELETE' : 'PUT', `${base}/${current!.id}`, z.object({ data: z.array(nativeCard).length(1) }), {}, removing ? undefined : body)).data[0]!;\n knownId = receipt.id;\n if (current && (receipt.id !== current.id || receipt.card_uri !== current.card_uri)) throw new Error('x: card mutation receipt identity mismatch');\n if (removing ? !receipt.deleted : !equal(content(receipt), { ...expected, id: receipt.id, card_uri: receipt.card_uri })) throw new Error('x: card mutation receipt differs from the approved content');\n const observed = await this.owned(account, receipt.id, removing);\n if (observed.card_uri !== receipt.card_uri || (removing ? !observed.deleted : !equal(content(observed), { ...expected, id: receipt.id, card_uri: receipt.card_uri }))) throw new Error('x: independent card readback differs from the approved content');\n return [receipt.id];\n } catch (error) {\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Record<string, unknown> : {};\n const previous = Array.isArray(details.resource_ids) ? details.resource_ids.filter((v): v is string => typeof v === 'string') : [];\n throw new AdportError('PROVIDER_ERROR', `${error instanceof Error ? error.message : 'x: card mutation was not confirmed'}. Reconcile the original card IDs before another mutation; no write was retried.`, { ...details, resource_ids: [...new Set([...(current ? [current.id] : []), ...(knownId ? [knownId] : []), ...previous])] });\n }\n } };\n }\n}\n","import { z } from 'zod';\nimport { cardUri, mediaKey, snowflake } from './creative-tools.js';\nimport { xId } from './schemas.js';\n\nexport const cardTypes = z.enum(['IMAGE_APP', 'IMAGE_CAROUSEL_APP', 'IMAGE_CAROUSEL_WEBSITE', 'IMAGE_MULTI_DEST_CAROUSEL_WEBSITE', 'IMAGE_WEBSITE', 'MIXED_MEDIA_MULTI_DEST_CAROUSEL_WEBSITE', 'MIXED_MEDIA_SINGLE_DEST_CAROUSEL_APP', 'MIXED_MEDIA_SINGLE_DEST_CAROUSEL_WEBSITE', 'VIDEO_APP', 'VIDEO_CAROUSEL_APP', 'VIDEO_CAROUSEL_WEBSITE', 'VIDEO_MULTI_DEST_CAROUSEL_WEBSITE', 'VIDEO_WEBSITE']);\nexport const cardButtonLabel = z.enum(['BOOK', 'CONNECT', 'INSTALL', 'OPEN', 'ORDER', 'PLAY', 'SHOP']);\nexport const cardWebsite = z.string().url().max(8192).refine(value => { try { const url = new URL(value);return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; } catch { return false; } }, 'Use an HTTP or HTTPS destination without embedded credentials');\nconst appId = z.string().min(1).max(512);\nconst appDestination = z.object({ type: z.literal('APP'), country_code: z.string().regex(/^[A-Z]{2}$/), googleplay_app_id: appId.optional(), ios_app_store_identifier: appId.optional(), googleplay_deep_link: z.string().url().max(8192).optional(), ios_deep_link: z.string().url().max(8192).optional() }).strict()\n .refine(v => !!v.googleplay_app_id || !!v.ios_app_store_identifier, 'Provide at least one app store identifier')\n .refine(v => !v.googleplay_deep_link || !!v.googleplay_app_id, 'An Android deep link needs googleplay_app_id')\n .refine(v => !v.ios_deep_link || !!v.ios_app_store_identifier, 'An iOS deep link needs ios_app_store_identifier');\nexport const cardComponent = z.discriminatedUnion('type', [\n z.object({ type: z.literal('MEDIA'), media_key: mediaKey }).strict(),\n z.object({ type: z.literal('SWIPEABLE_MEDIA'), media_keys: z.array(mediaKey).min(2).max(6) }).strict(),\n z.object({ type: z.literal('DETAILS'), title: z.string().min(1).max(10_000).describe('Native title length and content eligibility are validated by X only on apply.'), destination: z.object({ type: z.literal('WEBSITE'), url: cardWebsite }).strict() }).strict(),\n z.object({ type: z.literal('BUTTON'), label: z.object({ type: z.literal('ENUM'), value: cardButtonLabel }).strict(), destination: appDestination }).strict(),\n]);\n// Arrays avoid tuple prefixItems, which some MCP hosts cannot import.\nexport const cardComponents = z.array(cardComponent).length(2).refine(v => ['MEDIA', 'SWIPEABLE_MEDIA'].includes(v[0]!.type) && ['DETAILS', 'BUTTON'].includes(v[1]!.type), 'Use one media component followed by one website-details or app-button component');\nexport const cardSlides = z.array(cardComponents.refine(v => v[0]!.type === 'MEDIA' && v[1]!.type === 'DETAILS', 'Each multi-destination slide needs one MEDIA and one website DETAILS component')).min(2).max(6);\nconst layout = { components: cardComponents.optional(), slides: cardSlides.optional() };\nexport const createCard = z.object({ name: z.string().trim().min(1).max(80), ...layout }).strict().refine(v => !!v.components !== !!v.slides, 'Provide components or slides, never both');\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const updateCard = z.object({ card_id: snowflake, expected_configuration_hash: hash, acknowledge_shared_creative_effects: z.literal(true), name: z.string().trim().min(1).max(80).optional(), ...layout,\n title: z.string().min(1).max(10_000).optional(), website_url: cardWebsite.optional(), button_label: cardButtonLabel.optional(), slide_index: z.number().int().min(0).max(5).optional(),\n}).strict().refine(v => !(v.components && v.slides), 'Provide components or slides, never both')\n .refine(v => ['name', 'components', 'slides', 'title', 'website_url', 'button_label'].some(key => Object.hasOwn(v, key)), 'Provide card changes')\n .refine(v => !(v.components || v.slides) || !['title', 'website_url', 'button_label', 'slide_index'].some(key => Object.hasOwn(v, key)), 'Use a replacement layout or copy shortcuts, never both')\n .refine(v => v.slide_index === undefined || v.title !== undefined || v.website_url !== undefined || v.button_label !== undefined, 'A slide index requires a copy change');\nexport const deleteCard = z.object({ card_id: snowflake, expected_configuration_hash: hash, acknowledge_shared_creative_effects: z.literal(true) }).strict();\nexport const listCards = z.object({ account_id: xId, count: z.number().int().min(1).max(200).default(20), cursor: z.string().min(1).max(4096).optional(), card_types: z.array(cardTypes).min(1).max(13).optional(), card_ids: z.array(snowflake).min(1).max(200).optional(), card_uris: z.array(cardUri).min(1).max(200).optional(), q: z.string().min(1).max(80).optional(), include_legacy_cards: z.boolean().default(false), with_deleted: z.boolean().default(false), include_media: z.boolean().default(true) });\nexport const nativeCard = z.looseObject({ id: xId, card_uri: cardUri, name: z.string().nullish(), card_type: z.string(), deleted: z.boolean(), components: z.array(z.unknown()).max(100).nullish(), slides: z.array(z.array(z.unknown()).max(100)).max(100).nullish() });\nexport type NativeCard = z.infer<typeof nativeCard>;\nexport type CardLayout = { components?: z.infer<typeof cardComponents>; slides?: z.infer<typeof cardSlides> };\nexport const cardWrites = new Set(['x_create_card', 'x_update_card', 'x_delete_card']);\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport { audienceGet, audienceList, audiencePermissions, audienceUsers, createAudience, deleteAudience, updateAudience } from './audience-tools.js';\nimport type { XParams } from './client.js';\nimport type { XAdsEntities } from './entities.js';\nimport { lineItemSchema, xId as id } from './schemas.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\nconst audience = z.looseObject({ id, name: z.string(), description: z.string().nullable(), audience_type: z.string(), deleted: z.boolean(), permission_level: z.string(), owner_account_id: id.optional(), is_owner: z.boolean().optional(), targetable: z.boolean().optional(), audience_size: z.number().int().nonnegative().safe().nullable().optional(), partner_source: z.string().optional() });\ntype Audience = z.infer<typeof audience>;\nconst permission = z.looseObject({ id, custom_audience_id: id, granted_account_id: id, permission_level: z.string(), deleted: z.boolean() });\nconst target = z.looseObject({ campaign_id: id, campaign_name: z.string().nullable().optional(), line_items: z.array(z.looseObject({ id, name: z.string().nullable().optional(), servable: z.boolean() })) });\nconst criterion = z.looseObject({ id, line_item_id: id, targeting_type: z.string(), targeting_value: z.string(), operator_type: z.string().optional(), deleted: z.boolean() });\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst digest = (value: unknown) => createHash('sha256').update(canonical(value)).digest('hex');\nconst configuration = (value: Audience) => Object.fromEntries(['id', 'name', 'description', 'audience_type', 'permission_level', 'owner_account_id', 'is_owner', 'partner_source', 'deleted'].filter(key => value[key] !== undefined).map(key => [key, value[key]]));\nconst snapshot = (account: string, value: Audience) => digest({ account_id: account, configuration: configuration(value) });\nconst notes = ['Local preview only; X has no server dry run or conditional configuration update for this workflow.', 'No automatic write retry. Reconcile known IDs and receipts after an uncertain result.'];\nconst rejection = (error: unknown) => error instanceof AdportError && error.details !== null && typeof error.details === 'object' && 'http_status' in error.details && [401, 403, 429].includes(Number(error.details.http_status));\n\n/** X-owned v12 audience reference at 4e8f626, inspected 2026-11-05. */\nexport class XAudienceService {\n constructor(private readonly entities: XAdsEntities) {}\n private base(account: string) { return `accounts/${id.parse(account)}/custom_audiences`; }\n private scope(value: { request?: { params?: Row } }, account: string, resource?: string) {\n const params = value.request?.params;\n if (params && (params.account_id !== undefined && params.account_id !== account || resource && params.custom_audience_id !== undefined && params.custom_audience_id !== resource)) throw new AdportError('PROVIDER_ERROR', 'x: audience response scope differs from the selected account/ID');\n }\n private owned(value: Audience, account: string) {\n if (value.owner_account_id !== undefined && value.owner_account_id !== account || value.is_owner === false || value.owner_account_id === undefined && value.is_owner !== true || value.permission_level !== 'READ_WRITE') throw new AdportError('INVALID_INPUT', 'x: audience must be verifiably owned and writable by the selected account');\n if (value.deleted) throw new AdportError('INVALID_INPUT', 'x: deleted audiences cannot be modified');\n }\n private async page<S extends z.ZodType>(account: string, path: string, schema: S, params: XParams, resource?: string) {\n const data = await this.entities.client.request('GET', path, z.looseObject({ data: z.array(schema), next_cursor: z.string().nullable().optional(), total_count: z.number().int().nonnegative().safe().optional(), request: z.object({ params: z.record(z.string(), z.unknown()).optional() }).optional() }), params);\n this.scope(data, account, resource);\n if (data.next_cursor && data.next_cursor === params.cursor) throw new AdportError('PROVIDER_ERROR', 'x: audience pagination repeated its cursor');\n const identities = data.data.map(value => String((value as Row).id ?? (value as Row).campaign_id));\n if (new Set(identities).size !== identities.length || data.data.length > 1000) throw new AdportError('PROVIDER_ERROR', 'x: audience page exceeds its native limit or repeats entities');\n const complete = data.next_cursor === null ? true : data.next_cursor ? false : null;\n if (!params.cursor && data.total_count !== undefined && (data.total_count < data.data.length || complete && data.total_count !== data.data.length)) throw new AdportError('PROVIDER_ERROR', 'x: audience total count contradicts the native page');\n return { ...data, complete, truncated: complete !== true, next_cursor: data.next_cursor || undefined };\n }\n private pageParams(input: { cursor?: string; with_total_count: boolean } & Row): XParams {\n const params = Object.fromEntries(Object.entries(input).filter(([key, value]) => key !== 'with_total_count' && value !== undefined)) as XParams;\n if (input.with_total_count && !input.cursor) params.with_total_count = true;\n return params;\n }\n private record(value: Audience): Row {\n return { id: value.id, name: value.name, status: value.deleted ? 'Deleted' : value.targetable === true ? 'Targetable' : value.targetable === false ? 'Not targetable' : 'Targetability not reported',\n audience_type: value.audience_type, audience_size: value.audience_size ?? 'Not reported',\n ...(Array.isArray(value.reasons_not_targetable) && value.reasons_not_targetable.length ? { reasons_not_targetable: value.reasons_not_targetable } : {}),\n permission_level: value.permission_level,\n };\n }\n async list(raw: z.input<typeof audienceList>) {\n const { account_id, custom_audience_ids, ...input } = audienceList.parse(raw);\n await this.entities.getAccount(account_id);\n const params = this.pageParams(input);\n if (custom_audience_ids) params.custom_audience_ids = custom_audience_ids.join(',');\n const page = await this.page(account_id, this.base(account_id), audience, params);\n if (page.data.some(value => custom_audience_ids && !custom_audience_ids.includes(value.id) || !input.with_deleted && value.deleted || input.q && !value.name.toLowerCase().startsWith(input.q.toLowerCase()) || input.permission_scope === 'OWNER' && (value.owner_account_id !== undefined && value.owner_account_id !== account_id || value.is_owner === false) || input.permission_scope === 'SHARED' && (value.owner_account_id === account_id || value.is_owner === true))) throw new AdportError('PROVIDER_ERROR', 'x: audience list does not match its ID/deletion/ownership/name filters');\n const items = page.data.map(value => ({ ...value, configuration_hash: snapshot(account_id, value) }));\n return { ...page, data: items, records: items.map(value => this.record(value)), notes: [...(page.complete === null ? ['Native next_cursor is missing; completeness is unconfirmed.'] : []), ...(page.data.length > input.count ? ['The native endpoint exceeded the requested count; the full page is retained.'] : [])] };\n }\n async get(raw: z.input<typeof audienceGet>) {\n const input = audienceGet.parse(raw);await this.entities.getAccount(input.account_id);\n const response = await this.entities.client.request('GET', `${this.base(input.account_id)}/${input.custom_audience_id}`, z.looseObject({ data: audience, request: z.object({ params: z.record(z.string(), z.unknown()).optional() }).optional() }), { with_deleted: input.with_deleted });\n this.scope(response, input.account_id, input.custom_audience_id);\n if (response.data.id !== input.custom_audience_id || !input.with_deleted && response.data.deleted) throw new AdportError('PROVIDER_ERROR', 'x: audience ID/deletion filter mismatch');\n const value = { ...response.data, configuration_hash: snapshot(input.account_id, response.data) };\n return { audience: value, records: [this.record(value)] };\n }\n async permissions(raw: z.input<typeof audiencePermissions>) {\n const { account_id, custom_audience_id, granted_account_ids, custom_audience_permission_ids, ...input } = audiencePermissions.parse(raw);\n await this.get({ account_id, custom_audience_id });\n const params = this.pageParams(input);\n if (granted_account_ids) params.granted_account_ids = granted_account_ids.join(',');\n if (custom_audience_permission_ids) params.custom_audience_permission_ids = custom_audience_permission_ids.join(',');\n const page = await this.page(account_id, `${this.base(account_id)}/${custom_audience_id}/permissions`, permission, params, custom_audience_id);\n if (page.data.some(value => value.custom_audience_id !== custom_audience_id || granted_account_ids && !granted_account_ids.includes(value.granted_account_id) || custom_audience_permission_ids && !custom_audience_permission_ids.includes(value.id))) throw new AdportError('PROVIDER_ERROR', 'x: audience permission ID/filter mismatch');\n return { ...page, records: page.data };\n }\n private async collect<S extends z.ZodType>(account: string, resource: string, path: string, schema: S, params: XParams = {}) {\n const rows: z.infer<S>[] = [], seen = new Set<string>(), ids = new Set<string>();let cursor: string | undefined;\n for (let pageIndex = 0; pageIndex < 25; pageIndex++) {\n const page = await this.page(account, path, schema, { ...params, ...(cursor ? { cursor } : {}) }, resource);\n for (const value of page.data) {\n const identity = String((value as Row).id ?? (value as Row).campaign_id);\n if (ids.has(identity)) throw new AdportError('PROVIDER_ERROR', 'x: audience usage scan repeated an entity');ids.add(identity);rows.push(value);\n }\n if (rows.length > 5000 || page.complete === null) throw new AdportError('PROVIDER_ERROR', 'x: audience usage completeness could not be verified within the 5000-record limit');\n if (page.complete) return rows;\n if (seen.has(page.next_cursor!)) break;\n seen.add(page.next_cursor!);cursor = page.next_cursor;\n }\n throw new AdportError('PROVIDER_ERROR', 'x: audience usage paging is repeated or exceeds the 25-page limit');\n }\n async usage(account: string, resource: string) {\n const current = (await this.get({ account_id: account, custom_audience_id: resource })).audience, base = `${this.base(account)}/${id.parse(resource)}`;\n const targeted = await this.collect(account, resource, `${base}/targeted`, target, { with_active: false });\n const permissions = await this.collect(account, resource, `${base}/permissions`, permission, { count: 1000 });\n if (permissions.some(value => value.custom_audience_id !== resource)) throw new AdportError('PROVIDER_ERROR', 'x: usage returned another audience permission');\n const lines = await this.collect(account, resource, `accounts/${account}/line_items`, lineItemSchema, { with_deleted: true, with_draft: true, count: 1000 });\n const byLine = new Map(lines.map(value => [value.id, value]));\n if (targeted.some(campaign => campaign.line_items.some(line => byLine.get(line.id)?.campaign_id !== campaign.campaign_id))) throw new AdportError('PROVIDER_ERROR', 'x: targeted audience groups do not match the selected account hierarchy');\n const criteria: z.infer<typeof criterion>[] = [];\n let scannedCriteria = 0;\n for (let offset = 0; offset < lines.length; offset += 200) {\n const batch = lines.slice(offset, offset + 200), selected = new Set(batch.map(value => value.id));\n const values = await this.collect(account, resource, `accounts/${account}/targeting_criteria`, criterion, { line_item_ids: batch.map(value => value.id).join(','), with_deleted: false, count: 1000 });\n scannedCriteria += values.length;\n if (scannedCriteria > 5000) throw new AdportError('PROVIDER_ERROR', 'x: audience usage exceeds the 5000-criterion scan limit');\n if (values.some(value => !selected.has(value.line_item_id) || value.deleted)) throw new AdportError('PROVIDER_ERROR', 'x: usage criteria returned a different line item or deleted criterion');\n criteria.push(...values.filter(value => /AUDIENCE/.test(value.targeting_type) && value.targeting_value === resource));\n }\n const activePermissions = permissions.filter(value => !value.deleted), references = targeted.flatMap(value => value.line_items.map(line => ({ campaign_id: value.campaign_id, ...line })));\n const normalized = { account_id: account, audience_id: resource, references: references.map(value => ({ campaign_id: value.campaign_id, id: value.id, servable: value.servable })).sort((a, b) => canonical(a).localeCompare(canonical(b))), criteria: criteria.map(value => ({ id: value.id, line_item_id: value.line_item_id, targeting_type: value.targeting_type, targeting_value: value.targeting_value, operator_type: value.operator_type })).sort((a, b) => a.id.localeCompare(b.id)), permissions: activePermissions.map(value => ({ id: value.id, granted_account_id: value.granted_account_id, permission_level: value.permission_level })).sort((a, b) => a.id.localeCompare(b.id)) };\n const latest = (await this.get({ account_id: account, custom_audience_id: resource })).audience;\n if (latest.configuration_hash !== current.configuration_hash) throw new AdportError('INVALID_INPUT', 'x: audience configuration changed during usage inspection; read it again');\n return { audience: current, references, criteria, permissions: activePermissions, complete: true, usage_hash: digest(normalized), records: [{ id: resource, name: current.name, targeted_groups: references.length, direct_criteria: criteria.length, sharing_grants: activePermissions.length }], notes: ['Includes inactive targeting and direct inclusion/exclusion criteria. Native checks are not an atomic lock against changes in another client.'] };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'x_create_custom_audience', remove = op.tool === 'x_delete_custom_audience', members = op.tool === 'x_update_custom_audience_users';\n if (op.provider !== 'x' || op.kind !== (create ? 'create' : remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'x: audience provider/operation kind mismatch');\n const account = id.parse(op.accountId), base = this.base(account);\n await this.entities.getAccount(account);\n if (create) {\n const input = createAudience.parse(op.payload);\n return { summary: `Create empty X audience \"${input.name}\"`, changes: [`+ CRM placeholder ${JSON.stringify(input)}`], notes: [...notes, 'No members are uploaded and no targeting or sharing is added.'], coercions: [], budgetDeltas: [], execute: async () => {\n let resource: string | undefined;\n try {\n const receipt = await this.entities.client.request('POST', base, z.object({ data: z.looseObject({ id }) }), input);resource = receipt.data.id;\n const actual = (await this.get({ account_id: account, custom_audience_id: resource })).audience;this.owned(actual, account);\n if (actual.name !== input.name || actual.description !== (input.description ?? null) || actual.audience_type !== 'CRM' || actual.targetable === true || (actual.audience_size ?? 0) > 0) throw new Error('Metadata or empty-placeholder state differs');\n return { applied: true, resourceIds: [resource] };\n } catch (error) {\n if (!resource && rejection(error)) throw error;\n throw new AdportError('PROVIDER_ERROR', 'x: audience creation outcome unconfirmed; reconcile the owned inventory before another create', { ...(resource ? { resource_ids: [resource] } : {}) });\n }\n } };\n }\n const input = remove ? deleteAudience.parse(op.payload) : members ? audienceUsers.parse(op.payload) : op.tool === 'x_update_custom_audience' ? updateAudience.parse(op.payload) : undefined;\n if (!input) throw new AdportError('INVALID_INPUT', 'x: unsupported audience mutation');\n const current = (await this.get({ account_id: account, custom_audience_id: input.custom_audience_id })).audience;this.owned(current, account);\n if (current.configuration_hash !== input.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'x: audience configuration changed; read and preview it again');\n const path = `${base}/${current.id}`;\n if ('operations' in input) {\n if (current.audience_type !== 'CRM') throw new AdportError('INVALID_INPUT', 'x: native member updates require an owned CRM audience');\n for (const value of input.operations) if (value.params.expires_at && Date.parse(value.params.expires_at) <= (value.params.effective_at ? Date.parse(value.params.effective_at) : Date.now())) throw new AdportError('INVALID_INPUT', 'x: member expiry must follow its effective time');\n const count = input.operations.reduce((sum, value) => sum + value.params.users.length, 0), batchHash = digest(input.operations);\n const descriptions = input.operations.map(value => `${value.params.users.length} user ${value.params.users.length === 1 ? 'record' : 'records'}${value.params.effective_at ? `; effective ${value.params.effective_at}` : ''}${value.params.expires_at ? `; expiry ${value.params.expires_at}` : ''}`), changes = input.operations.map((value, index) => `${value.operation_type}: ${descriptions[index]}`);\n const uploadNotes = [...notes, 'Existing ads that use this audience can be affected. Native processing acceptance does not confirm audience readiness or exact membership. Native processing generally takes 6–8 hours.'];\n return { summary: `Submit member changes for X audience \"${current.name}\"`, changes: [...changes, `SHA256 ${batchHash}`], notes: uploadNotes, coercions: [], budgetDeltas: [],\n review: { provider: 'x', accountId: account, kind: op.kind, title: 'Submit audience members', subject: current.name, fields: [...input.operations.map((value, index) => ({ label: value.operation_type, after: descriptions[index]! })), { label: 'Batch SHA256', after: batchHash }], notices: uploadNotes }, execute: async () => {\n try {\n const receipt = await this.entities.client.request('POST', `${path}/users`, z.object({ data: z.object({ success_count: z.number().int().nonnegative().safe(), total_count: z.number().int().nonnegative().safe() }) }), {}, input.operations);\n if (receipt.data.success_count !== count || receipt.data.total_count !== count) throw new Error('Counts differ');\n return { applied: true, resourceIds: [current.id], details: { outcome: 'ACCEPTED_FOR_PROCESSING', accepted_records: count, batch_sha256: batchHash, readiness_confirmed: false }, warnings: ['Native audience processing and targeting readiness remain unconfirmed.'] };\n } catch (error) {\n if (rejection(error)) throw error;\n throw new AdportError('PROVIDER_ERROR', 'x: audience member submission outcome unconfirmed; do not replay the batch automatically', { resource_ids: [current.id], batch_sha256: batchHash, expected_records: count });\n }\n } };\n }\n if ('expected_usage_hash' in input) {\n const usage = await this.usage(account, current.id);\n if (usage.audience.configuration_hash !== input.expected_configuration_hash) throw new AdportError('INVALID_INPUT', 'x: audience configuration changed during deletion preflight');\n if (usage.usage_hash !== input.expected_usage_hash) throw new AdportError('INVALID_INPUT', 'x: audience usage changed; inspect it before another preview');\n if (usage.references.length || usage.criteria.length || usage.permissions.length) throw new AdportError('INVALID_INPUT', 'x: remove audience targeting, exclusions and sharing permissions before deletion');\n }\n const params = remove ? {} : Object.fromEntries(Object.entries(input).filter(([key, value]) => ['name', 'description'].includes(key) && value !== undefined)) as XParams;\n const expected = { ...configuration(current), ...params, ...(remove ? { deleted: true } : {}) };\n return { summary: `${remove ? 'Delete' : 'Update'} X audience \"${current.name}\"`, changes: [remove ? `- Audience ${current.id}` : `~ Metadata ${JSON.stringify(params)}`], notes, coercions: [], budgetDeltas: [],\n ...(!remove ? { review: { provider: 'x', accountId: account, kind: op.kind, title: 'Update audience', subject: current.name, fields: Object.entries(params).map(([key, value]) => ({ label: key === 'name' ? 'Name' : 'Description', before: key === 'name' ? current.name : current.description, after: value })), notices: notes } } : {}),\n execute: async () => {\n let accepted = false;\n try {\n const receipt = await this.entities.client.request(remove ? 'DELETE' : 'PUT', path, z.object({ data: z.looseObject({ id }) }), params);\n accepted = true;\n if (receipt.data.id !== current.id) throw new Error('ID differs');\n const actual = (await this.get({ account_id: account, custom_audience_id: current.id, with_deleted: remove })).audience;\n if (canonical(configuration(actual)) !== canonical(expected)) throw new Error('Metadata differs');\n return { applied: true, resourceIds: [current.id] };\n } catch (error) {\n if (!accepted && rejection(error)) throw error;\n throw new AdportError('PROVIDER_ERROR', `x: audience ${remove ? 'deletion' : 'update'} outcome unconfirmed; reconcile this ID before another mutation`, { resource_ids: [current.id] });\n }\n },\n };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { xId as id } from './schemas.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst name = z.string().trim().min(1).max(255);\nconst ids = z.array(id).min(1).max(200).refine(values => new Set(values).size === values.length, 'Use unique IDs');\nconst page = { cursor: z.string().min(1).max(4096).optional(), count: z.number().int().min(1).max(1000).default(200), with_total_count: z.boolean().default(false).describe('Request a total on the initial page; cursor requests omit this native flag') };\nexport const audienceList = z.object({ account_id: id, ...page, permission_scope: z.enum(['OWNER', 'SHARED']).default('OWNER'), custom_audience_ids: ids.optional(), q: z.string().min(1).max(255).optional(), with_deleted: z.boolean().default(false) }).strict();\nexport const audienceGet = z.object({ account_id: id, custom_audience_id: id, with_deleted: z.boolean().default(false) }).strict();\nexport const audiencePermissions = z.object({ account_id: id, custom_audience_id: id, ...page, granted_account_ids: ids.optional(), custom_audience_permission_ids: ids.optional() }).strict();\nexport const createAudience = z.object({ name, description: z.string().max(4096).optional() }).strict();\nexport const updateAudience = z.object({ custom_audience_id: id, expected_configuration_hash: hash, name: name.optional(), description: z.string().max(4096).optional() }).strict().refine(value => value.name !== undefined || value.description !== undefined, 'Provide a name or description');\nexport const deleteAudience = z.object({ custom_audience_id: id, expected_configuration_hash: hash, expected_usage_hash: hash }).strict();\nconst values = z.array(hash).min(1).max(100).refine(value => new Set(value).size === value.length, 'Identifiers must be unique within a user field');\nconst user = z.object({ email: values.optional(), device_id: values.optional(), handle: values.optional(), twitter_id: values.optional(), phone_number: values.optional(), partner_user_id: z.array(z.string().min(1).max(1024)).min(1).max(100).optional() }).strict().refine(value => Object.keys(value).length > 0, 'Each user needs an identifier');\nconst operation = z.object({ operation_type: z.enum(['Update', 'Delete']), params: z.object({ users: z.array(user).min(1).max(2500), effective_at: z.iso.datetime().optional(), expires_at: z.iso.datetime().optional() }).strict().refine(value => !value.expires_at || !value.effective_at || Date.parse(value.expires_at) > Date.parse(value.effective_at), 'Expiry must follow the effective time') }).strict();\nexport const audienceUsers = z.object({ custom_audience_id: id, expected_configuration_hash: hash, operations: z.array(operation).min(1).max(2500) }).strict()\n .refine(value => value.operations.reduce((total, op) => total + op.params.users.length, 0) <= 2500, 'Adport limit: 2500 total user records per approved call')\n .refine(value => Buffer.byteLength(JSON.stringify(value.operations)) <= 5_000_000, 'Native JSON body must not exceed 5000000 bytes');\n\nexport function xAudienceTools(provider: XAdsProvider): AnyToolDefinition[] {\n const output = z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) });\n const read = { namespace: 'x', presentation: 'records' as const, output, annotations: { readOnly: true } };\n const write = { namespace: 'x', provider: 'x' };\n return [\n defineTool({ ...read, name: 'x_custom_audiences', description: 'List owned or already shared X custom audiences with exact native cursor filters, targetability and configuration hashes. Load more retains selection; no members are returned.', input: audienceList, pagination: { cursorInput: 'cursor' }, handler: input => provider.audiences.list(input) }),\n defineTool({ ...read, name: 'x_get_custom_audience', description: 'Read one selected-account custom audience, ownership and configuration_hash. Processing/size/targetability are native diagnostics, not proof of exact member contents.', input: audienceGet, handler: input => provider.audiences.get(input) }),\n defineTool({ ...read, name: 'x_custom_audience_permissions', description: 'Inspect existing audience sharing permissions with native cursor/ID filters; does not grant, revoke or expand access.', input: audiencePermissions, pagination: { cursorInput: 'cursor' }, handler: input => provider.audiences.permissions(input) }),\n defineTool({ ...read, name: 'x_custom_audience_usage', description: 'Inspect all targeted campaigns, including inactive groups, sharing permissions and direct audience inclusion/exclusion criteria. Bounded complete scan supplies usage_hash for deletion; incomplete scans fail.', input: z.object({ account_id: id, custom_audience_id: id }).strict(), handler: input => provider.audiences.usage(input.account_id, input.custom_audience_id) }),\n guardedWriteTool({ ...write, name: 'x_create_custom_audience', kind: 'create', destructive: false, description: 'Create an empty owned CRM audience placeholder. Independently reads back ownership and approved metadata; no user upload, ad association, sharing or activation.', payload: createAudience }),\n guardedWriteTool({ ...write, name: 'x_update_custom_audience', kind: 'update', destructive: false, description: 'Edit an owned audience name or description using a fresh configuration_hash. Preserves omitted metadata and audience type; independently verifies native readback.', payload: updateAudience }),\n guardedWriteTool({ ...write, name: 'x_update_custom_audience_users', kind: 'update', destructive: true, description: 'Submit explicit Update/Delete member groups to an owned CRM audience. Identifiers must already be normalized SHA256, except native partner_user_id. Preview shows counts/digest; receipt confirms processing acceptance, not targeting readiness. No automatic retry.', payload: audienceUsers, sensitiveInputs: ['operations'] }),\n guardedWriteTool({ ...write, name: 'x_delete_custom_audience', kind: 'remove', destructive: true, description: 'Delete an owned unreferenced, unshared audience using current configuration and usage hashes. Checks inactive targeting and exclusions, then independently verifies deleted=true. No restore endpoint is claimed.', payload: deleteAudience }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsEntities } from './entities.js';\nimport { XAdsAnalytics, xAccountMidnight } from './analytics.js';\nimport { appTag, appTags, conversionStats, createTrackingTag, deleteTrackingTag, trackingTag, trackingTags, updateTrackingTag, webTag, webTags } from './measurement-tools.js';\nimport { campaignSchema, lineItemSchema, promotedTweetSchema, xId as id } from './schemas.js';\nimport type { XParams } from './client.js';\n\ntype Row = Record<string, unknown>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<WriteResult> };\nconst web = z.looseObject({ id, name: z.string(), type: z.string(), deleted: z.boolean() });\ntype Web = z.infer<typeof web>;\nconst app = z.looseObject({ id, app_store_identifier: z.string(), os_type: z.string(), conversion_type: z.string(), post_view_attribution_window: z.number().int().nonnegative(), post_engagement_attribution_window: z.number().int().nonnegative(), deleted: z.boolean() });\nconst tracking = z.looseObject({ id, line_item_id: id, tracking_tag_type: z.string(), tracking_tag_url: z.string(), deleted: z.boolean() });\ntype Tracking = z.infer<typeof tracking>;\nconst request = z.object({ params: z.record(z.string(), z.unknown()).optional() }).optional();\nconst canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);\nconst configuration = (value: Tracking) => Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at', 'updated_at', 'configuration_hash'].includes(key)));\nconst snapshot = (account: string, value: Tracking) => createHash('sha256').update(canonical({ account_id: account, configuration: configuration(value) })).digest('hex');\nconst webSnapshot = (account: string, value: Web) => createHash('sha256').update(canonical({ account_id: account, configuration: Object.fromEntries(['id', 'name', 'type', 'retargeting_enabled', 'click_window', 'view_through_window', 'deleted'].filter(key => value[key] !== undefined).map(key => [key, value[key]])) })).digest('hex');\nconst day = 86_400_000;\nconst notes = ['Local preview only; X has no server dry run or conditional update for this workflow.', 'Measurement on active ads may change immediately. No events are sent by this tool, no ads are activated and no budget or bid is changed.', 'No automatic write retry. Reconcile known IDs after an uncertain result.'];\nconst rejection = (error: unknown) => error instanceof AdportError && error.details !== null && typeof error.details === 'object' && 'http_status' in error.details && [401, 403, 429].includes(Number(error.details.http_status));\n\n/** Provider-owned v12 tracking/app references and MCP route map, commit 4e8f626. */\nexport class XMeasurementService {\n constructor(private readonly entities: XAdsEntities, private readonly analytics: XAdsAnalytics) {}\n private base(account: string, kind: string) { return `accounts/${id.parse(account)}/${kind}`; }\n private scope(value: { request?: { params?: Row } }, account: string, kind: string, resource?: string) {\n const params = value.request?.params;\n if (params && (params.account_id !== undefined && params.account_id !== account || resource && params[`${kind.slice(0, -1)}_id`] !== undefined && params[`${kind.slice(0, -1)}_id`] !== resource)) throw new AdportError('PROVIDER_ERROR', 'x: measurement response scope differs from the selected account/ID');\n }\n private rowScope(value: Row, account: string) {\n if (value.account_id !== undefined && value.account_id !== account) throw new AdportError('PROVIDER_ERROR', 'x: measurement resource belongs to a different account');\n }\n private async page<S extends z.ZodType<{ id: string; deleted: boolean } & Row>>(account: string, kind: string, schema: S, params: XParams, filters?: string[], lineIds?: string[]) {\n await this.entities.getAccount(account);\n const result = await this.entities.client.request('GET', this.base(account, kind), z.looseObject({ data: z.array(schema).max(5000), next_cursor: z.string().min(1).max(4096).nullable().optional(), total_count: z.number().int().nonnegative().safe().optional(), request }), params);\n this.scope(result, account, kind);\n if (result.next_cursor && result.next_cursor === params.cursor || new Set(result.data.map(value => value.id)).size !== result.data.length) throw new AdportError('PROVIDER_ERROR', 'x: measurement page repeats a cursor or resource ID');\n for (const value of result.data) {\n this.rowScope(value, account);\n if (filters && !filters.includes(value.id) || !params.with_deleted && value.deleted || lineIds && !lineIds.includes(String(value.line_item_id))) throw new AdportError('PROVIDER_ERROR', 'x: measurement page differs from requested filters');\n }\n return { ...result, complete: result.next_cursor === null ? true : result.next_cursor === undefined ? null : false, ...(result.data.length > Number(params.count) ? { warnings: ['X returned more records than requested; the complete native page is retained.'] } : {}) };\n }\n private async get<S extends z.ZodType<{ id: string; deleted: boolean } & Row>>(account: string, kind: string, resource: string, schema: S, withDeleted: boolean) {\n await this.entities.getAccount(account);\n const result = await this.entities.client.request('GET', `${this.base(account, kind)}/${id.parse(resource)}`, z.looseObject({ data: z.unknown(), request }), { with_deleted: withDeleted });\n const parsed = schema.safeParse(result.data);\n if (!parsed.success) throw new AdportError('PROVIDER_ERROR', 'x: unexpected measurement resource schema');\n this.scope(result, account, kind, resource);this.rowScope(parsed.data, account);\n if (parsed.data.id !== resource || !withDeleted && parsed.data.deleted) throw new AdportError('PROVIDER_ERROR', 'x: measurement resource ID/deletion state differs from the request');\n return { ...result, data: parsed.data };\n }\n async listWeb(value: unknown) {\n const { account_id, ...params } = webTags.parse(value), result = await this.page(account_id, 'web_event_tags', web, params);\n const data = result.data.map((value): Web & { configuration_hash: string } => ({ ...value, configuration_hash: webSnapshot(account_id, value) }));\n return { ...result, data, records: data.map(value => ({ id: value.id, name: value.name, type: value.type, status: value.deleted ? 'Deleted' : value.status ?? 'Not reported', ...(value.click_window !== undefined ? { click_window_days: value.click_window } : {}), ...(value.view_through_window !== undefined ? { view_through_window_days: value.view_through_window } : {}) })) };\n }\n async getWeb(value: unknown) {\n const input = webTag.parse(value), result = await this.get(input.account_id, 'web_event_tags', input.web_event_tag_id, web, input.with_deleted);\n const data: Web & { configuration_hash: string } = { ...result.data, configuration_hash: webSnapshot(input.account_id, result.data) };\n return { ...result, data, records: [data], notes: ['Embed code is returned as inert data. This read does not install a pixel or send an event.'] };\n }\n async listApp(value: unknown) {\n const { account_id, app_event_tag_ids, ...input } = appTags.parse(value), params = this.pageParams(input, { app_event_tag_ids });\n const result = await this.page(account_id, 'app_event_tags', app, params, app_event_tag_ids);\n return { ...result, records: result.data.map(value => ({ id: value.id, name: `${value.conversion_type} · ${value.app_store_identifier}`, status: value.deleted ? 'Deleted' : value.status ?? 'Not reported', os_type: value.os_type, post_view_window_days: value.post_view_attribution_window, post_engagement_window_days: value.post_engagement_attribution_window })) };\n }\n async getApp(value: unknown) {\n const input = appTag.parse(value), result = await this.get(input.account_id, 'app_event_tags', input.app_event_tag_id, app, input.with_deleted);\n return { ...result, records: [result.data] };\n }\n private pageParams(value: { cursor?: string; count: number; with_deleted: boolean; with_total_count: boolean }, filters: Record<string, string[] | undefined>): XParams {\n const { with_total_count, ...params } = value;\n return { ...params, ...(!params.cursor && with_total_count ? { with_total_count: true } : {}), ...Object.fromEntries(Object.entries(filters).filter(([, value]) => value !== undefined).map(([key, value]) => [key, value!.join(',')])) };\n }\n async listTracking(value: unknown) {\n const { account_id, tracking_tag_ids, line_item_ids, ...input } = trackingTags.parse(value), params = this.pageParams(input, { tracking_tag_ids, line_item_ids });\n const result = await this.page(account_id, 'tracking_tags', tracking, params, tracking_tag_ids, line_item_ids);\n if (result.data.length) {\n const lineIds = [...new Set(result.data.map(value => value.line_item_id))];\n const lines = new Map((await this.selectedParents(account_id, 'line_items', 'line_item_ids', lineItemSchema, lineIds)).map(value => [value.id, value]));\n const campaignIds = [...new Set([...lines.values()].map(value => value.campaign_id))];\n const campaigns = new Map((await this.selectedParents(account_id, 'campaigns', 'campaign_ids', campaignSchema, campaignIds)).map(value => [value.id, value]));\n for (const tag of result.data) {\n const line = lines.get(tag.line_item_id), campaign = line && campaigns.get(line.campaign_id);\n if (!line || !campaign || campaign.currency !== line.currency) throw new AdportError('PROVIDER_ERROR', 'x: tracking-tag parent hierarchy is not verified in the selected account');\n }\n }\n const data = result.data.map(value => ({ ...value, configuration_hash: snapshot(account_id, value) }));\n return { ...result, data, records: data.map(value => this.trackingRecord(value)) };\n }\n private async selectedParents<S extends z.ZodType<{ id: string }>>(account: string, kind: string, filter: string, schema: S, ids: string[]) {\n const rows: z.output<S>[] = [];\n for (let offset = 0; offset < ids.length; offset += 200) {\n const selected = ids.slice(offset, offset + 200), result = await this.entities.client.request('GET', this.base(account, kind), z.looseObject({ data: z.array(schema).max(1000), request }), { [filter]: selected.join(','), count: 1000, with_deleted: true, with_draft: true });\n this.scope(result, account, kind);\n if (new Set(result.data.map(value => value.id)).size !== result.data.length || result.data.some(value => !selected.includes(value.id)) || selected.some(value => !result.data.some(row => row.id === value))) throw new AdportError('PROVIDER_ERROR', 'x: tracking-tag parent hierarchy is incomplete or differs from requested IDs');\n rows.push(...result.data);\n }\n return rows;\n }\n async getTracking(value: unknown) {\n const input = trackingTag.parse(value), result = await this.get(input.account_id, 'tracking_tags', input.tracking_tag_id, tracking, input.with_deleted);\n await this.entities.getLineItem(input.account_id, result.data.line_item_id);\n const tag = { ...result.data, configuration_hash: snapshot(input.account_id, result.data) };\n return { ...result, data: tag, records: [this.trackingRecord(tag)] };\n }\n private trackingRecord(value: Tracking) {\n return { id: value.id, name: value.tracking_tag_type === 'IMPRESSION_TAG' ? 'Impression tracker' : value.tracking_tag_type === 'CLICK_TRACKER' ? 'Click tracker' : value.tracking_tag_type, status: value.deleted ? 'Deleted' : 'Associated', line_item_id: value.line_item_id, tracking_url: value.tracking_tag_url };\n }\n async plan(op: WriteOperation): Promise<Plan> {\n const create = op.tool === 'x_create_tracking_tag', remove = op.tool === 'x_delete_tracking_tag';\n if (op.provider !== 'x' || op.kind !== (create ? 'create' : remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'x: tracking-tag provider/operation kind mismatch');\n const account = id.parse(op.accountId);\n await this.entities.getAccount(account);\n const input = create ? createTrackingTag.parse(op.payload) : remove ? deleteTrackingTag.parse(op.payload) : op.tool === 'x_update_tracking_tag' ? updateTrackingTag.parse(op.payload) : undefined;\n if (!input) throw new AdportError('INVALID_INPUT', 'x: unsupported measurement mutation');\n const current = 'tracking_tag_id' in input ? (await this.getTracking({ account_id: account, tracking_tag_id: input.tracking_tag_id })).data : undefined;\n if (current && ('expected_configuration_hash' in input && current.configuration_hash !== input.expected_configuration_hash || current.deleted)) throw new AdportError('INVALID_INPUT', 'x: tracking-tag configuration changed; read and preview it again');\n const line = await this.entities.getLineItem(account, 'line_item_id' in input ? input.line_item_id : current!.line_item_id), campaign = await this.entities.getCampaign(account, line.campaign_id);\n if (line.deleted || campaign.deleted || line.entity_status === 'DRAFT' || campaign.entity_status === 'DRAFT') throw new AdportError('INVALID_INPUT', 'x: tracking-tag writes require a non-deleted, non-draft line item and campaign');\n const params: XParams = create ? { line_item_id: line.id, tracking_tag_type: (input as z.infer<typeof createTrackingTag>).tracking_tag_type, tracking_tag_url: (input as z.infer<typeof createTrackingTag>).tracking_tag_url } : 'tracking_tag_url' in input ? { tracking_tag_url: input.tracking_tag_url } : {};\n const title = `${create ? 'Associate' : remove ? 'Remove' : 'Update'} ${create ? params.tracking_tag_type === 'IMPRESSION_TAG' ? 'impression' : 'click' : current!.tracking_tag_type === 'IMPRESSION_TAG' ? 'impression' : 'click'} tracker`;\n const fields = [{ label: 'Ad group', after: line.name ?? line.id }, { label: 'Tracking URL', ...(current ? { before: current.tracking_tag_url } : {}), after: remove ? null : params.tracking_tag_url }];\n return { summary: `${title} · ${line.name ?? line.id}`, changes: [`${remove ? '-' : create ? '+' : '~'} ${JSON.stringify(params)}${current ? ` · tag ${current.id}` : ''}`], notes, coercions: [], budgetDeltas: [], review: { provider: 'x', accountId: account, kind: op.kind, title, subject: line.name ?? line.id, fields, notices: notes }, execute: async () => {\n let resource = current?.id, accepted = false;\n try {\n const receipt = await this.entities.client.request(create ? 'POST' : remove ? 'DELETE' : 'PUT', `${this.base(account, 'tracking_tags')}${current ? `/${current.id}` : ''}`, z.looseObject({ data: z.looseObject({ id }), request }), params);\n accepted = true;\n const expectedId = resource;resource = receipt.data.id;\n if (expectedId && resource !== expectedId) throw new Error('ID differs');\n this.scope(receipt, account, 'tracking_tags', resource);\n const actual = (await this.getTracking({ account_id: account, tracking_tag_id: resource, with_deleted: remove })).data;\n const expected = create ? { ...params, id: resource, deleted: false } : { ...configuration(current!), ...params, deleted: remove };\n if (Object.entries(expected).some(([key, value]) => canonical((actual as Row)[key]) !== canonical(value))) throw new Error('Configuration differs');\n return { applied: true, resourceIds: [resource] };\n } catch (error) {\n if (!accepted && rejection(error)) throw error;\n const details = error instanceof AdportError && error.details && typeof error.details === 'object' ? error.details as Row : {};\n const ids = [...new Set([current?.id, resource, ...(Array.isArray(details.resource_ids) ? details.resource_ids.filter(value => typeof value === 'string' && id.safeParse(value).success) as string[] : [])].filter((value): value is string => !!value))];\n throw new AdportError('PROVIDER_ERROR', 'x: tracking-tag mutation outcome unconfirmed; inspect the selected account before another write; do not replay automatically', { resource_ids: ids });\n }\n } };\n }\n async conversions(value: unknown) {\n const input = conversionStats.parse(value), account = await this.entities.getAccount(input.account_id);\n const start = xAccountMidnight(input.start_date, account.timezone), endDate = new Date(Date.parse(`${input.end_date}T00:00:00Z`) + day).toISOString().slice(0, 10), end = xAccountMidnight(endDate, account.timezone);\n if (account.timezone_switch_at && (!Number.isFinite(Date.parse(account.timezone_switch_at)) || start < Date.parse(account.timezone_switch_at))) throw new AdportError('INVALID_INPUT', 'x: requested dates predate the account timezone switch; previous reporting timezone is unknown');\n for (const resource of input.entity_ids) {\n if (input.entity === 'CAMPAIGN') await this.entities.getCampaign(input.account_id, resource);\n else if (input.entity === 'LINE_ITEM') await this.entities.getLineItem(input.account_id, resource);\n else {\n const { data } = await this.entities.client.request('GET', `accounts/${input.account_id}/promoted_tweets/${resource}`, z.object({ data: promotedTweetSchema }));\n if (data.id !== resource) throw new AdportError('PROVIDER_ERROR', 'x: conversion entity ID mismatch');\n await this.entities.getLineItem(input.account_id, data.line_item_id);\n }\n }\n const asynchronous = end - start > 7 * day || end < Date.now() - 7 * day;\n const result = await this.analytics.totals(input.account_id, { entity: input.entity, entity_ids: input.entity_ids.join(','), start_time: new Date(start).toISOString(), end_time: new Date(end).toISOString(), granularity: 'TOTAL', placement: input.placement, metric_groups: input.metric_group }, asynchronous);\n const prefix = input.metric_group === 'WEB_CONVERSION' ? 'conversion_' : 'mobile_conversion_';\n const data = result.data.map(row => ({ ...row, id_data: row.id_data.map(value => ({ ...value, metrics: Object.fromEntries(Object.entries(value.metrics).filter(([key]) => key.startsWith(prefix))) })) }));\n return { ...result, data, records: data.map(value => ({ id: value.id, name: `${input.entity} ${value.id}`, metric_group: input.metric_group, placement: input.placement, native_metrics: value.id_data[0]!.metrics })), normalized: false, placement: input.placement, metric_group: input.metric_group, notes: ['Native conversion objects are preserved without summing event types, attribution buckets or order quantities. Sale-amount currency/units are not normalized to revenue, CPA or ROAS.', 'This report covers only the selected placement and provider attribution settings. It does not send events or change tracking configuration.'] };\n }\n}\n","import { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { xId as id } from './schemas.js';\nimport { X_PLACEMENTS } from './analytics.js';\n\nconst ids = z.array(id).min(1).max(200).refine(value => new Set(value).size === value.length, 'Use unique IDs');\nconst page = { account_id: id, count: z.number().int().min(1).max(1000).default(200), cursor: z.string().min(1).max(4096).optional(), with_deleted: z.boolean().default(false), with_total_count: z.boolean().default(false).describe('Request a total on the initial page; native cursor requests omit this flag') };\nexport const webTags = z.object({ account_id: id, count: page.count, cursor: page.cursor, with_deleted: page.with_deleted }).strict();\nexport const appTags = z.object({ ...page, app_event_tag_ids: ids.optional() }).strict();\nexport const trackingTags = z.object({ ...page, tracking_tag_ids: ids.optional(), line_item_ids: ids.optional() }).strict();\nexport const webTag = z.object({ account_id: id, web_event_tag_id: id, with_deleted: page.with_deleted }).strict();\nexport const appTag = z.object({ account_id: id, app_event_tag_id: id, with_deleted: page.with_deleted }).strict();\nexport const trackingTag = z.object({ account_id: id, tracking_tag_id: id, with_deleted: page.with_deleted }).strict();\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst url = z.url({ protocol: /^https$/ }).max(8192).refine(value => { const parsed = new URL(value); return !parsed.username && !parsed.password && !parsed.hash; }, 'Use an HTTPS tracking URL without credentials or a fragment');\nexport const createTrackingTag = z.object({ line_item_id: id, tracking_tag_type: z.enum(['IMPRESSION_TAG', 'CLICK_TRACKER']), tracking_tag_url: url }).strict();\nexport const updateTrackingTag = z.object({ tracking_tag_id: id, expected_configuration_hash: hash, tracking_tag_url: url }).strict();\nexport const deleteTrackingTag = z.object({ tracking_tag_id: id, expected_configuration_hash: hash }).strict();\nexport const conversionStats = z.object({\n account_id: id, entity: z.enum(['CAMPAIGN', 'LINE_ITEM', 'PROMOTED_TWEET']),\n entity_ids: z.array(id).min(1).max(20).refine(value => new Set(value).size === value.length, 'Use unique entity IDs'),\n start_date: z.iso.date(), end_date: z.iso.date(), placement: z.enum(X_PLACEMENTS),\n metric_group: z.enum(['WEB_CONVERSION', 'MOBILE_CONVERSION']),\n}).strict().refine(value => value.end_date >= value.start_date && Date.parse(value.end_date) - Date.parse(value.start_date) < 30 * 86_400_000, 'Choose an inclusive range of at most 30 days');\n\nexport function xMeasurementTools(provider: XAdsProvider): AnyToolDefinition[] {\n const read = { namespace: 'x', presentation: 'records' as const, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }), annotations: { readOnly: true } };\n const write = { namespace: 'x', provider: 'x' };\n return [\n defineTool({ ...read, name: 'x_web_event_tags', description: 'Inspect native account-scoped website conversion tags and embed code as inert data. Native cursors preserve pagination. This does not create events or install a pixel.', input: webTags, pagination: { cursorInput: 'cursor' }, handler: input => provider.measurement.listWeb(input) }),\n defineTool({ ...read, name: 'x_get_web_event_tag', description: 'Read one website conversion tag by exact account and ID, without executing embed code or sending an event.', input: webTag, handler: input => provider.measurement.getWeb(input) }),\n defineTool({ ...read, name: 'x_app_event_tags', description: 'Inspect native app event tags, app identity, conversion type and attribution windows with exact ID filters and cursor pagination. Sends no app events.', input: appTags, pagination: { cursorInput: 'cursor' }, handler: input => provider.measurement.listApp(input) }),\n defineTool({ ...read, name: 'x_get_app_event_tag', description: 'Read one native app event tag and attribution windows in the selected account. Sends no events.', input: appTag, handler: input => provider.measurement.getApp(input) }),\n defineTool({ ...read, name: 'x_tracking_tags', description: 'Inspect native impression/click tracking tags with account/line-item ownership checks, configuration hashes and native cursor/ID filters.', input: trackingTags, pagination: { cursorInput: 'cursor' }, handler: input => provider.measurement.listTracking(input) }),\n defineTool({ ...read, name: 'x_get_tracking_tag', description: 'Read one impression/click tracking tag and its configuration_hash after checking its line item and campaign in the selected account.', input: trackingTag, handler: input => provider.measurement.getTracking(input) }),\n guardedWriteTool({ ...write, name: 'x_create_tracking_tag', kind: 'create', destructive: false, description: 'Associate an HTTPS impression or click tracker with an existing non-draft line item. May immediately change measurement on an active ad group. Verifies native receipt/readback; sends no test event and never retries automatically.', payload: createTrackingTag }),\n guardedWriteTool({ ...write, name: 'x_update_tracking_tag', kind: 'update', destructive: false, description: 'Change only a tracking-tag URL using a current configuration_hash. Preserves its parent/type and independently reads back the result. May affect active measurement immediately; no automatic retry.', payload: updateTrackingTag }),\n guardedWriteTool({ ...write, name: 'x_delete_tracking_tag', kind: 'remove', destructive: true, description: 'Disassociate a tracking tag using a current configuration_hash. Verifies native deleted=true and independent readback. Can stop third-party measurement; does not pause ads or claim a restore endpoint.', payload: deleteTrackingTag }),\n defineTool({ ...read, name: 'x_conversion_stats', description: 'Read native WEB_CONVERSION or separately requested MOBILE_CONVERSION objects for up to 20 verified entities and 30 account-local dates. Placement is explicit. Preserves native fields/units; does not label them normalized conversions, revenue, CPA or ROAS.', input: conversionStats, handler: input => provider.measurement.conversions(input) }),\n ];\n}\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type ReviewField, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport type { XCreativeService } from './creatives.js';\nimport { snowflake } from './creative-tools.js';\nimport type { XAdsEntities } from './entities.js';\nimport { createPost, createPromotions, createRepostPromotions, deletePromotion, nativePost, postFields, postList, promotionList, promotionSelection, renamePost, type NativePost } from './post-schemas.js';\nimport { promotedTweetSchema, xId } from './schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<string[] | WriteResult> }\nconst nativePromotion = promotedTweetSchema.extend({ account_id: xId.optional(), approval_status: z.string().optional() });\ntype Promotion = z.infer<typeof nativePromotion>;\nconst pageSchema = <T extends z.ZodType>(item: T) => z.object({ data: z.array(item).max(1000), next_cursor: z.string().nullable().optional() });\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst hash = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst equal = (a: unknown, b: unknown) => hash(a) === hash(b);\nconst sourceConfig = (value: Record<string, unknown>) => Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at', 'updated_at', 'media_url', 'poster_media_url'].includes(key)));\nconst postContent = (post: NativePost) => ({ ...post });\nconst postSnapshot = (account: string, post: NativePost) => hash({ account_id: account, post: postContent(post) });\nconst safeUrl = (value: unknown, cdn = false) => {\n if (typeof value !== 'string') return undefined;\n try { const url = new URL(value);return url.protocol === 'https:' && !url.username && !url.password && (!url.port || url.port === '443') && (!cdn || ['pbs.twimg.com', 'video.twimg.com', 'ton.twimg.com'].includes(url.hostname)) ? value : undefined; } catch { return undefined; }\n};\nconst notice = 'Native previews are local plans, not X validation. No write is retried automatically. Published posts, ad associations and actual delivery are separate states.';\n\n/** Official xdevplatform/docs creatives a9226e10 and campaign-management570f918c, checked2026-11-06. */\nexport class XPostService {\n constructor(private readonly entities: XAdsEntities, private readonly creatives: XCreativeService) {}\n private base(account: string) { return `accounts/${xId.parse(account)}`; }\n private async author(account: string, user: string, full = false) {\n const matches = (await this.creatives.users(account)).filter(row => row.user_id === user && !row.deleted);\n if (matches.length !== 1 || !['FULL', 'RETWEETS_ONLY'].includes(matches[0]!.promotable_user_type) || full && matches[0]!.promotable_user_type !== 'FULL') throw new AdportError('INVALID_INPUT', full ? 'x: this workflow requires a current FULL promotable author; RETWEETS_ONLY creates a different native post and needs its own receipt workflow' : 'x: post author is not an unambiguous current promotable user in this account');\n return matches[0]!;\n }\n private paging(ids: string[], next: string | null | undefined, previous?: string) {\n if (new Set(ids).size !== ids.length || next && next === previous) throw new AdportError('PROVIDER_ERROR', 'x: post pagination repeated an ID or cursor');\n return { truncated: next !== null, ...(next ? { next_cursor: next } : {}), ...(next === undefined ? { notes: ['Native continuation marker is missing; completeness is unconfirmed.'] } : {}) };\n }\n private async postPage(account: string, user: string, params: XParams) {\n const result = await this.entities.client.request('GET', `${this.base(account)}/tweets`, pageSchema(nativePost), { tweet_type: 'PUBLISHED', user_id: user, trim_user: true, ...Object.fromEntries(Object.entries(params).filter(([, value]) => value !== undefined)) });\n if (result.data.some(post => post.user.id_str !== user)) throw new AdportError('PROVIDER_ERROR', 'x: published post author filter mismatch');\n this.paging(result.data.map(post => post.id_str), result.next_cursor, typeof params.cursor === 'string' ? params.cursor : undefined);\n return result;\n }\n private async exactPosts(account: string, user: string, ids: string[]) {\n await this.author(account, user);\n const found = new Map<string, NativePost>(), cursors = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.postPage(account, user, { tweet_ids: ids.join(','), timeline_type: 'ALL', include_mentions_and_replies: true, count: 200, ...(cursor ? { cursor } : {}) });\n for (const post of result.data) {\n if (!ids.includes(post.id_str) || found.has(post.id_str)) throw new AdportError('PROVIDER_ERROR', 'x: targeted post lookup returned duplicate or unrequested IDs');\n found.set(post.id_str, post);\n }\n if (result.next_cursor === null) {\n if (ids.some(id => !found.has(id))) throw new AdportError('INVALID_INPUT', 'x: not every requested published post was returned for this account/author; missing data does not prove global absence');\n return ids.map(id => found.get(id)!);\n }\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('PROVIDER_ERROR', 'x: targeted post lookup is incomplete; no mutation submitted');\n }\n async get(account: string, user: string, id: string) {\n const post = (await this.exactPosts(xId.parse(account), snowflake.parse(user), [snowflake.parse(id)]))[0]!;\n return { ...post, snapshot_hash: postSnapshot(account, post) };\n }\n private visual(post: NativePost): Creative['media'] {\n const media = post.extended_entities?.media ?? post.entities?.media ?? [];\n return media.flatMap<Creative['media'][number]>(item => {\n const poster = safeUrl(item.media_url_https, true);\n if (item.type === 'photo') return poster ? [{ type: 'image' as const, url: poster }] : [];\n const video = item.video_info?.variants.filter(variant => variant.content_type === 'video/mp4' && safeUrl(variant.url, true)).sort((a, b) => (b.bitrate ?? 0) - (a.bitrate ?? 0))[0];\n return video ? [{ type: 'video' as const, url: video.url, ...(poster ? { poster_url: poster } : {}) }] : poster ? [{ type: 'image' as const, url: poster, alt: 'Video poster' }] : [];\n });\n }\n private creative(account: string, post: NativePost, canRename = true): Creative {\n return { id: post.id_str, provider: 'x', account_id: account, name: post.name ?? `Post ${post.id_str}`, type: post.nullcast ? 'PROMOTED_ONLY_POST' : 'ORGANIC_POST', status: 'PUBLISHED', headlines: [], descriptions: [post.full_text], landing_urls: (post.entities?.urls ?? []).flatMap(value => { const url = safeUrl(value.expanded_url);return url ? [url] : []; }), media: this.visual(post), actions: canRename ? [{ label: 'Rename post', tool: 'x_rename_published_post', arguments: { account_id: account, user_id: post.user.id_str, tweet_id: post.id_str, expected_snapshot_hash: postSnapshot(account, post) }, fields: [{ key: 'name', label: 'Post name', type: 'text', value: post.name ?? '', max_length: 80 }] }] : [] };\n }\n async list(raw: z.input<typeof postList>) {\n const input = postList.parse(raw), author = await this.author(input.account_id, input.user_id);\n const { account_id, user_id, ...params } = input;\n const result = await this.postPage(account_id, user_id, params);\n if (result.data.some(post => input.timeline_type !== 'ALL' && post.nullcast !== (input.timeline_type === 'NULLCAST'))) throw new AdportError('PROVIDER_ERROR', 'x: published timeline filter mismatch');\n return { items: result.data.map(post => ({ ...post, snapshot_hash: postSnapshot(account_id, post) })), creatives: result.data.map(post => this.creative(account_id, post, author.promotable_user_type === 'FULL')), ...this.paging(result.data.map(post => post.id_str), result.next_cursor, input.cursor), warnings: ['PUBLISHED describes post publication, not an ad association or delivery. Published copy is not editable through the native name route.'] };\n }\n async creationContext(account: string, raw: z.input<typeof postFields>) {\n const input = postFields.parse(raw), actor = await this.creatives.verifyComposer(account, input.as_user_id), sources = await this.creatives.verifyAttachments(account, input.media_keys ?? [], input.card_uri);\n if (Object.keys(input).some(key => key.startsWith('video_')) && !(sources.media.length === 1 && sources.media[0]!.media_type === 'VIDEO')) throw new AdportError('INVALID_INPUT', 'x: video metadata requires one ready native VIDEO attachment');\n const context = { account_id: account, request: input, actor, sources: { media: sources.media.map(sourceConfig), cards: sources.cards.map(sourceConfig) } };\n return { ...context, context_hash: hash(context), notes: ['Creates a distinct promoted-only published post, not an unpublished draft. Existing drafts are retained. It is not placed on the public timeline or served to followers by the nullcast endpoint, but remains published content usable by ads.', notice] };\n }\n async parents(account: string, lineId: string) {\n await this.entities.getAccount(account);\n const line = await this.entities.getLineItem(account, lineId), campaign = await this.entities.getCampaign(account, line.campaign_id);\n const lineConfig = Object.fromEntries(Object.entries(line).filter(([key]) => !['created_at', 'updated_at', 'approval_status', 'reasons_not_servable', 'servable'].includes(key)));\n return { line, campaign, snapshot: { line: lineConfig, campaign } };\n }\n private scopedPromotion(account: string, row: Promotion, line?: string) {\n if (row.account_id !== undefined && row.account_id !== account || line && row.line_item_id !== line) throw new AdportError('PROVIDER_ERROR', 'x: promoted-post account/line-item mismatch');\n return row;\n }\n private async promotionPage(account: string, line: string, params: XParams) {\n const result = await this.entities.client.request('GET', `${this.base(account)}/promoted_tweets`, pageSchema(nativePromotion), { line_item_ids: line, ...params });\n result.data.forEach(row => this.scopedPromotion(account, row, line));\n this.paging(result.data.map(row => row.id), result.next_cursor, typeof params.cursor === 'string' ? params.cursor : undefined);return result;\n }\n private async existing(account: string, line: string) {\n const rows: Promotion[] = [], cursors = new Set<string>(), ids = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.promotionPage(account, line, { count: 200, with_deleted: false, ...(cursor ? { cursor } : {}) });\n for (const row of result.data) { if (row.deleted || ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: active promotion scan contains deleted/duplicate rows');ids.add(row.id);rows.push(row); }\n if (result.next_cursor === null) return rows;\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('PROVIDER_ERROR', 'x: promotion scan is incomplete; no mutation submitted');\n }\n private promotionHash(account: string, row: Promotion, parents: unknown) { return hash({ account_id: account, promotion: row, parents }); }\n async getPromotion(account: string, id: string) {\n await this.entities.getAccount(account);\n const row = this.scopedPromotion(account, (await this.entities.client.request('GET', `${this.base(account)}/promoted_tweets/${xId.parse(id)}`, z.object({ data: nativePromotion }), { with_deleted: true })).data);\n if (row.id !== id) throw new AdportError('PROVIDER_ERROR', 'x: promoted-post ID mismatch');\n const parents = await this.parents(account, row.line_item_id);\n return { ...row, context_hash: this.promotionHash(account, row, parents.snapshot), parent: parents.snapshot };\n }\n async promotionContext(account: string, raw: z.input<typeof promotionSelection>) {\n const input = promotionSelection.parse(raw);await this.author(account, input.user_id, true);\n const parents = await this.parents(account, input.line_item_id);\n if (parents.line.deleted || parents.campaign.deleted || !['ACTIVE', 'PAUSED'].includes(parents.line.entity_status) || !['ACTIVE', 'PAUSED'].includes(parents.campaign.entity_status) || !['PROMOTED_TWEETS', 'PROMOTED_ACCOUNT'].includes(parents.line.product_type)) throw new AdportError('INVALID_INPUT', 'x: promotions require an existing supported non-draft campaign/ad group');\n const posts = await this.exactPosts(account, input.user_id, input.tweet_ids);\n if (posts.some(post => post.truncated)) throw new AdportError('INVALID_INPUT', 'x: source copy is truncated; read complete post content before promotion');\n const existing = (await this.existing(account, input.line_item_id)).filter(row => input.tweet_ids.includes(row.tweet_id));\n const context = { account_id: account, request: input, parent: parents.snapshot, posts, existing };\n return { ...context, context_hash: hash(context), notes: ['New native associations are ACTIVE; there is no PUT status. Under paused_creation the ad group itself must be PAUSED. The native API has no atomic compare-and-set, so snapshots do not lock concurrent account changes.', 'RETWEETS_ONLY copy promotion and scheduled associations are separate workflows.', notice] };\n }\n private async repostAuthors(account: string, source: string) {\n const users = await this.creatives.users(account, true), sources = users.filter(row => row.user_id === source && !row.deleted), receiving = users.filter(row => row.promotable_user_type === 'FULL' && !row.deleted);\n if (sources.length !== 1 || sources[0]!.promotable_user_type !== 'RETWEETS_ONLY' || receiving.length !== 1 || receiving[0]!.user_id === source) throw new AdportError('INVALID_INPUT', 'x: repost promotion needs one current RETWEETS_ONLY source author and one unambiguous FULL receiving author; use ordinary promotion for FULL sources');\n return { source_author: sourceConfig(sources[0]!), receiving_author: sourceConfig(receiving[0]!) };\n }\n private async repostState(account: string, input: z.infer<typeof promotionSelection>) {\n const authors = await this.repostAuthors(account, input.user_id);\n const parent = await this.parents(account, input.line_item_id);\n if (parent.line.deleted || parent.campaign.deleted || !['ACTIVE', 'PAUSED'].includes(parent.line.entity_status) || !['ACTIVE', 'PAUSED'].includes(parent.campaign.entity_status) || !['PROMOTED_TWEETS', 'PROMOTED_ACCOUNT'].includes(parent.line.product_type)) throw new AdportError('INVALID_INPUT', 'x: repost promotion requires supported existing non-draft parents');\n const posts = await this.exactPosts(account, input.user_id, input.tweet_ids);\n if (posts.some(post => post.truncated)) throw new AdportError('INVALID_INPUT', 'x: repost source copy is truncated; read complete content before promotion');\n const existing = (await this.existing(account, input.line_item_id)).sort((a, b) => a.id.localeCompare(b.id));\n return { account_id: account, request: input, ...authors, parent: parent.snapshot, posts, existing };\n }\n async repostContext(account: string, raw: z.input<typeof promotionSelection>) {\n const input = promotionSelection.parse(raw), context = await this.repostState(xId.parse(account), input);\n return { ...context, context_hash: hash(context), creatives: context.posts.map(post => this.creative(account, post, false)), truncated: false, notes: ['Each selected original produces a new PUBLISHED nullcast repost plus a native ACTIVE association. This is not an unpublished draft or organic timeline publication.', 'Existing reposts have different post IDs. Source-ID deduplication is not established by the native association inventory; approval explicitly permits new copies, including additional copies of previously promoted sources.', 'The tool correlates one approved source with one native POST receipt. Batches use at most four concurrent requests and can stop partially; no native write is retried. Independently observed copy metadata does not certify source-content or attachment rendering equivalence.', 'paused_creation requires a currently PAUSED ad group. No parent status or budget is changed; snapshots do not lock native concurrent changes.', notice] };\n }\n async promotions(raw: z.input<typeof promotionList>) {\n const input = promotionList.parse(raw), parents = await this.parents(input.account_id, input.line_item_id);\n if (input.user_id) await this.author(input.account_id, input.user_id);\n const result = await this.promotionPage(input.account_id, input.line_item_id, { count: input.count, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}) });\n if (!input.with_deleted && result.data.some(row => row.deleted)) throw new AdportError('PROVIDER_ERROR', 'x: native promotion deletion filter mismatch');\n const posts = new Map<string, NativePost>(), warnings: string[] = ['Native ACTIVE is association state, not proof of delivery. Removing an association retains its published post.'];\n if (input.user_id && result.data.length) {\n const wanted = [...new Set(result.data.map(row => row.tweet_id))].slice(0, 100);\n try { (await this.exactPosts(input.account_id, input.user_id, wanted)).forEach(post => posts.set(post.id_str, post)); }\n catch { warnings.push('Published content was not verified for the selected author; native association references remain visible.'); }\n if (new Set(result.data.map(row => row.tweet_id)).size > 100) warnings.push('Content hydration is limited to100 distinct posts per page.');\n }\n const creatives: Creative[] = result.data.map(row => {\n const post = posts.get(row.tweet_id), visual = post ? this.creative(input.account_id, post) : undefined;\n return { ...(visual ?? { provider: 'x', account_id: input.account_id, headlines: [], descriptions: [], landing_urls: [], media: [] }), id: row.id, name: post?.name ?? `Promoted post ${row.tweet_id}`, type: 'PROMOTED_POST_ASSOCIATION', status: row.deleted ? 'DISASSOCIATED' : row.entity_status, campaign_id: parents.campaign.id, ad_group_id: row.line_item_id, actions: row.deleted ? [] : [{ label: 'Remove from ad group', tool: 'x_delete_promoted_post', arguments: { account_id: input.account_id, promoted_tweet_id: row.id, expected_context_hash: this.promotionHash(input.account_id, row, parents.snapshot) }, fields: [] }] };\n });\n return { items: result.data.map(row => ({ ...row, context_hash: this.promotionHash(input.account_id, row, parents.snapshot) })), parent: parents.snapshot, creatives, warnings, ...this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor) };\n }\n private unconfirmed(error: unknown, known: string[]): never {\n const previous = error instanceof AdportError && error.details && typeof error.details === 'object' && 'resource_ids' in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((value): value is string => typeof value === 'string') : [];\n throw new AdportError('PROVIDER_ERROR', 'x: post/promotion outcome was not confirmed. Reconcile known IDs and current inventory before another mutation; no write was retried.', { resource_ids: [...new Set([...known, ...previous])] });\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const account = xId.parse(op.accountId), create = ['x_create_promoted_only_post', 'x_create_promoted_posts', 'x_create_repost_promotions'].includes(op.tool), remove = op.tool === 'x_delete_promoted_post';\n if (op.provider !== 'x' || op.kind !== (create ? 'create' : remove ? 'remove' : 'update')) throw new AdportError('INVALID_INPUT', 'x: post operation provider/kind mismatch');\n const review = (title: string, fields: ReviewField[], notices: string[]): Omit<Plan, 'execute'> => ({ summary: title, changes: fields.map(field => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notices, review: { provider: 'x', accountId: account, kind: op.kind, title, fields, notices } });\n if (op.tool === 'x_create_repost_promotions') {\n const { expected_context_hash, acknowledge_active_associations: _active, acknowledge_new_published_copies: _copies, ...input } = createRepostPromotions.parse(op.payload), context = await this.repostContext(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: repost source/author/parent/association context changed; read and preview again');\n if (guard.forcePausedCreation && context.parent.line.entity_status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'x: native repost associations are ACTIVE; paused_creation requires a currently PAUSED ad group');\n const receivingUser = snowflake.parse(context.receiving_author.user_id), baselineIds = new Set(context.existing.map(row => row.id)), baselineTweets = new Set(context.existing.map(row => row.tweet_id));\n const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap(entity => ['daily_budget_amount_local_micro', 'total_budget_amount_local_micro'].flatMap(key => { const value = entity[key as keyof typeof entity];return typeof value === 'number' ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : []; }));\n const fields: ReviewField[] = [{ label: 'Source author', after: input.user_id }, { label: 'Receiving author', after: receivingUser }, { label: 'Ad group', after: input.line_item_id }, { label: 'Ad-group status', after: context.parent.line.entity_status }, { label: 'Campaign status', after: context.parent.campaign.entity_status }, { label: 'New publication', after: `${input.tweet_ids.length} promoted-only repost(s)` }, { label: 'Association state', after: 'ACTIVE' }, ...context.posts.map(post => ({ label: `Source post ${post.id_str}`, after: post.full_text }))];\n return { ...review('Create promoted repost copies', fields, context.notes), budgetDeltas, execute: async () => {\n type Mapping = { source_tweet_id: string; copied_tweet_id: string; promoted_tweet_id: string };\n const mappings = new Map<string, Mapping>(), knownIds = new Set<string>(), knownCopies = new Set<string>(), attempted = new Set<string>(), ambiguous = new Set<string>(), failures: string[] = [];\n const receiptSources = new Map<string, Set<string>>();\n let next = 0, stopped = false;\n const record = (kind: 'association' | 'post', id: string, source: string) => {\n const key = `${kind}:${id}`, sources = receiptSources.get(key) ?? new Set<string>();sources.add(source);receiptSources.set(key, sources);\n if (sources.size > 1) { stopped = true;for (const value of sources) { ambiguous.add(value);mappings.delete(value); } }\n };\n const worker = async () => {\n while (!stopped && next < input.tweet_ids.length) {\n const source = input.tweet_ids[next++]!;\n try {\n const parent = await this.parents(account, input.line_item_id), authors = await this.repostAuthors(account, input.user_id), observedSource = (await this.exactPosts(account, input.user_id, [source]))[0]!;\n if (!equal(parent.snapshot, context.parent) || !equal(authors.source_author, context.source_author) || !equal(authors.receiving_author, context.receiving_author) || !equal(observedSource, context.posts.find(row => row.id_str === source))) throw new AdportError('PENDING_MISMATCH', 'x: repost preflight changed before the next native request');\n if (stopped) break;\n attempted.add(source);\n // One original per native request gives an explicit request/receipt mapping.\n const body = await this.entities.client.request('POST', `${this.base(account)}/promoted_tweets`, z.object({ data: z.unknown() }), { line_item_id: input.line_item_id, tweet_ids: source });\n const raw = Array.isArray(body.data) ? body.data : [body.data];\n for (const item of raw) if (item && typeof item === 'object') {\n const row = item as Record<string, unknown>, id = xId.safeParse(row.id), copy = snowflake.safeParse(row.tweet_id);if (id.success) { knownIds.add(id.data);record('association', id.data, source); }if (copy.success) { knownCopies.add(copy.data);record('post', copy.data, source); }\n }\n const rows = z.array(nativePromotion.extend({ tweet_id: snowflake })).length(1).parse(body.data), row = rows[0]!;\n if (ambiguous.has(source) || row.line_item_id !== input.line_item_id || row.deleted || row.entity_status !== 'ACTIVE' || row.account_id !== undefined && row.account_id !== account || input.tweet_ids.includes(row.tweet_id) || baselineIds.has(row.id) || baselineTweets.has(row.tweet_id)) throw new Error('repost receipt scope/state/mapping mismatch');\n const association = await this.getPromotion(account, row.id);\n if (!equal(nativePromotion.parse(association), row) || !equal(association.parent, context.parent)) throw new Error('repost association readback mismatch');\n const copy = (await this.exactPosts(account, receivingUser, [row.tweet_id]))[0]!;\n if (!copy.nullcast || copy.truncated) throw new Error('copied publication metadata mismatch');\n // Check uniqueness again after awaits, before accepting this concurrent result.\n if (ambiguous.has(source)) throw new Error('duplicate repost mapping');\n mappings.set(source, { source_tweet_id: source, copied_tweet_id: row.tweet_id, promoted_tweet_id: row.id });\n } catch (error) {\n stopped = true;failures.push(source);\n if (error instanceof AdportError && error.details && typeof error.details === 'object' && 'resource_ids' in error.details && Array.isArray(error.details.resource_ids)) for (const id of error.details.resource_ids) if (typeof id === 'string' && xId.safeParse(id).success) { knownIds.add(id);record('association', id, source); }\n if (error instanceof AdportError && error.details && typeof error.details === 'object' && 'reported_tweet_ids' in error.details && Array.isArray(error.details.reported_tweet_ids)) for (const id of error.details.reported_tweet_ids) if (typeof id === 'string' && snowflake.safeParse(id).success) { knownCopies.add(id);record('post', id, source); }\n }\n }\n };\n await Promise.all(Array.from({ length: Math.min(4, input.tweet_ids.length) }, worker));\n const confirmed = input.tweet_ids.flatMap(id => mappings.has(id) ? [mappings.get(id)!] : []);\n if (failures.length || confirmed.length !== input.tweet_ids.length) throw new AdportError('PROVIDER_ERROR', 'x: repost promotion was not fully confirmed. Reconcile the confirmed mappings and reported IDs before another preview; no request was retried and no rollback was attempted.', { resource_ids: [...knownIds], reported_tweet_ids: [...knownCopies], confirmed_source_copy_mappings: confirmed, ambiguous_source_ids: input.tweet_ids.filter(id => ambiguous.has(id)), source_outcomes: input.tweet_ids.filter(id => !mappings.has(id)).map(id => ({ source_tweet_id: id, state: attempted.has(id) ? 'UNCONFIRMED' : 'NOT_STARTED' })), unattempted_source_ids: input.tweet_ids.filter(id => !attempted.has(id)) });\n return { applied: true, resourceIds: confirmed.map(row => row.promoted_tweet_id), details: { source_copy_mappings: confirmed, mapping_basis: 'ONE_SOURCE_PER_NATIVE_REQUEST', copied_post_metadata_verified: true, source_copy_content_equivalence_verified: false, parent_status_or_budget_changed: false, next_tool: 'x_promoted_posts', next_arguments: { account_id: account, line_item_id: input.line_item_id, user_id: receivingUser } }, warnings: ['Mapping follows the documented native copy-promotion request and independently observed association/copy metadata. Source-content and attachment rendering equivalence was not certified; inspect the copied posts before delivery.'] };\n } };\n }\n if (op.tool === 'x_create_promoted_only_post') {\n const { expected_context_hash, confirm_publication: _confirm, ...input } = createPost.parse(op.payload), context = await this.creationContext(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('INVALID_INPUT', 'x: publication source context changed; read and preview it again');\n const params: XParams = { ...Object.fromEntries(Object.entries(input).filter(([key, value]) => key !== 'media_keys' && value !== undefined)), ...(input.media_keys ? { media_keys: input.media_keys.join(',') } : {}), nullcast: true, trim_user: true, tweet_mode: 'extended' };\n return { ...review('Create promoted-only post', [{ label: 'Author', after: input.as_user_id }, { label: 'Text', after: input.text ?? '(media only)' }, { label: 'Name', after: input.name ?? '(unnamed)' }, { label: 'Media', after: input.media_keys ?? [] }, { label: 'Card', after: input.card_uri ?? '(none)' }, { label: 'Replies', after: input.conversation_settings }, ...Object.entries(input).filter(([key]) => key.startsWith('video_')).map(([key, value]) => ({ label: key, after: value })), { label: 'Publication', after: 'PUBLISHED · promoted-only · no ad association' }], context.notes), execute: async () => {\n let known: string | undefined;\n try {\n const receipt = (await this.entities.client.request('POST', `${this.base(account)}/tweet`, z.object({ data: z.object({ id_str: snowflake, user: z.object({ id_str: snowflake }) }) }), params)).data;known = receipt.id_str;\n if (receipt.user.id_str !== input.as_user_id) throw new Error('author mismatch');\n const observed = (await this.exactPosts(account, input.as_user_id, [known]))[0]!;\n if (!observed.nullcast || observed.truncated || observed.conversation_settings !== input.conversation_settings || input.name !== undefined && observed.name !== input.name) throw new Error('publication readback mismatch');\n const textVerified = input.text === undefined || observed.full_text === input.text;\n return { applied: true, resourceIds: [known], details: { publication_confirmed: true, nullcast: true, ad_association_created: false, requested_text_exactly_observed: input.text === undefined ? null : textVerified, attachment_readback_verified: input.media_keys?.length || input.card_uri ? false : null }, warnings: [...(!textVerified ? ['Native published text differs from the submitted text, for example through URL rewriting. Inspect the exact post before promotion; requested text equivalence was not certified.'] : []), ...(input.media_keys?.length || input.card_uri ? ['Source ownership/readiness was checked; published attachment rendering was not independently certified. Inspect the published post before promotion.'] : [])] };\n } catch (error) { return this.unconfirmed(error, known ? [known] : []); }\n } };\n }\n if (op.tool === 'x_rename_published_post') {\n const input = renamePost.parse(op.payload);await this.author(account, input.user_id, true);\n const current = (await this.exactPosts(account, input.user_id, [input.tweet_id]))[0]!;\n if (postSnapshot(account, current) !== input.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'x: published post snapshot changed; read and preview it again');\n const expected = { ...current, name: input.name };\n return { ...review('Rename published post', [{ label: 'Post', after: current.id_str }, { label: 'Name', before: current.name, after: input.name }], ['Changes the advertiser label only. Published copy, attachments and ad associations remain separate.', notice]), execute: async () => {\n const known = [current.id_str];\n try {\n const receipt = (await this.entities.client.request('PUT', `${this.base(account)}/tweets/${current.id_str}/name`, z.object({ data: nativePost }), { name: input.name })).data;\n known.push(receipt.id_str);\n if (!equal(postContent(receipt), expected) || !equal(postContent((await this.exactPosts(account, input.user_id, [current.id_str]))[0]!), expected)) throw new Error('name preservation mismatch');\n return [current.id_str];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n if (op.tool === 'x_create_promoted_posts') {\n const { expected_context_hash, acknowledge_active_associations: _ack, ...input } = createPromotions.parse(op.payload), context = await this.promotionContext(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('INVALID_INPUT', 'x: promotion context changed; read and preview it again');\n if (context.existing.length) throw new AdportError('INVALID_INPUT', 'x: selected post already has a live association in this ad group; do not replay promotion');\n if (guard.forcePausedCreation && context.parent.line.entity_status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'x: native associations are ACTIVE; paused_creation requires a currently PAUSED ad group');\n const fields: ReviewField[] = [{ label: 'Ad group', after: context.parent.line.name ?? input.line_item_id }, { label: 'Campaign', after: context.parent.campaign.name }, { label: 'Ad-group status', after: context.parent.line.entity_status }, { label: 'Campaign status', after: context.parent.campaign.entity_status }, { label: 'Native association status', after: 'ACTIVE' }, ...context.posts.map(post => ({ label: `Post ${post.id_str}`, after: post.full_text }))];\n const base = review('Associate published posts with ad group', fields, [...context.notes, 'An ACTIVE association can serve when its parents permit delivery. No campaign/ad-group status is changed. DELETE disassociates; there is no per-association PUT pause.']);\n const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap(entity => ['daily_budget_amount_local_micro', 'total_budget_amount_local_micro'].flatMap(key => { const value = entity[key as keyof typeof entity];return typeof value === 'number' ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : []; }));\n return { ...base, budgetDeltas, execute: async () => {\n let known: string[] = [];\n try {\n const rows = (await this.entities.client.request('POST', `${this.base(account)}/promoted_tweets`, z.object({ data: z.array(nativePromotion).min(1).max(50) }), { line_item_id: input.line_item_id, tweet_ids: input.tweet_ids.join(',') })).data;known = rows.map(row => row.id);\n if (rows.length !== input.tweet_ids.length || new Set(known).size !== rows.length || new Set(rows.map(row => row.tweet_id)).size !== rows.length || rows.some(row => row.deleted || row.entity_status !== 'ACTIVE' || row.line_item_id !== input.line_item_id || !input.tweet_ids.includes(row.tweet_id) || row.account_id !== undefined && row.account_id !== account)) throw new Error('association receipt mismatch');\n for (const row of rows) { const observed = await this.getPromotion(account, row.id);if (!equal({ id: observed.id, line_item_id: observed.line_item_id, tweet_id: observed.tweet_id, entity_status: observed.entity_status, deleted: observed.deleted }, { id: row.id, line_item_id: row.line_item_id, tweet_id: row.tweet_id, entity_status: row.entity_status, deleted: row.deleted }) || !equal(observed.parent, context.parent)) throw new Error('association readback mismatch'); }\n return known;\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n if (op.tool !== 'x_delete_promoted_post') throw new AdportError('INVALID_INPUT', 'x: unsupported post operation');\n const input = deletePromotion.parse(op.payload), current = await this.getPromotion(account, input.promoted_tweet_id);\n if (current.context_hash !== input.expected_context_hash || current.deleted) throw new AdportError('INVALID_INPUT', 'x: promotion context changed or is already deleted; read and preview it again');\n return { ...review('Remove post from ad group', [{ label: 'Association', after: current.id }, { label: 'Published post', after: current.tweet_id }, { label: 'Ad group', after: current.line_item_id }, { label: 'Deleted', before: false, after: true }], ['Disassociates this one ad. The published post, media and other associations remain. Native entity_status may remain ACTIVE on the deleted tombstone; this is not post deletion or a PUT pause.', notice]), execute: async () => {\n const known = [current.id];\n try {\n const receipt = (await this.entities.client.request('DELETE', `${this.base(account)}/promoted_tweets/${current.id}`, z.object({ data: nativePromotion }))).data;known.push(receipt.id);this.scopedPromotion(account, receipt, current.line_item_id);\n const matches = (row: Promotion) => row.id === current.id && row.tweet_id === current.tweet_id && row.line_item_id === current.line_item_id && row.deleted;\n if (!matches(receipt) || !matches(await this.getPromotion(account, current.id))) throw new Error('disassociation readback mismatch');\n return [current.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n}\n","import { z } from 'zod';\nimport { cardUri, mediaKey, snowflake } from './creative-tools.js';\nimport { xId } from './schemas.js';\n\nconst unique = (values: string[]) => new Set(values).size === values.length;\nexport const postHash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const postFields = z.object({\n as_user_id: snowflake,\n text: z.string().max(10_000).optional().describe('X validates native weighted length/content at apply.'),\n name: z.string().min(1).max(80).optional(),\n media_keys: z.array(mediaKey).min(1).max(4).refine(unique, 'Use unique media keys').optional(),\n card_uri: cardUri.optional(),\n conversation_settings: z.enum(['EVERYONE', 'FOLLOWING', 'MENTIONED_USERS']).default('EVERYONE'),\n video_cta: z.enum(['VISIT_SITE', 'WATCH_NOW']).optional(),\n video_cta_value: z.url().refine(value => { const url = new URL(value);return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) URL without credentials').optional(),\n video_title: z.string().max(70).optional(),\n video_description: z.string().max(200).optional(),\n}).strict().refine(value => Boolean(value.text?.trim() || value.media_keys?.length), 'Provide text or media')\n .refine(value => (value.video_cta !== undefined) === (value.video_cta_value !== undefined), 'Provide video_cta and video_cta_value together');\nexport const createPost = postFields.safeExtend({ expected_context_hash: postHash, confirm_publication: z.literal(true) });\nexport const renamePost = z.object({ user_id: snowflake, tweet_id: snowflake, expected_snapshot_hash: postHash, name: z.string().min(1).max(80) }).strict();\nexport const postList = z.object({ account_id: xId, user_id: snowflake, timeline_type: z.enum(['NULLCAST', 'ORGANIC', 'ALL']).default('NULLCAST'), include_mentions_and_replies: z.boolean().default(false), name: z.string().min(1).max(80).optional(), count: z.number().int().min(1).max(200).default(20), cursor: z.string().min(1).max(4096).optional() }).strict();\nexport const postReference = z.object({ account_id: xId, user_id: snowflake, tweet_id: snowflake }).strict();\nexport const promotionSelection = z.object({ line_item_id: xId, user_id: snowflake, tweet_ids: z.array(snowflake).min(1).max(50).refine(unique, 'Use unique post IDs') }).strict();\nexport const createPromotions = promotionSelection.safeExtend({ expected_context_hash: postHash, acknowledge_active_associations: z.literal(true) });\nexport const createRepostPromotions = promotionSelection.safeExtend({ expected_context_hash: postHash, acknowledge_active_associations: z.literal(true), acknowledge_new_published_copies: z.literal(true) });\nexport const deletePromotion = z.object({ promoted_tweet_id: xId, expected_context_hash: postHash }).strict();\nexport const promotionList = z.object({ account_id: xId, line_item_id: xId, user_id: snowflake.optional(), count: z.number().int().min(1).max(200).default(20), cursor: z.string().min(1).max(4096).optional(), with_deleted: z.boolean().default(false) }).strict();\n\nconst urlEntity = z.object({ url: z.string(), expanded_url: z.string().optional(), display_url: z.string().optional(), indices: z.array(z.number().int().nonnegative()).length(2).optional() });\nconst mediaEntity = z.object({ id_str: snowflake, type: z.string(), media_key: mediaKey.optional(), media_url_https: z.string().optional(), url: z.string().optional(), expanded_url: z.string().optional(), video_info: z.object({ variants: z.array(z.object({ content_type: z.string(), url: z.string(), bitrate: z.number().nonnegative().optional() })).max(100) }).optional() });\nexport const nativePost = z.object({\n id_str: snowflake, user: z.object({ id_str: snowflake }), name: z.string().nullable(),\n full_text: z.string(), nullcast: z.boolean(), tweet_type: z.literal('PUBLISHED'),\n conversation_settings: z.string().optional(), truncated: z.boolean().optional(),\n entities: z.object({ urls: z.array(urlEntity).max(1000).optional(), media: z.array(mediaEntity).max(100).optional() }).optional(),\n extended_entities: z.object({ media: z.array(mediaEntity).max(100) }).optional(),\n});\nexport type NativePost = z.infer<typeof nativePost>;\nexport const postWrites = new Set(['x_create_promoted_only_post', 'x_rename_published_post', 'x_create_promoted_posts', 'x_create_repost_promotions', 'x_delete_promoted_post']);\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type ReviewField, type WriteGuard, type WriteOperation, type WritePreview, type WriteResult } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport type { XCreativeService } from './creatives.js';\nimport type { XAdsEntities } from './entities.js';\nimport type { XPostService } from './posts.js';\nimport { xId } from './schemas.js';\nimport { snowflake } from './creative-tools.js';\nimport { createScheduled, createScheduledPromotion, deleteScheduled, deleteScheduledPromotion, nativeScheduled, nativeScheduledPromotion, scheduledFields, scheduledList, scheduledPromotionList, scheduledPromotionSelection, updateScheduled, type ScheduledPost, type ScheduledPromotion } from './scheduled-schemas.js';\n\ninterface Plan extends Omit<WritePreview, 'serverValidated'> { execute(): Promise<string[] | WriteResult> }\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => [k, canonical(v)])) : value;\nconst equal = (left: unknown, right: unknown) => JSON.stringify(canonical(left)) === JSON.stringify(canonical(right));\nconst hash = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst config = (post: ScheduledPost) => { const { completed_at: _completed, ...rest } = post;return { ...rest, scheduled_at: new Date(post.scheduled_at).toISOString() }; };\nconst sourceConfig = (row: Record<string, unknown>) => Object.fromEntries(Object.entries(row).filter(([key]) => !['created_at', 'updated_at', 'media_url', 'poster_media_url'].includes(key)));\nconst pageSchema = <T extends z.ZodType>(item: T) => z.object({ data: z.array(item).max(1000), next_cursor: z.string().min(1).max(4096).nullable().optional() });\nconst notices = ['X publishes this promoted-only post automatically at its scheduled time. No parent delivery setting is changed.', 'Previews are local plans, not native validation. Scheduling, publication, ad association and actual delivery are separate states. No write is retried automatically.'];\n\n/** Official xdevplatform/docs creatives a9226e10 and campaign-management570f918c, checked2026-11-06. */\nexport class XScheduledService {\n constructor(private readonly entities: XAdsEntities, private readonly creatives: XCreativeService, private readonly posts: XPostService) {}\n private base(account: string) { return `accounts/${xId.parse(account)}`; }\n private async author(account: string, user: string) {\n snowflake.parse(user);\n const matches = (await this.creatives.users(account)).filter(row => row.user_id === user && !row.deleted);\n if (matches.length !== 1 || !['FULL', 'RETWEETS_ONLY'].includes(matches[0]!.promotable_user_type)) throw new AdportError('INVALID_INPUT', 'x: schedule author must be an unambiguous current account-associated user');\n return matches[0]!;\n }\n private scoped(account: string, row: ScheduledPost, user?: string) {\n if (row.account_id !== undefined && row.account_id !== account || user !== undefined && row.user_id !== user) throw new AdportError('PROVIDER_ERROR', 'x: scheduled-post account/author mismatch');\n return row;\n }\n private paging(ids: string[], next: string | null | undefined, previous?: string) {\n if (new Set(ids).size !== ids.length || next && next === previous) throw new AdportError('PROVIDER_ERROR', 'x: scheduled pagination repeated an ID or cursor');\n return { truncated: next !== null, ...(next ? { next_cursor: next } : {}), ...(next === undefined ? { notes: ['Native continuation marker is missing; completeness is unconfirmed.'] } : {}) };\n }\n private async raw(account: string, id: string, user?: string) {\n const row = (await this.entities.client.request('GET', `${this.base(account)}/scheduled_tweets/${snowflake.parse(id)}`, z.object({ data: nativeScheduled }))).data;\n if (row.id !== id) throw new AdportError('PROVIDER_ERROR', 'x: scheduled-post ID mismatch');\n return this.scoped(account, row, user);\n }\n private async promotionPage(account: string, params: XParams, line?: string) {\n const result = await this.entities.client.request('GET', `${this.base(account)}/scheduled_promoted_tweets`, pageSchema(nativeScheduledPromotion), { ...params, ...(line ? { line_item_ids: line } : {}) });\n if (result.data.some(row => row.account_id !== undefined && row.account_id !== account || line && row.line_item_id !== line)) throw new AdportError('PROVIDER_ERROR', 'x: scheduled-ad account/parent mismatch');\n this.paging(result.data.map(row => row.id), result.next_cursor, typeof params.cursor === 'string' ? params.cursor : undefined);return result;\n }\n private async associations(account: string, scheduledId: string) {\n const rows: ScheduledPromotion[] = [], ids = new Set<string>(), cursors = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.promotionPage(account, { count: 200, with_deleted: false, ...(cursor ? { cursor } : {}) });\n for (const row of result.data) { if (row.deleted || ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: scheduled-ad inventory contains deleted/duplicate rows');ids.add(row.id);if (row.scheduled_tweet_id === scheduledId) rows.push(row); }\n if (result.next_cursor === null) return rows.sort((a, b) => a.id.localeCompare(b.id));\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('INVALID_INPUT', 'x: scheduled-ad inventory is incomplete; cannot prepare a safe mutation');\n }\n async get(account: string, user: string, id: string) {\n const author = await this.author(account, user), post = await this.raw(account, id, user), associations = await this.associations(account, id);\n return { ...post, associations, snapshot_hash: hash({ account, author: sourceConfig(author), post: config(post), associations }) };\n }\n private mutable(post: ScheduledPost) {\n if (post.scheduled_status !== 'SCHEDULED' || post.tweet_id !== null || post.completed_at || !post.nullcast || Date.parse(post.scheduled_at) <= Date.now()) throw new AdportError('INVALID_INPUT', 'x: this mutation requires a still-future promoted-only SCHEDULED post; inspect published posts/ads after publication');\n }\n private schedule(time: string) {\n const now = Date.now(), last = new Date(now);last.setUTCFullYear(last.getUTCFullYear() + 1);\n if (Date.parse(time) < now + 15 * 60_000 || Date.parse(time) > last.getTime()) throw new AdportError('INVALID_INPUT', 'x: choose a UTC minute at least15minutes and at most one calendar year ahead');\n }\n private async visualMedia(account: string, rows: ScheduledPost[], include: boolean) {\n const keys = include ? [...new Set(rows.flatMap(row => row.media_keys))] : [], values = new Map<string, Creative['media']>();\n // Bound fan-out independently of the native page size. Remaining copy is still shown.\n const pending = keys.slice(0, 40);let index = 0, failed = 0;\n await Promise.all(Array.from({ length: Math.min(4, pending.length) }, async () => { while (index < pending.length) { const key = pending[index++]!;try { const media = await this.creatives.media(account, key);if (!media.deleted) values.set(key, this.creatives.visual(media)); } catch { failed++; } } }));\n return { values, notes: [...(keys.length > 40 ? ['Media previews are limited to40unique library items per page. Use a smaller page for remaining previews.'] : []), ...(failed ? ['Some native media previews are unavailable; schedule copy and IDs are preserved.'] : [])] };\n }\n async list(value: z.input<typeof scheduledList>) {\n const input = scheduledList.parse(value);await this.author(input.account_id, input.user_id);\n const result = await this.entities.client.request('GET', `${this.base(input.account_id)}/scheduled_tweets`, pageSchema(nativeScheduled), { user_id: input.user_id, count: input.count, ...(input.cursor ? { cursor: input.cursor } : {}) });\n result.data.forEach(row => this.scoped(input.account_id, row, input.user_id));const page = this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor), media = await this.visualMedia(input.account_id, result.data, input.include_media);\n const creatives: Creative[] = result.data.map(row => ({ id: row.id, provider: 'x', account_id: input.account_id, name: row.name ?? `Scheduled post ${row.id}`, type: row.nullcast ? 'SCHEDULED_PROMOTED_ONLY_POST' : 'SCHEDULED_ORGANIC_POST', status: row.scheduled_status, headlines: [], descriptions: [row.text, `Scheduled: ${row.scheduled_at}`, ...(row.tweet_id ? [`Published post: ${row.tweet_id}`] : [])], landing_urls: [], media: row.media_keys.flatMap(key => media.values.get(key) ?? []), actions: [] }));\n return { account_id: input.account_id, items: result.data, creatives, ...page, notes: [...(page.notes ?? []), ...media.notes] };\n }\n async creationContext(account: string, value: z.input<typeof scheduledFields>) {\n const input = scheduledFields.parse(value);this.schedule(input.scheduled_at);const author = await this.author(account, input.as_user_id), actor = await this.creatives.verifyComposer(account, input.as_user_id), sources = await this.creatives.verifyAttachments(account, input.media_keys ?? [], input.card_uri);\n return { context_hash: hash({ account, input, author: sourceConfig(author), actor, media: sources.media.map(sourceConfig), cards: sources.cards.map(sourceConfig) }), request: input, nullcast: true, ad_association_created: false, notes: notices };\n }\n async promotions(value: z.input<typeof scheduledPromotionList>) {\n const input = scheduledPromotionList.parse(value);await this.posts.parents(input.account_id, input.line_item_id);\n const result = await this.promotionPage(input.account_id, { count: input.count, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}) }, input.line_item_id);\n if (!input.with_deleted && result.data.some(row => row.deleted)) throw new AdportError('PROVIDER_ERROR', 'x: scheduled-ad filter returned deleted rows');\n return { account_id: input.account_id, line_item_id: input.line_item_id, items: result.data, records: result.data, ...this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor) };\n }\n async getPromotion(account: string, id: string) {\n const row = (await this.entities.client.request('GET', `${this.base(account)}/scheduled_promoted_tweets/${xId.parse(id)}`, z.object({ data: nativeScheduledPromotion }), { with_deleted: true })).data;\n if (row.id !== id || row.account_id !== undefined && row.account_id !== account) throw new AdportError('PROVIDER_ERROR', 'x: scheduled-ad ID/account mismatch');\n const parent = await this.posts.parents(account, row.line_item_id);\n // A deleted schedule is a hard404. Tombstone readback does not require its source.\n const source = row.deleted ? null : await this.raw(account, row.scheduled_tweet_id);\n if (source) await this.author(account, source.user_id);\n return { ...row, source, parent: parent.snapshot, context_hash: hash({ account, row, source: source ? config(source) : null, parent: parent.snapshot }) };\n }\n async promotionContext(account: string, value: z.input<typeof scheduledPromotionSelection>) {\n const input = scheduledPromotionSelection.parse(value), post = await this.get(account, input.user_id, input.scheduled_tweet_id);await this.creatives.verifyComposer(account, input.user_id);this.mutable(post);\n const parent = await this.posts.parents(account, input.line_item_id);\n if (parent.line.deleted || parent.campaign.deleted || !['ACTIVE', 'PAUSED'].includes(parent.line.entity_status) || !['ACTIVE', 'PAUSED'].includes(parent.campaign.entity_status) || !['PROMOTED_TWEETS', 'PROMOTED_ACCOUNT'].includes(parent.line.product_type)) throw new AdportError('INVALID_INPUT', 'x: scheduled promotion requires supported existing non-draft parents');\n const existing = post.associations.filter(row => row.line_item_id === input.line_item_id);\n return { context_hash: hash({ account, input, post, parent: parent.snapshot, existing }), post, parent: parent.snapshot, existing, notes: [...notices, 'Native scheduled associations have no status field or PUT pause. They can promote after publication when parent settings allow.'] };\n }\n private unconfirmed(error: unknown, ids: string[]): never {\n const details = error instanceof AdportError ? error.details as Record<string, unknown> | undefined : undefined;\n const known = Array.isArray(details?.resource_ids) ? details.resource_ids.filter((value): value is string => typeof value === 'string') : [];\n throw new AdportError('PROVIDER_ERROR', 'x: scheduled write outcome was not confirmed. Reconcile known IDs and current inventory; do not replay the mutation.', { resource_ids: [...new Set([...ids, ...known])] });\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const account = xId.parse(op.accountId), kind = op.tool.startsWith('x_create_') ? 'create' : op.tool.startsWith('x_delete_') ? 'remove' : 'update';\n if (op.provider !== 'x' || op.kind !== kind) throw new AdportError('INVALID_INPUT', 'x: scheduled operation provider/kind mismatch');\n const review = (title: string, fields: ReviewField[], notes = notices): Omit<Plan, 'execute'> => ({ summary: title, changes: fields.map(field => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: { provider: 'x', accountId: account, kind, title, fields, notices: notes } });\n if (op.tool === 'x_create_scheduled_post') {\n const { expected_context_hash, acknowledge_automatic_publication: _ack, ...input } = createScheduled.parse(op.payload), context = await this.creationContext(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('INVALID_INPUT', 'x: schedule source context changed; read and preview again');\n const wanted = { user_id: input.as_user_id, text: input.text ?? '', name: input.name ?? null, scheduled_at: input.scheduled_at, media_keys: input.media_keys ?? [], card_uri: input.card_uri ?? null, nullcast: true, scheduled_status: 'SCHEDULED', tweet_id: null };\n const params: XParams = { ...Object.fromEntries(Object.entries(input).filter(([key, v]) => key !== 'media_keys' && v !== undefined)), ...(input.media_keys?.length ? { media_keys: input.media_keys.join(',') } : {}), nullcast: true };\n return { ...review('Schedule promoted-only post', [{ label: 'Author', after: input.as_user_id }, { label: 'Publish automatically at', after: input.scheduled_at }, { label: 'Copy', after: wanted.text }, { label: 'Name', after: wanted.name }, { label: 'Media', after: wanted.media_keys }, { label: 'Card', after: wanted.card_uri }, { label: 'Publication', after: 'SCHEDULED · promoted-only · no ad association' }]), execute: async () => {\n const known: string[] = [];\n try {\n const row = (await this.entities.client.request('POST', `${this.base(account)}/scheduled_tweets`, z.object({ data: nativeScheduled }), params)).data;known.push(row.id);this.scoped(account, row, input.as_user_id);\n const observed = await this.raw(account, row.id, input.as_user_id);\n for (const value of [row, observed]) if (!Object.entries(wanted).every(([key, v]) => key === 'scheduled_at' ? Date.parse(value.scheduled_at) === Date.parse(String(v)) : equal(value[key as keyof ScheduledPost], v))) throw new Error('schedule receipt/readback mismatch');\n return { applied: true, resourceIds: known, details: { scheduled_status: 'SCHEDULED', nullcast: true, scheduled_at: observed.scheduled_at, published_tweet_id: null, ad_association_created: false } };\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n if (op.tool === 'x_update_scheduled_post' || op.tool === 'x_delete_scheduled_post') {\n const input = op.tool === 'x_update_scheduled_post' ? updateScheduled.parse(op.payload) : deleteScheduled.parse(op.payload), current = await this.get(account, input.user_id, input.scheduled_tweet_id);\n if (current.snapshot_hash !== input.expected_snapshot_hash) throw new AdportError('INVALID_INPUT', 'x: schedule snapshot changed; read and preview again');\n await this.creatives.verifyComposer(account, input.user_id);this.mutable(current);\n if (op.tool === 'x_delete_scheduled_post') {\n if (current.associations.length) throw new AdportError('INVALID_INPUT', 'x: remove live scheduled ad associations before deleting their source schedule');\n return { ...review('Permanently delete scheduled post', [{ label: 'Scheduled post', after: current.id }, { label: 'Copy', before: current.text, after: '(deleted)' }, { label: 'Automatic publication', before: current.scheduled_at, after: 'Cancelled' }], ['Hard deletion cannot be undone. The schedule must remain unpublished and have no live scheduled ad associations. Existing published posts/media are separate.', notices[1]!]), execute: async () => {\n const known = [current.id];\n try {\n const receipt = (await this.entities.client.request('DELETE', `${this.base(account)}/scheduled_tweets/${current.id}`, z.object({ data: nativeScheduled }))).data;\n known.push(receipt.id);\n if (!equal(config(receipt), { ...config(nativeScheduled.parse(current)), scheduled_status: 'DELETED' })) throw new Error('deletion receipt mismatch');\n try { await this.raw(account, current.id, input.user_id);throw new Error('deleted schedule still exists'); } catch (error) { if (!(error instanceof AdportError && (error.details as Record<string, unknown> | undefined)?.http_status === 404)) throw error; }\n return [current.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n const parsed = updateScheduled.parse(input), changed = Object.fromEntries(Object.entries(parsed).filter(([key, value]) => ['scheduled_at', 'text', 'name', 'media_keys', 'card_uri'].includes(key) && value !== undefined)), wanted = nativeScheduled.parse({ ...current, ...changed });\n if (equal(config(wanted), config(nativeScheduled.parse(current)))) throw new AdportError('INVALID_INPUT', 'x: no scheduled-post configuration changed');\n if (!wanted.text.trim() && !wanted.media_keys.length) throw new AdportError('INVALID_INPUT', 'x: scheduled post requires text or media');\n this.schedule(wanted.scheduled_at);await this.creatives.verifyAttachments(account, wanted.media_keys, wanted.card_uri);\n if (current.associations.length && parsed.acknowledge_shared_effects !== true) throw new AdportError('INVALID_INPUT', 'x: editing this schedule affects existing ad associations; acknowledge_shared_effects is required');\n const params: XParams = Object.fromEntries(Object.entries(changed).map(([key, value]) => [key, Array.isArray(value) ? value.join(',') : value === null ? '' : value]));\n return { ...review('Edit scheduled post', [...Object.entries(changed).map(([key, after]) => ({ label: key, before: current[key as keyof ScheduledPost], after })), { label: 'Affected ad associations', after: current.associations.map(row => ({ id: row.id, line_item_id: row.line_item_id })) }]), execute: async () => {\n const known = [current.id];\n try { const row = (await this.entities.client.request('PUT', `${this.base(account)}/scheduled_tweets/${current.id}`, z.object({ data: nativeScheduled }), params)).data;known.push(row.id);if (!equal(config(row), config(wanted)) || !equal(config(await this.raw(account, current.id, input.user_id)), config(wanted))) throw new Error('schedule edit preservation mismatch');return [current.id]; } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n if (op.tool === 'x_create_scheduled_promoted_post') {\n const { expected_context_hash, acknowledge_automatic_promotion: _ack, ...input } = createScheduledPromotion.parse(op.payload), context = await this.promotionContext(account, input);\n if (context.context_hash !== expected_context_hash || context.existing.length) throw new AdportError('INVALID_INPUT', 'x: scheduled promotion context changed or already associated; read again without replay');\n if (guard.forcePausedCreation && context.parent.line.entity_status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'x: paused_creation requires a currently PAUSED ad group for automatic scheduled promotion');\n const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap(entity => ['daily_budget_amount_local_micro', 'total_budget_amount_local_micro'].flatMap(key => { const amount = entity[key as keyof typeof entity];return typeof amount === 'number' ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: amount, toMicros: amount }] : []; }));\n return { ...review('Associate scheduled post with ad group', [{ label: 'Scheduled post', after: input.scheduled_tweet_id }, { label: 'Copy', after: context.post.text }, { label: 'Publication time', after: context.post.scheduled_at }, { label: 'Ad group', after: input.line_item_id }, { label: 'Ad-group status', after: context.parent.line.entity_status }, { label: 'Campaign status', after: context.parent.campaign.entity_status }, { label: 'Promotion', after: 'Automatic after publication when parents permit delivery' }], context.notes), budgetDeltas, execute: async () => {\n const known: string[] = [];\n try {\n const row = (await this.entities.client.request('POST', `${this.base(account)}/scheduled_promoted_tweets`, z.object({ data: nativeScheduledPromotion }), { line_item_id: input.line_item_id, scheduled_tweet_id: input.scheduled_tweet_id })).data;known.push(row.id);\n if (row.deleted || row.line_item_id !== input.line_item_id || row.scheduled_tweet_id !== input.scheduled_tweet_id || row.tweet_id !== null || row.account_id !== undefined && row.account_id !== account) throw new Error('scheduled-ad receipt mismatch');\n const observed = await this.getPromotion(account, row.id);if (!equal(nativeScheduledPromotion.parse(observed), row) || !equal(observed.parent, context.parent)) throw new Error('scheduled-ad readback mismatch');\n const source = await this.raw(account, input.scheduled_tweet_id, input.user_id);if (!equal(config(source), config(nativeScheduled.parse(context.post)))) throw new Error('scheduled source changed');this.mutable(source);return known;\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n if (op.tool !== 'x_delete_scheduled_promoted_post') throw new AdportError('INVALID_INPUT', 'x: unsupported scheduled operation');\n const input = deleteScheduledPromotion.parse(op.payload), current = await this.getPromotion(account, input.scheduled_promoted_tweet_id);\n if (current.context_hash !== input.expected_context_hash || current.deleted || current.tweet_id !== null) throw new AdportError('INVALID_INPUT', 'x: scheduled association changed, is deleted or already published; inspect current ads');\n const source = await this.raw(account, current.scheduled_tweet_id);await this.author(account, source.user_id);this.mutable(source);\n return { ...review('Remove scheduled post from ad group', [{ label: 'Association', after: current.id }, { label: 'Scheduled post', after: source.id }, { label: 'Ad group', after: current.line_item_id }, { label: 'Deleted', before: false, after: true }], ['Removes this one ad association before publication. The scheduled post still publishes automatically. It is not schedule cancellation or published-post deletion.', notices[1]!]), execute: async () => {\n const known = [current.id];\n try { const row = (await this.entities.client.request('DELETE', `${this.base(account)}/scheduled_promoted_tweets/${current.id}`, z.object({ data: nativeScheduledPromotion }))).data, wanted = { ...nativeScheduledPromotion.parse(current), deleted: true };known.push(row.id);if (!equal(row, wanted) || !equal(nativeScheduledPromotion.parse(await this.getPromotion(account, current.id)), wanted)) throw new Error('scheduled-ad removal mismatch');return [current.id]; } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n}\n","import { z } from 'zod';\nimport { cardUri, mediaKey, snowflake } from './creative-tools.js';\nimport { postHash } from './post-schemas.js';\nimport { xId } from './schemas.js';\n\nconst unique = (values: string[]) => new Set(values).size === values.length;\nconst mediaKeys = z.array(mediaKey).max(4).refine(unique, 'Use unique media keys');\n// X ignores seconds. Reject sub-minute input instead of silently changing approval.\nexport const scheduledTime = z.iso.datetime().regex(/T\\d{2}:\\d{2}:00Z$/, 'Use a UTC minute, ending in :00Z');\nexport const scheduledFields = z.object({\n as_user_id: snowflake, scheduled_at: scheduledTime,\n text: z.string().max(10_000).optional(), name: z.string().min(1).max(80).optional(),\n media_keys: mediaKeys.optional(), card_uri: cardUri.optional(),\n}).strict().refine(value => Boolean(value.text?.trim() || value.media_keys?.length), 'Provide text or media');\nexport const createScheduled = scheduledFields.safeExtend({ expected_context_hash: postHash, acknowledge_automatic_publication: z.literal(true) });\nexport const updateScheduled = z.object({\n user_id: snowflake, scheduled_tweet_id: snowflake, expected_snapshot_hash: postHash,\n scheduled_at: scheduledTime.optional(), text: z.string().max(10_000).optional(), name: z.string().max(80).optional(),\n media_keys: mediaKeys.optional(), card_uri: cardUri.nullable().optional(),\n acknowledge_automatic_publication: z.literal(true), acknowledge_shared_effects: z.boolean().optional(),\n}).strict().refine(value => ['scheduled_at', 'text', 'name', 'media_keys', 'card_uri'].some(key => value[key as keyof typeof value] !== undefined), 'Provide a changed field');\nexport const deleteScheduled = z.object({ user_id: snowflake, scheduled_tweet_id: snowflake, expected_snapshot_hash: postHash, acknowledge_permanent_deletion: z.literal(true) }).strict();\nexport const scheduledReference = z.object({ account_id: xId, user_id: snowflake, scheduled_tweet_id: snowflake }).strict();\nexport const scheduledList = z.object({ account_id: xId, user_id: snowflake, count: z.number().int().min(1).max(200).default(20), cursor: z.string().min(1).max(4096).optional(), include_media: z.boolean().default(true) }).strict();\nexport const nativeScheduled = z.object({\n id: snowflake, user_id: snowflake, account_id: xId.optional(), name: z.string().nullable(), text: z.string(),\n scheduled_status: z.string(), nullcast: z.boolean(), scheduled_at: z.iso.datetime(),\n card_uri: cardUri.nullable(), media_keys: mediaKeys, tweet_id: snowflake.nullable(),\n completed_at: z.iso.datetime().nullable().optional(),\n});\nexport type ScheduledPost = z.infer<typeof nativeScheduled>;\nexport const nativeScheduledPromotion = z.object({ id: xId, account_id: xId.optional(), line_item_id: xId, scheduled_tweet_id: snowflake, tweet_id: snowflake.nullable(), deleted: z.boolean() });\nexport type ScheduledPromotion = z.infer<typeof nativeScheduledPromotion>;\nexport const scheduledPromotionList = z.object({ account_id: xId, line_item_id: xId, count: z.number().int().min(1).max(200).default(20), cursor: z.string().min(1).max(4096).optional(), with_deleted: z.boolean().default(false) }).strict();\nexport const scheduledPromotionSelection = z.object({ user_id: snowflake, line_item_id: xId, scheduled_tweet_id: snowflake }).strict();\nexport const createScheduledPromotion = scheduledPromotionSelection.safeExtend({ expected_context_hash: postHash, acknowledge_automatic_promotion: z.literal(true) });\nexport const deleteScheduledPromotion = z.object({ scheduled_promoted_tweet_id: xId, expected_context_hash: postHash }).strict();\nexport const scheduledWrites = new Set(['x_create_scheduled_post', 'x_update_scheduled_post', 'x_delete_scheduled_post', 'x_create_scheduled_promoted_post', 'x_delete_scheduled_promoted_post']);\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type ReviewField, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport type { XAdsEntities } from './entities.js';\nimport type { XPostService } from './posts.js';\nimport { accountMediaList, accountMediaTypes, createDirectMedia, deleteDirectMedia, directMediaList, directMediaSelection, nativeAccountMedia, nativeDirectMedia } from './direct-media-schemas.js';\nimport { xId } from './schemas.js';\n\ntype Asset = z.infer<typeof nativeAccountMedia>;\ntype Association = z.infer<typeof nativeDirectMedia>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst pageSchema = <T extends z.ZodType>(item: T) => z.object({ data: z.array(item).max(1000), next_cursor: z.string().nullable().optional() });\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst hash = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst configuration = (value: Record<string, unknown>) => Object.fromEntries(Object.entries(value).filter(([key]) => !['created_at', 'updated_at', 'account_id', 'configuration_hash'].includes(key)));\nconst associationConfiguration = (row: Association) => ({ id: row.id, line_item_id: row.line_item_id, account_media_id: row.account_media_id, creative_type: row.creative_type, landing_url: row.landing_url ?? null, entity_status: row.entity_status, deleted: row.deleted });\nconst equal = (left: unknown, right: unknown) => hash(left) === hash(right);\nconst sourceType = (type: string) => type === 'PREROLL' ? 'video' : accountMediaTypes.includes(type as typeof accountMediaTypes[number]) && type !== 'VAST_PREROLL' ? 'image' : undefined;\nconst url = (value: unknown, media = false) => {\n if (typeof value !== 'string') return undefined;\n try { const parsed = new URL(value);return !parsed.username && !parsed.password && (media ? parsed.protocol === 'https:' && (!parsed.port || parsed.port === '443') && ['pbs.twimg.com', 'video.twimg.com', 'ton.twimg.com'].includes(parsed.hostname) : ['https:', 'http:'].includes(parsed.protocol)) ? value : undefined; } catch { return undefined; }\n};\nconst notice = 'Local preview is not native validation. Account Media assets, ad associations and actual delivery are separate. Native eligibility remains authoritative; no write is retried.';\n\n/** Official X v12 account_media/media_creatives contracts refreshed2026-11-06. */\nexport class XDirectMediaService {\n constructor(private readonly entities: XAdsEntities, private readonly posts: XPostService) {}\n private base(account: string) { return `accounts/${xId.parse(account)}`; }\n private scope<T extends { id: string; account_id?: string }>(account: string, row: T, id?: string) {\n if (row.account_id !== undefined && row.account_id !== account || id !== undefined && row.id !== id) throw new AdportError('PROVIDER_ERROR', 'x: direct-media account or resource ID mismatch');\n return row;\n }\n private paging(ids: string[], next: string | null | undefined, previous?: string) {\n if (new Set(ids).size !== ids.length || next && next === previous) throw new AdportError('PROVIDER_ERROR', 'x: direct-media pagination repeated an ID or cursor');\n return { truncated: next !== null, ...(next ? { next_cursor: next } : {}), ...(next === undefined || next === '' ? { notes: ['Native continuation marker is missing; completeness is unconfirmed.'] } : {}) };\n }\n private visual(asset: Asset): Creative['media'] {\n const type = sourceType(asset.creative_type), safe = url(asset.media_url, true);\n return !asset.deleted && type && safe ? [{ type, url: safe }] : [];\n }\n assetCard(account: string, asset: Asset): Creative {\n return { id: asset.id, provider: 'x', account_id: account, name: `Account media ${asset.id}`, type: asset.creative_type, status: asset.deleted ? 'DELETED' : 'PRESENT', headlines: [], descriptions: [], landing_urls: [], media: this.visual(asset), actions: [] };\n }\n async getAsset(account: string, id: string) {\n await this.entities.getAccount(account);\n const row = this.scope(account, (await this.entities.client.request('GET', `${this.base(account)}/account_media/${xId.parse(id)}`, z.object({ data: nativeAccountMedia }), { with_deleted: true })).data, id);\n return { ...row, configuration_hash: hash({ account_id: account, asset: configuration(row) }) };\n }\n async assets(raw: z.input<typeof accountMediaList>) {\n const input = accountMediaList.parse(raw);await this.entities.getAccount(input.account_id);\n const result = await this.entities.client.request('GET', `${this.base(input.account_id)}/account_media`, pageSchema(nativeAccountMedia), { count: input.count, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}), ...(input.creative_types ? { creative_types: input.creative_types.join(',') } : {}) });\n for (const row of result.data) { this.scope(input.account_id, row);if (!input.with_deleted && row.deleted || input.creative_types && !input.creative_types.includes(row.creative_type as typeof accountMediaTypes[number])) throw new AdportError('PROVIDER_ERROR', 'x: Account Media native filter mismatch'); }\n const paging = this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor);\n return { items: result.data, creatives: result.data.map(row => this.assetCard(input.account_id, row)), ...paging, notes: ['Account Media IDs are not media-library keys. Presence does not establish processing readiness, byte identity or ad eligibility.', ...paging.notes ?? []] };\n }\n private async page(account: string, line: string, params: XParams) {\n const result = await this.entities.client.request('GET', `${this.base(account)}/media_creatives`, pageSchema(nativeDirectMedia), { line_item_ids: line, ...params });\n for (const row of result.data) { this.scope(account, row);if (row.line_item_id !== line || params.with_deleted === false && row.deleted) throw new AdportError('PROVIDER_ERROR', 'x: media-creative ad-group/deletion filter mismatch'); }\n this.paging(result.data.map(row => row.id), result.next_cursor, typeof params.cursor === 'string' ? params.cursor : undefined);return result;\n }\n private async existing(account: string, line: string) {\n const rows: Association[] = [], ids = new Set<string>(), cursors = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.page(account, line, { count: 200, with_deleted: false, ...(cursor ? { cursor } : {}) });\n for (const row of result.data) { if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: media-creative inventory repeated an ID');ids.add(row.id);rows.push(row); }\n if (result.next_cursor === null) return rows.sort((a, b) => a.id.localeCompare(b.id));\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('PROVIDER_ERROR', 'x: media-creative inventory is incomplete; no association was submitted');\n }\n private associationHash(account: string, row: Association, parent: unknown) { return hash({ account_id: account, association: associationConfiguration(row), parent }); }\n async get(account: string, id: string) {\n await this.entities.getAccount(account);\n const row = this.scope(account, (await this.entities.client.request('GET', `${this.base(account)}/media_creatives/${xId.parse(id)}`, z.object({ data: nativeDirectMedia }), { with_deleted: true })).data, id);\n const parent = await this.posts.parents(account, row.line_item_id);\n return { ...row, parent: parent.snapshot, context_hash: this.associationHash(account, row, parent.snapshot) };\n }\n async context(account: string, raw: z.input<typeof directMediaSelection>) {\n const input = directMediaSelection.parse(raw), parent = await this.posts.parents(account, input.line_item_id), source = await this.getAsset(account, input.account_media_id);\n if (parent.line.deleted || parent.campaign.deleted || !['ACTIVE', 'PAUSED'].includes(parent.line.entity_status) || !['ACTIVE', 'PAUSED'].includes(parent.campaign.entity_status) || parent.line.product_type !== 'MEDIA') throw new AdportError('INVALID_INPUT', 'x: direct media needs an existing non-draft MEDIA ad group and campaign');\n if (source.deleted || !sourceType(source.creative_type)) throw new AdportError('INVALID_INPUT', 'x: choose an existing PREROLL or documented TAP image asset; VAST/unknown authoring is not verified');\n if (source.creative_type === 'PREROLL' && input.landing_url !== undefined) throw new AdportError('INVALID_INPUT', 'x: landing_url is ignored for preroll; use separate native preroll CTA settings');\n if (parent.line.objective === 'WEBSITE_CLICKS' && !input.landing_url) throw new AdportError('INVALID_INPUT', 'x: WEBSITE_CLICKS requires an explicit landing_url');\n const existing = await this.existing(account, input.line_item_id), context = { account_id: account, request: input, source: configuration(source), parent: parent.snapshot, existing: existing.map(associationConfiguration) };\n return { ...context, context_hash: hash(context), creatives: [this.assetCard(account, source)], truncated: false, notes: ['Native creation adds an ACTIVE association. paused_creation requires a currently PAUSED ad group; parent delivery and budgets are preserved.', 'The source is an existing native Account Media ID. No upload, media-library registration, post publication, CTA edit or source-byte verification is performed.', 'Omitted display destinations may use native defaults. Preroll click destinations belong to separate line-item CTA settings. Format/objective/placement compatibility is checked by X.', 'Snapshots do not atomically lock native concurrent changes. Reconcile unknown outcomes before any new association.', notice] };\n }\n async list(raw: z.input<typeof directMediaList>) {\n const input = directMediaList.parse(raw), parent = await this.posts.parents(input.account_id, input.line_item_id), result = await this.page(input.account_id, input.line_item_id, { count: input.count, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}) });\n const sources = new Map<string, Asset>(), warnings: string[] = [], wanted = [...new Set(result.data.map(row => row.account_media_id))];let index = 0;\n if (input.include_media) await Promise.all(Array.from({ length: Math.min(4, wanted.length) }, async () => { while (index < wanted.length) { const id = wanted[index++]!;try { sources.set(id, await this.getAsset(input.account_id, id)); } catch { warnings.push(`Account Media ${id} could not be read; its association remains visible.`); } } }));\n const creatives: Creative[] = result.data.map(row => {\n const source = sources.get(row.account_media_id), matching = source && !source.deleted && source.creative_type === row.creative_type;\n if (source && !matching) warnings.push(`Account Media ${row.account_media_id} is deleted or has a different format; its preview is unavailable.`);\n const destination = row.creative_type === 'PREROLL' || row.creative_type === 'VAST_PREROLL' ? undefined : url(row.landing_url);\n return { id: row.id, provider: 'x', account_id: input.account_id, campaign_id: parent.campaign.id, ad_group_id: row.line_item_id, name: `Media ad ${row.id}`, type: `${row.creative_type}_ASSOCIATION`, status: row.deleted ? 'DISASSOCIATED' : row.entity_status, headlines: [], descriptions: [], landing_urls: destination ? [destination] : [], media: matching ? this.visual(source) : [], actions: row.deleted ? [] : [{ label: 'Remove from ad group', tool: 'x_delete_media_creative', arguments: { account_id: input.account_id, media_creative_id: row.id, expected_context_hash: this.associationHash(input.account_id, row, parent.snapshot) }, fields: [] }] };\n });\n return { items: result.data.map(row => ({ ...row, context_hash: this.associationHash(input.account_id, row, parent.snapshot) })), parent: parent.snapshot, creatives, warnings, notes: ['Native ACTIVE is association state, not evidence of ad delivery. Removing an association retains its Account Media source.', 'Preroll CTA settings are separate; this gallery does not infer a preroll destination from landing_url.'], ...this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor) };\n }\n private unconfirmed(error: unknown, known: string[]): never {\n const previous = error instanceof AdportError && error.details && typeof error.details === 'object' && 'resource_ids' in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((value): value is string => typeof value === 'string' && xId.safeParse(value).success) : [];\n throw new AdportError('PROVIDER_ERROR', 'x: direct-media association outcome was not confirmed. Reconcile known IDs and current inventory before another mutation; no write was retried.', { resource_ids: [...new Set([...known, ...previous])] });\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const account = xId.parse(op.accountId), create = op.tool === 'x_create_media_creative';\n if (op.provider !== 'x' || op.kind !== (create ? 'create' : 'remove')) throw new AdportError('INVALID_INPUT', 'x: direct-media operation provider/kind mismatch');\n const review = (title: string, fields: ReviewField[], notes: string[]): Omit<Plan, 'execute'> => ({ summary: title, changes: fields.map(field => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: { provider: 'x', accountId: account, kind: op.kind, title, fields, notices: notes } });\n if (create) {\n const { expected_context_hash, acknowledge_active_association: _ack, ...input } = createDirectMedia.parse(op.payload), context = await this.context(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: media source/parent/destination/association context changed; read and preview again');\n if (context.existing.some(row => row.account_media_id === input.account_media_id)) throw new AdportError('INVALID_INPUT', 'x: this Account Media already has a live association in the ad group; do not replay creation');\n if (guard.forcePausedCreation && context.parent.line.entity_status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'x: native associations are ACTIVE; paused_creation requires a currently PAUSED ad group');\n const preview = review('Associate direct media', [{ label: 'Account Media', after: input.account_media_id }, { label: 'Format', after: String(context.source.creative_type) }, { label: 'Ad group', after: input.line_item_id }, { label: 'Campaign', after: context.parent.campaign.id }, { label: 'Native association status', after: 'ACTIVE' }, { label: 'Parent delivery', after: String(context.parent.line.entity_status) }, { label: 'Display destination', after: input.landing_url ?? (context.source.creative_type === 'PREROLL' ? 'Separate preroll CTA settings' : 'Native default') }], context.notes);\n const budgetDeltas = [context.parent.campaign, context.parent.line].flatMap(entity => ['daily_budget_amount_local_micro', 'total_budget_amount_local_micro'].flatMap(key => { const value = entity[key as keyof typeof entity];return typeof value === 'number' ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : []; }));\n return { ...preview, budgetDeltas, execute: async () => {\n const known: string[] = [];\n try {\n const row = (await this.entities.client.request('POST', `${this.base(account)}/media_creatives`, z.object({ data: nativeDirectMedia }), input)).data;known.push(row.id);this.scope(account, row);\n if (context.existing.some(prior => prior.id === row.id) || row.deleted || row.entity_status !== 'ACTIVE' || row.line_item_id !== input.line_item_id || row.account_media_id !== input.account_media_id || row.creative_type !== context.source.creative_type || input.landing_url !== undefined && row.landing_url !== input.landing_url) throw new Error('Association receipt differs');\n const observed = await this.get(account, row.id), afterSource = await this.getAsset(account, input.account_media_id);\n if (!equal(associationConfiguration(row), associationConfiguration(observed)) || !equal(observed.parent, context.parent) || !equal(configuration(afterSource), context.source)) throw new Error('Association readback/source differs');\n return [row.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n if (op.tool !== 'x_delete_media_creative') throw new AdportError('INVALID_INPUT', 'x: unsupported direct-media operation');\n const input = deleteDirectMedia.parse(op.payload), current = await this.get(account, input.media_creative_id);\n if (current.deleted || current.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: media association/parent changed or was deleted; read and preview again');\n return { ...review('Remove media from ad group', [{ label: 'Association', after: current.id }, { label: 'Account Media retained', after: current.account_media_id }, { label: 'Ad group', after: current.line_item_id }, { label: 'Deleted', before: false, after: true }], ['Removes this one serving association. Its Account Media source, library media, posts, other associations and parent status/budgets are retained.', 'Native entity_status may remain ACTIVE on the deleted tombstone. This is not source deletion or a PUT pause.', notice]), execute: async () => {\n const known = [current.id];\n try {\n const receipt = (await this.entities.client.request('DELETE', `${this.base(account)}/media_creatives/${current.id}`, z.object({ data: nativeDirectMedia }))).data;known.push(receipt.id);this.scope(account, receipt);\n const matches = (row: Association) => row.id === current.id && row.line_item_id === current.line_item_id && row.account_media_id === current.account_media_id && row.creative_type === current.creative_type && (row.landing_url ?? null) === (current.landing_url ?? null) && row.deleted;\n const observed = await this.get(account, current.id);\n if (!matches(receipt) || !matches(observed) || !equal(observed.parent, current.parent)) throw new Error('Disassociation receipt/readback differs');\n return [current.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n}\n","import { z } from 'zod';\nimport { mediaCreativeSchema, xId } from './schemas.js';\n\nexport const accountMediaTypes = ['BANNER', 'BANNER_TABLET', 'INTERSTITIAL', 'INTERSTITIAL_LANDSCAPE', 'INTERSTITIAL_LANDSCAPE_TABLET', 'INTERSTITIAL_TABLET', 'MEDIUM_RECTANGLE', 'PREROLL', 'VAST_PREROLL'] as const;\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nconst page = { count: z.number().int().min(1).max(50).default(20), cursor: z.string().min(1).max(4096).optional(), with_deleted: z.boolean().default(false) };\nexport const accountMediaList = z.object({ account_id: xId, ...page, creative_types: z.array(z.enum(accountMediaTypes)).min(1).max(accountMediaTypes.length).refine(values => new Set(values).size === values.length, 'Use unique creative types').optional() }).strict();\nexport const directMediaList = z.object({ account_id: xId, line_item_id: xId, ...page, include_media: z.boolean().default(true) }).strict();\nexport const nativeAccountMedia = z.looseObject({ id: xId, creative_type: z.string(), video_id: z.string().nullable().optional(), media_url: z.string().nullable().optional(), deleted: z.boolean(), account_id: xId.optional() });\nexport const nativeDirectMedia = mediaCreativeSchema.extend({ creative_type: z.string(), landing_url: z.string().nullable().optional(), approval_status: z.string().optional(), account_id: xId.optional() });\nconst destination = z.string().url().max(4096).refine(value => { const url = new URL(value); return ['https:', 'http:'].includes(url.protocol) && !url.username && !url.password; }, 'Use an HTTP(S) destination without embedded credentials');\nexport const directMediaSelection = z.object({ line_item_id: xId, account_media_id: xId, landing_url: destination.optional() }).strict();\nexport const createDirectMedia = directMediaSelection.extend({ expected_context_hash: hash, acknowledge_active_association: z.literal(true) }).strict();\nexport const deleteDirectMedia = z.object({ media_creative_id: xId, expected_context_hash: hash }).strict();\nexport const directMediaWrites = new Set(['x_create_media_creative', 'x_delete_media_creative']);\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type CreativeAction, type ReviewField, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsEntities } from './entities.js';\nimport type { XPostService } from './posts.js';\nimport { createPrerollCta, deletePrerollCta, nativePrerollCta, prerollCtaLabels, prerollCtaList, prerollCtaSelection, prerollCtaValues, updatePrerollCta } from './preroll-cta-schemas.js';\nimport { xId } from './schemas.js';\n\ntype Cta = z.infer<typeof nativePrerollCta>;\ntype Parent = Awaited<ReturnType<XPostService['parents']>>['snapshot'];\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst pageSchema = z.object({ data: z.array(nativePrerollCta).max(1000), next_cursor: z.string().nullable().optional() });\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst hash = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst equal = (left: unknown, right: unknown) => hash(left) === hash(right);\nconst config = (row: Cta) => ({ id: row.id, line_item_id: row.line_item_id, call_to_action: row.call_to_action, call_to_action_url: row.call_to_action_url, deleted: row.deleted });\nconst configs = (rows: Cta[]) => rows.map(config).sort((a, b) => a.id.localeCompare(b.id));\nconst label = (value: string) => prerollCtaLabels[value as keyof typeof prerollCtaLabels] ?? value;\nconst safeDestination = (value: string) => { try { const url = new URL(value);return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !/[\\x00-\\x1f\\x7f]/.test(value) ? value : undefined; } catch { return undefined; } };\nconst notices = ['CTA settings belong to the ad group and can affect all of its current and future preroll ads, not just one media association. Associated ads are not enumerated or frozen by this snapshot.', 'CTA presence is not proof of ad delivery or native placement rendering. Parent status, budgets, bids, media and ad associations are preserved.', 'Local preview is not native validation. Snapshots do not atomically lock native concurrent changes; no mutation is automatically retried.'];\n\n/** Official X v12 preroll CTA GET/POST/PUT/DELETE contract refreshed2026-11-06. */\nexport class XPrerollCtaService {\n constructor(private readonly entities: XAdsEntities, private readonly posts: XPostService) {}\n private base(account: string) { return `accounts/${xId.parse(account)}/preroll_call_to_actions`; }\n private scope(account: string, row: Cta, id?: string, line?: string) {\n if (row.account_id !== undefined && row.account_id !== account || id !== undefined && row.id !== id || line !== undefined && row.line_item_id !== line) throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA account/resource/ad-group mismatch');\n return row;\n }\n private paging(ids: string[], next: string | null | undefined, previous?: string) {\n if (new Set(ids).size !== ids.length || next && next === previous) throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA pagination repeated an ID or cursor');\n return { truncated: next !== null, ...(next ? { next_cursor: next } : {}), ...(next === undefined || next === '' ? { notes: ['Native continuation marker is missing; completeness is unconfirmed.'] } : {}) };\n }\n private async page(account: string, line: string | undefined, count: number, withDeleted: boolean, cursor?: string) {\n const result = await this.entities.client.request('GET', this.base(account), pageSchema, { ...(line ? { line_item_ids: line } : {}), count, with_deleted: withDeleted, ...(cursor ? { cursor } : {}) });\n if (result.data.length > count) throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA page exceeds its requested bound');\n for (const row of result.data) { this.scope(account, row, undefined, line);if (!withDeleted && row.deleted) throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA deletion filter mismatch'); }\n this.paging(result.data.map(row => row.id), result.next_cursor, cursor);return result;\n }\n private async inventory(account: string, line: string) {\n const rows: Cta[] = [], ids = new Set<string>(), cursors = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.page(account, line, 200, false, cursor);\n for (const row of result.data) { if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA inventory repeated an ID');ids.add(row.id);rows.push(row); }\n if (result.next_cursor === null) return configs(rows);\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA inventory is incomplete; no mutation submitted');\n }\n private contextHash(account: string, row: Cta, parent: Parent, active: Cta[]) { return hash({ account_id: account, cta: config(row), parent, active_ctas: configs(active) }); }\n private card(account: string, row: Cta, parent?: Parent, contextHash?: string): Creative {\n const options = prerollCtaValues.map(value => ({ value, label: prerollCtaLabels[value] }));\n const fields: CreativeAction['fields'] = [...(prerollCtaValues.includes(row.call_to_action as typeof prerollCtaValues[number]) ? [{ key: 'call_to_action', label: 'Button', type: 'select' as const, value: row.call_to_action, options }] : []), { key: 'call_to_action_url', label: 'Destination', type: 'text', value: row.call_to_action_url, max_length: 4096 }];\n const args = { account_id: account, preroll_call_to_action_id: row.id, expected_context_hash: contextHash, acknowledge_ad_group_scope: true };\n const destination = safeDestination(row.call_to_action_url);\n const actions: Creative['actions'] = row.deleted || !parent || !contextHash ? [] : [...(this.canAuthor(parent) ? [{ label: 'Edit CTA', tool: 'x_update_preroll_cta', arguments: args, fields }] : []), { label: 'Remove CTA', tool: 'x_delete_preroll_cta', arguments: args, fields: [] }];\n return { id: row.id, provider: 'x', account_id: account, ...(parent ? { campaign_id: parent.campaign.id } : {}), ad_group_id: row.line_item_id, name: `Preroll CTA ${row.id}`, type: 'PREROLL_CTA', status: row.deleted ? 'DELETED' : 'PRESENT', headlines: [label(row.call_to_action)], descriptions: [], landing_urls: destination ? [destination] : [], media: [], actions };\n }\n private canAuthor(parent: Parent) { return !parent.line.deleted && !parent.campaign.deleted && ['ACTIVE', 'PAUSED'].includes(String(parent.line.entity_status)) && ['ACTIVE', 'PAUSED'].includes(parent.campaign.entity_status) && parent.line.objective === 'PREROLL_VIEWS'; }\n private eligible(parent: Parent) {\n if (!this.canAuthor(parent)) throw new AdportError('INVALID_INPUT', 'x: preroll CTA authoring needs an existing non-draft PREROLL_VIEWS ad group and campaign');\n }\n async context(account: string, raw: z.input<typeof prerollCtaSelection>) {\n const input = prerollCtaSelection.parse(raw), parent = (await this.posts.parents(account, input.line_item_id)).snapshot;this.eligible(parent);\n const active = await this.inventory(account, input.line_item_id), context = { account_id: account, request: input, parent, active_ctas: active };\n return { ...context, context_hash: hash(context), cta_options: prerollCtaValues.map(value => ({ value, label: label(value) })), notes: ['Native POST sets the ad group CTA. Existing active CTA settings must be updated explicitly; this workflow refuses an implicit replacement.', 'Under paused_creation, setting a new CTA requires a currently PAUSED ad group.', ...notices] };\n }\n async get(account: string, id: string) {\n await this.entities.getAccount(account);\n const row = this.scope(account, (await this.entities.client.request('GET', `${this.base(account)}/${xId.parse(id)}`, z.object({ data: nativePrerollCta }), { with_deleted: true })).data, id);\n const parent = (await this.posts.parents(account, row.line_item_id)).snapshot, active = await this.inventory(account, row.line_item_id);\n if (!row.deleted && !active.some(item => equal(item, config(row))) || row.deleted && active.some(item => item.id === row.id)) throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA exact record differs from its current active inventory');\n const contextHash = this.contextHash(account, row, parent, active);\n return { ...row, parent, active_ctas: active, context_hash: contextHash, creatives: [this.card(account, row, parent, contextHash)], truncated: false, notes: notices };\n }\n async list(raw: z.input<typeof prerollCtaList>) {\n const input = prerollCtaList.parse(raw), parent = input.line_item_id ? (await this.posts.parents(input.account_id, input.line_item_id)).snapshot : undefined;\n if (!parent) await this.entities.getAccount(input.account_id);\n const result = await this.page(input.account_id, input.line_item_id, input.count, input.with_deleted, input.cursor);\n const warnings: string[] = [];let active: Cta[] | undefined;\n if (parent && input.line_item_id && result.data.some(row => !row.deleted)) try { active = await this.inventory(input.account_id, input.line_item_id); } catch { warnings.push('Complete CTA context could not be read. These settings remain visible without edit/removal actions; inspect the exact CTA before changing it.'); }\n const records = result.data.map(row => {\n const matched = active?.some(item => equal(item, config(row))), contextHash = matched && active && parent ? this.contextHash(input.account_id, row, parent, active) : undefined;\n if (active && !row.deleted && !matched) warnings.push(`CTA ${row.id} changed during this read; its edit actions are unavailable.`);\n return { row, contextHash };\n });\n const paging = this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor);\n return { items: records.map(({ row, contextHash }) => ({ ...row, ...(contextHash ? { context_hash: contextHash } : {}) })), ...(parent ? { parent } : {}), creatives: records.map(({ row, contextHash }) => this.card(input.account_id, row, parent, contextHash)), warnings, ...paging, notes: [...notices, ...paging.notes ?? []] };\n }\n private unconfirmed(error: unknown, known: string[]): never {\n const prior = error instanceof AdportError && error.details && typeof error.details === 'object' && 'resource_ids' in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((id): id is string => typeof id === 'string' && xId.safeParse(id).success) : [];\n throw new AdportError('PROVIDER_ERROR', 'x: preroll CTA outcome was not confirmed. Reconcile known IDs and current ad-group settings before another mutation; no write was retried.', { resource_ids: [...new Set([...known, ...prior])] });\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const account = xId.parse(op.accountId), create = op.tool === 'x_create_preroll_cta', update = op.tool === 'x_update_preroll_cta', remove = op.tool === 'x_delete_preroll_cta';\n if (op.provider !== 'x' || !create && !update && !remove || op.kind !== (create ? 'create' : update ? 'update' : 'remove')) throw new AdportError('INVALID_INPUT', 'x: preroll CTA operation provider/kind mismatch');\n const review = (title: string, parent: Parent, fields: ReviewField[]): Omit<Plan, 'execute'> => {\n const scope: ReviewField[] = [{ label: 'Ad group', after: String(parent.line.name ?? parent.line.id) }, { label: 'Parent delivery', after: String(parent.line.entity_status) }, { label: 'Scope', after: 'All preroll ads in this ad group' }];\n const notes = remove ? ['Removing a CTA does not pause preroll ads. Media and ad associations remain.', ...notices] : notices;\n return { summary: title, changes: [...fields, ...scope].map(field => `${field.label}: ${JSON.stringify(field.before)} → ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: { provider: 'x', accountId: account, kind: op.kind, title, fields: [...fields, ...scope], notices: notes } };\n };\n if (create) {\n const { expected_context_hash, acknowledge_ad_group_scope: _ack, ...input } = createPrerollCta.parse(op.payload), context = await this.context(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: preroll CTA creation context changed; read and preview again');\n if (context.active_ctas.length) throw new AdportError('INVALID_INPUT', 'x: the ad group already has active CTA settings; use an explicit CTA update');\n if (guard.forcePausedCreation && context.parent.line.entity_status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'x: paused_creation requires a currently PAUSED ad group before setting a new CTA');\n const preview = review('Set preroll CTA', context.parent, [{ label: 'Button', after: label(input.call_to_action) }, { label: 'Destination', after: input.call_to_action_url }]);\n const budgetDeltas = [context.parent.line, context.parent.campaign].flatMap(entity => ['daily_budget_amount_local_micro', 'total_budget_amount_local_micro'].flatMap(key => { const amount = entity[key as keyof typeof entity];return typeof amount === 'number' ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: amount, toMicros: amount }] : []; }));\n return { ...preview, budgetDeltas, execute: async () => {\n const known: string[] = [];\n try {\n const row = (await this.entities.client.request('POST', this.base(account), z.object({ data: nativePrerollCta }), input)).data;known.push(row.id);this.scope(account, row);\n const expected = { ...input, id: row.id, deleted: false };\n if (!equal(config(row), expected)) throw new Error('CTA creation receipt differs');\n const observed = await this.get(account, row.id);\n if (!equal(config(observed), expected) || !equal(observed.parent, context.parent) || !equal(observed.active_ctas, [expected])) throw new Error('CTA creation readback differs');\n return [row.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n const input = update ? updatePrerollCta.parse(op.payload) : deletePrerollCta.parse(op.payload), current = await this.get(account, input.preroll_call_to_action_id);\n if (current.deleted || current.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: preroll CTA or parent/inventory context changed or was deleted; read and preview again');\n if (update) this.eligible(current.parent);\n const patch: Record<string, string> = {};\n if (update) {\n const edit = updatePrerollCta.parse(op.payload);\n for (const key of ['call_to_action', 'call_to_action_url'] as const) if (edit[key] !== undefined && edit[key] !== current[key]) patch[key] = edit[key];\n if (!Object.keys(patch).length) throw new AdportError('INVALID_INPUT', 'x: change the CTA button or destination before requesting a preview');\n }\n const expected = { ...config(current), ...patch, deleted: remove }, expectedActive = current.active_ctas.flatMap(row => row.id === current.id ? remove ? [] : [expected] : [row]);\n const fields: ReviewField[] = update ? Object.entries(patch).map(([key, value]) => ({ label: key === 'call_to_action' ? 'Button' : 'Destination', before: key === 'call_to_action' ? label(current.call_to_action) : current.call_to_action_url, after: key === 'call_to_action' ? label(value) : value })) : [{ label: 'CTA', after: current.id }, { label: 'Button', before: label(current.call_to_action), after: '(removed)' }, { label: 'Destination', before: current.call_to_action_url, after: '(removed)' }];\n return { ...review(update ? 'Edit preroll CTA' : 'Remove preroll CTA', current.parent, fields), execute: async () => {\n const known = [current.id];\n try {\n const row = (await this.entities.client.request(update ? 'PUT' : 'DELETE', `${this.base(account)}/${current.id}`, z.object({ data: nativePrerollCta }), patch)).data;known.push(row.id);this.scope(account, row);\n if (!equal(config(row), expected)) throw new Error('CTA edit/removal receipt differs');\n const observed = await this.get(account, current.id);\n if (!equal(config(observed), expected) || !equal(observed.parent, current.parent) || !equal(observed.active_ctas, configs(expectedActive))) throw new Error('CTA edit/removal readback differs');\n return [current.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n}\n","import { z } from 'zod';\nimport { xId } from './schemas.js';\n\nexport const prerollCtaValues = ['GO_TO', 'SEE_MORE', 'SHOP', 'VISIT_SITE', 'WATCH_NOW'] as const;\nexport const prerollCtaLabels: Record<typeof prerollCtaValues[number], string> = { GO_TO: 'Go to', SEE_MORE: 'See more', SHOP: 'Shop', VISIT_SITE: 'Visit site', WATCH_NOW: 'Watch now' };\nconst hash = z.string().regex(/^[a-f0-9]{64}$/), button = z.enum(prerollCtaValues);\nconst destination = z.string().url().max(4096).refine(value => { const url = new URL(value);return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password && !/[\\x00-\\x1f\\x7f]/.test(value); }, 'Use an HTTP(S) destination without embedded credentials or control characters');\nexport const nativePrerollCta = z.object({ id: xId, line_item_id: xId, call_to_action: z.string().min(1), call_to_action_url: z.string(), deleted: z.boolean(), account_id: xId.optional() });\nexport const prerollCtaList = z.object({ account_id: xId, line_item_id: xId.optional(), count: z.number().int().min(1).max(50).default(20), cursor: z.string().min(1).max(4096).optional(), with_deleted: z.boolean().default(false) }).strict();\nexport const prerollCtaSelection = z.object({ line_item_id: xId, call_to_action: button, call_to_action_url: destination }).strict();\nexport const createPrerollCta = prerollCtaSelection.extend({ expected_context_hash: hash, acknowledge_ad_group_scope: z.literal(true) }).strict();\nexport const updatePrerollCta = z.object({ preroll_call_to_action_id: xId, expected_context_hash: hash, acknowledge_ad_group_scope: z.literal(true), call_to_action: button.optional(), call_to_action_url: destination.optional() }).strict().refine(input => input.call_to_action !== undefined || input.call_to_action_url !== undefined, 'Provide a CTA button or destination change');\nexport const deletePrerollCta = z.object({ preroll_call_to_action_id: xId, expected_context_hash: hash, acknowledge_ad_group_scope: z.literal(true) }).strict();\nexport const prerollCtaWrites = new Set(['x_create_preroll_cta', 'x_update_preroll_cta', 'x_delete_preroll_cta']);\n","import { createHash } from 'node:crypto';\nimport { AdportError, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport { accountMediaUsage, deleteAccountMedia } from './account-media-schemas.js';\nimport { nativeAccountMedia, nativeDirectMedia } from './direct-media-schemas.js';\nimport type { XDirectMediaService } from './direct-media.js';\nimport type { XAdsEntities } from './entities.js';\nimport { xId } from './schemas.js';\n\ntype Association = z.infer<typeof nativeDirectMedia>;\nconst page = z.object({ data: z.array(nativeDirectMedia).max(1000), next_cursor: z.string().nullable().optional() });\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst hash = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst configuration = (row: Record<string, unknown>) => Object.fromEntries(Object.entries(row).filter(([key]) => !['created_at', 'updated_at', 'account_id', 'configuration_hash'].includes(key)));\nconst reference = (row: Association) => ({ id: row.id, line_item_id: row.line_item_id, account_media_id: row.account_media_id, creative_type: row.creative_type, landing_url: row.landing_url ?? null, entity_status: row.entity_status, deleted: row.deleted });\n\n/** Native v12 Account Media DELETE and account-wide media_creatives GET, refreshed2026-11-06. */\nexport class XAccountMediaService {\n constructor(private readonly entities: XAdsEntities, private readonly media: XDirectMediaService) {}\n private async references(account: string, source: string) {\n const references: Association[] = [], ids = new Set<string>(), cursors = new Set<string>();let cursor: string | undefined;\n // No documented source-ID filter exists. Include tombstones and deleted-parent\n // associations; a partial scan must never authorize source deletion.\n for (let index = 0; index < 10; index++) {\n const result = await this.entities.client.request('GET', `accounts/${account}/media_creatives`, page, { count: 1000, with_deleted: true, ...(cursor ? { cursor } : {}) });\n for (const row of result.data) {\n if (row.account_id !== undefined && row.account_id !== account || ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: Account Media usage scan returned a different account or repeated association');\n ids.add(row.id);if (row.account_media_id === source) references.push(row);\n }\n if (result.next_cursor === null) return { references: references.sort((a, b) => a.id.localeCompare(b.id)), scanned_associations: ids.size };\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursors.add(result.next_cursor);cursor = result.next_cursor;\n }\n throw new AdportError('PROVIDER_ERROR', 'x: Account Media usage is incomplete; no source deletion is permitted. Reconcile the account inventory before trying again.');\n }\n private async context(account: string, id: string) {\n xId.parse(account);xId.parse(id);\n const asset = await this.media.getAsset(account, id), inventory = await this.references(account, id), references = inventory.references.map(reference), active = references.filter(row => !row.deleted);\n const context_hash = hash({ account_id: account, source: configuration(asset), references }), can_delete = !asset.deleted && active.length === 0, creative = this.media.assetCard(account, asset);\n if (can_delete) creative.actions = [{ label: 'Delete asset', tool: 'x_delete_account_media', arguments: { account_id: account, account_media_id: id, expected_context_hash: context_hash, acknowledge_source_deletion: true }, fields: [] }];\n const notes = ['Account Media is a native source asset, distinct from media-library keys, upload receipts and Adport project files.', 'Detach every non-deleted media_creative reference before source deletion, including references under deleted or paused parents. Each disassociation has its own preview/apply approval.', 'The complete bounded account-wide association scan is a snapshot, not an atomic native lock. Reconcile unknown outcomes; no mutation is retried.'];\n return { asset, references, non_deleted_references: active.length, can_delete, context_hash, scanned_associations: inventory.scanned_associations, truncated: false, creatives: [creative], notes };\n }\n async usage(account: string, id: string, options: { reference_offset?: number; reference_limit?: number; expected_context_hash?: string } = {}) {\n const input = accountMediaUsage.parse({ ...options, account_id: account, account_media_id: id }), context = await this.context(account, id);\n if (input.expected_context_hash !== undefined && input.expected_context_hash !== context.context_hash) throw new AdportError('PENDING_MISMATCH', 'x: Account Media reference pages changed; inspect usage again from the first page');\n const end = input.reference_offset + input.reference_limit;\n return { ...context, references: context.references.slice(input.reference_offset, end), reference_total: context.references.length, reference_offset: input.reference_offset, usage_complete: true, references_truncated: end < context.references.length, ...(end < context.references.length ? { next_reference_offset: end } : {}) };\n }\n async plan(op: WriteOperation): Promise<Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> }> {\n if (op.provider !== 'x' || op.kind !== 'remove' || op.tool !== 'x_delete_account_media') throw new AdportError('INVALID_INPUT', 'x: unsupported Account Media source operation');\n const account = xId.parse(op.accountId), input = deleteAccountMedia.parse(op.payload), context = await this.context(account, input.account_media_id);\n if (context.asset.deleted || context.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: Account Media source or usage changed; inspect usage and preview again');\n if (!context.can_delete) throw new AdportError('INVALID_INPUT', 'x: Account Media still has non-deleted ad associations. Review and detach each association before deleting its source.');\n const fields = [{ label: 'Account Media', after: context.asset.id }, { label: 'Format', after: context.asset.creative_type }, { label: 'Non-deleted ad associations', after: 0 }, { label: 'Deleted', before: false, after: true }];\n const notes = [...context.notes, 'Deletes this one Account Media source. No media-library/project-file deletion, ad disassociation, parent status/budget change or publication request is sent. This is source deletion, not a reversible ad pause.'];\n return { summary: `Delete Account Media ${context.asset.id}`, changes: fields.map(field => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: { provider: 'x', accountId: account, kind: 'remove', title: 'Delete Account Media', fields, notices: notes }, execute: async () => {\n const known = [context.asset.id];\n try {\n const row = (await this.entities.client.request('DELETE', `accounts/${account}/account_media/${context.asset.id}`, z.object({ data: nativeAccountMedia }))).data;known.push(row.id);\n if (row.account_id !== undefined && row.account_id !== account || hash(configuration(row)) !== hash(configuration({ ...context.asset, deleted: true }))) throw new Error('Source deletion receipt differs');\n const after = await this.context(account, context.asset.id);\n if (hash(configuration(after.asset)) !== hash(configuration(row)) || hash(after.references) !== hash(context.references)) throw new Error('Source deletion readback or references differ');\n return [context.asset.id];\n } catch (error) {\n const prior = error instanceof AdportError && error.details && typeof error.details === 'object' && 'resource_ids' in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((id): id is string => typeof id === 'string' && xId.safeParse(id).success) : [];\n throw new AdportError('PROVIDER_ERROR', 'x: Account Media source deletion was not confirmed. Inspect the known source ID and association inventory before another mutation; no DELETE was retried.', { resource_ids: [...new Set([...known, ...prior])] });\n }\n } };\n }\n}\n","import { z } from 'zod';\nimport { xId } from './schemas.js';\n\nexport const accountMediaIdentity = z.object({ account_id: xId, account_media_id: xId }).strict();\nexport const accountMediaUsage = accountMediaIdentity.extend({ reference_offset: z.number().int().min(0).max(9999).default(0), reference_limit: z.number().int().min(1).max(100).default(50), expected_context_hash: z.string().regex(/^[a-f0-9]{64}$/).optional() }).strict().refine(input => input.reference_offset === 0 || input.expected_context_hash !== undefined, 'Later reference pages require the original context hash');\nexport const deleteAccountMedia = z.object({ account_media_id: xId, expected_context_hash: z.string().regex(/^[a-f0-9]{64}$/), acknowledge_source_deletion: z.literal(true) }).strict();\n","import { createHash } from 'node:crypto';\nimport { AdportError, type Creative, type ReviewField, type WriteGuard, type WriteOperation, type WritePreview } from '@adport/core';\nimport { z } from 'zod';\nimport type { XParams } from './client.js';\nimport type { XCreativeService } from './creatives.js';\nimport type { XAdsEntities } from './entities.js';\nimport type { XPostService } from './posts.js';\nimport { createPromotedAccount, deletePromotedAccount, nativePromotedAccount, promotedAccountList, promotedAccountSelection } from './promoted-account-schemas.js';\nimport { xId } from './schemas.js';\n\ntype Association = z.infer<typeof nativePromotedAccount>;\ntype Plan = Omit<WritePreview, 'serverValidated'> & { execute(): Promise<string[]> };\nconst pageSchema = z.object({ data: z.array(nativePromotedAccount).max(1000), next_cursor: z.string().nullable().optional() });\nconst canonical = (value: unknown): unknown => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => [key, canonical(item)])) : value;\nconst hash = (value: unknown) => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');\nconst configuration = (row: Association) => ({ id: row.id, line_item_id: row.line_item_id, user_id: row.user_id, entity_status: row.entity_status, deleted: row.deleted });\nconst equal = (a: unknown, b: unknown) => hash(a) === hash(b);\nconst notice = 'Local preview is not X validation. Native eligibility remains authoritative, and no write is retried automatically.';\n\n/** Official X v12 promoted_accounts reference, docs09e643bc, checked2026-11-06. */\nexport class XPromotedAccountService {\n constructor(private readonly entities: XAdsEntities, private readonly creatives: XCreativeService, private readonly posts: XPostService) {}\n private base(account: string) { return `accounts/${xId.parse(account)}`; }\n private scope(account: string, row: Association, id?: string, line?: string) {\n if (row.account_id !== undefined && row.account_id !== account || id !== undefined && row.id !== id || line !== undefined && row.line_item_id !== line) throw new AdportError('PROVIDER_ERROR', 'x: promoted-account resource/account/ad-group mismatch');\n return row;\n }\n private paging(ids: string[], next: string | null | undefined, previous?: string) {\n if (new Set(ids).size !== ids.length || next && next === previous) throw new AdportError('PROVIDER_ERROR', 'x: promoted-account pagination repeated an ID or cursor');\n return { truncated: next !== null, ...(next ? { next_cursor: next } : {}), ...(next === undefined || next === '' ? { notes: ['Native continuation marker is missing; completeness is unconfirmed.'] } : {}) };\n }\n private async page(account: string, line: string, params: XParams) {\n const result = await this.entities.client.request('GET', `${this.base(account)}/promoted_accounts`, pageSchema, { line_item_ids: line, ...params });\n for (const row of result.data) { this.scope(account, row, undefined, line);if (params.with_deleted === false && row.deleted) throw new AdportError('PROVIDER_ERROR', 'x: promoted-account deletion filter mismatch'); }\n this.paging(result.data.map(row => row.id), result.next_cursor, typeof params.cursor === 'string' ? params.cursor : undefined);return result;\n }\n private async existing(account: string, line: string) {\n const rows: Association[] = [], ids = new Set<string>(), cursors = new Set<string>();let cursor: string | undefined;\n for (let page = 0; page < 10; page++) {\n const result = await this.page(account, line, { count: 200, with_deleted: false, ...(cursor ? { cursor } : {}) });\n for (const row of result.data) { if (ids.has(row.id)) throw new AdportError('PROVIDER_ERROR', 'x: promoted-account inventory repeated an ID');ids.add(row.id);rows.push(row); }\n if (result.next_cursor === null) return rows.sort((a, b) => a.id.localeCompare(b.id));\n if (!result.next_cursor || cursors.has(result.next_cursor)) break;\n cursor = result.next_cursor;cursors.add(cursor);\n }\n throw new AdportError('PROVIDER_ERROR', 'x: promoted-account inventory is incomplete; no association submitted');\n }\n private associationHash(account: string, row: Association, parent: unknown) { return hash({ account_id: account, association: configuration(row), parent }); }\n async get(account: string, id: string) {\n await this.entities.getAccount(account);\n const row = this.scope(account, (await this.entities.client.request('GET', `${this.base(account)}/promoted_accounts/${xId.parse(id)}`, z.object({ data: nativePromotedAccount }), { with_deleted: true })).data, id);\n const parent = await this.posts.parents(account, row.line_item_id);\n return { ...row, parent: parent.snapshot, context_hash: this.associationHash(account, row, parent.snapshot) };\n }\n private card(account: string, row: Association, parent: Awaited<ReturnType<XPostService['parents']>>['snapshot'], removable: boolean): Creative {\n return { id: row.id, provider: 'x', account_id: account, campaign_id: String(parent.campaign.id), ad_group_id: row.line_item_id, name: `Promoted account ${row.user_id}`, type: 'PROMOTED_ACCOUNT_ASSOCIATION', status: row.deleted ? 'DISASSOCIATED' : row.entity_status, headlines: [], descriptions: [`X profile ${row.user_id}`], landing_urls: [`https://x.com/i/user/${row.user_id}`], media: [], actions: removable && !row.deleted ? [{ label: 'Remove from ad group', tool: 'x_delete_promoted_account', arguments: { account_id: account, promoted_account_id: row.id, expected_context_hash: this.associationHash(account, row, parent) }, fields: [] }] : [] };\n }\n async list(raw: z.input<typeof promotedAccountList>) {\n const input = promotedAccountList.parse(raw), parent = await this.posts.parents(input.account_id, input.line_item_id);\n if (parent.line.product_type !== 'PROMOTED_ACCOUNT') throw new AdportError('INVALID_INPUT', 'x: select a PROMOTED_ACCOUNT ad group');\n const result = await this.page(input.account_id, input.line_item_id, { count: input.count, with_deleted: input.with_deleted, ...(input.cursor ? { cursor: input.cursor } : {}) });\n return { items: result.data.map(row => ({ ...row, context_hash: this.associationHash(input.account_id, row, parent.snapshot) })), parent: parent.snapshot, creatives: result.data.map(row => this.card(input.account_id, row, parent.snapshot, true)), ...this.paging(result.data.map(row => row.id), result.next_cursor, input.cursor), warnings: ['Native ACTIVE describes the association, not parent delivery. Profile content is live; this endpoint supplies identity references rather than profile artwork.', ...(result.data.length > input.count ? ['X returned more rows than requested; all were retained.'] : [])] };\n }\n async context(account: string, raw: z.input<typeof promotedAccountSelection>) {\n const input = promotedAccountSelection.parse(raw), accountState = await this.entities.getAccount(account);\n if (accountState.deleted) throw new AdportError('INVALID_INPUT', 'x: the selected ad account is deleted');\n const parent = await this.posts.parents(account, input.line_item_id);\n if (parent.line.deleted || parent.campaign.deleted || !['ACTIVE', 'PAUSED'].includes(parent.line.entity_status) || !['ACTIVE', 'PAUSED'].includes(parent.campaign.entity_status) || parent.line.product_type !== 'PROMOTED_ACCOUNT' || parent.line.objective !== 'FOLLOWERS') throw new AdportError('INVALID_INPUT', 'x: choose an existing non-draft FOLLOWERS/PROMOTED_ACCOUNT ad group and campaign');\n const users = await this.creatives.users(account, true);\n if (users.some(row => row.account_id !== undefined && row.account_id !== account)) throw new AdportError('PROVIDER_ERROR', 'x: promotable-user account echo mismatch');\n const matches = users.filter(row => row.user_id === input.user_id && !row.deleted);\n if (matches.length !== 1 || matches[0]!.promotable_user_type !== 'FULL') throw new AdportError('INVALID_INPUT', 'x: select one unambiguous current FULL promotable user from this account');\n const row = matches[0]!, user = { id: row.id, user_id: row.user_id, promotable_user_type: row.promotable_user_type, deleted: row.deleted }, existing = await this.existing(account, input.line_item_id);\n const context = { account_id: account, request: input, user, parent: parent.snapshot, existing: existing.map(configuration) };\n return { ...context, context_hash: hash(context), creatives: [{ id: input.user_id, provider: 'x', account_id: account, campaign_id: parent.campaign.id, ad_group_id: input.line_item_id, name: `Profile ${input.user_id}`, type: 'PROMOTABLE_PROFILE', status: 'FULL', headlines: [], descriptions: [], landing_urls: [`https://x.com/i/user/${input.user_id}`], media: [], actions: [] }], truncated: false, notes: ['Native creation adds an ACTIVE association. paused_creation requires a currently PAUSED ad group; parent delivery and budgets are preserved.', 'The promoted identity is bound to this context; live X profile text/artwork is not snapshotted, uploaded or edited. No post is published and no new profile is created.', 'Snapshots do not atomically lock concurrent native changes. Reconcile unknown outcomes before another request.', notice] };\n }\n private unconfirmed(error: unknown, known: string[]): never {\n const previous = error instanceof AdportError && error.details && typeof error.details === 'object' && 'resource_ids' in error.details && Array.isArray(error.details.resource_ids) ? error.details.resource_ids.filter((id): id is string => typeof id === 'string' && xId.safeParse(id).success) : [];\n throw new AdportError('PROVIDER_ERROR', 'x: promoted-account association outcome unconfirmed. Inspect known IDs and current inventory before another mutation; no write was retried.', { resource_ids: [...new Set([...known, ...previous])] });\n }\n async plan(op: WriteOperation, guard: WriteGuard): Promise<Plan> {\n const account = xId.parse(op.accountId), create = op.tool === 'x_create_promoted_account';\n if (op.provider !== 'x' || !['x_create_promoted_account', 'x_delete_promoted_account'].includes(op.tool) || op.kind !== (create ? 'create' : 'remove')) throw new AdportError('INVALID_INPUT', 'x: promoted-account operation provider/kind mismatch');\n const review = (title: string, fields: ReviewField[], notes: string[]): Omit<Plan, 'execute'> => ({ summary: title, changes: fields.map(field => `${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes, review: { provider: 'x', accountId: account, kind: op.kind, title, fields, notices: notes } });\n if (create) {\n const { expected_context_hash, acknowledge_active_association: _active, acknowledge_live_profile: _profile, ...input } = createPromotedAccount.parse(op.payload), context = await this.context(account, input);\n if (context.context_hash !== expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: promoted identity/parent/association context changed; read and preview again');\n if (context.existing.some(row => row.user_id === input.user_id)) throw new AdportError('INVALID_INPUT', 'x: this user is already promoted in the ad group; do not replay creation');\n if (guard.forcePausedCreation && context.parent.line.entity_status !== 'PAUSED') throw new AdportError('POLICY_VIOLATION', 'x: native profile associations are ACTIVE; paused_creation requires a currently PAUSED ad group');\n const budgetDeltas = [context.parent.campaign, context.parent.line].flatMap(entity => ['daily_budget_amount_local_micro', 'total_budget_amount_local_micro'].flatMap(key => { const value = entity[key as keyof typeof entity];return typeof value === 'number' ? [{ target: `${entity.id} ${key} existing pool`, currency: context.parent.campaign.currency, fromMicros: value, toMicros: value }] : []; }));\n return { ...review('Promote X account', [{ label: 'Profile user ID', after: input.user_id }, { label: 'Ad group', after: input.line_item_id }, { label: 'Campaign', after: context.parent.campaign.id }, { label: 'Native association status', after: 'ACTIVE' }, { label: 'Parent delivery', after: String(context.parent.line.entity_status) }, { label: 'Profile content', after: 'Live X profile; not snapshotted or edited' }], context.notes), budgetDeltas, execute: async () => {\n const known: string[] = [];\n try {\n const row = (await this.entities.client.request('POST', `${this.base(account)}/promoted_accounts`, z.object({ data: nativePromotedAccount }), input)).data;known.push(row.id);this.scope(account, row, undefined, input.line_item_id);\n if (context.existing.some(prior => prior.id === row.id) || row.deleted || row.entity_status !== 'ACTIVE' || row.user_id !== input.user_id) throw new Error('Promoted-account receipt differs');\n const observed = await this.get(account, row.id);\n if (!equal(configuration(row), configuration(observed)) || !equal(observed.parent, context.parent)) throw new Error('Promoted-account readback/parent differs');\n return [row.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n const input = deletePromotedAccount.parse(op.payload), current = await this.get(account, input.promoted_account_id);\n if (current.deleted || current.context_hash !== input.expected_context_hash) throw new AdportError('PENDING_MISMATCH', 'x: promoted-account association/parent changed or was deleted; read and preview again');\n return { ...review('Remove promoted account from ad group', [{ label: 'Association', after: current.id }, { label: 'Profile retained', after: current.user_id }, { label: 'Ad group', after: current.line_item_id }, { label: 'Deleted', before: false, after: true }], ['Removes this one ad association. The X profile, other associations, posts and parent delivery/budgets are retained.', 'A deleted tombstone may retain native ACTIVE status. No PUT edit or profile deletion occurs.', notice]), execute: async () => {\n const known = [current.id];\n try {\n const row = (await this.entities.client.request('DELETE', `${this.base(account)}/promoted_accounts/${current.id}`, z.object({ data: nativePromotedAccount }))).data;known.push(row.id);this.scope(account, row, current.id, current.line_item_id);\n const observed = await this.get(account, current.id), matches = (value: Association) => value.id === current.id && value.line_item_id === current.line_item_id && value.user_id === current.user_id && value.deleted;\n if (!matches(row) || !matches(observed) || !equal(observed.parent, current.parent)) throw new Error('Promoted-account deletion/readback differs');\n return [current.id];\n } catch (error) { return this.unconfirmed(error, known); }\n } };\n }\n}\n","import { z } from 'zod';\nimport { snowflake } from './creative-tools.js';\nimport { promotedAccountSchema, xId } from './schemas.js';\n\nconst hash = z.string().regex(/^[a-f0-9]{64}$/);\nexport const nativePromotedAccount = promotedAccountSchema.extend({ user_id: snowflake, account_id: xId.optional(), approval_status: z.string().optional() });\nexport const promotedAccountList = z.object({ account_id: xId, line_item_id: xId, count: z.number().int().min(1).max(50).default(20), cursor: z.string().min(1).max(4096).optional(), with_deleted: z.boolean().default(false) }).strict();\nexport const promotedAccountSelection = z.object({ line_item_id: xId, user_id: snowflake }).strict();\nexport const createPromotedAccount = promotedAccountSelection.extend({ expected_context_hash: hash, acknowledge_active_association: z.literal(true), acknowledge_live_profile: z.literal(true) }).strict();\nexport const deletePromotedAccount = z.object({ promoted_account_id: xId, expected_context_hash: hash }).strict();\nexport const promotedAccountWrites = new Set(['x_create_promoted_account', 'x_delete_promoted_account']);\n","import { z } from 'zod';\nimport { defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport type { XAdsProvider } from './provider.js';\nimport { createCampaignSchema, setBudgetSchema, setStatusSchema, xId } from './schemas.js';\nimport { xManagementTools } from './management-tools.js';\nimport { xTargetingTools } from './targeting-tools.js';\nimport { xCreativeTools } from './creative-tools.js';\nimport { xMediaTools } from './media-tools.js';\nimport { xCardTools } from './card-tools.js';\nimport { xAudienceTools } from './audience-tools.js';\nimport { xMeasurementTools } from './measurement-tools.js';\nimport { xPostTools } from './post-tools.js';\nimport { xScheduledTools } from './scheduled-tools.js';\nimport { xDirectMediaTools } from './direct-media-tools.js';\nimport { xPrerollCtaTools } from './preroll-cta-tools.js';\nimport { xAccountMediaTools } from './account-media-tools.js';\nimport { xPromotedAccountTools } from './promoted-account-tools.js';\n\nexport function xTools(provider: XAdsProvider): AnyToolDefinition[] {\n return [\n ...xManagementTools(provider),\n ...xTargetingTools(provider),\n ...xCreativeTools(provider),\n ...xMediaTools(provider),\n ...xCardTools(provider),\n ...xAudienceTools(provider),\n ...xMeasurementTools(provider),\n ...xPostTools(provider),\n ...xScheduledTools(provider),\n ...xDirectMediaTools(provider),\n ...xPrerollCtaTools(provider),\n ...xAccountMediaTools(provider),\n ...xPromotedAccountTools(provider),\n defineTool({ name: 'x_get_campaign', namespace: 'x', description: 'Read one campaign’s native budget, funding, currency and delivery configuration within the selected account.', input: z.object({ account_id: xId, campaign_id: xId }), annotations: { readOnly: true }, handler: input => provider.getCampaign(input.account_id, input.campaign_id) }),\n defineTool({ name: 'x_get_line_item', namespace: 'x', description: 'Read native line-item bid, budgets, schedule and other configuration, verifying its ID and account-scoped campaign/currency.', input: z.object({ account_id: xId, line_item_id: xId }), annotations: { readOnly: true }, handler: input => provider.getLineItem(input.account_id, input.line_item_id) }),\n defineTool({ name: 'x_list_campaigns', namespace: 'x', description: 'List X Ads campaigns including inactive, deleted and draft campaigns.', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listCampaigns(input.account_id) }),\n defineTool({ name: 'x_list_funding_instruments', namespace: 'x', description: 'List existing funding instruments for campaign creation; does not create or change billing.', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listFundingInstruments(input.account_id) }),\n defineTool({ name: 'x_list_line_items', namespace: 'x', description: 'List X Ads line items (ad groups).', input: z.object({ account_id: xId }), annotations: { readOnly: true }, handler: input => provider.listLineItems(input.account_id) }),\n guardedWriteTool({ name: 'x_create_campaign', namespace: 'x', provider: 'x', kind: 'create', description: 'Create a paused X Ads campaign with an existing funding instrument and account-currency budgets in integer micros. Preview is local.', payload: createCampaignSchema }),\n guardedWriteTool({ name: 'x_set_campaign_status', namespace: 'x', provider: 'x', kind: 'update', description: 'Pause or activate an existing X Ads campaign.', payload: setStatusSchema }),\n guardedWriteTool({ name: 'x_set_budget', namespace: 'x', provider: 'x', kind: 'update', description: 'Change an existing X Ads daily or total campaign budget in integer micros, preserving the other cap.', payload: setBudgetSchema }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { snowflake } from './creative-tools.js';\nimport { createCard, deleteCard, listCards, updateCard } from './card-schemas.js';\nimport { xId } from './schemas.js';\n\nexport function xCardTools(provider: XAdsProvider): AnyToolDefinition[] {\n const catalog = { category: 'creatives', exposure: 'standard' } as const;\n return [\n defineTool({ name: 'x_cards', namespace: 'x', description: 'Browse native website/app/carousel cards with bounded media previews, copy edits and cursor pagination. Cards are separate from post publication and ad delivery. Legacy inclusion is explicit; this inventory does not replace exact-URI cards/all lookup.', input: listCards, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, catalog, annotations: { readOnly: true, openWorld: false }, handler: v => provider.cards.list(v) }),\n defineTool({ name: 'x_get_card', namespace: 'x', description: 'Read one modern card by numeric ID within the selected account, including full native configuration and configuration_hash for edits/deletion.', input: z.object({ account_id: xId, card_id: snowflake, with_deleted: z.boolean().default(false) }), catalog, annotations: { readOnly: true, openWorld: false }, handler: v => provider.cards.get(v.account_id, v.card_id, v.with_deleted) }),\n guardedWriteTool({ name: 'x_create_card', namespace: 'x', provider: 'x', kind: 'create', description: 'Create an unattached website/app or carousel card from ready account-owned image/video media. Uses the native JSON body and independently verifies content. Does not publish posts or create ad associations. Local preview only; never repeat an unconfirmed creation.', payload: createCard, destructive: false, openWorld: false, catalog }),\n guardedWriteTool({ name: 'x_update_card', namespace: 'x', provider: 'x', kind: 'update', description: 'Edit one modern card using its current configuration hash. Omitted fields stay unchanged; components/slides replace their layout. Copy shortcuts edit a supported current layout and require slide_index for multi-destination cards. Shared changes can affect existing posts/ads immediately; acknowledgement required. No automatic retry.', payload: updateCard, destructive: true, openWorld: false, catalog }),\n guardedWriteTool({ name: 'x_delete_card', namespace: 'x', provider: 'x', kind: 'remove', description: 'Delete one modern card after a matching snapshot and shared-effects acknowledgement. Existing uses may be affected; no restore endpoint is established. Verifies exact native deletion/readback; does not pause an ad or campaign. No automatic retry.', payload: deleteCard, destructive: true, openWorld: false, catalog }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { createPost, createPromotions, createRepostPromotions, deletePromotion, postFields, postList, postReference, promotionList, promotionSelection, renamePost } from './post-schemas.js';\nimport { xId } from './schemas.js';\n\nexport function xPostTools(provider: XAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'x', catalog: { category: 'creatives' as const, exposure: 'specialist' as const } };\n const read = { readOnly: true };\n return [\n defineTool({ ...shared, name: 'x_published_posts', description: 'View published promoted-only/organic posts for an explicit account-associated author, with native media/copy and guarded name edits. PUBLISHED is not ad delivery. Native cursors support Load more; text edits use a new post.', input: postList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: read, handler: input => provider.posts.list(input) }),\n defineTool({ ...shared, name: 'x_get_published_post', description: 'Read an exact published post for this account and current promotable author, including snapshot_hash. Never treats a missing response as global absence or substitutes rounded numeric IDs.', input: postReference, annotations: read, handler: input => provider.posts.get(input.account_id, input.user_id, input.tweet_id) }),\n defineTool({ ...shared, name: 'x_post_creation_context', description: 'Check exact promoted-only post fields, FULL/composer authority and ready account-owned media/cards. Returns context_hash for publication. Creates nothing; existing drafts stay separate.', input: postFields.safeExtend({ account_id: xId }), annotations: read, handler: ({ account_id, ...input }) => provider.posts.creationContext(account_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_create_promoted_only_post', provider: 'x', kind: 'create', destructive: false, description: 'Create a distinct PUBLISHED promoted-only post with nullcast=true, expected_context_hash and confirm_publication. Does not publish organically, consume a draft or associate an ad. Native text/attachment rendering is qualified by independent readback; no replay.', payload: createPost }),\n guardedWriteTool({ ...shared, name: 'x_rename_published_post', provider: 'x', kind: 'update', description: 'Rename an owned published post with expected_snapshot_hash. Uses native PUT tweets/id/name; published copy/media/status and associations are preserved and independently read back.', payload: renamePost }),\n defineTool({ ...shared, name: 'x_promoted_posts', description: 'View one verified ad group’s promoted-post associations with native cursor paging and guarded disassociation. Optional user_id hydrates published content for that associated author. ACTIVE is association state, not proof of delivery.', input: promotionList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: read, handler: input => provider.posts.promotions(input) }),\n defineTool({ ...shared, name: 'x_get_promoted_post', description: 'Read an exact account-owned promoted-post association, its parent settings and context_hash. ID is the association ID, not the published tweet_id. Tombstone can retain native ACTIVE status.', input: z.object({ account_id: xId, promoted_tweet_id: xId }).strict(), annotations: read, handler: input => provider.posts.getPromotion(input.account_id, input.promoted_tweet_id) }),\n defineTool({ ...shared, name: 'x_promotion_context', description: 'Read complete current source/parent context for associating1–50 existing FULL-author posts to one ad group. Hash binds posts, parent delivery/money and matching existing associations. Does not promote; RETWEETS_ONLY copying is separate.', input: promotionSelection.safeExtend({ account_id: xId }), annotations: read, handler: ({ account_id, ...input }) => provider.posts.promotionContext(account_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_create_promoted_posts', provider: 'x', kind: 'create', destructive: true, description: 'Associate1–50 verified published FULL-author posts with one ad group. Requires context_hash and acknowledging native ACTIVE associations. paused_creation requires a currently PAUSED ad group. Existing posts/parents/budgets stay; no fictitious PUT pause.', payload: createPromotions }),\n defineTool({ ...shared, name: 'x_repost_promotion_context', description: 'Review one to 50 published posts from a current RETWEETS_ONLY author for native copy promotion. Verifies unique FULL receiving author, complete source/parent/association inventory and context_hash. New nullcast copies get different IDs; existing reposts cannot be reliably deduplicated by source ID.', input: promotionSelection.safeExtend({ account_id: xId }), output: creativesOutput.passthrough(), presentation: 'creatives', annotations: read, handler: ({ account_id, ...input }) => provider.posts.repostContext(account_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_create_repost_promotions', provider: 'x', kind: 'create', destructive: true, description: 'Promote one to 50 authorized RETWEETS_ONLY source posts as new published nullcast copies and ACTIVE associations. Requires context_hash and both acknowledgements. Uses one source per native request, at most four concurrent; paused_creation requires a PAUSED ad group. Returns explicit source/copy/association mappings. Partial outcomes stop new writes, retain known IDs and are never replayed.', payload: createRepostPromotions }),\n guardedWriteTool({ ...shared, name: 'x_delete_promoted_post', provider: 'x', kind: 'remove', destructive: true, description: 'Disassociate one exact promoted-post association with expected_context_hash, native DELETE and independent tombstone readback. Retains published post/media/other associations. This is the native ad-level removal/pause workflow; re-promotion needs a new preview.', payload: deletePromotion }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { xId } from './schemas.js';\nimport { createScheduled, createScheduledPromotion, deleteScheduled, deleteScheduledPromotion, scheduledFields, scheduledList, scheduledPromotionList, scheduledPromotionSelection, scheduledReference, updateScheduled } from './scheduled-schemas.js';\n\nexport function xScheduledTools(provider: XAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'x', catalog: { category: 'creatives' as const, exposure: 'specialist' as const } }, annotations = { readOnly: true };\n const write = { ...shared, provider: 'x', destructive: true };\n return [\n defineTool({ ...shared, name: 'x_scheduled_posts', description: 'View one account-associated author’s scheduled posts, copy, native state and bounded media previews. Native cursors support Load more; SCHEDULED is automatic future publication, not a paused ad.', input: scheduledList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations, handler: input => provider.scheduled.list(input) }),\n defineTool({ ...shared, name: 'x_get_scheduled_post', description: 'Read an exact author/account-owned scheduled post, matching current ad associations and snapshot_hash. Scheduled ID and eventual published tweet_id are distinct. Complete association inventory is required for edit/delete context.', input: scheduledReference, annotations, handler: input => provider.scheduled.get(input.account_id, input.user_id, input.scheduled_tweet_id) }),\n defineTool({ ...shared, name: 'x_scheduled_post_context', description: 'Check FULL/composer authority, owned ready attachments and a UTC-minute schedule,15minutes to one calendar year ahead. Returns context_hash without creating content. Only promoted-only nullcast publication is supported.', input: scheduledFields.safeExtend({ account_id: xId }), annotations, handler: ({ account_id, ...input }) => provider.scheduled.creationContext(account_id, input) }),\n guardedWriteTool({ ...write, name: 'x_create_scheduled_post', kind: 'create', description: 'Schedule a new promoted-only post with expected_context_hash and automatic-publication acknowledgement. Forces nullcast=true; no draft consumption or ad association. Independent native receipt/readback; uncertain writes are never replayed.', payload: createScheduled }),\n guardedWriteTool({ ...write, name: 'x_update_scheduled_post', kind: 'update', description: 'Edit a still-future, promoted-only SCHEDULED post with expected_snapshot_hash. Omitted fields remain; media_keys:[] and card_uri:null clear attachments. Existing associations require shared-effects acknowledgement. No organic-state change.', payload: updateScheduled }),\n guardedWriteTool({ ...write, name: 'x_delete_scheduled_post', kind: 'remove', description: 'Permanently cancel/delete a still-future promoted-only schedule after snapshot and deletion acknowledgement. Requires no live scheduled ad associations. Native DELETED receipt plus independent HTTP404; published posts are separate.', payload: deleteScheduled }),\n defineTool({ ...shared, name: 'x_scheduled_promoted_posts', description: 'List one account-owned ad group’s scheduled-post associations with native cursors. These have no native status/PUT pause; tweet_id appears after publication. Does not infer delivery from association existence.', input: scheduledPromotionList, output: z.looseObject({ records: z.array(z.record(z.string(), z.unknown())) }), presentation: 'records', annotations, pagination: { cursorInput: 'cursor' }, handler: input => provider.scheduled.promotions(input) }),\n defineTool({ ...shared, name: 'x_get_scheduled_promoted_post', description: 'Read an exact scheduled ad association, source schedule, parent configuration and context_hash. Uses the association ID, distinct from scheduled_tweet_id and eventual published tweet_id.', input: z.object({ account_id: xId, scheduled_promoted_tweet_id: xId }).strict(), annotations, handler: input => provider.scheduled.getPromotion(input.account_id, input.scheduled_promoted_tweet_id) }),\n defineTool({ ...shared, name: 'x_scheduled_promotion_context', description: 'Check exact future FULL-author schedule, complete matching association inventory and parent delivery/budget context. Returns context_hash for automatic promotion; creates nothing.', input: scheduledPromotionSelection.safeExtend({ account_id: xId }), annotations, handler: ({ account_id, ...input }) => provider.scheduled.promotionContext(account_id, input) }),\n guardedWriteTool({ ...write, name: 'x_create_scheduled_promoted_post', kind: 'create', description: 'Associate one still-future schedule with an ad group after context_hash and automatic-promotion acknowledgement. paused_creation requires a currently PAUSED ad group; native has no association status or PUT pause. Existing money pools remain policy-checked.', payload: createScheduledPromotion }),\n guardedWriteTool({ ...write, name: 'x_delete_scheduled_promoted_post', kind: 'remove', description: 'Remove one exact scheduled ad association before its publication time, with expected_context_hash and independent tombstone readback. Keeps the scheduled post; after publication inspect/remove the ordinary promoted-post association instead.', payload: deleteScheduledPromotion }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { accountMediaList, createDirectMedia, deleteDirectMedia, directMediaList, directMediaSelection } from './direct-media-schemas.js';\nimport { xId } from './schemas.js';\n\nexport function xDirectMediaTools(provider: XAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'x', catalog: { category: 'creatives' as const, exposure: 'specialist' as const } };\n const annotations = { readOnly: true };\n return [\n defineTool({ ...shared, name: 'x_account_media', description: 'View native Account Media assets with cursor paging and safe image/video previews. These IDs are distinct from media-library keys and serving associations. Unknown or VAST formats retain native metadata without invented previews.', input: accountMediaList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations, handler: input => provider.directMedia.assets(input) }),\n defineTool({ ...shared, name: 'x_get_account_media', description: 'Read one exact account-owned Account Media asset and configuration hash. Does not turn a media-library key or upload receipt into an Account Media ID.', input: z.object({ account_id: xId, account_media_id: xId }).strict(), annotations, handler: input => provider.directMedia.getAsset(input.account_id, input.account_media_id) }),\n defineTool({ ...shared, name: 'x_media_creatives', description: 'View direct-media ad associations in one verified ad group, with native paging, source previews and guarded disassociation actions. Native ACTIVE association state is separate from parent delivery.', input: directMediaList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations, handler: input => provider.directMedia.list(input) }),\n defineTool({ ...shared, name: 'x_get_media_creative', description: 'Read an exact direct-media association, parent configuration and context_hash. Media-creative IDs are distinct from their source account_media_id. Deleted tombstones may retain ACTIVE.', input: z.object({ account_id: xId, media_creative_id: xId }).strict(), annotations, handler: input => provider.directMedia.get(input.account_id, input.media_creative_id) }),\n defineTool({ ...shared, name: 'x_media_creative_context', description: 'Review an existing Account Media asset, MEDIA ad group and complete bounded association inventory before linking. Binds source, parent, destination and existing associations in context_hash. Supports PREROLL and documented TAP image formats; VAST authoring is unverified.', input: directMediaSelection.extend({ account_id: xId }).strict(), output: creativesOutput.passthrough(), presentation: 'creatives', annotations, handler: ({ account_id, ...input }) => provider.directMedia.context(account_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_create_media_creative', provider: 'x', kind: 'create', destructive: true, description: 'Associate one verified Account Media asset with a MEDIA ad group using context_hash and explicit native ACTIVE acknowledgement. paused_creation requires a PAUSED ad group. WEBSITE_CLICKS needs landing_url; preroll destinations use separate native CTA settings. Checks receipt/readback; no upload, parent edit or replay.', payload: createDirectMedia }),\n guardedWriteTool({ ...shared, name: 'x_delete_media_creative', provider: 'x', kind: 'remove', destructive: true, description: 'Disassociate one exact direct-media ad with expected_context_hash, native DELETE and independent tombstone readback. Preserves Account Media, library assets, other associations and parent status/budgets. No fictitious PUT pause or automatic replay.', payload: deleteDirectMedia }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { createPrerollCta, deletePrerollCta, prerollCtaList, prerollCtaSelection, updatePrerollCta } from './preroll-cta-schemas.js';\nimport { xId } from './schemas.js';\n\nexport function xPrerollCtaTools(provider: XAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'x', catalog: { category: 'creatives' as const, exposure: 'specialist' as const } }, annotations = { readOnly: true };\n return [\n defineTool({ ...shared, name: 'x_preroll_ctas', description: 'Browse native preroll CTA buttons/destinations with cursor paging. Account-wide browsing avoids parent fan-out; inspect an exact CTA for editing. Optional line_item_id enables scoped edit/removal actions bound to full inventory and parent settings. Incomplete edit context stays read-only.', input: prerollCtaList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations, handler: input => provider.prerollCtas.list(input) }),\n defineTool({ ...shared, name: 'x_get_preroll_cta', description: 'Read an exact account-owned preroll CTA, parent and complete active CTA inventory, with context_hash and guarded widget edits. CTA scope is the ad group, not one media association.', input: z.object({ account_id: xId, preroll_call_to_action_id: xId }).strict(), output: creativesOutput.passthrough(), presentation: 'creatives', annotations, handler: input => provider.prerollCtas.get(input.account_id, input.preroll_call_to_action_id) }),\n defineTool({ ...shared, name: 'x_preroll_cta_context', description: 'Review a new preroll button/destination and complete current ad-group CTA inventory before creation. Returns context_hash; requires an existing non-draft PREROLL_VIEWS ad group. Existing CTA settings need explicit update, not an implicit POST replacement.', input: prerollCtaSelection.extend({ account_id: xId }).strict(), annotations, handler: ({ account_id, ...input }) => provider.prerollCtas.context(account_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_create_preroll_cta', provider: 'x', kind: 'create', destructive: true, description: 'Set one native preroll CTA with context_hash and explicit ad-group scope acknowledgement. Refuses existing active CTAs; paused_creation requires a PAUSED ad group. Five native button presets; exact URL/receipt/readback checks. No ad creation, activation or replay.', payload: createPrerollCta }),\n guardedWriteTool({ ...shared, name: 'x_update_preroll_cta', provider: 'x', kind: 'update', destructive: true, description: 'Edit supplied native CTA button/destination fields with expected_context_hash and ad-group scope acknowledgement. Sends only actual changes, preserves omitted fields and parent settings, and verifies the receipt plus independent readback. Affects the ad group’s preroll ads.', payload: updatePrerollCta }),\n guardedWriteTool({ ...shared, name: 'x_delete_preroll_cta', provider: 'x', kind: 'remove', destructive: true, description: 'Remove one exact preroll CTA with expected_context_hash and ad-group scope acknowledgement. Checks native tombstone and remaining CTA inventory; retains media, ads and parent delivery/budgets. Removing a CTA does not pause ads; no automatic replay.', payload: deletePrerollCta }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { accountMediaUsage, deleteAccountMedia } from './account-media-schemas.js';\nimport type { XAdsProvider } from './provider.js';\n\nexport function xAccountMediaTools(provider: XAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'x', catalog: { category: 'creatives' as const, exposure: 'specialist' as const } };\n return [\n defineTool({ ...shared, name: 'x_account_media_usage', description: 'Inspect one Account Media source and complete bounded usage, including deleted-parent references. Reference details are paged; later offsets require the original context hash. Returns deletion eligibility; used sources need separately reviewed disassociation first.', input: accountMediaUsage, output: creativesOutput.passthrough(), presentation: 'creatives', annotations: { readOnly: true }, handler: ({ account_id, account_media_id, ...input }) => provider.accountMedia.usage(account_id, account_media_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_delete_account_media', provider: 'x', kind: 'remove', destructive: true, description: 'Delete one unused native Account Media source with expected_context_hash and explicit source-deletion acknowledgement. Requires a complete usage scan with no non-deleted ad associations; checks DELETE receipt and independent source/usage readback. No automatic detach, library deletion or retry.', payload: deleteAccountMedia }),\n ];\n}\n","import { creativesOutput, defineTool, guardedWriteTool, type AnyToolDefinition } from '@adport/core';\nimport { z } from 'zod';\nimport type { XAdsProvider } from './provider.js';\nimport { createPromotedAccount, deletePromotedAccount, promotedAccountList, promotedAccountSelection } from './promoted-account-schemas.js';\nimport { xId } from './schemas.js';\n\nexport function xPromotedAccountTools(provider: XAdsProvider): AnyToolDefinition[] {\n const shared = { namespace: 'x', catalog: { category: 'creatives' as const, exposure: 'specialist' as const } };\n return [\n defineTool({ ...shared, name: 'x_promoted_accounts', description: 'View profile-ad associations in one verified PROMOTED_ACCOUNT ad group, with cursor paging, profile links and guarded removal. Native ACTIVE is association state; parent delivery remains separate.', input: promotedAccountList, output: creativesOutput.passthrough(), presentation: 'creatives', pagination: { cursorInput: 'cursor' }, annotations: { readOnly: true }, handler: input => provider.promotedAccounts.list(input) }),\n defineTool({ ...shared, name: 'x_get_promoted_account', description: 'Read one exact promoted-account association, including deleted tombstones, verified parents and context_hash. Profile content is live and is not snapshotted by this Ads endpoint.', input: z.object({ account_id: xId, promoted_account_id: xId }).strict(), annotations: { readOnly: true }, handler: input => provider.promotedAccounts.get(input.account_id, input.promoted_account_id) }),\n defineTool({ ...shared, name: 'x_promoted_account_context', description: 'Review a current FULL promotable user, FOLLOWERS ad group and complete bounded association inventory before linking. Binds identity, parent configuration and existing associations to context_hash; no publication or profile edit.', input: promotedAccountSelection.extend({ account_id: xId }).strict(), output: creativesOutput.passthrough(), presentation: 'creatives', annotations: { readOnly: true }, handler: ({ account_id, ...input }) => provider.promotedAccounts.context(account_id, input) }),\n guardedWriteTool({ ...shared, name: 'x_create_promoted_account', provider: 'x', kind: 'create', destructive: true, description: 'Associate one verified FULL promotable profile using expected_context_hash and explicit ACTIVE/live-profile acknowledgements. paused_creation requires a PAUSED ad group. Rejects duplicates, checks receipt and readback, and never retries an uncertain write.', payload: createPromotedAccount }),\n guardedWriteTool({ ...shared, name: 'x_delete_promoted_account', provider: 'x', kind: 'remove', destructive: true, description: 'Disassociate one exact profile ad with expected_context_hash, native DELETE and independent tombstone readback. Preserves the X profile, other ads, parent delivery and budgets. No profile deletion or fictitious PUT status edit.', payload: deletePromotedAccount }),\n ];\n}\n","import { AdportError } from '@adport/core';\nimport { createXSigner, type XAdsCredentials } from './client.js';\n\ntype App = Pick<XAdsCredentials, 'consumerKey' | 'consumerSecret'>;\nexport interface XUserTokens { accessToken: string; accessTokenSecret: string }\nexport interface XRequestTokens { requestToken: string; requestTokenSecret: string }\nconst REQUEST_TOKEN_URL = 'https://api.x.com/oauth/request_token';\nconst ACCESS_TOKEN_URL = 'https://api.x.com/oauth/access_token';\nconst INVALIDATE_TOKEN_URL = 'https://api.x.com/1.1/oauth/invalidate_token.json';\nconst LIMIT = 16 * 1024;\n\nfunction validToken(value: unknown): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= 4096 && !/[\\s\\x00-\\x1f\\x7f]/.test(value);\n}\nfunction requireValues(...values: unknown[]): void {\n if (!values.every(validToken)) throw new AdportError('INVALID_INPUT', 'x: OAuth credentials or verifier are missing or malformed');\n}\nfunction failure(message: string): AdportError { return new AdportError('PROVIDER_ERROR', `x: ${message}`); }\n\nasync function textBody(response: Response): Promise<string> {\n const reader = response.body?.getReader();\n if (!reader) throw failure('empty OAuth response');\n const chunks: Uint8Array[] = []; let length = 0;\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n length += value.byteLength;\n if (length > LIMIT) { await reader.cancel(); throw failure('OAuth response exceeded size limit'); }\n chunks.push(value);\n }\n return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));\n } catch { throw failure('invalid or oversized OAuth response'); }\n finally { reader.releaseLock(); }\n}\n\nasync function signedPost(app: App, url: string, parameters: Record<string, string>, token: { key: string; secret: string } | undefined, fetchImpl: typeof fetch): Promise<Response> {\n requireValues(app.consumerKey, app.consumerSecret);\n const signer = createXSigner(app);\n // OAuth-specific parameters belong in the Authorization header. Include\n // them in the signature once, and send no query string or request body.\n const authorization = signer.authorize({ method: 'POST', url, data: parameters }, token);\n let response: Response;\n try {\n response = await fetchImpl(url, { method: 'POST', headers: { ...signer.toHeader({ ...authorization, ...parameters }) }, redirect: 'error', signal: AbortSignal.timeout(30_000) });\n } catch { throw failure('OAuth transport failed; restart authorization rather than replaying the exchange'); }\n if (response.status !== 200) throw failure(`OAuth request failed (HTTP ${response.status})`);\n return response;\n}\n\nasync function tokens(response: Response): Promise<URLSearchParams> {\n // The official examples return form-encoded tokens, not JSON, despite the\n // generic endpoint metadata saying JSON. Reject duplicate token fields.\n const values = new URLSearchParams(await textBody(response));\n for (const key of ['oauth_token', 'oauth_token_secret']) {\n if (values.getAll(key).length !== 1 || !validToken(values.get(key))) throw failure('malformed OAuth token response');\n }\n return values;\n}\n\nexport async function requestXToken(app: App, callback: string, fetchImpl: typeof fetch = fetch): Promise<XRequestTokens> {\n let url: URL;\n try { url = new URL(callback); } catch { throw new AdportError('INVALID_INPUT', 'x: an exact registered HTTPS callback is required'); }\n if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) throw new AdportError('INVALID_INPUT', 'x: an exact registered HTTPS callback without query or fragment is required');\n const values = await tokens(await signedPost(app, REQUEST_TOKEN_URL, { oauth_callback: url.href }, undefined, fetchImpl));\n if (values.getAll('oauth_callback_confirmed').length !== 1 || values.get('oauth_callback_confirmed') !== 'true') throw failure('OAuth callback was not confirmed');\n return { requestToken: values.get('oauth_token')!, requestTokenSecret: values.get('oauth_token_secret')! };\n}\n\nexport function buildXAuthorizationUrl(requestToken: string): string {\n requireValues(requestToken);\n return `https://api.x.com/oauth/authorize?${new URLSearchParams({ oauth_token: requestToken })}`;\n}\n\nexport async function exchangeXToken(app: App, request: XRequestTokens, verifier: string, fetchImpl: typeof fetch = fetch): Promise<XUserTokens> {\n requireValues(request.requestToken, request.requestTokenSecret, verifier);\n const values = await tokens(await signedPost(app, ACCESS_TOKEN_URL, { oauth_verifier: verifier }, { key: request.requestToken, secret: request.requestTokenSecret }, fetchImpl));\n return { accessToken: values.get('oauth_token')!, accessTokenSecret: values.get('oauth_token_secret')! };\n}\n\nexport async function revokeXToken(credentials: XAdsCredentials, fetchImpl: typeof fetch = fetch): Promise<void> {\n requireValues(credentials.accessToken, credentials.accessTokenSecret);\n const response = await signedPost(credentials, INVALIDATE_TOKEN_URL, {}, { key: credentials.accessToken, secret: credentials.accessTokenSecret }, fetchImpl);\n let value: unknown;\n try { value = JSON.parse(await textBody(response)); } catch { throw failure('invalid OAuth revocation response'); }\n if (!value || typeof value !== 'object' || !('access_token' in value) || value.access_token !== credentials.accessToken) throw failure('OAuth revocation was not confirmed for this token');\n}\n","export { XAdsClient, X_ADS_API_BASE, type XAdsCredentials, type XParams } from './client.js';\nexport { XAdsEntities } from './entities.js';\nexport { XAdsProvider } from './provider.js';\nexport { XAdsAnalytics } from './analytics.js';\nexport { xTools } from './tools.js';\nexport { requestXToken, buildXAuthorizationUrl, exchangeXToken, revokeXToken, type XRequestTokens, type XUserTokens } from './oauth.js';\n\nimport { type CredentialStore, type ProviderModule } from '@adport/core';\nimport { XAdsClient, type XAdsCredentials } from './client.js';\nimport { XAdsProvider } from './provider.js';\nimport { xTools } from './tools.js';\n\nexport function xCredentialsFromData(data: Record<string, string> | undefined): XAdsCredentials | undefined {\n if (!data?.consumer_key?.trim() || !data.consumer_secret?.trim() || !data.access_token?.trim() || !data.access_token_secret?.trim()) return undefined;\n return { consumerKey: data.consumer_key, consumerSecret: data.consumer_secret, accessToken: data.access_token, accessTokenSecret: data.access_token_secret };\n}\nexport function xEnvironmentData(): Record<string, string> {\n return { consumer_key: process.env.X_CONSUMER_KEY ?? '', consumer_secret: process.env.X_CONSUMER_SECRET ?? '', access_token: process.env.X_ACCESS_TOKEN ?? '', access_token_secret: process.env.X_ACCESS_TOKEN_SECRET ?? '' };\n}\nexport async function resolveXCredentials(store: CredentialStore): Promise<XAdsCredentials | undefined> {\n return xCredentialsFromData((await store.get('x'))?.data) ?? xCredentialsFromData(xEnvironmentData());\n}\nexport async function createXModule(store: CredentialStore): Promise<ProviderModule | undefined> {\n const credentials = await resolveXCredentials(store);\n if (!credentials) return undefined;\n const provider = new XAdsProvider(new XAdsClient(credentials));\n return { provider, tools: xTools(provider) };\n}\n"],"mappings":";AAAA,SAAS,YAAY,aAAa,uBAAuB;AACzD,OAAO,WAAW;AAClB,SAAS,SAAS;AAClB,SAAS,mBAAmB;AAErB,IAAM,iBAAiB;AAUvB,SAAS,cAAc,aAA6E;AACzG,QAAM,QAAQ,IAAI,MAAM;AAAA,IACtB,UAAU,EAAE,KAAK,YAAY,aAAa,QAAQ,YAAY,eAAe;AAAA,IAC7E,kBAAkB;AAAA,IAClB,eAAe,CAAC,MAAM,QAAQ,WAAW,QAAQ,GAAG,EAAE,OAAO,IAAI,EAAE,OAAO,QAAQ;AAAA,EACpF,CAAC;AAED,QAAM,WAAW,MAAM,YAAY,EAAE,EAAE,SAAS,KAAK;AACrD,SAAO;AACT;AAEO,IAAM,aAAN,MAAiB;AAAA,EAItB,YAAY,aAA+C,YAA0B,OAAO;AAAjC;AACzD,QAAI,OAAO,OAAO,WAAW,EAAE,KAAK,WAAS,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,CAAC,KACrF,CAAC,YAAY,eAAe,CAAC,YAAY,kBAAkB,CAAC,YAAY,eAAe,CAAC,YAAY,mBAAmB;AACvH,YAAM,IAAI,YAAY,iBAAiB,iDAAiD;AAAA,IAC1F;AACA,SAAK,SAAS,cAAc,WAAW;AACvC,SAAK,QAAQ,EAAE,KAAK,YAAY,aAAa,QAAQ,YAAY,kBAAkB;AACnF,SAAK,aAAa,WAAW,UAAU,YAAY,cAAc,EAAE,OAAO,qBAAqB,YAAY,iBAAiB,EAAE,EAAE,OAAO;AAAA,EACzI;AAAA,EAR2D;AAAA,EAH1C;AAAA,EACA;AAAA,EACA;AAAA,EAWjB,MAAM,QAAW,QAAiB,MAAc,QAAsB,SAAkB,CAAC,GAAG,UAAgC;AAC1H,QAAI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BAAqB,IAAI,cAAc,QAAQ,IAAI,kBAAkB,IAAI,qBAAqB,QAAQ,IAAI,yBAAyB,GAAG;AAC9N;AACA,eAAsB,oBAAoB,OAA8D;AACtG,SAAO,sBAAsB,MAAM,MAAM,IAAI,GAAG,IAAI,IAAI,KAAK,qBAAqB,iBAAiB,CAAC;AACtG;AACA,eAAsB,cAAc,OAA6D;AAC/F,QAAM,cAAc,MAAM,oBAAoB,KAAK;AACnD,MAAI,CAAC,YAAa,QAAO;AACzB,QAAM,WAAW,IAAI,aAAa,IAAI,WAAW,WAAW,CAAC;AAC7D,SAAO,EAAE,UAAU,OAAO,OAAO,QAAQ,EAAE;AAC7C;","names":["url","ids","rows","cursor","page","z","AdportError","z","z","AdportError","z","AdportError","z","AdportError","z","AdportError","url","ids","target","z","AdportError","AdportError","z","AdportError","z","z","micros","z","name","objective","AdportError","micros","currency","matches","z","value","target","ids","AdportError","z","defineTool","guardedWriteTool","z","z","defineTool","guardedWriteTool","z","AdportError","value","page","ids","cursor","audience","values","add","AdportError","z","defineTool","guardedWriteTool","z","z","name","defineTool","guardedWriteTool","z","url","rows","ids","cursor","page","AdportError","user","values","value","input","current","fields","expected","key","AdportError","z","defineTool","guardedWriteTool","z","z","guardedWriteTool","defineTool","z","AdportError","user","input","bound","AdportError","z","z","z","url","z","AdportError","layout","destination","unique","rows","name","createHash","AdportError","z","defineTool","guardedWriteTool","z","hash","z","name","values","defineTool","guardedWriteTool","z","criterion","canonical","createHash","AdportError","page","rows","ids","cursor","values","input","createHash","AdportError","z","defineTool","guardedWriteTool","z","ids","z","page","hash","defineTool","guardedWriteTool","z","canonical","configuration","snapshot","createHash","notes","rejection","AdportError","value","ids","rows","data","createHash","AdportError","z","z","values","z","url","z","canonical","hash","createHash","equal","safeUrl","url","user","matches","AdportError","ids","cursor","page","rows","notices","input","row","copy","current","createHash","AdportError","z","z","unique","values","mediaKeys","z","canonical","equal","hash","createHash","sourceConfig","pageSchema","z","user","matches","AdportError","ids","rows","cursor","page","time","values","notes","input","current","source","createHash","AdportError","z","z","hash","z","page","values","url","pageSchema","z","canonical","hash","createHash","configuration","equal","url","notice","AdportError","ids","rows","cursor","page","destination","notes","input","matches","createHash","AdportError","z","z","hash","z","destination","url","pageSchema","z","canonical","hash","createHash","equal","config","rows","url","notices","AdportError","ids","cursor","page","destination","fields","notes","input","expected","createHash","AdportError","z","z","z","page","z","canonical","hash","createHash","configuration","ids","cursor","AdportError","notes","createHash","AdportError","z","z","hash","z","pageSchema","z","canonical","hash","createHash","configuration","equal","notice","AdportError","ids","rows","cursor","page","row","matches","user","notes","input","z","AdportError","rows","placement","values","z","defineTool","guardedWriteTool","creativesOutput","defineTool","guardedWriteTool","z","defineTool","creativesOutput","z","guardedWriteTool","creativesOutput","defineTool","guardedWriteTool","z","defineTool","creativesOutput","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","z","defineTool","creativesOutput","guardedWriteTool","z","creativesOutput","defineTool","guardedWriteTool","z","defineTool","creativesOutput","z","guardedWriteTool","creativesOutput","defineTool","guardedWriteTool","z","defineTool","creativesOutput","z","guardedWriteTool","creativesOutput","defineTool","guardedWriteTool","defineTool","creativesOutput","guardedWriteTool","creativesOutput","defineTool","guardedWriteTool","z","defineTool","creativesOutput","z","guardedWriteTool","defineTool","z","guardedWriteTool","AdportError","values","AdportError","app","url","request"]}
|