@adport/provider-tiktok 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -72,7 +72,8 @@ var TikTokClient = class {
72
72
  }
73
73
  const envelope = JSON.parse(raw);
74
74
  if (envelope.code !== 0) {
75
- const hint = CODE_HINTS[envelope.code];
75
+ const pixelPermission = ["pixel/list", "pixel/event/stats"].includes(path2?.replace(/^\/|\/$/g, "") ?? "") && envelope.code === 40001;
76
+ const hint = pixelPermission ? "Pixel access was denied. Check the developer app\u2019s Pixel/measurement permission and this advertiser\u2019s grant. After the app gains approval, reconnect TikTok in Adport Cloud (or run `adport connect tiktok`) and select the same advertiser. Reconnecting alone cannot add an unapproved app permission." : CODE_HINTS[envelope.code];
76
77
  throw new AdportError(
77
78
  "PROVIDER_ERROR",
78
79
  `TikTok API error ${envelope.code}: ${envelope.message}${hint ? `
@@ -86,7 +87,7 @@ var TikTokClient = class {
86
87
 
87
88
  // src/provider.ts
88
89
  import {
89
- AdportError as AdportError21,
90
+ AdportError as AdportError22,
90
91
  LocalMediaResolver,
91
92
  resolveDateRange
92
93
  } from "@adport/core";
@@ -1333,21 +1334,21 @@ function tiktokAutomatedRuleTools(provider) {
1333
1334
  }
1334
1335
 
1335
1336
  // src/catalogs.ts
1336
- import { createHash as createHash13 } from "crypto";
1337
- import { AdportError as AdportError19 } from "@adport/core";
1338
- import { z as z21 } from "zod";
1337
+ import { createHash as createHash14 } from "crypto";
1338
+ import { AdportError as AdportError20 } from "@adport/core";
1339
+ import { z as z22 } from "zod";
1339
1340
 
1340
1341
  // src/catalog-tools.ts
1341
1342
  import { creativesOutput, defineTool as defineTool4, guardedWriteTool as guardedWriteTool3 } from "@adport/core";
1342
- import { z as z20 } from "zod";
1343
+ import { z as z21 } from "zod";
1343
1344
 
1344
1345
  // src/catalog-schema.ts
1345
1346
  import { z as z9 } from "zod";
1346
1347
  var catalogId = z9.string().regex(/^\d{1,30}$/);
1347
1348
  var catalogInput = z9.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId }).strict();
1348
- var catalogPermissionSelection = z9.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId.optional(), resource_kind: z9.enum(["catalog", "catalog_creation"]).optional() }).strict();
1349
- var validCatalogPermission = (input) => input.resource_kind === "catalog_creation" ? !input.catalog_id && (!input.mode || ["none", "create"].includes(input.mode)) : !!input.catalog_id && input.mode !== "create";
1350
- var catalogPermissionSnapshot = catalogPermissionSelection.refine(validCatalogPermission, "Choose an exact catalog or creation delegation without a catalog ID");
1349
+ var catalogPermissionSelection = z9.object({ account_id: catalogId, bc_id: catalogId, catalog_id: catalogId.optional(), resource_kind: z9.enum(["catalog", "catalog_creation", "catalog_migration"]).optional() }).strict();
1350
+ var validCatalogPermission = (input) => input.resource_kind === "catalog_creation" ? !input.catalog_id && (!input.mode || ["none", "create"].includes(input.mode)) : input.resource_kind === "catalog_migration" ? !!input.catalog_id && (!input.mode || input.mode === "none" || input.mode === "migrate" && input.acknowledge_source_ownership === true && input.acknowledge_shared_effects === true) : !!input.catalog_id && (!input.mode || ["none", "read", "write"].includes(input.mode));
1351
+ var catalogPermissionSnapshot = catalogPermissionSelection.refine(validCatalogPermission, "Choose an exact catalog/transfer, or creation delegation without a catalog ID");
1351
1352
 
1352
1353
  // src/catalog-product-sets.ts
1353
1354
  import { createHash as createHash6 } from "crypto";
@@ -1561,14 +1562,14 @@ var TikTokCatalogProductSets = class {
1561
1562
  await this.authorizeParent(scope, true);
1562
1563
  const current = (await this.native(scope, input.product_set_id))[0];
1563
1564
  if (hash4(scope, current) !== input.expected_configuration_hash) throw new AdportError10("INVALID_INPUT", "Product-set configuration changed. Read and preview it again.");
1564
- const notes6 = ["The set may be reused by other ads or accounts. Only its name changes; filter conditions are preserved.", "Preview is local. TikTok checks native eligibility on apply. No ads are activated or tracking events sent.", "An uncertain result retains the known set ID. Inspect it before another write; never replay automatically."];
1565
+ const notes7 = ["The set may be reused by other ads or accounts. Only its name changes; filter conditions are preserved.", "Preview is local. TikTok checks native eligibility on apply. No ads are activated or tracking events sent.", "An uncertain result retains the known set ID. Inspect it before another write; never replay automatically."];
1565
1566
  return {
1566
1567
  summary: `Rename TikTok product set ${current.product_set_name}`,
1567
1568
  changes: [`~ Product-set name ${JSON.stringify(current.product_set_name)} \u2192 ${JSON.stringify(input.product_set_name)}`],
1568
1569
  coercions: [],
1569
1570
  budgetDeltas: [],
1570
- notes: notes6,
1571
- review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Rename product set", subject: current.product_set_name, fields: [{ label: "Name", before: current.product_set_name, after: input.product_set_name }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices: notes6 },
1571
+ notes: notes7,
1572
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Rename product set", subject: current.product_set_name, fields: [{ label: "Name", before: current.product_set_name, after: input.product_set_name }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices: notes7 },
1572
1573
  execute: async () => {
1573
1574
  await this.authorizeParent(scope, true);
1574
1575
  try {
@@ -1606,14 +1607,14 @@ var TikTokCatalogProductSets = class {
1606
1607
  return { file, count: skus.size };
1607
1608
  };
1608
1609
  const prepared = await prepare();
1609
- const notes6 = ["Creates an E-commerce set from the exact approved CSV; no ads are activated or budgets changed.", "Adport caps the template at 5,000 SKU rows. TikTok checks SKU eligibility and membership on apply; independent readback confirms the set ID/name, not full membership or ingestion.", "No automatic retry. Reconcile an uncertain creation by its known ID or unique name before another upload."];
1610
+ const notes7 = ["Creates an E-commerce set from the exact approved CSV; no ads are activated or budgets changed.", "Adport caps the template at 5,000 SKU rows. TikTok checks SKU eligibility and membership on apply; independent readback confirms the set ID/name, not full membership or ingestion.", "No automatic retry. Reconcile an uncertain creation by its known ID or unique name before another upload."];
1610
1611
  return {
1611
1612
  summary: `Create TikTok product set ${input.product_set_name} from CSV`,
1612
1613
  changes: [`+ Product set ${JSON.stringify(input.product_set_name)} from ${prepared.count} SKU rows`, `+ File ${JSON.stringify(prepared.file.name)}; ${prepared.file.bytes.byteLength} bytes; SHA-256 ${prepared.file.sha256}`],
1613
1614
  coercions: [],
1614
1615
  budgetDeltas: [],
1615
- notes: notes6,
1616
- review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "File", after: prepared.file.name }, { label: "SKU rows", after: String(prepared.count) }, { label: "SHA-256", after: prepared.file.sha256 }], notices: notes6 },
1616
+ notes: notes7,
1617
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "File", after: prepared.file.name }, { label: "SKU rows", after: String(prepared.count) }, { label: "SHA-256", after: prepared.file.sha256 }], notices: notes7 },
1617
1618
  execute: async () => {
1618
1619
  const { file } = await prepare();
1619
1620
  const form = new FormData();
@@ -1643,14 +1644,14 @@ var TikTokCatalogProductSets = class {
1643
1644
  if (parent.configuration_hash !== input.expected_catalog_hash) throw new AdportError10("INVALID_INPUT", "Catalog configuration changed. Read the catalog and review creation again.");
1644
1645
  };
1645
1646
  await verifyParent();
1646
- const notes6 = ["Creates a filter-defined set in the selected catalog; it does not create or activate an ad.", "Field names and catalog-specific values are checked by TikTok on apply; this is a local preview. Adport allows up to 1,024 combined values.", "No automatic retry. An unknown creation outcome must be reconciled before another create."];
1647
+ const notes7 = ["Creates a filter-defined set in the selected catalog; it does not create or activate an ad.", "Field names and catalog-specific values are checked by TikTok on apply; this is a local preview. Adport allows up to 1,024 combined values.", "No automatic retry. An unknown creation outcome must be reconciled before another create."];
1647
1648
  return {
1648
1649
  summary: `Create TikTok product set ${input.product_set_name}`,
1649
1650
  changes: [`+ Product set ${JSON.stringify(input.product_set_name)}`, `+ Product selection ${canonical6(input.conditions)}`],
1650
1651
  coercions: [],
1651
1652
  budgetDeltas: [],
1652
- notes: notes6,
1653
- review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Create product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Product selection", after: describeProductSetConditions(input.conditions), format: "text" }], notices: notes6 },
1653
+ notes: notes7,
1654
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Create product set", subject: input.product_set_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Product selection", after: describeProductSetConditions(input.conditions), format: "text" }], notices: notes7 },
1654
1655
  execute: async () => {
1655
1656
  await verifyParent();
1656
1657
  let createdId;
@@ -1671,14 +1672,14 @@ var TikTokCatalogProductSets = class {
1671
1672
  await this.authorizeParent(scope, true);
1672
1673
  const current = (await this.native(scope, input.product_set_id))[0];
1673
1674
  if (hash4(scope, current) !== input.expected_configuration_hash) throw new AdportError10("INVALID_INPUT", "Product-set configuration changed. Read and review it again.");
1674
- const notes6 = ["Replaces the complete filter definition. Existing ads using this shared set may select different products after apply.", "The name is preserved. No ad is activated and no budget or tracking event is changed.", "Catalog-specific fields and values are checked by TikTok on apply; preview is local. No automatic retry after an uncertain result."];
1675
+ const notes7 = ["Replaces the complete filter definition. Existing ads using this shared set may select different products after apply.", "The name is preserved. No ad is activated and no budget or tracking event is changed.", "Catalog-specific fields and values are checked by TikTok on apply; preview is local. No automatic retry after an uncertain result."];
1675
1676
  return {
1676
1677
  summary: `Change TikTok product selection for ${current.product_set_name}`,
1677
1678
  changes: [`~ Product selection ${canonical6(current.conditions)} \u2192 ${canonical6(input.conditions)}`],
1678
1679
  coercions: [],
1679
1680
  budgetDeltas: [],
1680
- notes: notes6,
1681
- review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Change product selection", subject: current.product_set_name, fields: [{ label: "Product selection", before: describeProductSetConditions(current.conditions), after: describeProductSetConditions(input.conditions), format: "text" }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices: notes6 },
1681
+ notes: notes7,
1682
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Change product selection", subject: current.product_set_name, fields: [{ label: "Product selection", before: describeProductSetConditions(current.conditions), after: describeProductSetConditions(input.conditions), format: "text" }, { label: "Catalog", after: input.catalog_id }, { label: "Product set", after: input.product_set_id }], notices: notes7 },
1682
1683
  execute: async () => {
1683
1684
  await this.authorizeParent(scope, true);
1684
1685
  try {
@@ -1703,14 +1704,14 @@ var TikTokCatalogProductSets = class {
1703
1704
  current.push(row3);
1704
1705
  }
1705
1706
  const ids2 = current.map((row3) => row3.product_set_id);
1706
- const notes6 = ["Permanently deletes the selected shared set definitions. Existing ads may reference them; there is no automatic restoration.", "The full selected set list and each configuration hash are checked before apply. TikTok checks native dependencies and eligibility.", "No automatic retry after a partial or uncertain result. Reconcile every known ID before another delete."];
1707
+ const notes7 = ["Permanently deletes the selected shared set definitions. Existing ads may reference them; there is no automatic restoration.", "The full selected set list and each configuration hash are checked before apply. TikTok checks native dependencies and eligibility.", "No automatic retry after a partial or uncertain result. Reconcile every known ID before another delete."];
1707
1708
  return {
1708
1709
  summary: `Delete ${current.length} TikTok product set${current.length === 1 ? "" : "s"}`,
1709
1710
  changes: current.map((row3) => `- Product set ${row3.product_set_id}: ${JSON.stringify(row3.product_set_name)}`),
1710
1711
  coercions: [],
1711
1712
  budgetDeltas: [],
1712
- notes: notes6,
1713
- review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Delete product sets", subject: current.length === 1 ? current[0].product_set_name : `${current.length} product sets`, fields: current.map((row3) => ({ label: `Product set ${row3.product_set_id}`, before: row3.product_set_name, after: "Permanently deleted" })), notices: notes6 },
1713
+ notes: notes7,
1714
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Delete product sets", subject: current.length === 1 ? current[0].product_set_name : `${current.length} product sets`, fields: current.map((row3) => ({ label: `Product set ${row3.product_set_id}`, before: row3.product_set_name, after: "Permanently deleted" })), notices: notes7 },
1714
1715
  execute: async () => {
1715
1716
  await this.authorizeParent(scope, true);
1716
1717
  try {
@@ -1919,15 +1920,15 @@ var TikTokCatalogFeeds = class {
1919
1920
  if (op.provider !== "tiktok" || !Object.hasOwn(kinds, op.tool) || op.kind !== kinds[op.tool]) throw new AdportError11("INVALID_INPUT", "TikTok feed operation/provider kind mismatch.");
1920
1921
  const create = op.tool === "tiktok_create_catalog_feed", input = create ? catalogFeedCreate.parse(op.payload) : op.tool === "tiktok_update_catalog_feed" ? catalogFeedUpdate.parse(op.payload) : op.tool === "tiktok_set_catalog_feed_schedule_status" ? catalogFeedSwitch.parse(op.payload) : catalogFeedDelete.parse(op.payload);
1921
1922
  const scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), parent = await this.authorizeParent(scope, true);
1922
- const review = (title2, subject, fields2, notes7) => ({ provider: "tiktok", accountId: scope.account_id, kind: op.kind, title: title2, subject, fields: [{ label: "Catalog", after: input.catalog_id }, ...fields2], notices: notes7 });
1923
+ const review = (title2, subject, fields2, notes8) => ({ provider: "tiktok", accountId: scope.account_id, kind: op.kind, title: title2, subject, fields: [{ label: "Catalog", after: input.catalog_id }, ...fields2], notices: notes8 });
1923
1924
  if ("expected_catalog_hash" in input) {
1924
1925
  if (input.expected_catalog_hash !== parent.configuration_hash) throw new AdportError11("INVALID_INPUT", "Catalog configuration changed. Read and review feed creation again.");
1925
1926
  if (input.feed_type === "COUNTRY_FEED" && parent.catalog_conf.is_multi_country !== true) throw new AdportError11("INVALID_INPUT", "A country feed requires a verified multi-country catalog. Native existing-product eligibility is checked on apply.");
1926
1927
  const sourceSecrets = input.schedule_param ? [input.schedule_param.source.uri, input.schedule_param.source.username, input.schedule_param.source.password].filter((item) => typeof item === "string" && item.length > 0) : [];
1927
1928
  const displayName = sourceSecrets.reduce((name4, secret) => name4.replaceAll(secret, "[redacted]"), input.feed_name);
1928
1929
  const fields2 = [{ label: "Name", after: displayName }, { label: "Update mode", after: input.update_mode }, ...input.feed_type ? [{ label: "Feed type", after: input.feed_type }] : [], ...scheduleFields(input.schedule_param)];
1929
- const notes7 = [input.schedule_param ? "Supplying a source schedule can start automatic native product processing immediately. OVERWRITE can remove products missing from the source." : "No source schedule is supplied. The created feed must remain OFF with no source URI.", "Country feeds also require existing products; native eligibility is checked on apply.", ...commonNotes];
1930
- return { summary: `Create TikTok catalog feed ${displayName}`, changes: fields2.map((field) => `+ ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes7, review: review("Create catalog feed", displayName, fields2, notes7), execute: async () => {
1930
+ const notes8 = [input.schedule_param ? "Supplying a source schedule can start automatic native product processing immediately. OVERWRITE can remove products missing from the source." : "No source schedule is supplied. The created feed must remain OFF with no source URI.", "Country feeds also require existing products; native eligibility is checked on apply.", ...commonNotes];
1931
+ return { summary: `Create TikTok catalog feed ${displayName}`, changes: fields2.map((field) => `+ ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes8, review: review("Create catalog feed", displayName, fields2, notes8), execute: async () => {
1931
1932
  const fresh = await this.authorizeParent(scope, true);
1932
1933
  if (fresh.configuration_hash !== input.expected_catalog_hash) throw new AdportError11("INVALID_INPUT", "Catalog changed before creating the feed. Review again.");
1933
1934
  let createdId;
@@ -1945,12 +1946,12 @@ var TikTokCatalogFeeds = class {
1945
1946
  }
1946
1947
  const current = (await this.native(scope, input.feed_id))[0], name3 = publicText(current.feed_name, current);
1947
1948
  if (input.expected_configuration_hash !== configurationHash(scope, current)) throw new AdportError11("INVALID_INPUT", "Feed configuration changed. Read and review it again.");
1948
- let path2, body, expected = config(current), fields, notes6;
1949
+ let path2, body, expected = config(current), fields, notes7;
1949
1950
  if (op.tool === "tiktok_delete_catalog_feed") {
1950
1951
  path2 = "catalog/feed/delete";
1951
1952
  body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id };
1952
1953
  fields = [{ label: "Feed", before: name3, after: "Permanently deleted" }];
1953
- notes6 = ["Permanently removes this shared feed. Review dependent catalog products and ads; no restoration or compensating write is automatic.", ...commonNotes];
1954
+ notes7 = ["Permanently removes this shared feed. Review dependent catalog products and ads; no restoration or compensating write is automatic.", ...commonNotes];
1954
1955
  } else if (op.tool === "tiktok_set_catalog_feed_schedule_status") {
1955
1956
  const targetStatus = catalogFeedSwitch.parse(input).status;
1956
1957
  if (!current.status || current.status === targetStatus) throw new AdportError11("INVALID_INPUT", "Schedule status must be known and change to the opposite ON/OFF value.");
@@ -1960,7 +1961,7 @@ var TikTokCatalogFeeds = class {
1960
1961
  body = { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_id: input.feed_id, status: targetStatus };
1961
1962
  expected = { ...expected, status: targetStatus };
1962
1963
  fields = [{ label: "Automatic processing", before: current.status, after: targetStatus }, { label: "Source", after: { origin: origin(source2?.uri), fingerprint: source2?.uri ? digest5(source2.uri) : "Not configured" } }];
1963
- notes6 = ["ON resumes automatic product processing and may change products selected by existing ads. OFF stops future scheduled runs; it does not undo previous imports.", ...commonNotes];
1964
+ notes7 = ["ON resumes automatic product processing and may change products selected by existing ads. OFF stops future scheduled runs; it does not undo previous imports.", ...commonNotes];
1964
1965
  } else {
1965
1966
  const update = catalogFeedUpdate.parse(input);
1966
1967
  path2 = "catalog/feed/update";
@@ -1968,10 +1969,10 @@ var TikTokCatalogFeeds = class {
1968
1969
  expected = { ...expected, schedule: { ...expected.schedule, update_mode: update.update_mode } };
1969
1970
  if (update.schedule_param) expected.schedule = { ...expected.schedule, ...scheduleConfig({ ...update.schedule_param, uri: update.schedule_param.source.uri, update_mode: update.update_mode }) };
1970
1971
  fields = [{ label: "Update mode", before: current.last_update_param?.update_mode ?? "Not reported", after: update.update_mode }, ...scheduleFields(update.schedule_param, current)];
1971
- notes6 = ["Replaces the supplied source/schedule configuration. Existing automatic runs can use it immediately; OVERWRITE can remove products missing from the source.", "Supply any required source authentication explicitly when replacing the schedule. Native credential values are unavailable for preservation/readback.", ...commonNotes];
1972
+ notes7 = ["Replaces the supplied source/schedule configuration. Existing automatic runs can use it immediately; OVERWRITE can remove products missing from the source.", "Supply any required source authentication explicitly when replacing the schedule. Native credential values are unavailable for preservation/readback.", ...commonNotes];
1972
1973
  }
1973
1974
  const remove = op.kind === "remove", title = remove ? "Delete catalog feed" : "status" in input ? "Change feed schedule status" : "Update catalog feed";
1974
- return { summary: `${title} ${name3}`, changes: fields.map((field) => `${remove ? "-" : "~"} ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes6, review: review(title, name3, fields, notes6), execute: async () => {
1975
+ return { summary: `${title} ${name3}`, changes: fields.map((field) => `${remove ? "-" : "~"} ${field.label}: ${JSON.stringify(field.after)}`), coercions: [], budgetDeltas: [], notes: notes7, review: review(title, name3, fields, notes7), execute: async () => {
1975
1976
  await this.authorizeParent(scope, true);
1976
1977
  try {
1977
1978
  const raw = await this.client.post(path2, body);
@@ -2210,14 +2211,14 @@ var TikTokCatalogProducts = class {
2210
2211
  return { parent, feed: feed2, file, rowCount, columns: header.length };
2211
2212
  };
2212
2213
  const initial = await prepare();
2213
- const notes6 = ["Submits a one-time asynchronous import into this existing feed. Native processing validates catalog-specific columns, feed ownership and product eligibility; local CSV validation does not certify the provider template.", input.update_mode === "OVERWRITE" ? "OVERWRITE removes existing feed products missing from this file and can change ads using them." : "INCREMENTAL adds products and updates matching products; products omitted from the CSV remain.", "This request does not change the feed\u2019s saved update mode or activate ads. Feed scheduling is managed separately; read fresh feed state before changing automation.", "The result is an accepted task ID, not completed ingestion. Read tiktok_catalog_product_log until terminal and inspect item errors. Never automatically replay an uncertain import."];
2214
+ const notes7 = ["Submits a one-time asynchronous import into this existing feed. Native processing validates catalog-specific columns, feed ownership and product eligibility; local CSV validation does not certify the provider template.", input.update_mode === "OVERWRITE" ? "OVERWRITE removes existing feed products missing from this file and can change ads using them." : "INCREMENTAL adds products and updates matching products; products omitted from the CSV remain.", "This request does not change the feed\u2019s saved update mode or activate ads. Feed scheduling is managed separately; read fresh feed state before changing automation.", "The result is an accepted task ID, not completed ingestion. Read tiktok_catalog_product_log until terminal and inspect item errors. Never automatically replay an uncertain import."];
2214
2215
  return {
2215
2216
  summary: `Import ${initial.rowCount} product rows into TikTok feed ${input.feed_id}`,
2216
2217
  changes: [`~ One-time ${input.update_mode} product import into ${initial.feed.feed_type} ${input.feed_id}`, `+ CSV ${JSON.stringify(initial.file.name)}; ${initial.file.bytes.byteLength} bytes; SHA-256 ${initial.file.sha256}`],
2217
2218
  coercions: [],
2218
2219
  budgetDeltas: [],
2219
- notes: notes6,
2220
- review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Import catalog file", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Feed", after: input.feed_id }, { label: "Feed type", after: initial.feed.feed_type }, { label: "Feed schedule", after: initial.feed.status }, { label: "Import mode", after: input.update_mode }, { label: "Product rows", after: String(initial.rowCount) }, { label: "CSV columns", after: String(initial.columns) }, { label: "SHA-256", after: initial.file.sha256 }], notices: notes6 },
2220
+ notes: notes7,
2221
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "update", title: "Import catalog file", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Feed", after: input.feed_id }, { label: "Feed type", after: initial.feed.feed_type }, { label: "Feed schedule", after: initial.feed.status }, { label: "Import mode", after: input.update_mode }, { label: "Product rows", after: String(initial.rowCount) }, { label: "CSV columns", after: String(initial.columns) }, { label: "SHA-256", after: initial.file.sha256 }], notices: notes7 },
2221
2222
  execute: async () => {
2222
2223
  await prepare();
2223
2224
  const grant = await providerUrl(input, { maxBytes: MAX_PROJECT_MEDIA_BYTES2, contentTypes: ["text/csv"] });
@@ -2555,14 +2556,14 @@ var TikTokCatalogProductAuthoring = class {
2555
2556
  }
2556
2557
  }
2557
2558
  if (assets.length) reviewFields.push({ label: "Adport media", after: assets });
2558
- const notes6 = ["Local preview only. TikTok validates native permissions, product fields and feed membership during asynchronous processing.", "Shared catalog changes can change existing ads wherever products or product sets are used; no ad status or budget is changed.", "Acceptance is not completed processing, product audit approval or ad eligibility. Inspect the exact native job, then read product context.", "TikTok permits one active product operation per catalog. Wait for prior jobs; busy/uncertain submissions are never automatically retried.", ...assets.length ? ["Media bytes/checksums are verified at preview and apply. Private download grants are minted only at apply; the payload hash binds logical media references, not an expiring URL.", "Images require at least 500\xD7500 pixels. Native media fetching/audit and any ongoing URL refetch behavior remain unverified; grants expire."] : [], ...upload ? ["Incremental upsert: uploading an existing external identity may replace its product data. Existing configuration was not inspected by this upsert preview."] : remove ? ["Removal cannot be undone through this operation; historical reporting may remain."] : ["Only supplied top-level fields are sent. Nested-object merge behavior remains native; no unverified preservation is promised."], ...reviewTruncated ? [`Review is limited to 20 products and 40 editable fields from ${count5} products; the full submitted payload is bound by its SHA-256 and identical-argument approval.`] : []];
2559
+ const notes7 = ["Local preview only. TikTok validates native permissions, product fields and feed membership during asynchronous processing.", "Shared catalog changes can change existing ads wherever products or product sets are used; no ad status or budget is changed.", "Acceptance is not completed processing, product audit approval or ad eligibility. Inspect the exact native job, then read product context.", "TikTok permits one active product operation per catalog. Wait for prior jobs; busy/uncertain submissions are never automatically retried.", ...assets.length ? ["Media bytes/checksums are verified at preview and apply. Private download grants are minted only at apply; the payload hash binds logical media references, not an expiring URL.", "Images require at least 500\xD7500 pixels. Native media fetching/audit and any ongoing URL refetch behavior remain unverified; grants expire."] : [], ...upload ? ["Incremental upsert: uploading an existing external identity may replace its product data. Existing configuration was not inspected by this upsert preview."] : remove ? ["Removal cannot be undone through this operation; historical reporting may remain."] : ["Only supplied top-level fields are sent. Nested-object merge behavior remains native; no unverified preservation is promised."], ...reviewTruncated ? [`Review is limited to 20 products and 40 editable fields from ${count5} products; the full submitted payload is bound by its SHA-256 and identical-argument approval.`] : []];
2559
2560
  return {
2560
2561
  summary: `${title} \xB7 ${count5} ${type}`,
2561
2562
  changes: [`${remove ? "-" : "~"} ${count5} selected ${type} products in catalog ${input.catalog_id}, feed ${input.feed_id}.`, `Approved native payload SHA-256 ${digest6(body)}.`],
2562
2563
  coercions: [],
2563
2564
  budgetDeltas: [],
2564
- notes: notes6,
2565
- review: { provider: "tiktok", accountId: scope.account_id, kind: op.kind, title, subject: `${count5} products`, fields: reviewFields, notices: notes6 },
2565
+ notes: notes7,
2566
+ review: { provider: "tiktok", accountId: scope.account_id, kind: op.kind, title, subject: `${count5} products`, fields: reviewFields, notices: notes7 },
2566
2567
  execute: async () => {
2567
2568
  await this.authorizeParent(scope, true);
2568
2569
  let nativeBody = body;
@@ -2603,12 +2604,12 @@ import { constants, promises as fs } from "fs";
2603
2604
  import path from "path";
2604
2605
  import { AdportError as AdportError15, adportHome } from "@adport/core";
2605
2606
  import { z as z16 } from "zod";
2606
- var catalogScope = z16.object({ accountId: z16.string().regex(/^\d{1,30}$/), businessId: z16.string().regex(/^\d{1,30}$/), resourceId: z16.string().regex(/^\d{1,30}$/), kind: z16.enum(["catalog", "catalog_creation"]) }).strict();
2607
- var catalogAccessMode = z16.enum(["none", "read", "write", "create"]);
2607
+ var catalogScope = z16.object({ accountId: z16.string().regex(/^\d{1,30}$/), businessId: z16.string().regex(/^\d{1,30}$/), resourceId: z16.string().regex(/^\d{1,30}$/), kind: z16.enum(["catalog", "catalog_creation", "catalog_migration"]) }).strict();
2608
+ var catalogAccessMode = z16.enum(["none", "read", "write", "create", "migrate"]);
2608
2609
  function catalogGrant(scope, mode2 = "none", revision = 0) {
2609
2610
  const parsed = catalogScope.parse(scope);
2610
2611
  catalogAccessMode.parse(mode2);
2611
- if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === "catalog_creation" && (parsed.resourceId !== parsed.businessId || !["none", "create"].includes(mode2)) || parsed.kind === "catalog" && mode2 === "create") throw new AdportError15("INVALID_INPUT", "Invalid TikTok catalog access configuration.");
2612
+ if (!Number.isSafeInteger(revision) || revision < 0 || parsed.kind === "catalog_creation" && (parsed.resourceId !== parsed.businessId || !["none", "create"].includes(mode2)) || parsed.kind === "catalog" && !["none", "read", "write"].includes(mode2) || parsed.kind === "catalog_migration" && !["none", "migrate"].includes(mode2)) throw new AdportError15("INVALID_INPUT", "Invalid TikTok catalog access configuration.");
2612
2613
  return { scope: parsed, mode: mode2, revision, hash: createHash9("sha256").update(JSON.stringify([parsed.accountId, parsed.businessId, parsed.kind, parsed.resourceId, mode2, revision])).digest("hex") };
2613
2614
  }
2614
2615
  function catalogScopeKey(scope) {
@@ -2623,6 +2624,13 @@ async function requireCatalogAccess(store, scope, write = false) {
2623
2624
  return grant;
2624
2625
  }
2625
2626
  var creationScope = (accountId, businessId) => catalogScope.parse({ accountId, businessId, resourceId: businessId, kind: "catalog_creation" });
2627
+ var migrationScope = (accountId, businessId, resourceId) => catalogScope.parse({ accountId, businessId, resourceId, kind: "catalog_migration" });
2628
+ async function requireCatalogMigrationAccess(store, scope, write = false) {
2629
+ if (!store || scope.kind !== "catalog_migration" || write && !store.canWrite) throw new AdportError15("POLICY_VIOLATION", "Catalog migration requires a separate exact owner delegation and a writable connection.");
2630
+ const grant = await store.authorize(scope, write);
2631
+ if (catalogScopeKey(grant.scope) !== catalogScopeKey(scope) || grant.mode !== "migrate") throw new AdportError15("POLICY_VIOLATION", "An owner must attest source ownership and delegate this exact catalog transfer to this Business Center. Creation and catalog read/write grants do not authorize transfers.");
2632
+ return grant;
2633
+ }
2626
2634
  async function requireCatalogCreationAccess(store, scope, write = false) {
2627
2635
  if (!store || scope.kind !== "catalog_creation" || scope.resourceId !== scope.businessId || write && !store.canWrite) throw new AdportError15("POLICY_VIOLATION", "Catalog creation requires owner-delegated creation access and a writable connection.");
2628
2636
  const grant = await store.authorize(scope, write);
@@ -2814,14 +2822,14 @@ var TikTokCatalogLifecycle = class {
2814
2822
  if (requested.some((code2) => !current.available_region_codes.includes(code2))) throw new AdportError16("INVALID_INPUT", "A selected region is not available in this Business Center.");
2815
2823
  };
2816
2824
  await prepare();
2817
- const c = input.catalog_conf, notes6 = ["Local preview only. Native creation eligibility, allowlists and supported type/currency/region combinations are checked on apply.", "Creates an empty Business Center catalog. No products, ads, budgets, tracking or events are created.", "The owner delegated read/write management of this successfully created, independently verified catalog ID only. Existing catalogs are not adopted or enumerated.", "Type, region, currency, channel and additional targeting configuration cannot be edited later. Uncertain creation or access adoption retains known IDs; reconcile before another create."];
2825
+ const c = input.catalog_conf, notes7 = ["Local preview only. Native creation eligibility, allowlists and supported type/currency/region combinations are checked on apply.", "Creates an empty Business Center catalog. No products, ads, budgets, tracking or events are created.", "The owner delegated read/write management of this successfully created, independently verified catalog ID only. Existing catalogs are not adopted or enumerated.", "Type, region, currency, channel and additional targeting configuration cannot be edited later. Uncertain creation or access adoption retains known IDs; reconcile before another create."];
2818
2826
  return {
2819
2827
  summary: `Create TikTok catalog "${input.name}"`,
2820
2828
  changes: [`+ ${input.catalog_type} catalog ${input.name} in Business Center ${input.bc_id}`, `+ Immutable catalog configuration ${canonical9(c)}`, "+ Project read/write grant for the independently verified new catalog ID only"],
2821
2829
  coercions: [],
2822
2830
  budgetDeltas: [],
2823
- notes: notes6,
2824
- review: { provider: "tiktok", accountId: op.accountId, kind: "create", title: "Create catalog", subject: input.name, fields: [{ label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: input.catalog_type }, { label: "Primary region", after: c.region_code ?? "Multi-country" }, { label: "Currency", after: c.currency }, { label: "Multi-country", after: c.is_multi_country ?? false }, { label: "Channel", after: c.channel ?? "Native default" }, { label: "Additional regions", after: c.additional_config_list?.map((row3) => row3.region_code + ":" + row3.currency).join(", ") || "None" }, { label: "New catalog project access", after: "Read and write" }], notices: notes6 },
2831
+ notes: notes7,
2832
+ review: { provider: "tiktok", accountId: op.accountId, kind: "create", title: "Create catalog", subject: input.name, fields: [{ label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: input.catalog_type }, { label: "Primary region", after: c.region_code ?? "Multi-country" }, { label: "Currency", after: c.currency }, { label: "Multi-country", after: c.is_multi_country ?? false }, { label: "Channel", after: c.channel ?? "Native default" }, { label: "Additional regions", after: c.additional_config_list?.map((row3) => row3.region_code + ":" + row3.currency).join(", ") || "None" }, { label: "New catalog project access", after: "Read and write" }], notices: notes7 },
2825
2833
  execute: async () => {
2826
2834
  await prepare();
2827
2835
  let id6;
@@ -2847,14 +2855,14 @@ var TikTokCatalogLifecycle = class {
2847
2855
  if (current2.configuration_hash !== input.expected_configuration_hash || current2.catalog_name !== input.confirm_catalog_name) throw new AdportError16("PENDING_MISMATCH", "Catalog configuration/name changed. Read it and request a fresh deletion preview.");
2848
2856
  return current2;
2849
2857
  };
2850
- const current = await prepare(), notes6 = ["Permanently deletes the entire shared catalog, including its current products and feeds. Existing ads or other accounts may be affected. No restore endpoint or global/atomic usage guarantee is available.", "Dependent contents are not enumerated or frozen by this configuration snapshot. Deletion applies to the entire catalog and its contents at apply time.", "Native deletion receipt and filtered catalog absence are checked independently. Provider errors are not absence; uncertain results are never replayed.", "Adport access grants remain separate owner settings; revocation is available without native catalog access."];
2858
+ const current = await prepare(), notes7 = ["Permanently deletes the entire shared catalog, including its current products and feeds. Existing ads or other accounts may be affected. No restore endpoint or global/atomic usage guarantee is available.", "Dependent contents are not enumerated or frozen by this configuration snapshot. Deletion applies to the entire catalog and its contents at apply time.", "Native deletion receipt and filtered catalog absence are checked independently. Provider errors are not absence; uncertain results are never replayed.", "Adport access grants remain separate owner settings; revocation is available without native catalog access."];
2851
2859
  return {
2852
2860
  summary: `Permanently delete TikTok catalog "${current.catalog_name}"`,
2853
2861
  changes: [`- Entire catalog ${input.catalog_id} and its current products/feeds`, "- Catalog availability to existing shared consumers"],
2854
2862
  coercions: [],
2855
2863
  budgetDeltas: [],
2856
- notes: notes6,
2857
- review: { provider: "tiktok", accountId: op.accountId, kind: "remove", title: "Delete catalog permanently", subject: current.catalog_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: current.catalog_type }, { label: "Contents affected", after: "All current products and feeds; not enumerated or frozen" }], notices: notes6 },
2864
+ notes: notes7,
2865
+ review: { provider: "tiktok", accountId: op.accountId, kind: "remove", title: "Delete catalog permanently", subject: current.catalog_name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Business Center", after: input.bc_id }, { label: "Catalog type", after: current.catalog_type }, { label: "Contents affected", after: "All current products and feeds; not enumerated or frozen" }], notices: notes7 },
2858
2866
  execute: async () => {
2859
2867
  await prepare();
2860
2868
  try {
@@ -2873,43 +2881,140 @@ var TikTokCatalogLifecycle = class {
2873
2881
  }
2874
2882
  };
2875
2883
 
2876
- // src/catalog-event-sources.ts
2884
+ // src/catalog-migration.ts
2877
2885
  import { createHash as createHash11 } from "crypto";
2878
2886
  import { AdportError as AdportError17 } from "@adport/core";
2879
2887
  import { z as z18 } from "zod";
2880
2888
  var hash9 = z18.string().regex(/^[a-f0-9]{64}$/);
2881
- var nativeId8 = z18.union([catalogId, z18.number().int().positive().safe()]).transform(String);
2882
- var code = z18.string().min(1).max(256).regex(/^[^\u0000-\u0020\u007f]+$/);
2883
- var text3 = z18.string().max(4e3);
2889
+ var catalogMigration = catalogInput.omit({ account_id: true }).extend({
2890
+ expected_migration_access_hash: hash9,
2891
+ expected_destination_hash: hash9,
2892
+ confirm_catalog_id: z18.string(),
2893
+ acknowledge_shared_effects: z18.literal(true),
2894
+ acknowledge_source_ownership_not_independently_verified: z18.literal(true)
2895
+ }).strict().refine((input) => input.confirm_catalog_id === input.catalog_id, "Confirm the exact source catalog ID");
2896
+ var notes6 = [
2897
+ "Source ownership is attested by the project owner, not independently verified by an Adport source lookup. TikTok enforces source-advertiser ownership when applying the transfer.",
2898
+ "The destination Business Center Admin role is read from TikTok at preview and apply. The source catalog must not already be present there.",
2899
+ "Transfers the entire catalog, including its products, product sets and video templates. Existing users, ads and shared consumers may be affected; dependent contents are not enumerated or frozen.",
2900
+ "No ads are activated and no budgets or tracking events are changed. Native ownership transfer has no automatic retry or rollback.",
2901
+ "After transfer, the owner must separately grant read/write access to the exact destination catalog. Existing project grants are not expanded."
2902
+ ];
2903
+ var TikTokCatalogMigration = class {
2904
+ constructor(client, store, lookup) {
2905
+ this.client = client;
2906
+ this.store = store;
2907
+ this.lookup = lookup;
2908
+ }
2909
+ client;
2910
+ store;
2911
+ lookup;
2912
+ async destination(bcId) {
2913
+ let response2;
2914
+ try {
2915
+ response2 = await this.client.get("bc/get", { bc_id: bcId, page: 1, page_size: 1 });
2916
+ } catch {
2917
+ throw new AdportError17("PROVIDER_ERROR", "TikTok destination Business Center lookup failed. Check the current token\u2019s Business Center permission and exact ID. No transfer was submitted.");
2918
+ }
2919
+ const parsed = z18.looseObject({
2920
+ list: z18.array(z18.looseObject({ bc_info: z18.looseObject({ bc_id: z18.string(), name: z18.string().optional() }), user_role: z18.string() })).length(1),
2921
+ page_info: z18.looseObject({ page: z18.literal(1), total_page: z18.number().int().min(0).max(1), total_number: z18.number().int().min(0).max(1).optional() }).optional()
2922
+ }).safeParse(response2);
2923
+ if (!parsed.success || parsed.data.list[0].bc_info.bc_id !== bcId || parsed.data.list[0].user_role !== "ADMIN" || parsed.data.page_info?.total_number === 0) throw new AdportError17("POLICY_VIOLATION", "The exact destination Business Center and native Admin role could not be verified.");
2924
+ const selected5 = parsed.data.list[0];
2925
+ return { bc_id: bcId, name: selected5.bc_info.name ?? bcId, user_role: selected5.user_role };
2926
+ }
2927
+ async context(raw) {
2928
+ const input = catalogInput.parse(raw), grant = await requireCatalogMigrationAccess(this.store, migrationScope(input.account_id, input.bc_id, input.catalog_id));
2929
+ const destination = await this.destination(input.bc_id);
2930
+ if (await this.lookup(input)) throw new AdportError17("INVALID_INPUT", "This catalog is already in the destination Business Center. Do not transfer it again; review its exact catalog access separately.");
2931
+ return {
2932
+ expected_migration_access_hash: grant.hash,
2933
+ expected_destination_hash: createHash11("sha256").update(JSON.stringify({ ...input, destination })).digest("hex"),
2934
+ source_ownership: "OWNER_ATTESTED_NOT_INDEPENDENTLY_VERIFIED",
2935
+ destination,
2936
+ records: [{ id: input.catalog_id, name: "Catalog transfer", source_advertiser_id: input.account_id, destination_business_center_id: input.bc_id, source_ownership: "Owner attested", destination_role: destination.user_role }],
2937
+ notes: [...notes6]
2938
+ };
2939
+ }
2940
+ async plan(op) {
2941
+ if (op.provider !== "tiktok" || op.tool !== "tiktok_migrate_catalog" || op.kind !== "update") throw new AdportError17("INVALID_INPUT", "Unsupported catalog migration operation.");
2942
+ const input = catalogMigration.parse(op.payload), selection = { account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id };
2943
+ const prepare = async () => {
2944
+ await requireCatalogMigrationAccess(this.store, migrationScope(op.accountId, input.bc_id, input.catalog_id), true);
2945
+ const current2 = await this.context(selection);
2946
+ if (current2.expected_migration_access_hash !== input.expected_migration_access_hash || current2.expected_destination_hash !== input.expected_destination_hash) throw new AdportError17("PENDING_MISMATCH", "Transfer delegation or destination changed. Read migration context and review a new preview.");
2947
+ return current2;
2948
+ };
2949
+ const current = await prepare();
2950
+ return {
2951
+ summary: `Transfer TikTok catalog ${input.catalog_id} to ${current.destination.name}`,
2952
+ changes: [`~ Entire catalog ${input.catalog_id}: advertiser ${op.accountId} \u2192 Business Center ${input.bc_id}`],
2953
+ coercions: [],
2954
+ budgetDeltas: [],
2955
+ notes: [...notes6],
2956
+ review: { provider: "tiktok", accountId: op.accountId, kind: "update", title: "Transfer catalog ownership", subject: input.catalog_id, fields: [
2957
+ { label: "Source advertiser", after: op.accountId },
2958
+ { label: "Catalog", after: input.catalog_id },
2959
+ { label: "Destination Business Center", after: input.bc_id },
2960
+ { label: "Source ownership verification", after: "Owner attestation; native check at apply" },
2961
+ { label: "Destination role", after: "ADMIN" },
2962
+ { label: "Contents affected", after: "Entire catalog and its current products, product sets and video templates" },
2963
+ { label: "Project read/write grants", after: "Unchanged" }
2964
+ ], notices: [...notes6] },
2965
+ execute: async () => {
2966
+ await prepare();
2967
+ try {
2968
+ await this.client.post("catalog/capitalize", { advertiser_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id });
2969
+ await requireCatalogMigrationAccess(this.store, migrationScope(op.accountId, input.bc_id, input.catalog_id), true);
2970
+ if (!await this.lookup(selection)) throw new Error("Destination catalog was not found");
2971
+ return [input.catalog_id];
2972
+ } catch (error) {
2973
+ const details = error instanceof AdportError17 && error.details && typeof error.details === "object" ? error.details : {};
2974
+ throw new AdportError17("PROVIDER_ERROR", "Catalog transfer or destination readback is unconfirmed. Inspect the exact destination catalog before another transfer; no request was retried.", { resource_ids: [input.catalog_id], ...Number.isInteger(details.code) ? { provider_code: details.code } : {} });
2975
+ }
2976
+ }
2977
+ };
2978
+ }
2979
+ };
2980
+
2981
+ // src/catalog-event-sources.ts
2982
+ import { createHash as createHash12 } from "crypto";
2983
+ import { AdportError as AdportError18 } from "@adport/core";
2984
+ import { z as z19 } from "zod";
2985
+ var hash10 = z19.string().regex(/^[a-f0-9]{64}$/);
2986
+ var nativeId8 = z19.union([catalogId, z19.number().int().positive().safe()]).transform(String);
2987
+ var code = z19.string().min(1).max(256).regex(/^[^\u0000-\u0020\u007f]+$/);
2988
+ var text3 = z19.string().max(4e3);
2884
2989
  var selectedFields = { app_id: catalogId.optional(), pixel_code: code.optional() };
2885
2990
  var hasSource = (value) => !!(value.app_id || value.pixel_code);
2886
- var paging2 = { cursor: z18.string().min(1).max(512).optional(), page_size: z18.number().int().min(1).max(100).default(30) };
2991
+ var paging2 = { cursor: z19.string().min(1).max(512).optional(), page_size: z19.number().int().min(1).max(100).default(30) };
2887
2992
  var catalogEventList = catalogInput.extend(paging2).strict();
2888
- var catalogEventApps = catalogInput.extend({ ...paging2, app_platform_ids: z18.array(z18.string().min(1).max(1e3)).min(1).max(100).refine((ids2) => new Set(ids2).size === ids2.length, "Platform IDs must be unique").optional() }).strict();
2889
- var catalogEventContext = catalogInput.extend({ ...selectedFields, purpose: z18.enum(["bind", "unbind"]).default("bind") }).strict().refine(hasSource, "Select an app_id, pixel_code or both");
2890
- var catalogEventChange = catalogInput.omit({ account_id: true }).extend({ ...selectedFields, expected_catalog_hash: hash9, expected_bindings_hash: hash9, expected_sources_hash: hash9, acknowledge_shared_effects: z18.literal(true), acknowledge_measurement_effects: z18.literal(true) }).strict().refine(hasSource, "Select an app_id, pixel_code or both; an empty selector cannot unbind all sources");
2993
+ var catalogEventApps = catalogInput.extend({ ...paging2, app_platform_ids: z19.array(z19.string().min(1).max(1e3)).min(1).max(100).refine((ids2) => new Set(ids2).size === ids2.length, "Platform IDs must be unique").optional() }).strict();
2994
+ var catalogEventContext = catalogInput.extend({ ...selectedFields, purpose: z19.enum(["bind", "unbind"]).default("bind") }).strict().refine(hasSource, "Select an app_id, pixel_code or both");
2995
+ var catalogEventChange = catalogInput.omit({ account_id: true }).extend({ ...selectedFields, expected_catalog_hash: hash10, expected_bindings_hash: hash10, expected_sources_hash: hash10, acknowledge_shared_effects: z19.literal(true), acknowledge_measurement_effects: z19.literal(true) }).strict().refine(hasSource, "Select an app_id, pixel_code or both; an empty selector cannot unbind all sources");
2891
2996
  var canonical10 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
2892
- var digest8 = (value) => createHash11("sha256").update(canonical10(value)).digest("hex");
2997
+ var digest8 = (value) => createHash12("sha256").update(canonical10(value)).digest("hex");
2893
2998
  var key = (value) => value.type + ":" + value.id;
2894
2999
  var identities = (rows) => rows.map(({ type, id: id6 }) => ({ type, id: id6 })).sort((a, b) => key(a).localeCompare(key(b)));
2895
- var invalid7 = () => new AdportError17("PROVIDER_ERROR", "TikTok catalog event-source scope, identifiers or response shape could not be verified.");
3000
+ var invalid7 = () => new AdportError18("PROVIDER_ERROR", "TikTok catalog event-source scope, identifiers or response shape could not be verified.");
2896
3001
  var failure3 = (error, message, ids2) => {
2897
- const details = error instanceof AdportError17 && error.details && typeof error.details === "object" ? error.details : {};
2898
- return new AdportError17("PROVIDER_ERROR", message + " Provider bodies stay hidden; no request was retried.", { ...Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
3002
+ const details = error instanceof AdportError18 && error.details && typeof error.details === "object" ? error.details : {};
3003
+ return new AdportError18("PROVIDER_ERROR", message + " Provider bodies stay hidden; no request was retried.", { ...Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
2899
3004
  };
2900
- var nativeApp = z18.object({ advertiser_id: nativeId8, app_id: nativeId8, app_name: text3, app_platform_id: z18.string().min(1).max(1e3), platform: z18.enum(["ANDROID", "IOS"]).optional(), package_name: text3.optional(), self_attribution_enabled: z18.boolean().optional(), skan_allowed: z18.enum(["ALLOWED", "NOT_ALLOWED"]).optional(), advanced_dedicated_campaign_allowed: z18.boolean().optional(), is_attribution_flex_enable: z18.boolean().optional() });
2901
- var matching2 = z18.object({ email: z18.boolean().optional(), phone_number: z18.boolean().optional(), name: z18.boolean().optional(), address: z18.boolean().optional(), external_id: z18.boolean().optional() });
2902
- var nativePixel = z18.object({ pixel_id: nativeId8, pixel_code: code, pixel_name: text3, advertiser_id: nativeId8.optional(), asset_ownership: z18.object({ asset_relation_status: z18.string().nullable().optional(), ownership_status: z18.boolean().optional(), owner_bc_id: nativeId8.nullable().optional() }).optional(), advanced_matching_fields: matching2.optional(), automatic_advanced_matching_fields: matching2.optional(), enable_first_party_cookies: z18.boolean().optional(), enable_expanded_data_sharing: z18.boolean().optional() });
3005
+ var nativeApp = z19.object({ advertiser_id: nativeId8, app_id: nativeId8, app_name: text3, app_platform_id: z19.string().min(1).max(1e3), platform: z19.enum(["ANDROID", "IOS"]).optional(), package_name: text3.optional(), self_attribution_enabled: z19.boolean().optional(), skan_allowed: z19.enum(["ALLOWED", "NOT_ALLOWED"]).optional(), advanced_dedicated_campaign_allowed: z19.boolean().optional(), is_attribution_flex_enable: z19.boolean().optional() });
3006
+ var matching2 = z19.object({ email: z19.boolean().optional(), phone_number: z19.boolean().optional(), name: z19.boolean().optional(), address: z19.boolean().optional(), external_id: z19.boolean().optional() });
3007
+ var nativePixel = z19.object({ pixel_id: nativeId8, pixel_code: code, pixel_name: text3, advertiser_id: nativeId8.optional(), asset_ownership: z19.object({ asset_relation_status: z19.string().nullable().optional(), ownership_status: z19.boolean().optional(), owner_bc_id: nativeId8.nullable().optional() }).optional(), advanced_matching_fields: matching2.optional(), automatic_advanced_matching_fields: matching2.optional(), enable_first_party_cookies: z19.boolean().optional(), enable_expanded_data_sharing: z19.boolean().optional() });
2903
3008
  function page(scope, rows, cursor, size) {
2904
3009
  const snapshot3 = digest8({ scope, rows });
2905
3010
  let index = 0;
2906
3011
  if (cursor) {
2907
3012
  try {
2908
- const parsed = z18.object({ h: hash9, i: z18.number().int().positive().safe() }).strict().parse(JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")));
3013
+ const parsed = z19.object({ h: hash10, i: z19.number().int().positive().safe() }).strict().parse(JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")));
2909
3014
  if (parsed.h !== snapshot3 || parsed.i >= rows.length) throw new Error();
2910
3015
  index = parsed.i;
2911
3016
  } catch {
2912
- throw new AdportError17("INVALID_INPUT", "The source inventory, selection or cursor changed. Read the first page again.");
3017
+ throw new AdportError18("INVALID_INPUT", "The source inventory, selection or cursor changed. Read the first page again.");
2913
3018
  }
2914
3019
  }
2915
3020
  const selected5 = rows.slice(index, index + size), next = index + selected5.length;
@@ -2930,7 +3035,7 @@ var TikTokCatalogEventSources = class {
2930
3035
  }
2931
3036
  }
2932
3037
  async bindings(scope) {
2933
- const response2 = z18.object({ catalog_id: nativeId8, bc_id: nativeId8.optional(), event_sources: z18.array(z18.object({ event_source_name: text3.nullable().optional(), app_id: nativeId8.nullable().optional(), pixel_code: code.nullable().optional() }).refine(hasSource)).max(5e3) }).safeParse(await this.get("catalog/eventsource_bind/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id }));
3038
+ const response2 = z19.object({ catalog_id: nativeId8, bc_id: nativeId8.optional(), event_sources: z19.array(z19.object({ event_source_name: text3.nullable().optional(), app_id: nativeId8.nullable().optional(), pixel_code: code.nullable().optional() }).refine(hasSource)).max(5e3) }).safeParse(await this.get("catalog/eventsource_bind/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id }));
2934
3039
  if (!response2.success || response2.data.catalog_id !== scope.catalog_id || response2.data.bc_id !== void 0 && response2.data.bc_id !== scope.bc_id) throw invalid7();
2935
3040
  const rows = response2.data.event_sources.flatMap((row3) => [...row3.app_id ? [{ type: "APP", id: row3.app_id, name: row3.event_source_name ?? "App event source" }] : [], ...row3.pixel_code ? [{ type: "PIXEL", id: row3.pixel_code, name: row3.event_source_name ?? "Web Pixel" }] : []]);
2936
3041
  if (rows.length > 5e3 || new Set(rows.map(key)).size !== rows.length) throw invalid7();
@@ -2944,7 +3049,7 @@ var TikTokCatalogEventSources = class {
2944
3049
  async apps(value) {
2945
3050
  const input = catalogEventApps.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });
2946
3051
  await this.parent(scope);
2947
- const response2 = z18.object({ apps: z18.array(nativeApp).max(5e3) }).safeParse(await this.get("app/list", { advertiser_id: scope.account_id, ...input.app_platform_ids ? { app_platform_ids: input.app_platform_ids } : {} }));
3052
+ const response2 = z19.object({ apps: z19.array(nativeApp).max(5e3) }).safeParse(await this.get("app/list", { advertiser_id: scope.account_id, ...input.app_platform_ids ? { app_platform_ids: input.app_platform_ids } : {} }));
2948
3053
  if (!response2.success || response2.data.apps.some((row3) => row3.advertiser_id !== scope.account_id || input.app_platform_ids && !input.app_platform_ids.includes(row3.app_platform_id)) || new Set(response2.data.apps.map((row3) => row3.app_id)).size !== response2.data.apps.length) throw invalid7();
2949
3054
  const rows = response2.data.apps.sort((a, b) => a.app_id.localeCompare(b.app_id)), result = page({ ...scope, kind: "apps", app_platform_ids: input.app_platform_ids ?? null }, rows, input.cursor, input.page_size);
2950
3055
  return { apps: result.selected, records: result.selected.map((row3) => ({ id: row3.app_id, name: row3.app_name, platform: row3.platform ?? "Not reported", app_platform_id: row3.app_platform_id, skan_allowed: row3.skan_allowed ?? "Not reported" })), total_in_response: rows.length, complete: result.complete, truncated: result.truncated, ..."next_cursor" in result ? { next_cursor: result.next_cursor } : {}, notes: ["Advertiser app discovery, not a guarantee of catalog binding eligibility. Use the native app_id for event-source binding; app_platform_id and tiktok_app_id are different identifiers.", "Native endpoint is unpaged; Adport snapshot-pages at most 5,000 apps, up to 100 per local page. Tracking URLs, partner tokens, raw icons and other private fields are omitted."] };
@@ -2952,13 +3057,13 @@ var TikTokCatalogEventSources = class {
2952
3057
  async selected(scope, input, purpose) {
2953
3058
  const sources = [];
2954
3059
  if (input.app_id) {
2955
- const response2 = z18.object({ app: nativeApp }).safeParse(await this.get("app/info", { advertiser_id: scope.account_id, app_id: input.app_id }));
3060
+ const response2 = z19.object({ app: nativeApp }).safeParse(await this.get("app/info", { advertiser_id: scope.account_id, app_id: input.app_id }));
2956
3061
  if (!response2.success || response2.data.app.advertiser_id !== scope.account_id || response2.data.app.app_id !== input.app_id) throw invalid7();
2957
3062
  const app = response2.data.app;
2958
3063
  sources.push({ type: "APP", id: app.app_id, name: app.app_name, ...app });
2959
3064
  }
2960
3065
  if (input.pixel_code) {
2961
- const response2 = z18.object({ pixels: z18.array(nativePixel).max(20), page_info: z18.object({ page: z18.literal(1), page_size: z18.literal(20), total_page: z18.number().int().nonnegative().safe().optional(), total_number: z18.number().int().nonnegative().safe().optional() }).optional() }).safeParse(await this.get("pixel/list", { advertiser_id: scope.account_id, code: input.pixel_code, page: 1, page_size: 20, ...purpose === "bind" ? { filtering: { available_for_catalog_only: true } } : {} }));
3066
+ const response2 = z19.object({ pixels: z19.array(nativePixel).max(20), page_info: z19.object({ page: z19.literal(1), page_size: z19.literal(20), total_page: z19.number().int().nonnegative().safe().optional(), total_number: z19.number().int().nonnegative().safe().optional() }).optional() }).safeParse(await this.get("pixel/list", { advertiser_id: scope.account_id, code: input.pixel_code, page: 1, page_size: 20, ...purpose === "bind" ? { filtering: { available_for_catalog_only: true } } : {} }));
2962
3067
  if (!response2.success || response2.data.pixels.length !== 1 || (response2.data.page_info?.total_page ?? 1) !== 1 || response2.data.page_info?.total_number !== void 0 && response2.data.page_info.total_number !== 1) throw invalid7();
2963
3068
  const pixel = response2.data.pixels[0];
2964
3069
  if (pixel.pixel_code !== input.pixel_code || pixel.advertiser_id !== void 0 && pixel.advertiser_id !== scope.account_id || pixel.asset_ownership?.asset_relation_status === "UNBOUND") throw invalid7();
@@ -2969,7 +3074,7 @@ var TikTokCatalogEventSources = class {
2969
3074
  async contextFor(scope, input, purpose, write = false) {
2970
3075
  const parent = await this.parent(scope, write), bindings = await this.bindings(scope), selected5 = await this.selected(scope, input, purpose);
2971
3076
  const keys = new Set(bindings.rows.map(key));
2972
- if (selected5.sources.some((row3) => purpose === "bind" ? keys.has(key(row3)) : !keys.has(key(row3)))) throw new AdportError17("INVALID_INPUT", purpose === "bind" ? "A selected source is already bound. Select only new bindings, or split the change." : "Every selected source must already be bound. No unbind-all operation is inferred.");
3077
+ if (selected5.sources.some((row3) => purpose === "bind" ? keys.has(key(row3)) : !keys.has(key(row3)))) throw new AdportError18("INVALID_INPUT", purpose === "bind" ? "A selected source is already bound. Select only new bindings, or split the change." : "Every selected source must already be bound. No unbind-all operation is inferred.");
2973
3078
  return { parent, bindings, selected: selected5 };
2974
3079
  }
2975
3080
  async context(value) {
@@ -2978,22 +3083,22 @@ var TikTokCatalogEventSources = class {
2978
3083
  }
2979
3084
  async plan(op) {
2980
3085
  const bind = op.tool === "tiktok_bind_catalog_event_sources";
2981
- if (op.provider !== "tiktok" || !(bind && op.kind === "update" || op.tool === "tiktok_unbind_catalog_event_sources" && op.kind === "remove")) throw new AdportError17("INVALID_INPUT", "Unsupported catalog event-source operation or kind.");
3086
+ if (op.provider !== "tiktok" || !(bind && op.kind === "update" || op.tool === "tiktok_unbind_catalog_event_sources" && op.kind === "remove")) throw new AdportError18("INVALID_INPUT", "Unsupported catalog event-source operation or kind.");
2982
3087
  const input = catalogEventChange.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), purpose = bind ? "bind" : "unbind";
2983
3088
  const prepare = async () => {
2984
3089
  const current2 = await this.contextFor(scope, input, purpose, true);
2985
- if (current2.parent.configuration_hash !== input.expected_catalog_hash || current2.bindings.hash !== input.expected_bindings_hash || current2.selected.hash !== input.expected_sources_hash) throw new AdportError17("PENDING_MISMATCH", "Catalog, bindings or selected sources changed. Read context and request a new preview.");
3090
+ if (current2.parent.configuration_hash !== input.expected_catalog_hash || current2.bindings.hash !== input.expected_bindings_hash || current2.selected.hash !== input.expected_sources_hash) throw new AdportError18("PENDING_MISMATCH", "Catalog, bindings or selected sources changed. Read context and request a new preview.");
2986
3091
  return current2;
2987
3092
  };
2988
3093
  const current = await prepare(), selected5 = current.selected.sources, title = bind ? "Bind catalog event sources" : "Unbind catalog event sources";
2989
- const notes6 = ["Local preview only. Changes shared catalog product/event matching and may affect measurement, retargeting and existing ads.", "No tracking installation, event ingestion, budget or ad-status change. Source access and native catalog eligibility remain authoritative.", "All unselected binding identities are checked after the write. There is no atomic cross-resource guarantee; uncertain or partial results are never replayed."];
3094
+ const notes7 = ["Local preview only. Changes shared catalog product/event matching and may affect measurement, retargeting and existing ads.", "No tracking installation, event ingestion, budget or ad-status change. Source access and native catalog eligibility remain authoritative.", "All unselected binding identities are checked after the write. There is no atomic cross-resource guarantee; uncertain or partial results are never replayed."];
2990
3095
  return {
2991
3096
  summary: title + " \xB7 catalog " + input.catalog_id,
2992
3097
  changes: selected5.map((row3) => `${bind ? "+" : "-"} ${row3.type} ${row3.name} (${row3.id})`),
2993
3098
  coercions: [],
2994
3099
  budgetDeltas: [],
2995
- notes: notes6,
2996
- review: { provider: "tiktok", accountId: scope.account_id, kind: bind ? "update" : "remove", title, subject: input.catalog_id, fields: [{ label: "Catalog", after: input.catalog_id }, ...selected5.map((row3) => ({ label: row3.type === "APP" ? "App event source" : "Web Pixel", before: bind ? "Not bound" : row3.name + " (" + row3.id + ")", after: bind ? row3.name + " (" + row3.id + ")" : "Unbound" })), { label: "Other bindings preserved", after: String(current.bindings.rows.length - (bind ? 0 : selected5.length)) }], notices: notes6 },
3100
+ notes: notes7,
3101
+ review: { provider: "tiktok", accountId: scope.account_id, kind: bind ? "update" : "remove", title, subject: input.catalog_id, fields: [{ label: "Catalog", after: input.catalog_id }, ...selected5.map((row3) => ({ label: row3.type === "APP" ? "App event source" : "Web Pixel", before: bind ? "Not bound" : row3.name + " (" + row3.id + ")", after: bind ? row3.name + " (" + row3.id + ")" : "Unbound" })), { label: "Other bindings preserved", after: String(current.bindings.rows.length - (bind ? 0 : selected5.length)) }], notices: notes7 },
2997
3102
  execute: async () => {
2998
3103
  const fresh = await prepare(), selectedKeys = new Set(selected5.map(key)), expected = bind ? [...fresh.bindings.rows, ...selected5] : fresh.bindings.rows.filter((row3) => !selectedKeys.has(key(row3)));
2999
3104
  try {
@@ -3012,41 +3117,41 @@ var TikTokCatalogEventSources = class {
3012
3117
  };
3013
3118
 
3014
3119
  // src/catalog-videos.ts
3015
- import { createHash as createHash12 } from "crypto";
3016
- import { AdportError as AdportError18, csvRows as csvRows4, MAX_PROJECT_MEDIA_BYTES as MAX_PROJECT_MEDIA_BYTES4, verifyMedia as verifyMedia4 } from "@adport/core";
3017
- import { z as z19 } from "zod";
3018
- var hash10 = z19.string().regex(/^[a-f0-9]{64}$/);
3019
- var count4 = z19.number().int().nonnegative().safe();
3020
- var nativeId9 = z19.union([catalogId, z19.number().int().positive().safe()]).transform(String);
3021
- var videoId = z19.string().min(1).max(1024).regex(/^[^\u0000-\u0020\u007f]+$/);
3022
- var time = z19.string().max(40).regex(/^[0-9TZ :.+-]*$/);
3023
- var text4 = z19.string().max(256 * 1024).nullable().optional();
3120
+ import { createHash as createHash13 } from "crypto";
3121
+ import { AdportError as AdportError19, csvRows as csvRows4, MAX_PROJECT_MEDIA_BYTES as MAX_PROJECT_MEDIA_BYTES4, verifyMedia as verifyMedia4 } from "@adport/core";
3122
+ import { z as z20 } from "zod";
3123
+ var hash11 = z20.string().regex(/^[a-f0-9]{64}$/);
3124
+ var count4 = z20.number().int().nonnegative().safe();
3125
+ var nativeId9 = z20.union([catalogId, z20.number().int().positive().safe()]).transform(String);
3126
+ var videoId = z20.string().min(1).max(1024).regex(/^[^\u0000-\u0020\u007f]+$/);
3127
+ var time = z20.string().max(40).regex(/^[0-9TZ :.+-]*$/);
3128
+ var text4 = z20.string().max(256 * 1024).nullable().optional();
3024
3129
  var metadata = { category: text4, brand: text4, creator: text4, video_type: text4, description: text4, landing_page_url: text4, custom_label_0: text4, custom_label_1: text4, custom_label_2: text4, custom_label_3: text4, custom_label_4: text4 };
3025
3130
  var metadataKeys = Object.keys(metadata);
3026
- var nativeVideo = z19.object({
3131
+ var nativeVideo = z20.object({
3027
3132
  ...metadata,
3028
3133
  catalog_video_id: videoId,
3029
- video_name: z19.string().max(4e3),
3030
- video_link: z19.string().max(256 * 1024).optional(),
3031
- sku_id_list: z19.array(z19.string().max(100)).max(20).optional(),
3134
+ video_name: z20.string().max(4e3),
3135
+ video_link: z20.string().max(256 * 1024).optional(),
3136
+ sku_id_list: z20.array(z20.string().max(100)).max(20).optional(),
3032
3137
  video_id: videoId.nullable().optional(),
3033
- video_signature: z19.string().max(128).nullable().optional(),
3034
- status: z19.enum(["PENDING", "SUCCESS", "FAILED"]),
3035
- active_status: z19.enum(["ACTIVATED", "DEACTIVATED"]).optional(),
3138
+ video_signature: z20.string().max(128).nullable().optional(),
3139
+ status: z20.enum(["PENDING", "SUCCESS", "FAILED"]),
3140
+ active_status: z20.enum(["ACTIVATED", "DEACTIVATED"]).optional(),
3036
3141
  create_time: time.optional(),
3037
- preview_url: z19.string().max(16384).nullable().optional(),
3142
+ preview_url: z20.string().max(16384).nullable().optional(),
3038
3143
  catalog_id: nativeId9.optional(),
3039
3144
  bc_id: nativeId9.optional()
3040
3145
  });
3041
3146
  var displayMetadata = (row3) => Object.fromEntries(metadataKeys.filter((key2) => key2 !== "landing_page_url" && row3[key2] !== void 0).map((key2) => [key2, typeof row3[key2] === "string" ? row3[key2].slice(0, 1e3) : row3[key2]]));
3042
- var source = catalogInput.extend({ media_id: z19.string().uuid(), expected_sha256: hash10 }).strict();
3147
+ var source = catalogInput.extend({ media_id: z20.string().uuid(), expected_sha256: hash11 }).strict();
3043
3148
  var catalogVideoImportContext = source;
3044
- var catalogVideoList = catalogInput.extend({ catalog_video_ids: z19.array(videoId).min(1).max(50).refine((ids2) => new Set(ids2).size === ids2.length, "Video IDs must be unique").optional(), page: z19.number().int().positive().safe().default(1), page_size: z19.number().int().min(1).max(50).default(20) }).strict();
3149
+ var catalogVideoList = catalogInput.extend({ catalog_video_ids: z20.array(videoId).min(1).max(50).refine((ids2) => new Set(ids2).size === ids2.length, "Video IDs must be unique").optional(), page: z20.number().int().positive().safe().default(1), page_size: z20.number().int().min(1).max(50).default(20) }).strict();
3045
3150
  var catalogVideoLog = catalogInput.extend({ feed_log_id: catalogId }).strict();
3046
- var catalogVideoUpload = source.omit({ account_id: true }).extend({ expected_catalog_hash: hash10, expected_associations_hash: hash10, sync_to_selected_account: z19.boolean().default(false), acknowledge_account_copy: z19.literal(true).optional(), acknowledge_shared_effects: z19.literal(true), acknowledge_possible_delivery: z19.literal(true), acknowledge_async_processing: z19.literal(true) }).strict().refine((value) => !value.sync_to_selected_account || value.acknowledge_account_copy === true, "Syncing creates separate advertiser-library copies; acknowledge_account_copy is required");
3047
- var catalogVideoDelete = catalogInput.omit({ account_id: true }).extend({ catalog_video_id: videoId, expected_configuration_hash: hash10, acknowledge_shared_effects: z19.literal(true) }).strict();
3151
+ var catalogVideoUpload = source.omit({ account_id: true }).extend({ expected_catalog_hash: hash11, expected_associations_hash: hash11, sync_to_selected_account: z20.boolean().default(false), acknowledge_account_copy: z20.literal(true).optional(), acknowledge_shared_effects: z20.literal(true), acknowledge_possible_delivery: z20.literal(true), acknowledge_async_processing: z20.literal(true) }).strict().refine((value) => !value.sync_to_selected_account || value.acknowledge_account_copy === true, "Syncing creates separate advertiser-library copies; acknowledge_account_copy is required");
3152
+ var catalogVideoDelete = catalogInput.omit({ account_id: true }).extend({ catalog_video_id: videoId, expected_configuration_hash: hash11, acknowledge_shared_effects: z20.literal(true) }).strict();
3048
3153
  var canonical11 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
3049
- var digest9 = (value) => createHash12("sha256").update(canonical11(value)).digest("hex");
3154
+ var digest9 = (value) => createHash13("sha256").update(canonical11(value)).digest("hex");
3050
3155
  var object3 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
3051
3156
  var safeUrl2 = (value, httpsOnly = true) => {
3052
3157
  if (typeof value !== "string" || /[\u0000-\u0020\u007f]/.test(value)) return;
@@ -3067,10 +3172,10 @@ var sourceInfo = (value) => {
3067
3172
  };
3068
3173
  var config2 = (row3) => ({ ...Object.fromEntries(metadataKeys.filter((key2) => row3[key2] !== void 0).map((key2) => [key2, row3[key2]])), catalog_video_id: row3.catalog_video_id, video_name: row3.video_name, video_link: row3.video_link, sku_id_list: row3.sku_id_list, active_status: row3.active_status });
3069
3174
  var configurationHash2 = (scope, row3) => digest9({ ...scope, configuration: config2(row3) });
3070
- var invalid8 = () => new AdportError18("PROVIDER_ERROR", "TikTok returned an unexpected catalog-video scope, identifier or shape. No request was retried.");
3175
+ var invalid8 = () => new AdportError19("PROVIDER_ERROR", "TikTok returned an unexpected catalog-video scope, identifier or shape. No request was retried.");
3071
3176
  var failure4 = (error, message, ids2) => {
3072
- const details = object3(error instanceof AdportError18 ? error.details : void 0);
3073
- return new AdportError18("PROVIDER_ERROR", `${message} Provider bodies and source URLs stay hidden; no request was retried.`, { ...Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
3177
+ const details = object3(error instanceof AdportError19 ? error.details : void 0);
3178
+ return new AdportError19("PROVIDER_ERROR", `${message} Provider bodies and source URLs stay hidden; no request was retried.`, { ...Number.isSafeInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {}, ...ids2 ? { resourceIds: ids2 } : {} });
3074
3179
  };
3075
3180
  var columns = ["video_name", "video_link", "sku_id_list", "category", "brand", "creator", "video_type", "description", "landing_page_url", "custom_label_0", "custom_label_1", "custom_label_2", "custom_label_3", "custom_label_4"];
3076
3181
  var TikTokCatalogVideos = class {
@@ -3084,7 +3189,7 @@ var TikTokCatalogVideos = class {
3084
3189
  media;
3085
3190
  async parent(scope, write = false) {
3086
3191
  const parent = await this.authorizeParent(scope, write);
3087
- if (parent.catalog_type !== "ECOM" || parent.catalog_conf.is_multi_country === true) throw new AdportError18("INVALID_INPUT", "Catalog videos require a single-country E-commerce catalog.");
3192
+ if (parent.catalog_type !== "ECOM" || parent.catalog_conf.is_multi_country === true) throw new AdportError19("INVALID_INPUT", "Catalog videos require a single-country E-commerce catalog.");
3088
3193
  return parent;
3089
3194
  }
3090
3195
  async request(path2, args) {
@@ -3095,9 +3200,9 @@ var TikTokCatalogVideos = class {
3095
3200
  }
3096
3201
  }
3097
3202
  async native(scope, ids2, page3 = 1, size = 20) {
3098
- const result = z19.object({ videos: z19.array(nativeVideo).max(ids2 ? ids2.length : size), page_info: z19.unknown().optional() }).safeParse(await this.request("catalog/video/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id, ...ids2 ? { catalog_video_ids: ids2 } : { page: page3, page_size: size } }));
3203
+ const result = z20.object({ videos: z20.array(nativeVideo).max(ids2 ? ids2.length : size), page_info: z20.unknown().optional() }).safeParse(await this.request("catalog/video/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id, ...ids2 ? { catalog_video_ids: ids2 } : { page: page3, page_size: size } }));
3099
3204
  if (!result.success) throw invalid8();
3100
- const pageInfo7 = ids2 || result.data.page_info === void 0 ? void 0 : z19.object({ page: z19.number().int().positive().safe(), page_size: z19.number().int().positive().max(50), total_page: count4.optional(), total_number: count4.optional() }).safeParse(result.data.page_info);
3205
+ const pageInfo7 = ids2 || result.data.page_info === void 0 ? void 0 : z20.object({ page: z20.number().int().positive().safe(), page_size: z20.number().int().positive().max(50), total_page: count4.optional(), total_number: count4.optional() }).safeParse(result.data.page_info);
3101
3206
  if (pageInfo7 && !pageInfo7.success) throw invalid8();
3102
3207
  const rows = result.data.videos, info = pageInfo7?.data;
3103
3208
  if (new Set(rows.map((row3) => row3.catalog_video_id)).size !== rows.length || rows.some((row3) => ids2 && !ids2.includes(row3.catalog_video_id) || row3.catalog_id !== void 0 && row3.catalog_id !== scope.catalog_id || row3.bc_id !== void 0 && row3.bc_id !== scope.bc_id) || !ids2 && info && (info.page !== page3 || info.page_size !== size)) throw invalid8();
@@ -3148,10 +3253,10 @@ var TikTokCatalogVideos = class {
3148
3253
  async log(value) {
3149
3254
  const input = catalogVideoLog.parse(value), scope = catalogInput.parse({ account_id: input.account_id, bc_id: input.bc_id, catalog_id: input.catalog_id });
3150
3255
  await this.parent(scope);
3151
- const issue = z19.object({ field: z19.string().max(256 * 1024).optional(), affected_video_count: count4 });
3152
- const result = z19.object({
3153
- video_feed_log: z19.object({ catalog_id: nativeId9, bc_id: nativeId9.optional(), feed_log_id: nativeId9.optional(), feed_id: nativeId9.optional(), add_count: count4.optional(), update_count: count4.optional(), delete_count: count4.optional(), error_count: count4.optional(), warn_count: count4.optional(), process_status: z19.enum(["PROCESSING", "SUCCESS", "FAILED", "WAITING"]), start_time: time.optional(), end_time: time.optional() }),
3154
- feed_log_data: z19.object({ error_affected_videos: z19.array(issue).max(1e3).nullable().optional(), warn_affected_videos: z19.array(issue).max(1e3).nullable().optional() }).nullable().optional()
3256
+ const issue = z20.object({ field: z20.string().max(256 * 1024).optional(), affected_video_count: count4 });
3257
+ const result = z20.object({
3258
+ video_feed_log: z20.object({ catalog_id: nativeId9, bc_id: nativeId9.optional(), feed_log_id: nativeId9.optional(), feed_id: nativeId9.optional(), add_count: count4.optional(), update_count: count4.optional(), delete_count: count4.optional(), error_count: count4.optional(), warn_count: count4.optional(), process_status: z20.enum(["PROCESSING", "SUCCESS", "FAILED", "WAITING"]), start_time: time.optional(), end_time: time.optional() }),
3259
+ feed_log_data: z20.object({ error_affected_videos: z20.array(issue).max(1e3).nullable().optional(), warn_affected_videos: z20.array(issue).max(1e3).nullable().optional() }).nullable().optional()
3155
3260
  }).safeParse(await this.request("catalog/video/log", { bc_id: input.bc_id, catalog_id: input.catalog_id, feed_log_id: input.feed_log_id, language: "en" }));
3156
3261
  if (!result.success) throw invalid8();
3157
3262
  const row3 = result.data.video_feed_log;
@@ -3170,43 +3275,43 @@ var TikTokCatalogVideos = class {
3170
3275
  }
3171
3276
  async source(scope, mediaId, sha, write = false) {
3172
3277
  const parent = await this.parent(scope, write), media = this.media;
3173
- if (!media) throw new AdportError18("NOT_CONNECTED", "Catalog-video imports require a CSV staged through Adport agent, widget, dashboard or cloud CLI media tools.");
3278
+ if (!media) throw new AdportError19("NOT_CONNECTED", "Catalog-video imports require a CSV staged through Adport agent, widget, dashboard or cloud CLI media tools.");
3174
3279
  let raw;
3175
3280
  try {
3176
3281
  raw = await media.read({ media_id: mediaId, expected_sha256: sha }, { maxBytes: MAX_PROJECT_MEDIA_BYTES4, contentTypes: ["text/csv"] });
3177
3282
  } catch {
3178
- throw new AdportError18("INVALID_INPUT", "Catalog-video CSV bytes/checksum could not be verified. Refresh the immutable media reference.");
3283
+ throw new AdportError19("INVALID_INPUT", "Catalog-video CSV bytes/checksum could not be verified. Refresh the immutable media reference.");
3179
3284
  }
3180
3285
  const file = verifyMedia4(raw.bytes, raw.name, sha, { maxBytes: MAX_PROJECT_MEDIA_BYTES4, contentTypes: ["text/csv"] }), rows = csvRows4(file.bytes, { maxRows: 5001, maxColumns: columns.length }), first = rows.next();
3181
- if (first.done || new Set(first.value).size !== first.value.length || first.value.some((key2) => !columns.includes(key2)) || columns.slice(0, 3).some((key2) => !first.value.includes(key2))) throw new AdportError18("INVALID_INPUT", "Use the documented catalog-video CSV headers: video_name, video_link, sku_id_list and optional native metadata columns.");
3286
+ if (first.done || new Set(first.value).size !== first.value.length || first.value.some((key2) => !columns.includes(key2)) || columns.slice(0, 3).some((key2) => !first.value.includes(key2))) throw new AdportError19("INVALID_INPUT", "Use the documented catalog-video CSV headers: video_name, video_link, sku_id_list and optional native metadata columns.");
3182
3287
  const previews = [], allSkus = /* @__PURE__ */ new Set();
3183
3288
  let rowCount = 0;
3184
3289
  for (const fields of rows) {
3185
3290
  const row3 = Object.fromEntries(first.value.map((key2, i) => [key2, fields[i]]));
3186
- if (!row3.video_name?.trim() || row3.video_name.length > 500 || !safeUrl2(row3.video_link, false) || row3.landing_page_url && !safeUrl2(row3.landing_page_url, false) || ["category", "brand", "creator", "video_type", "description"].some((key2) => (row3[key2]?.length ?? 0) > 500)) throw new AdportError18("INVALID_INPUT", "Each catalog-video row needs a nonempty name up to 500 characters and a valid HTTP(S) video URL. Optional metadata up to 500 characters; native would null longer values.");
3291
+ if (!row3.video_name?.trim() || row3.video_name.length > 500 || !safeUrl2(row3.video_link, false) || row3.landing_page_url && !safeUrl2(row3.landing_page_url, false) || ["category", "brand", "creator", "video_type", "description"].some((key2) => (row3[key2]?.length ?? 0) > 500)) throw new AdportError19("INVALID_INPUT", "Each catalog-video row needs a nonempty name up to 500 characters and a valid HTTP(S) video URL. Optional metadata up to 500 characters; native would null longer values.");
3187
3292
  const skus = row3.sku_id_list.split(",");
3188
- if (!skus.length || skus.length > 20 || skus.some((sku) => !sku || sku !== sku.trim() || sku.length > 100 || /[\u0000-\u001f\u007f]/.test(sku)) || new Set(skus).size !== skus.length) throw new AdportError18("INVALID_INPUT", "Each video needs 1\u201320 distinct exact SKU IDs, comma-separated without surrounding whitespace. Quote the CSV field when it contains commas.");
3293
+ if (!skus.length || skus.length > 20 || skus.some((sku) => !sku || sku !== sku.trim() || sku.length > 100 || /[\u0000-\u001f\u007f]/.test(sku)) || new Set(skus).size !== skus.length) throw new AdportError19("INVALID_INPUT", "Each video needs 1\u201320 distinct exact SKU IDs, comma-separated without surrounding whitespace. Quote the CSV field when it contains commas.");
3189
3294
  for (const sku of skus) allSkus.add(sku);
3190
- if (allSkus.size > 5e3) throw new AdportError18("INVALID_INPUT", "Adport verifies at most 5,000 distinct SKU associations per import. Use smaller CSV batches.");
3295
+ if (allSkus.size > 5e3) throw new AdportError19("INVALID_INPUT", "Adport verifies at most 5,000 distinct SKU associations per import. Use smaller CSV batches.");
3191
3296
  if (previews.length < 20) previews.push({ row: rowCount + 2, name: row3.video_name, sku_ids: skus, source: sourceInfo(row3.video_link) });
3192
3297
  rowCount++;
3193
3298
  }
3194
- if (!rowCount) throw new AdportError18("INVALID_INPUT", "The catalog-video CSV needs at least one data row.");
3299
+ if (!rowCount) throw new AdportError19("INVALID_INPUT", "The catalog-video CSV needs at least one data row.");
3195
3300
  const skuIds = [...allSkus].sort(), found = /* @__PURE__ */ new Map();
3196
3301
  for (let start = 0; start < skuIds.length; start += 1e3) {
3197
3302
  const selected5 = skuIds.slice(start, start + 1e3);
3198
3303
  for (let page3 = 1; page3 <= 2; page3++) {
3199
- const result = z19.object({ list: z19.array(z19.object({ sku_id: z19.string().min(1).max(100), product_id: nativeId9, ad_creation_eligible: z19.string(), catalog_id: nativeId9.optional(), bc_id: nativeId9.optional() })).max(500), page_info: z19.object({ page: z19.number().int().positive(), page_size: z19.number().int().positive(), total_page: count4.optional(), total_number: count4.optional() }).optional() }).safeParse(await this.request("catalog/product/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id, sku_ids: selected5, page: page3, page_size: 500 }));
3304
+ const result = z20.object({ list: z20.array(z20.object({ sku_id: z20.string().min(1).max(100), product_id: nativeId9, ad_creation_eligible: z20.string(), catalog_id: nativeId9.optional(), bc_id: nativeId9.optional() })).max(500), page_info: z20.object({ page: z20.number().int().positive(), page_size: z20.number().int().positive(), total_page: count4.optional(), total_number: count4.optional() }).optional() }).safeParse(await this.request("catalog/product/get", { bc_id: scope.bc_id, catalog_id: scope.catalog_id, sku_ids: selected5, page: page3, page_size: 500 }));
3200
3305
  if (!result.success || result.data.page_info && (result.data.page_info.page !== page3 || result.data.page_info.page_size !== 500)) throw invalid8();
3201
3306
  for (const row3 of result.data.list) {
3202
3307
  if (!selected5.includes(row3.sku_id) || found.has(row3.sku_id) || row3.catalog_id !== void 0 && row3.catalog_id !== scope.catalog_id || row3.bc_id !== void 0 && row3.bc_id !== scope.bc_id) throw invalid8();
3203
- if (row3.ad_creation_eligible !== "AVAILABLE") throw new AdportError18("INVALID_INPUT", "Every associated SKU must be natively AVAILABLE for ad creation. No import was submitted.");
3308
+ if (row3.ad_creation_eligible !== "AVAILABLE") throw new AdportError19("INVALID_INPUT", "Every associated SKU must be natively AVAILABLE for ad creation. No import was submitted.");
3204
3309
  found.set(row3.sku_id, { sku_id: row3.sku_id, product_id: row3.product_id, ad_creation_eligible: row3.ad_creation_eligible });
3205
3310
  }
3206
3311
  if (selected5.every((sku) => found.has(sku))) break;
3207
3312
  if (!result.data.list.length || !result.data.page_info || result.data.page_info.total_page === void 0 || page3 >= result.data.page_info.total_page) break;
3208
3313
  }
3209
- if (!selected5.every((sku) => found.has(sku))) throw new AdportError18("INVALID_INPUT", "Not every selected SKU association could be verified in the catalog. No import was submitted.");
3314
+ if (!selected5.every((sku) => found.has(sku))) throw new AdportError19("INVALID_INPUT", "Not every selected SKU association could be verified in the catalog. No import was submitted.");
3210
3315
  }
3211
3316
  const associations = [...found.values()].sort((a, b) => a.sku_id.localeCompare(b.sku_id));
3212
3317
  return { parent, file, rowCount, skuCount: skuIds.length, previews, associations_hash: digest9({ ...scope, sha256: file.sha256, associations }) };
@@ -3227,35 +3332,35 @@ var TikTokCatalogVideos = class {
3227
3332
  };
3228
3333
  }
3229
3334
  async plan(op) {
3230
- if (op.provider !== "tiktok") throw new AdportError18("INVALID_INPUT", "TikTok catalog-video provider differs.");
3335
+ if (op.provider !== "tiktok") throw new AdportError19("INVALID_INPUT", "TikTok catalog-video provider differs.");
3231
3336
  if (op.tool === "tiktok_upload_catalog_videos" && op.kind === "create") {
3232
3337
  const input = catalogVideoUpload.parse(op.payload), scope = catalogInput.parse({ account_id: op.accountId, bc_id: input.bc_id, catalog_id: input.catalog_id }), media = this.media, providerUrl = media?.providerUrl?.bind(media);
3233
- if (!providerUrl) throw new AdportError18("NOT_CONNECTED", "Catalog-video CSV imports require the hosted project media library to create a private download grant.");
3338
+ if (!providerUrl) throw new AdportError19("NOT_CONNECTED", "Catalog-video CSV imports require the hosted project media library to create a private download grant.");
3234
3339
  const prepare = async () => {
3235
3340
  const result = await this.source(scope, input.media_id, input.expected_sha256, true);
3236
- if (result.parent.configuration_hash !== input.expected_catalog_hash || result.associations_hash !== input.expected_associations_hash) throw new AdportError18("PENDING_MISMATCH", "Catalog configuration or SKU associations changed. Read import context and request a fresh preview.");
3341
+ if (result.parent.configuration_hash !== input.expected_catalog_hash || result.associations_hash !== input.expected_associations_hash) throw new AdportError19("PENDING_MISMATCH", "Catalog configuration or SKU associations changed. Read import context and request a fresh preview.");
3237
3342
  return result;
3238
3343
  };
3239
- const initial = await prepare(), notes6 = ["Local preview only. This adds catalog videos asynchronously and may make them available to existing Video Shopping Ads using the associated products. Ad statuses and budgets are not changed.", "Only one catalog-video file task can run at a time. Wait for prior tasks; uncertain/failed submissions are never automatically retried.", "Native video extraction, media eligibility and any advertiser-library sync remain separate from task acceptance.", input.sync_to_selected_account ? `Requests a separate video copy in the selected advertiser ${scope.account_id}. TikTok ignores ineligible accounts; this request does not confirm sync. Catalog deletion does not delete advertiser copies.` : "No advertiser-library sync is requested."];
3344
+ const initial = await prepare(), notes7 = ["Local preview only. This adds catalog videos asynchronously and may make them available to existing Video Shopping Ads using the associated products. Ad statuses and budgets are not changed.", "Only one catalog-video file task can run at a time. Wait for prior tasks; uncertain/failed submissions are never automatically retried.", "Native video extraction, media eligibility and any advertiser-library sync remain separate from task acceptance.", input.sync_to_selected_account ? `Requests a separate video copy in the selected advertiser ${scope.account_id}. TikTok ignores ineligible accounts; this request does not confirm sync. Catalog deletion does not delete advertiser copies.` : "No advertiser-library sync is requested."];
3240
3345
  return {
3241
3346
  summary: `Upload ${initial.rowCount} catalog videos`,
3242
3347
  changes: [`+ ${initial.rowCount} video rows and ${initial.skuCount} distinct SKU associations in catalog ${input.catalog_id}.`, `CSV SHA-256 ${input.expected_sha256}; selected advertiser sync requested: ${input.sync_to_selected_account}.`],
3243
3348
  coercions: [],
3244
3349
  budgetDeltas: [],
3245
- notes: notes6,
3246
- review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload catalog videos", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Video rows", after: initial.rowCount }, { label: "Associated SKUs", after: initial.skuCount }, { label: "Ad-account copy requested", after: input.sync_to_selected_account ? scope.account_id : "No" }, { label: "CSV SHA-256", after: input.expected_sha256 }, { label: "SKU association snapshot", after: input.expected_associations_hash }], notices: notes6 },
3350
+ notes: notes7,
3351
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "create", title: "Upload catalog videos", subject: initial.file.name, fields: [{ label: "Catalog", after: input.catalog_id }, { label: "Video rows", after: initial.rowCount }, { label: "Associated SKUs", after: initial.skuCount }, { label: "Ad-account copy requested", after: input.sync_to_selected_account ? scope.account_id : "No" }, { label: "CSV SHA-256", after: input.expected_sha256 }, { label: "SKU association snapshot", after: input.expected_associations_hash }], notices: notes7 },
3247
3352
  execute: async () => {
3248
3353
  await prepare();
3249
3354
  let grant;
3250
3355
  try {
3251
3356
  grant = await providerUrl({ media_id: input.media_id, expected_sha256: input.expected_sha256 }, { maxBytes: MAX_PROJECT_MEDIA_BYTES4, contentTypes: ["text/csv"] });
3252
3357
  } catch {
3253
- throw new AdportError18("PROVIDER_ERROR", "Private CSV staging failed. No native catalog-video upload was submitted.");
3358
+ throw new AdportError19("PROVIDER_ERROR", "Private CSV staging failed. No native catalog-video upload was submitted.");
3254
3359
  }
3255
- if (grant.sha256 !== input.expected_sha256 || !safeUrl2(grant.url) || !(Date.parse(grant.expires_at) > Date.now() + 10 * 6e4)) throw new AdportError18("PROVIDER_ERROR", "The private CSV grant could not be verified. No catalog-video upload was submitted.");
3360
+ if (grant.sha256 !== input.expected_sha256 || !safeUrl2(grant.url) || !(Date.parse(grant.expires_at) > Date.now() + 10 * 6e4)) throw new AdportError19("PROVIDER_ERROR", "The private CSV grant could not be verified. No catalog-video upload was submitted.");
3256
3361
  let job;
3257
3362
  try {
3258
- const result = z19.object({ feed_log_id: nativeId9 }).parse(await this.client.post("catalog/video/file", { bc_id: input.bc_id, catalog_id: input.catalog_id, file_url: grant.url, ...input.sync_to_selected_account ? { advertiser_ids: [scope.account_id] } : {} }));
3363
+ const result = z20.object({ feed_log_id: nativeId9 }).parse(await this.client.post("catalog/video/file", { bc_id: input.bc_id, catalog_id: input.catalog_id, file_url: grant.url, ...input.sync_to_selected_account ? { advertiser_ids: [scope.account_id] } : {} }));
3259
3364
  job = result.feed_log_id;
3260
3365
  const actual = await this.log({ ...scope, feed_log_id: job });
3261
3366
  if (actual.log.process_status === "FAILED" || (actual.log.error_count ?? 0) > 0) throw new Error("Native task failed or has item errors");
@@ -3271,19 +3376,19 @@ var TikTokCatalogVideos = class {
3271
3376
  const prepare = async () => {
3272
3377
  await this.parent(scope, true);
3273
3378
  const result = await this.native(scope, [input.catalog_video_id]);
3274
- if (result.rows.length !== 1) throw new AdportError18("INVALID_INPUT", "The exact catalog video could not be verified. Refresh the gallery.");
3379
+ if (result.rows.length !== 1) throw new AdportError19("INVALID_INPUT", "The exact catalog video could not be verified. Refresh the gallery.");
3275
3380
  const row3 = result.rows[0];
3276
- if (configurationHash2(scope, row3) !== input.expected_configuration_hash) throw new AdportError18("PENDING_MISMATCH", "The catalog video changed. Read its configuration and request a fresh preview.");
3381
+ if (configurationHash2(scope, row3) !== input.expected_configuration_hash) throw new AdportError19("PENDING_MISMATCH", "The catalog video changed. Read its configuration and request a fresh preview.");
3277
3382
  return row3;
3278
3383
  };
3279
- const current = await prepare(), notes6 = ["Local preview only. Removes one catalog video and its product associations; existing catalog ads may be affected.", "Video copies already synced into advertiser creative libraries are not removed. No global/atomic usage guarantee or restore endpoint is available."];
3384
+ const current = await prepare(), notes7 = ["Local preview only. Removes one catalog video and its product associations; existing catalog ads may be affected.", "Video copies already synced into advertiser creative libraries are not removed. No global/atomic usage guarantee or restore endpoint is available."];
3280
3385
  return {
3281
3386
  summary: `Remove catalog video "${current.video_name}"`,
3282
3387
  changes: [`- Catalog video ${input.catalog_video_id} and its catalog SKU associations.`, "Advertiser-library copies may remain."],
3283
3388
  coercions: [],
3284
3389
  budgetDeltas: [],
3285
- notes: notes6,
3286
- review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Remove from catalog", subject: current.video_name, fields: [{ label: "Catalog video", after: input.catalog_video_id }, { label: "Associated SKUs", after: current.sku_id_list ?? "Not reported" }, { label: "Extraction", after: current.status }, { label: "Activation", after: current.active_status ?? "Not reported" }], notices: notes6 },
3390
+ notes: notes7,
3391
+ review: { provider: "tiktok", accountId: scope.account_id, kind: "remove", title: "Remove from catalog", subject: current.video_name, fields: [{ label: "Catalog video", after: input.catalog_video_id }, { label: "Associated SKUs", after: current.sku_id_list ?? "Not reported" }, { label: "Extraction", after: current.status }, { label: "Activation", after: current.active_status ?? "Not reported" }], notices: notes7 },
3287
3392
  execute: async () => {
3288
3393
  await prepare();
3289
3394
  try {
@@ -3297,17 +3402,19 @@ var TikTokCatalogVideos = class {
3297
3402
  }
3298
3403
  };
3299
3404
  }
3300
- throw new AdportError18("INVALID_INPUT", "Unsupported TikTok catalog-video operation or kind.");
3405
+ throw new AdportError19("INVALID_INPUT", "Unsupported TikTok catalog-video operation or kind.");
3301
3406
  }
3302
3407
  };
3303
3408
 
3304
3409
  // src/catalog-tools.ts
3305
- var hash11 = z20.string().regex(/^[a-f0-9]{64}$/);
3306
- var catalogRename = catalogInput.omit({ account_id: true }).extend({ name: z20.string().trim().min(1).max(128), expected_configuration_hash: hash11, acknowledge_shared_effects: z20.literal(true) }).strict();
3307
- var catalogAccessChange = catalogPermissionSelection.omit({ account_id: true }).extend({ mode: z20.enum(["none", "read", "write", "create"]), expected_access_hash: hash11 }).strict().refine(validCatalogPermission, "Creation delegation accepts create/none without a catalog ID; catalog grants accept read/write/none with an exact catalog ID");
3410
+ var hash12 = z21.string().regex(/^[a-f0-9]{64}$/);
3411
+ var catalogRename = catalogInput.omit({ account_id: true }).extend({ name: z21.string().trim().min(1).max(128), expected_configuration_hash: hash12, acknowledge_shared_effects: z21.literal(true) }).strict();
3412
+ var catalogAccessChange = catalogPermissionSelection.omit({ account_id: true }).extend({ mode: z21.enum(["none", "read", "write", "create", "migrate"]), expected_access_hash: hash12, acknowledge_source_ownership: z21.literal(true).optional(), acknowledge_shared_effects: z21.literal(true).optional() }).strict().refine(validCatalogPermission, "Choose exact catalog read/write access, creation without a catalog ID, or an exact transfer with owner and shared-effects acknowledgements");
3308
3413
  function tiktokCatalogTools(provider, accessManagement = false) {
3309
- const read = { namespace: "tiktok", annotations: { readOnly: true }, presentation: "records", output: z20.looseObject({ records: z20.array(z20.record(z20.string(), z20.unknown())) }) };
3414
+ const read = { namespace: "tiktok", annotations: { readOnly: true }, presentation: "records", output: z21.looseObject({ records: z21.array(z21.record(z21.string(), z21.unknown())) }) };
3310
3415
  return [
3416
+ defineTool4({ ...read, name: "tiktok_catalog_migration_context", catalog: { category: "administration", exposure: "specialist" }, description: "Read a separate owner-attested exact transfer grant, verify destination Business Center Admin and absence of the source catalog there. Source ownership is not independently verified; TikTok enforces it at apply. Returns hashes for a guarded transfer.", input: catalogInput, handler: (input) => provider.catalogs.migration.context(input) }),
3417
+ guardedWriteTool3({ name: "tiktok_migrate_catalog", namespace: "tiktok", provider: "tiktok", catalog: { category: "administration", exposure: "specialist" }, kind: "update", destructive: true, description: "Transfer an exact advertiser-owned catalog to a Business Center using separate owner-attested delegation and destination hashes. Whole-catalog/shared effects; native ownership check at apply and exact destination readback. No project grant expansion, rollback or automatic retry.", payload: catalogMigration }),
3311
3418
  defineTool4({ ...read, name: "tiktok_catalog_creation_context", catalog: { category: "creatives", exposure: "specialist" }, description: "Read an owner-delegated creation grant hash and available regions for one advertiser/Business Center. Covers all ten catalog types; native allowlists and currency combinations remain authoritative. No existing catalogs are enumerated or granted.", input: catalogCreationInput, handler: (input) => provider.catalogs.lifecycle.context(input) }),
3312
3419
  guardedWriteTool3({ name: "tiktok_create_catalog", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: false, description: "Create an empty catalog using creation-delegation/region hashes and explicit immutable configuration. Independently verifies the native ID/configuration, then adopts only that new ID for project read/write access under owner delegation. No ads, products or spend; no automatic replay.", payload: catalogCreate }),
3313
3420
  guardedWriteTool3({ name: "tiktok_delete_catalog", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Permanently delete one writable catalog with fresh configuration_hash, exact name confirmation and contents/shared-effects acknowledgement. Deletes current products/feeds; contents are not enumerated/frozen. Verifies native receipt and filtered absence; errors are not absence. No restore or replay.", payload: catalogDelete }),
@@ -3316,19 +3423,19 @@ function tiktokCatalogTools(provider, accessManagement = false) {
3316
3423
  defineTool4({ ...read, name: "tiktok_catalog_event_source_context", catalog: { category: "measurement", exposure: "specialist" }, description: "Verify one app_id, pixel_code or both under the selected advertiser and read catalog/binding/source hashes for bind or unbind. Bind checks Pixel catalog availability; unbind checks existing membership. No events or writes.", input: catalogEventContext, handler: (input) => provider.catalogs.eventSources.context(input) }),
3317
3424
  guardedWriteTool3({ name: "tiktok_bind_catalog_event_sources", namespace: "tiktok", provider: "tiktok", catalog: { category: "measurement", exposure: "specialist" }, kind: "update", destructive: true, description: "Bind selected advertiser app/Pixel sources to a writable catalog using fresh context hashes and shared/measurement-effects acknowledgement. Can affect existing catalog matching/ads. Rechecks sources and all bindings; no tracking installation, event sending or automatic replay.", payload: catalogEventChange }),
3318
3425
  guardedWriteTool3({ name: "tiktok_unbind_catalog_event_sources", namespace: "tiktok", provider: "tiktok", catalog: { category: "measurement", exposure: "specialist" }, kind: "remove", destructive: true, description: "Unbind explicit selected advertiser app/Pixel sources using fresh context hashes. Requires existing membership and shared/measurement-effects acknowledgement. Verifies absence and preservation of unselected binding identities. No unbind-all inference or replay; no events sent.", payload: catalogEventChange }),
3319
- defineTool4({ ...read, name: "tiktok_catalog_videos", catalog: { category: "creatives", exposure: "specialist" }, description: "List videos in the selected TikTok catalog with SKU links, processing status and six-hour previews. Read-only. If permitted, the gallery links to the separately listed tiktok_delete_catalog_video tool for preview and approval.", input: catalogVideoList, output: creativesOutput.extend({ videos: z20.array(z20.record(z20.string(), z20.unknown())), complete: z20.boolean().nullable(), next_page: z20.number().int().positive().optional(), notes: z20.array(z20.string()), page_info: z20.record(z20.string(), z20.unknown()).optional(), missing_ids: z20.array(z20.string()).optional() }), presentation: "creatives", pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.catalogs.videos.list(input) }),
3426
+ defineTool4({ ...read, name: "tiktok_catalog_videos", catalog: { category: "creatives", exposure: "specialist" }, description: "List videos in the selected TikTok catalog with SKU links, processing status and six-hour previews. Read-only. If permitted, the gallery links to the separately listed tiktok_delete_catalog_video tool for preview and approval.", input: catalogVideoList, output: creativesOutput.extend({ videos: z21.array(z21.record(z21.string(), z21.unknown())), complete: z21.boolean().nullable(), next_page: z21.number().int().positive().optional(), notes: z21.array(z21.string()), page_info: z21.record(z21.string(), z21.unknown()).optional(), missing_ids: z21.array(z21.string()).optional() }), presentation: "creatives", pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.catalogs.videos.list(input) }),
3320
3427
  defineTool4({ ...read, name: "tiktok_catalog_video_log", catalog: { category: "creatives", exposure: "specialist" }, description: "Read one catalog-video handling task with exact catalog binding. Preserves native processing states/counts and bounded diagnostic field counts. Does not certify video extraction, ad eligibility or advertiser sync; source links/downloads and free-form diagnostics stay hidden.", input: catalogVideoLog, handler: (input) => provider.catalogs.videos.log(input) }),
3321
3428
  defineTool4({ ...read, name: "tiktok_catalog_video_import_context", catalog: { category: "creatives", exposure: "specialist" }, description: "Inspect a checksum-bound project CSV for catalog videos and verify every referenced SKU is AVAILABLE for ad creation. Returns catalog/association hashes for upload. Up to 5,000 rows/distinct SKUs and 20 SKUs/video; source URLs stay private. No upload or media-eligibility claim.", input: catalogVideoImportContext, handler: (input) => provider.catalogs.videos.importContext(input) }),
3322
3429
  guardedWriteTool3({ name: "tiktok_upload_catalog_videos", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "create", destructive: true, description: "Submit a checksum-bound library CSV to the native catalog-video file API, using fresh import-context hashes. May feed existing catalog ads; explicit delivery/shared/async acknowledgement required. Optional sync targets only the selected advertiser and requires copy acknowledgement. Returns an accepted job, not ingestion/sync success; no replay.", payload: catalogVideoUpload }),
3323
3430
  guardedWriteTool3({ name: "tiktok_delete_catalog_video", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Remove one composite catalog-video ID with its fresh configuration_hash and shared-effects acknowledgement. Rechecks native state, issues one delete and verifies filtered-view absence. Existing catalog ads may be affected; synced advertiser-library copies remain separate. No automatic replay or restore.", payload: catalogVideoDelete }),
3324
- defineTool4({ ...read, name: "tiktok_catalog_product_schema", catalog: { category: "creatives", exposure: "specialist" }, presentation: void 0, output: z20.looseObject({ schema: z20.record(z20.string(), z20.unknown()) }), description: "Read the official structural product schema for this granted catalog\u2019s native type and upload/update operation. Covers all ten catalog types. Native semantic requirements still apply; no products or ads are changed.", input: catalogProductSchema, handler: (input) => provider.catalogs.productAuthoring.schema(input) }),
3431
+ defineTool4({ ...read, name: "tiktok_catalog_product_schema", catalog: { category: "creatives", exposure: "specialist" }, presentation: void 0, output: z21.looseObject({ schema: z21.record(z21.string(), z21.unknown()) }), description: "Read the official structural product schema for this granted catalog\u2019s native type and upload/update operation. Covers all ten catalog types. Native semantic requirements still apply; no products or ads are changed.", input: catalogProductSchema, handler: (input) => provider.catalogs.productAuthoring.schema(input) }),
3325
3432
  defineTool4({ ...read, name: "tiktok_catalog_product_context", catalog: { category: "creatives", exposure: "specialist" }, description: "Read exact native product IDs, safe editable configuration and products_hash for JSON edits/removal. Verifies catalog/feed and every selected ID; URL origins/fingerprints only. This is selected configuration, not complete catalog inventory or proof of feed membership.", input: catalogProductContext, handler: (input) => provider.catalogs.productAuthoring.context(input) }),
3326
3433
  guardedWriteTool3({ name: "tiktok_upsert_catalog_products", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Upload up to5,000 native JSON products using the catalog-type schema. Can replace existing external identities; fresh catalog/feed hashes and explicit replacement/shared/async acknowledgements required. Returns an accepted task, not completed ingestion. No automatic replay.", payload: catalogProductUpsert, sensitiveInputs: ["products"] }),
3327
3434
  guardedWriteTool3({ name: "tiktok_update_catalog_products", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Patch product fields selected by verified native product IDs and products_hash. External identities are derived from native context and cannot be edited. Fresh catalog/feed hashes required; asynchronous task and shared-effects acknowledgements. Read the schema first; no automatic replay.", payload: catalogProductUpdate, sensitiveInputs: ["updates"] }),
3328
3435
  guardedWriteTool3({ name: "tiktok_delete_catalog_products", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "remove", destructive: true, description: "Remove verified native product IDs using products_hash and fresh catalog/feed hashes. Maps native external IDs to documented deletion selectors; Entertainment removal is undocumented and refused. Requires removal/shared/async acknowledgements. Returns accepted task; never replays.", payload: catalogProductDelete }),
3329
- defineTool4({ ...read, name: "tiktok_catalog_access", catalog: { category: "administration", exposure: "specialist" }, description: "List only this project/account\u2019s explicit Business Center catalog grants. Advertiser access alone grants no catalog access. No native Business Center inventory is enumerated.", input: z20.object({ account_id: catalogId }).strict(), handler: (input) => provider.catalogs.access(input.account_id) }),
3436
+ defineTool4({ ...read, name: "tiktok_catalog_access", catalog: { category: "administration", exposure: "specialist" }, description: "List only this project/account\u2019s explicit Business Center catalog grants. Advertiser access alone grants no catalog access. No native Business Center inventory is enumerated.", input: z21.object({ account_id: catalogId }).strict(), handler: (input) => provider.catalogs.access(input.account_id) }),
3330
3437
  defineTool4({ ...read, name: "tiktok_get_catalog", description: "Read one explicitly granted Business Center catalog, native eligibility and configuration_hash. Verifies exact catalog and Business Center IDs; does not enumerate unrelated catalogs.", input: catalogInput, handler: (input) => provider.catalogs.get(input) }),
3331
- defineTool4({ ...read, name: "tiktok_catalog_products", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse product/media summaries in an explicitly granted catalog. Native product-ID or ECOM SKU filters, exact string IDs and page navigation. At most100/page and10,000 accessible matches; missing pagination stays unknown. Compact view, not full editable configuration.", input: catalogProductList, output: creativesOutput.extend({ products: z20.array(z20.record(z20.string(), z20.unknown())), complete: z20.boolean().nullable(), next_page: z20.number().int().positive().optional(), native_access_limit: z20.literal(1e4), native_limit_reached: z20.boolean(), notes: z20.array(z20.string()), page_info: z20.record(z20.string(), z20.unknown()).optional() }), presentation: "creatives", pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.catalogs.products.list(input) }),
3438
+ defineTool4({ ...read, name: "tiktok_catalog_products", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse product/media summaries in an explicitly granted catalog. Native product-ID or ECOM SKU filters, exact string IDs and page navigation. At most100/page and10,000 accessible matches; missing pagination stays unknown. Compact view, not full editable configuration.", input: catalogProductList, output: creativesOutput.extend({ products: z21.array(z21.record(z21.string(), z21.unknown())), complete: z21.boolean().nullable(), next_page: z21.number().int().positive().optional(), native_access_limit: z21.literal(1e4), native_limit_reached: z21.boolean(), notes: z21.array(z21.string()), page_info: z21.record(z21.string(), z21.unknown()).optional() }), presentation: "creatives", pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.catalogs.products.list(input) }),
3332
3439
  defineTool4({ ...read, name: "tiktok_catalog_product_log", catalog: { category: "creatives", exposure: "specialist" }, description: "Read one product import task after verifying its catalog/feed. Native processing state, counts and bounded diagnostic field counts; no free-form error text or download capabilities. SUCCESS is not ad eligibility. Requires the feed_log_id returned on import.", input: catalogProductLog, handler: (input) => provider.catalogs.products.log(input) }),
3333
3440
  guardedWriteTool3({ name: "tiktok_import_catalog_file", namespace: "tiktok", provider: "tiktok", catalog: { category: "creatives", exposure: "specialist" }, kind: "update", destructive: true, description: "Submit a checksum-bound project CSV as a one-time catalog feed import. Fresh catalog/feed hashes, explicit mode and asynchronous/shared-effects acknowledgement; OVERWRITE also requires deletion acknowledgement. Returns an accepted native job, not completed ingestion. Never automatically replay.", payload: catalogFileImport }),
3334
3441
  defineTool4({ ...read, name: "tiktok_catalog_feeds", catalog: { category: "creatives", exposure: "specialist" }, description: "Browse feeds in one explicitly granted catalog, with safe source fingerprints and configuration_hash. Native lists are unpaged; Adport bounds to 5,000 and snapshot-pages locally. Credentials, source paths and query values stay hidden.", input: catalogFeedList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.catalogs.feeds.list(input) }),
@@ -3353,15 +3460,15 @@ function tiktokCatalogTools(provider, accessManagement = false) {
3353
3460
  }
3354
3461
 
3355
3462
  // src/catalogs.ts
3356
- var id4 = z21.string().regex(/^\d{1,30}$/);
3357
- var nativeCatalog = z21.looseObject({ catalog_id: id4, catalog_name: z21.string(), catalog_type: z21.string(), bc_info: z21.looseObject({ bc_id: id4, bc_name: z21.string().optional() }), catalog_conf: z21.record(z21.string(), z21.unknown()) });
3463
+ var id4 = z22.string().regex(/^\d{1,30}$/);
3464
+ var nativeCatalog = z22.looseObject({ catalog_id: id4, catalog_name: z22.string(), catalog_type: z22.string(), bc_info: z22.looseObject({ bc_id: id4, bc_name: z22.string().optional() }), catalog_conf: z22.record(z22.string(), z22.unknown()) });
3358
3465
  var canonical12 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
3359
3466
  var config3 = (value) => ({ catalog_id: value.catalog_id, catalog_name: value.catalog_name, catalog_type: value.catalog_type, bc_id: value.bc_info.bc_id, catalog_conf: value.catalog_conf });
3360
- var configurationHash3 = (account, value) => createHash13("sha256").update(canonical12({ account_id: account, ...config3(value) })).digest("hex");
3467
+ var configurationHash3 = (account, value) => createHash14("sha256").update(canonical12({ account_id: account, ...config3(value) })).digest("hex");
3361
3468
  var scopeOf = (input) => ({ accountId: input.account_id, businessId: input.bc_id, resourceId: input.catalog_id, kind: "catalog" });
3362
3469
  var nativeError = (error) => {
3363
- const details = error instanceof AdportError19 && error.details && typeof error.details === "object" ? error.details : {};
3364
- return new AdportError19("PROVIDER_ERROR", "TikTok catalog request failed. Check the token\u2019s Business Center/catalog permissions and native API eligibility. No request was retried.", { ...Number.isInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {} });
3470
+ const details = error instanceof AdportError20 && error.details && typeof error.details === "object" ? error.details : {};
3471
+ return new AdportError20("PROVIDER_ERROR", "TikTok catalog request failed. Check the token\u2019s Business Center/catalog permissions and native API eligibility. No request was retried.", { ...Number.isInteger(details.code) ? { provider_code: details.code } : {}, ...typeof details.request_id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(details.request_id) ? { request_id: details.request_id } : {} });
3365
3472
  };
3366
3473
  var TikTokCatalogService = class {
3367
3474
  constructor(client, store, media) {
@@ -3378,6 +3485,7 @@ var TikTokCatalogService = class {
3378
3485
  this.productAuthoring = new TikTokCatalogProductAuthoring(client, authorizeParent, this.feeds, this.products, media);
3379
3486
  this.videos = new TikTokCatalogVideos(client, authorizeParent, media);
3380
3487
  this.eventSources = new TikTokCatalogEventSources(client, authorizeParent);
3488
+ this.migration = new TikTokCatalogMigration(client, store, (input) => this.native(input, true));
3381
3489
  this.lifecycle = new TikTokCatalogLifecycle(client, store, authorizeParent, (input) => this.native(input, true));
3382
3490
  }
3383
3491
  client;
@@ -3389,8 +3497,9 @@ var TikTokCatalogService = class {
3389
3497
  videos;
3390
3498
  eventSources;
3391
3499
  lifecycle;
3500
+ migration;
3392
3501
  manager() {
3393
- if (!this.store?.canManage) throw new AdportError19("POLICY_VIOLATION", "Only the local owner or a signed-in project owner/admin in Accounts can change catalog access.");
3502
+ if (!this.store?.canManage) throw new AdportError20("POLICY_VIOLATION", "Only the local owner or a signed-in project owner/admin in Accounts can change catalog access.");
3394
3503
  return this.store;
3395
3504
  }
3396
3505
  async native(input, allowAbsent = false) {
@@ -3398,21 +3507,21 @@ var TikTokCatalogService = class {
3398
3507
  try {
3399
3508
  data = await this.client.get("catalog/get", { bc_id: input.bc_id, catalog_id: input.catalog_id, page: 1, page_size: 1e3 });
3400
3509
  } catch (error) {
3401
- if (error instanceof AdportError19 && ["POLICY_VIOLATION", "NOT_CONNECTED"].includes(error.code)) throw error;
3510
+ if (error instanceof AdportError20 && ["POLICY_VIOLATION", "NOT_CONNECTED"].includes(error.code)) throw error;
3402
3511
  throw nativeError(error);
3403
3512
  }
3404
- const result = z21.looseObject({ list: allowAbsent ? z21.array(nativeCatalog).max(1) : z21.array(nativeCatalog).length(1), page_info: z21.looseObject({ page: z21.number().int().positive(), total_page: z21.number().int().nonnegative() }).optional() }).safeParse(data);
3405
- if (!result.success || result.data.list.some((row3) => row3.catalog_id !== input.catalog_id || row3.bc_info.bc_id !== input.bc_id) || result.data.page_info && (result.data.page_info.page !== 1 || result.data.page_info.total_page > 1 || !result.data.list.length && typeof result.data.page_info.total_number === "number" && result.data.page_info.total_number !== 0)) throw new AdportError19("PROVIDER_ERROR", "TikTok returned an unexpected catalog/Business Center scope or incomplete exact-ID response.");
3513
+ const result = z22.looseObject({ list: allowAbsent ? z22.array(nativeCatalog).max(1) : z22.array(nativeCatalog).length(1), page_info: z22.looseObject({ page: z22.number().int().positive(), total_page: z22.number().int().nonnegative() }).optional() }).safeParse(data);
3514
+ if (!result.success || result.data.list.some((row3) => row3.catalog_id !== input.catalog_id || row3.bc_info.bc_id !== input.bc_id) || result.data.page_info && (result.data.page_info.page !== 1 || result.data.page_info.total_page > 1 || !result.data.list.length && typeof result.data.page_info.total_number === "number" && result.data.page_info.total_number !== 0)) throw new AdportError20("PROVIDER_ERROR", "TikTok returned an unexpected catalog/Business Center scope or incomplete exact-ID response.");
3406
3515
  return result.data.list[0];
3407
3516
  }
3408
3517
  async access(accountId) {
3409
3518
  id4.parse(accountId);
3410
3519
  const grants = await this.store?.list(accountId) ?? [];
3411
- if (grants.some((value) => value.scope.accountId !== accountId)) throw new AdportError19("POLICY_VIOLATION", "Catalog grants do not match the selected advertiser.");
3520
+ if (grants.some((value) => value.scope.accountId !== accountId)) throw new AdportError20("POLICY_VIOLATION", "Catalog grants do not match the selected advertiser.");
3412
3521
  return { grants, records: grants.map((value) => ({ id: value.scope.resourceId, name: value.scope.kind === "catalog" ? "Catalog " + value.scope.resourceId : "Catalog creation", business_center_id: value.scope.businessId, access: value.mode })), notes: ["Only explicit project grants are returned. An advertiser account does not implicitly authorize other Business Center assets."] };
3413
3522
  }
3414
3523
  async accessSnapshot(value) {
3415
- const input = catalogPermissionSnapshot.parse(value), scope = input.resource_kind === "catalog_creation" ? creationScope(input.account_id, input.bc_id) : scopeOf({ ...input, catalog_id: input.catalog_id }), grant = await this.manager().get(scope);
3524
+ const input = catalogPermissionSnapshot.parse(value), scope = input.resource_kind === "catalog_migration" ? migrationScope(input.account_id, input.bc_id, input.catalog_id) : input.resource_kind === "catalog_creation" ? creationScope(input.account_id, input.bc_id) : scopeOf({ ...input, catalog_id: input.catalog_id }), grant = await this.manager().get(scope);
3416
3525
  return { grant, records: [{ id: scope.resourceId, name: scope.kind === "catalog_creation" ? "Creation delegation" : "Catalog access", business_center_id: input.bc_id, access: grant.mode }] };
3417
3526
  }
3418
3527
  async get(value) {
@@ -3422,6 +3531,7 @@ var TikTokCatalogService = class {
3422
3531
  return { catalog: data, records: [{ id: catalog.catalog_id, name: catalog.catalog_name, native_ad_eligibility: catalog.ad_creation_eligible ?? "Not reported", type: catalog.catalog_type, business_center: catalog.bc_info.bc_name ?? input.bc_id, currency: catalog.catalog_conf.currency ?? "Not reported", country: catalog.catalog_conf.country ?? "Not reported" }] };
3423
3532
  }
3424
3533
  async plan(op) {
3534
+ if (op.tool === "tiktok_migrate_catalog") return this.migration.plan(op);
3425
3535
  if (["tiktok_create_catalog", "tiktok_delete_catalog"].includes(op.tool)) return this.lifecycle.plan(op);
3426
3536
  if (["tiktok_bind_catalog_event_sources", "tiktok_unbind_catalog_event_sources"].includes(op.tool)) return this.eventSources.plan(op);
3427
3537
  if (["tiktok_upload_catalog_videos", "tiktok_delete_catalog_video"].includes(op.tool)) return this.videos.plan(op);
@@ -3429,52 +3539,53 @@ var TikTokCatalogService = class {
3429
3539
  if (op.tool === "tiktok_import_catalog_file") return this.products.plan(op);
3430
3540
  if (["tiktok_create_catalog_feed", "tiktok_update_catalog_feed", "tiktok_set_catalog_feed_schedule_status", "tiktok_delete_catalog_feed"].includes(op.tool)) return this.feeds.plan(op);
3431
3541
  if (["tiktok_create_product_set", "tiktok_upload_product_set", "tiktok_update_product_set_conditions", "tiktok_delete_product_sets", "tiktok_rename_product_set"].includes(op.tool)) return this.productSets.plan(op);
3432
- if (op.provider !== "tiktok" || op.kind !== "update") throw new AdportError19("INVALID_INPUT", "TikTok catalog provider/operation kind mismatch.");
3542
+ if (op.provider !== "tiktok" || op.kind !== "update") throw new AdportError20("INVALID_INPUT", "TikTok catalog provider/operation kind mismatch.");
3433
3543
  const account = id4.parse(op.accountId);
3434
3544
  if (op.tool === "tiktok_set_catalog_access") {
3435
- const store = this.manager(), input2 = catalogAccessChange.parse(op.payload), scope2 = input2.resource_kind === "catalog_creation" ? creationScope(account, input2.bc_id) : scopeOf({ ...input2, account_id: account, catalog_id: input2.catalog_id }), current2 = await store.get(scope2);
3436
- if (current2.hash !== input2.expected_access_hash) throw new AdportError19("POLICY_VIOLATION", "Catalog access changed. Read and review it again.");
3437
- const creation = scope2.kind === "catalog_creation";
3545
+ const store = this.manager(), input2 = catalogAccessChange.parse(op.payload), scope2 = input2.resource_kind === "catalog_migration" ? migrationScope(account, input2.bc_id, input2.catalog_id) : input2.resource_kind === "catalog_creation" ? creationScope(account, input2.bc_id) : scopeOf({ ...input2, account_id: account, catalog_id: input2.catalog_id }), current2 = await store.get(scope2);
3546
+ if (current2.hash !== input2.expected_access_hash) throw new AdportError20("POLICY_VIOLATION", "Catalog access changed. Read and review it again.");
3547
+ const creation = scope2.kind === "catalog_creation", migration = scope2.kind === "catalog_migration";
3548
+ if (migration && input2.mode !== "none") await this.migration.destination(input2.bc_id);
3438
3549
  if (creation && input2.mode !== "none") await this.lifecycle.availableCountries(input2.bc_id);
3439
- const catalog = creation || input2.mode === "none" ? void 0 : await this.native({ account_id: account, bc_id: input2.bc_id, catalog_id: input2.catalog_id });
3440
- const title = input2.mode === "none" ? "Revoke catalog access" : creation ? "Delegate catalog creation" : "Grant catalog access", notes7 = ["This changes Adport project access, not TikTok\u2019s native user permissions.", "Write access covers this Business Center catalog wherever it is reused. Agents cannot expand their own hosted access.", ...creation ? ["Delegates creation in this exact Business Center and read/write management of verified new catalog IDs only. Existing catalogs are excluded.", "Revoking creation delegation does not revoke independent grants already issued for new catalogs. Native eligibility remains authoritative."] : []];
3550
+ const catalog = creation || migration || input2.mode === "none" ? void 0 : await this.native({ account_id: account, bc_id: input2.bc_id, catalog_id: input2.catalog_id });
3551
+ const title = input2.mode === "none" ? "Revoke catalog access" : creation ? "Delegate catalog creation" : migration ? "Delegate owner-attested catalog transfer" : "Grant catalog access", notes8 = ["This changes Adport project access, not TikTok\u2019s native user permissions.", "Write access covers this Business Center catalog wherever it is reused. Agents cannot expand their own hosted access.", ...migration ? ["The owner attests ownership of this exact source-advertiser catalog and authorizes moving it to this exact Business Center. Source ownership is not independently verified by Adport; TikTok checks it at apply.", "This permits only the reviewed ownership transfer. Catalog creation and ongoing read/write management require separate grants. The whole shared catalog and its consumers may be affected."] : [], ...creation ? ["Delegates creation in this exact Business Center and read/write management of verified new catalog IDs only. Existing catalogs are excluded.", "Revoking creation delegation does not revoke independent grants already issued for new catalogs. Native eligibility remains authoritative."] : []];
3441
3552
  return {
3442
3553
  summary: `${title} \xB7 ${catalog?.catalog_name ?? (creation ? "Business Center " + input2.bc_id : input2.catalog_id)}`,
3443
3554
  changes: [`~ Project access ${current2.mode} \u2192 ${input2.mode} for Business Center ${input2.bc_id}, ${creation ? "new catalogs only" : "catalog " + input2.catalog_id}`],
3444
3555
  coercions: [],
3445
3556
  budgetDeltas: [],
3446
- notes: notes7,
3447
- review: { provider: "tiktok", accountId: account, kind: "update", title, subject: catalog?.catalog_name ?? (creation ? "Business Center " + input2.bc_id : input2.catalog_id), fields: [{ label: "Business Center", after: catalog?.bc_info.bc_name ?? input2.bc_id }, { label: creation ? "Resource" : "Catalog", after: creation ? "New catalogs created through this project" : input2.catalog_id }, { label: "Project access", before: current2.mode, after: input2.mode === "create" ? "Create and manage verified new catalogs" : input2.mode }], notices: notes7 },
3557
+ notes: notes8,
3558
+ review: { provider: "tiktok", accountId: account, kind: "update", title, subject: catalog?.catalog_name ?? (creation ? "Business Center " + input2.bc_id : input2.catalog_id), fields: [{ label: "Business Center", after: catalog?.bc_info.bc_name ?? input2.bc_id }, { label: creation ? "Resource" : "Catalog", after: creation ? "New catalogs created through this project" : input2.catalog_id }, { label: "Project access", before: current2.mode, after: input2.mode === "create" ? "Create and manage verified new catalogs" : input2.mode === "migrate" ? "Transfer this owner-attested source catalog only" : input2.mode }], notices: notes8 },
3448
3559
  execute: async () => {
3449
3560
  const result = await store.compareAndSet(scope2, input2.expected_access_hash, input2.mode), actual = await store.get(scope2);
3450
- if (catalogScopeKey(result.scope) !== catalogScopeKey(scope2) || result.mode !== input2.mode || actual.hash !== result.hash) throw new AdportError19("POLICY_VIOLATION", "Catalog access receipt is unconfirmed. Inspect access before retrying.");
3561
+ if (catalogScopeKey(result.scope) !== catalogScopeKey(scope2) || result.mode !== input2.mode || actual.hash !== result.hash) throw new AdportError20("POLICY_VIOLATION", "Catalog access receipt is unconfirmed. Inspect access before retrying.");
3451
3562
  return [scope2.resourceId];
3452
3563
  }
3453
3564
  };
3454
3565
  }
3455
- if (op.tool !== "tiktok_update_catalog") throw new AdportError19("INVALID_INPUT", "Unsupported TikTok catalog mutation.");
3566
+ if (op.tool !== "tiktok_update_catalog") throw new AdportError20("INVALID_INPUT", "Unsupported TikTok catalog mutation.");
3456
3567
  const input = catalogRename.parse(op.payload), source2 = { account_id: account, bc_id: input.bc_id, catalog_id: input.catalog_id }, scope = scopeOf(source2);
3457
3568
  await requireCatalogAccess(this.store, scope, true);
3458
3569
  const current = await this.native(source2);
3459
- if (configurationHash3(account, current) !== input.expected_configuration_hash) throw new AdportError19("INVALID_INPUT", "Catalog configuration changed. Read and preview it again.");
3460
- const notes6 = ["Local preview only; TikTok checks native permissions and eligibility on apply.", "The catalog may be reused by other ads or accounts. This operation updates its name and does not activate ads or change a budget.", "No automatic retry. Inspect the exact catalog after an uncertain result."];
3570
+ if (configurationHash3(account, current) !== input.expected_configuration_hash) throw new AdportError20("INVALID_INPUT", "Catalog configuration changed. Read and preview it again.");
3571
+ const notes7 = ["Local preview only; TikTok checks native permissions and eligibility on apply.", "The catalog may be reused by other ads or accounts. This operation updates its name and does not activate ads or change a budget.", "No automatic retry. Inspect the exact catalog after an uncertain result."];
3461
3572
  return {
3462
3573
  summary: `Rename TikTok catalog ${current.catalog_name}`,
3463
3574
  changes: [`~ Catalog name ${JSON.stringify(current.catalog_name)} \u2192 ${JSON.stringify(input.name)}`],
3464
3575
  coercions: [],
3465
3576
  budgetDeltas: [],
3466
- notes: notes6,
3467
- review: { provider: "tiktok", accountId: account, kind: "update", title: "Rename catalog", subject: current.catalog_name, fields: [{ label: "Name", before: current.catalog_name, after: input.name }, { label: "Business Center", after: current.bc_info.bc_name ?? input.bc_id }], notices: notes6 },
3577
+ notes: notes7,
3578
+ review: { provider: "tiktok", accountId: account, kind: "update", title: "Rename catalog", subject: current.catalog_name, fields: [{ label: "Name", before: current.catalog_name, after: input.name }, { label: "Business Center", after: current.bc_info.bc_name ?? input.bc_id }], notices: notes7 },
3468
3579
  execute: async () => {
3469
3580
  await requireCatalogAccess(this.store, scope, true);
3470
3581
  try {
3471
- const result = z21.object({ catalog_id: id4 }).parse(await this.client.post("catalog/update", { bc_id: input.bc_id, catalog_id: input.catalog_id, name: input.name }));
3582
+ const result = z22.object({ catalog_id: id4 }).parse(await this.client.post("catalog/update", { bc_id: input.bc_id, catalog_id: input.catalog_id, name: input.name }));
3472
3583
  if (result.catalog_id !== input.catalog_id) throw new Error("ID differs");
3473
3584
  const actual = await this.native(source2);
3474
3585
  if (canonical12(config3(actual)) !== canonical12({ ...config3(current), catalog_name: input.name })) throw new Error("Configuration differs");
3475
3586
  return [input.catalog_id];
3476
3587
  } catch {
3477
- throw new AdportError19("PROVIDER_ERROR", "TikTok catalog rename outcome is unconfirmed. Read the known catalog before another write; do not replay automatically.", { resource_ids: [input.catalog_id] });
3588
+ throw new AdportError20("PROVIDER_ERROR", "TikTok catalog rename outcome is unconfirmed. Read the known catalog before another write; do not replay automatically.", { resource_ids: [input.catalog_id] });
3478
3589
  }
3479
3590
  }
3480
3591
  };
@@ -3482,29 +3593,29 @@ var TikTokCatalogService = class {
3482
3593
  };
3483
3594
 
3484
3595
  // src/audience-sharing.ts
3485
- import { createHash as createHash14 } from "crypto";
3486
- import { AdportError as AdportError20 } from "@adport/core";
3487
- import { z as z23 } from "zod";
3596
+ import { createHash as createHash15 } from "crypto";
3597
+ import { AdportError as AdportError21 } from "@adport/core";
3598
+ import { z as z24 } from "zod";
3488
3599
 
3489
3600
  // src/audience-sharing-schemas.ts
3490
- import { z as z22 } from "zod";
3491
- var selectedIds = z22.array(audienceId).min(1).max(10).refine((values) => new Set(values).size === values.length, "Use unique IDs");
3492
- var sharingSelection = z22.object({ custom_audience_ids: selectedIds, shared_advertiser_ids: selectedIds }).strict();
3601
+ import { z as z23 } from "zod";
3602
+ var selectedIds = z23.array(audienceId).min(1).max(10).refine((values) => new Set(values).size === values.length, "Use unique IDs");
3603
+ var sharingSelection = z23.object({ custom_audience_ids: selectedIds, shared_advertiser_ids: selectedIds }).strict();
3493
3604
  var audienceSharesRead = sharingSelection.safeExtend({ account_id: audienceId });
3494
- var audienceSharingContext = audienceSharesRead.safeExtend({ bc_id: audienceId, action: z22.enum(["SHARE", "UNSHARE"]).default("SHARE") }).refine((value) => value.action !== "UNSHARE" || value.custom_audience_ids.length === 1 && value.shared_advertiser_ids.length === 1, "Cancellation selects one audience/recipient pair");
3495
- var shareAudiences = sharingSelection.safeExtend({ bc_id: audienceId, expected_context_hash: z22.string().regex(/^[a-f0-9]{64}$/), acknowledge_recipient_access: z22.literal(true) });
3496
- var unshareAudience = z22.object({ bc_id: audienceId, custom_audience_id: audienceId, shared_advertiser_id: audienceId, expected_context_hash: z22.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z22.literal(true) }).strict();
3605
+ var audienceSharingContext = audienceSharesRead.safeExtend({ bc_id: audienceId, action: z23.enum(["SHARE", "UNSHARE"]).default("SHARE") }).refine((value) => value.action !== "UNSHARE" || value.custom_audience_ids.length === 1 && value.shared_advertiser_ids.length === 1, "Cancellation selects one audience/recipient pair");
3606
+ var shareAudiences = sharingSelection.safeExtend({ bc_id: audienceId, expected_context_hash: z23.string().regex(/^[a-f0-9]{64}$/), acknowledge_recipient_access: z23.literal(true) });
3607
+ var unshareAudience = z23.object({ bc_id: audienceId, custom_audience_id: audienceId, shared_advertiser_id: audienceId, expected_context_hash: z23.string().regex(/^[a-f0-9]{64}$/), acknowledge_shared_effects: z23.literal(true) }).strict();
3497
3608
  var audienceSharingWrites = /* @__PURE__ */ new Set(["tiktok_share_custom_audiences", "tiktok_unshare_custom_audience"]);
3498
3609
 
3499
3610
  // src/audience-sharing.ts
3500
3611
  var canonical13 = (value) => JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
3501
- var hash12 = (value) => createHash14("sha256").update(canonical13(value)).digest("hex");
3502
- var nativeShare = z23.object({ custom_audience_id: audienceNativeId, shared_advertiser_id: audienceNativeId, shared_advertiser_name: z23.string().max(4096), status: z23.string().max(128) });
3503
- var asset = z23.object({ asset_id: audienceNativeId, asset_type: z23.literal("ADVERTISER"), asset_name: z23.string().max(4096), advertiser_role: z23.string().max(128) });
3504
- var pageInfo6 = z23.object({ page: z23.number().int().positive().safe(), page_size: z23.number().int().min(1).max(50), total_page: z23.number().int().nonnegative().safe().optional(), total_number: z23.number().int().nonnegative().safe().optional() });
3612
+ var hash13 = (value) => createHash15("sha256").update(canonical13(value)).digest("hex");
3613
+ var nativeShare = z24.object({ custom_audience_id: audienceNativeId, shared_advertiser_id: audienceNativeId, shared_advertiser_name: z24.string().max(4096), status: z24.string().max(128) });
3614
+ var asset = z24.object({ asset_id: audienceNativeId, asset_type: z24.literal("ADVERTISER"), asset_name: z24.string().max(4096), advertiser_role: z24.string().max(128) });
3615
+ var pageInfo6 = z24.object({ page: z24.number().int().positive().safe(), page_size: z24.number().int().min(1).max(50), total_page: z24.number().int().nonnegative().safe().optional(), total_number: z24.number().int().nonnegative().safe().optional() });
3505
3616
  var supported = /* @__PURE__ */ new Set(["Customer File Audience", "Engagement Audience", "App Activity Audience", "Website Audience", "Lookalike Audience"]);
3506
3617
  var notices = ["This changes audience access for the selected destination advertisers. Revocation can affect ads already targeting a shared audience. No ad, budget or delivery status is changed.", "Business Center membership and source role are checked from the authorized user\u2019s native asset view. Native eligibility, account ownership requirements, quotas and concurrent operations remain authoritative.", "Sharing-log presence and native audience status are separate from matching, targetability or delivery. No conditional-write, atomic batch or automatic replay is available."];
3507
- var invalid9 = () => new AdportError20("PROVIDER_ERROR", "TikTok sharing scope, native representation or inventory completeness could not be verified.");
3618
+ var invalid9 = () => new AdportError21("PROVIDER_ERROR", "TikTok sharing scope, native representation or inventory completeness could not be verified.");
3508
3619
  var preserved = (row3) => {
3509
3620
  const { shared: _shared, ...configuration4 } = configuration(row3);
3510
3621
  return configuration4;
@@ -3522,16 +3633,16 @@ var TikTokAudienceSharing = class {
3522
3633
  try {
3523
3634
  return await this.client.get(path2, input);
3524
3635
  } catch (error) {
3525
- const details = error instanceof AdportError20 && error.details && typeof error.details === "object" ? error.details : {};
3526
- throw new AdportError20("PROVIDER_ERROR", "TikTok audience sharing read failed. Check existing native permissions; no access was changed.", { ...Number.isSafeInteger(details.code) ? { native_code: details.code } : {} });
3636
+ const details = error instanceof AdportError21 && error.details && typeof error.details === "object" ? error.details : {};
3637
+ throw new AdportError21("PROVIDER_ERROR", "TikTok audience sharing read failed. Check existing native permissions; no access was changed.", { ...Number.isSafeInteger(details.code) ? { native_code: details.code } : {} });
3527
3638
  }
3528
3639
  }
3529
3640
  owned(account, row3, share) {
3530
- if (row3.is_creator !== true || row3.owner_id !== account) throw new AdportError20("POLICY_VIOLATION", "Audience sharing requires explicit selected-advertiser ownership; recipient access is insufficient.");
3531
- if (share && (!supported.has(row3.type.trim()) || row3.is_valid !== true || row3.is_expiring !== false || row3.native_error_reported)) throw new AdportError20("INVALID_INPUT", "Only a documented shareable, available, non-expiring audience without a native error can be shared.");
3641
+ if (row3.is_creator !== true || row3.owner_id !== account) throw new AdportError21("POLICY_VIOLATION", "Audience sharing requires explicit selected-advertiser ownership; recipient access is insufficient.");
3642
+ if (share && (!supported.has(row3.type.trim()) || row3.is_valid !== true || row3.is_expiring !== false || row3.native_error_reported)) throw new AdportError21("INVALID_INPUT", "Only a documented shareable, available, non-expiring audience without a native error can be shared.");
3532
3643
  }
3533
3644
  async log(account, audience) {
3534
- const parsed = z23.object({ list: z23.array(nativeShare).max(5e3) }).safeParse(await this.get("dmp/custom_audience/share/log", { advertiser_id: account, custom_audience_id: audience }));
3645
+ const parsed = z24.object({ list: z24.array(nativeShare).max(5e3) }).safeParse(await this.get("dmp/custom_audience/share/log", { advertiser_id: account, custom_audience_id: audience }));
3535
3646
  if (!parsed.success || parsed.data.list.some((row3) => row3.custom_audience_id !== audience) || new Set(parsed.data.list.map((row3) => row3.shared_advertiser_id)).size !== parsed.data.list.length) throw invalid9();
3536
3647
  return parsed.data.list.sort((a, b) => a.shared_advertiser_id.localeCompare(b.shared_advertiser_id));
3537
3648
  }
@@ -3541,7 +3652,7 @@ var TikTokAudienceSharing = class {
3541
3652
  return rows;
3542
3653
  }
3543
3654
  selection(account, targets) {
3544
- if (targets.includes(account)) throw new AdportError20("INVALID_INPUT", "Choose destination advertisers other than the source.");
3655
+ if (targets.includes(account)) throw new AdportError21("INVALID_INPUT", "Choose destination advertisers other than the source.");
3545
3656
  }
3546
3657
  view(logs, targets) {
3547
3658
  return [...logs.values()].flat().filter((row3) => targets.includes(row3.shared_advertiser_id));
@@ -3559,7 +3670,7 @@ var TikTokAudienceSharing = class {
3559
3670
  const wanted = /* @__PURE__ */ new Set([source2, ...targets]), found = /* @__PURE__ */ new Map(), seen = /* @__PURE__ */ new Set();
3560
3671
  let complete = false;
3561
3672
  for (let page3 = 1; page3 <= 100; page3++) {
3562
- const parsed = z23.object({ list: z23.array(asset).max(50), page_info: pageInfo6.optional() }).safeParse(await this.get("bc/asset/get", { bc_id: bc, asset_type: "ADVERTISER", page: page3, page_size: 50 }));
3673
+ const parsed = z24.object({ list: z24.array(asset).max(50), page_info: pageInfo6.optional() }).safeParse(await this.get("bc/asset/get", { bc_id: bc, asset_type: "ADVERTISER", page: page3, page_size: 50 }));
3563
3674
  if (!parsed.success || parsed.data.page_info && (parsed.data.page_info.page !== page3 || parsed.data.page_info.page_size !== 50)) throw invalid9();
3564
3675
  const info = parsed.data.page_info;
3565
3676
  if (info && (info.total_page !== void 0 && info.total_page < page3 && parsed.data.list.length > 0 || info.total_number !== void 0 && (parsed.data.list.length !== Math.max(0, Math.min(50, info.total_number - (page3 - 1) * 50)) || info.total_page !== void 0 && (info.total_number === 0 ? info.total_page > 1 : info.total_page !== Math.ceil(info.total_number / 50))))) throw invalid9();
@@ -3575,8 +3686,8 @@ var TikTokAudienceSharing = class {
3575
3686
  break;
3576
3687
  }
3577
3688
  }
3578
- if (found.size !== wanted.size) throw new AdportError20("INVALID_INPUT", complete ? "Selected source/destination accounts are not all accessible in this Business Center." : "Business Center membership is unconfirmed; inventory is incomplete.");
3579
- if (!["ADMIN", "OPERATOR"].includes(found.get(source2).advertiser_role)) throw new AdportError20("POLICY_VIOLATION", "Audience sharing requires the authorized user to be Admin or Operator on the source advertiser.");
3689
+ if (found.size !== wanted.size) throw new AdportError21("INVALID_INPUT", complete ? "Selected source/destination accounts are not all accessible in this Business Center." : "Business Center membership is unconfirmed; inventory is incomplete.");
3690
+ if (!["ADMIN", "OPERATOR"].includes(found.get(source2).advertiser_role)) throw new AdportError21("POLICY_VIOLATION", "Audience sharing requires the authorized user to be Admin or Operator on the source advertiser.");
3580
3691
  return [...found.values()].sort((a, b) => a.asset_id.localeCompare(b.asset_id));
3581
3692
  }
3582
3693
  async prepare(value) {
@@ -3587,7 +3698,7 @@ var TikTokAudienceSharing = class {
3587
3698
  audiences.forEach((row3) => this.owned(input.account_id, row3, input.action === "SHARE"));
3588
3699
  const logs = await this.logs(input.account_id, input.custom_audience_ids);
3589
3700
  const fingerprint = { input, accounts, audiences: audiences.map((row3) => ({ snapshot_hash: row3.snapshot_hash, configuration: preserved(row3) })), logs: [...logs].map(([id6, rows]) => [id6, rows.map(({ shared_advertiser_name: _name, ...row3 }) => row3)]) };
3590
- return { input, accounts, audiences, logs, context_hash: hash12(fingerprint) };
3701
+ return { input, accounts, audiences, logs, context_hash: hash13(fingerprint) };
3591
3702
  }
3592
3703
  async context(value) {
3593
3704
  const current = await this.prepare(value), selected5 = this.view(current.logs, current.input.shared_advertiser_ids);
@@ -3595,14 +3706,14 @@ var TikTokAudienceSharing = class {
3595
3706
  }
3596
3707
  async plan(op) {
3597
3708
  const share = op.tool === "tiktok_share_custom_audiences";
3598
- if (op.provider !== "tiktok" || op.kind !== "update" || !share && op.tool !== "tiktok_unshare_custom_audience") throw new AdportError20("INVALID_INPUT", "Unsupported audience-sharing operation/provider kind.");
3709
+ if (op.provider !== "tiktok" || op.kind !== "update" || !share && op.tool !== "tiktok_unshare_custom_audience") throw new AdportError21("INVALID_INPUT", "Unsupported audience-sharing operation/provider kind.");
3599
3710
  const selected5 = share ? shareAudiences.parse(op.payload) : unshareAudience.parse(op.payload), input = share ? { account_id: op.accountId, ...shareAudiences.parse(selected5), action: "SHARE" } : { account_id: op.accountId, bc_id: selected5.bc_id, custom_audience_ids: [unshareAudience.parse(selected5).custom_audience_id], shared_advertiser_ids: [unshareAudience.parse(selected5).shared_advertiser_id], action: "UNSHARE" };
3600
3711
  const selection = audienceSharingContext.parse(Object.fromEntries(Object.entries(input).filter(([key2]) => !["expected_context_hash", "acknowledge_recipient_access"].includes(key2))));
3601
- if (canonical13([...new Set(op.affectedAccountIds ?? [])].sort()) !== canonical13([...selection.shared_advertiser_ids].sort())) throw new AdportError20("POLICY_VIOLATION", "All destination accounts must be bound to the shared policy operation.");
3712
+ if (canonical13([...new Set(op.affectedAccountIds ?? [])].sort()) !== canonical13([...selection.shared_advertiser_ids].sort())) throw new AdportError21("POLICY_VIOLATION", "All destination accounts must be bound to the shared policy operation.");
3602
3713
  const current = await this.prepare(selection);
3603
- if (current.context_hash !== selected5.expected_context_hash) throw new AdportError20("PENDING_MISMATCH", "Audience sharing, source configuration or account authority changed; read and preview again.");
3714
+ if (current.context_hash !== selected5.expected_context_hash) throw new AdportError21("PENDING_MISMATCH", "Audience sharing, source configuration or account authority changed; read and preview again.");
3604
3715
  const existing = this.view(current.logs, selection.shared_advertiser_ids);
3605
- if (share ? existing.length > 0 : existing.length !== 1) throw new AdportError20("INVALID_INPUT", share ? "A selected audience/recipient pair already appears in the sharing log. Reconcile partial outcomes and select only intended new pairs; do not replay sharing." : "The exact audience/recipient pair is not present in the current explicit sharing log.");
3716
+ if (share ? existing.length > 0 : existing.length !== 1) throw new AdportError21("INVALID_INPUT", share ? "A selected audience/recipient pair already appears in the sharing log. Reconcile partial outcomes and select only intended new pairs; do not replay sharing." : "The exact audience/recipient pair is not present in the current explicit sharing log.");
3606
3717
  const title = share ? "Share custom audiences" : "Revoke audience sharing";
3607
3718
  return { summary: title, changes: current.audiences.map((row3) => `${share ? "+" : "-"} ${row3.name} \xB7 ${selection.shared_advertiser_ids.length} recipient(s)`), coercions: [], budgetDeltas: [], notes: notices, review: { provider: "tiktok", accountId: op.accountId, kind: "update", title, fields: [{ label: "Business Center", after: selection.bc_id }, { label: "Owned audiences", after: current.audiences.map((row3) => ({ id: row3.audience_id, name: row3.name, type: row3.type })) }, { label: "Recipient accounts", after: current.accounts.filter((row3) => row3.asset_id !== op.accountId).map((row3) => ({ id: row3.asset_id, name: row3.asset_name })) }, { label: "Audience access", before: share ? "Not shared with selected recipients" : "Shared with selected recipient", after: share ? "Grant selected recipients access" : "Revoke selected recipient access" }], notices }, execute: async () => {
3608
3719
  const outcomes = [];
@@ -3620,8 +3731,8 @@ var TikTokAudienceSharing = class {
3620
3731
  if (after.some((row3) => canonical13(preserved(row3)) !== canonical13(preserved(current.audiences.find((before) => before.audience_id === row3.audience_id))))) throw invalid9();
3621
3732
  return { applied: true, resourceIds: selection.custom_audience_ids, details: { state: share ? "RECIPIENT_PAIRS_OBSERVED" : "RECIPIENT_PAIR_ABSENT", outcomes, audience_configuration_preserved: true, audience_availability_verified: false, ads_changed: false, next_tool: "tiktok_custom_audience_shares", next_arguments: { account_id: op.accountId, custom_audience_ids: selection.custom_audience_ids, shared_advertiser_ids: selection.shared_advertiser_ids } }, ...share ? { warnings: ["Recipient pairs are present in the native sharing log. Audience targeting availability remains unverified; inspect native status before use."] } : {} };
3622
3733
  } catch (error) {
3623
- const details = error instanceof AdportError20 && error.details && typeof error.details === "object" ? error.details : {};
3624
- throw new AdportError20("PROVIDER_ERROR", "Audience sharing outcome is unconfirmed. Reconcile every selected pair in the sharing log before a new preview. No mutation was retried.", { resourceIds: selection.custom_audience_ids, observed_pairs: outcomes, ...Number.isSafeInteger(details.code) ? { native_code: details.code } : {} });
3734
+ const details = error instanceof AdportError21 && error.details && typeof error.details === "object" ? error.details : {};
3735
+ throw new AdportError21("PROVIDER_ERROR", "Audience sharing outcome is unconfirmed. Reconcile every selected pair in the sharing log before a new preview. No mutation was retried.", { resourceIds: selection.custom_audience_ids, observed_pairs: outcomes, ...Number.isSafeInteger(details.code) ? { native_code: details.code } : {} });
3625
3736
  }
3626
3737
  } };
3627
3738
  }
@@ -3647,7 +3758,7 @@ var TikTokAdsProvider = class {
3647
3758
  this.app = app;
3648
3759
  const authorizeAccounts = async (ids2) => {
3649
3760
  const authorized = await client.get("oauth2/advertiser/get", { app_id: this.appId(), secret: this.secret() });
3650
- if (!Array.isArray(authorized.list) || authorized.list.some((row3) => typeof row3.advertiser_id !== "string") || ids2.some((id6) => !authorized.list.some((row3) => row3.advertiser_id === id6))) throw new AdportError21("POLICY_VIOLATION", "Every selected advertiser must be in the current native authorization.");
3761
+ if (!Array.isArray(authorized.list) || authorized.list.some((row3) => typeof row3.advertiser_id !== "string") || ids2.some((id6) => !authorized.list.some((row3) => row3.advertiser_id === id6))) throw new AdportError22("POLICY_VIOLATION", "Every selected advertiser must be in the current native authorization.");
3651
3762
  };
3652
3763
  this.creatives = new TikTokCreativeService(client, media);
3653
3764
  this.audiences = new TikTokAudienceService(client);
@@ -3803,6 +3914,7 @@ var TikTokAdsProvider = class {
3803
3914
  const resourceIds2 = await plan.execute();
3804
3915
  if (!Array.isArray(resourceIds2)) return resourceIds2;
3805
3916
  if (op.tool === "tiktok_create_catalog") return { applied: true, resourceIds: resourceIds2, details: { configuration_readback: "VERIFIED", project_catalog_access: "write", products_created: false, ads_created: false } };
3917
+ if (op.tool === "tiktok_migrate_catalog") return { applied: true, resourceIds: resourceIds2, details: { destination_catalog_readback: "VERIFIED", source_ownership: "OWNER_ATTESTED_NATIVE_ENFORCED", project_catalog_access: "UNCHANGED" } };
3806
3918
  if (op.tool === "tiktok_delete_catalog") return { applied: true, resourceIds: resourceIds2, details: { deletion_readback: "ABSENT_FROM_FILTERED_CATALOG_VIEW", resource_grant_retained: true } };
3807
3919
  if (op.tool === "tiktok_upload_catalog_videos") {
3808
3920
  const payload3 = op.payload;
@@ -3829,6 +3941,7 @@ var TikTokAdsProvider = class {
3829
3941
  if (["tiktok_upload_audience_file", "tiktok_create_customer_audience", "tiktok_update_customer_audience_users", "tiktok_rename_custom_audience", "tiktok_delete_custom_audiences"].includes(op.tool)) return this.customAudiences.plan(op);
3830
3942
  const payload3 = op.payload;
3831
3943
  switch (op.tool) {
3944
+ case "tiktok_migrate_catalog":
3832
3945
  case "tiktok_create_catalog":
3833
3946
  case "tiktok_delete_catalog":
3834
3947
  case "tiktok_bind_catalog_event_sources":
@@ -3881,7 +3994,7 @@ var TikTokAdsProvider = class {
3881
3994
  case "tiktok_api_delete":
3882
3995
  return this.planApiDelete(op.accountId, payload3);
3883
3996
  default:
3884
- throw new AdportError21("PROVIDER_ERROR", `tiktok: unsupported write tool ${op.tool}`);
3997
+ throw new AdportError22("PROVIDER_ERROR", `tiktok: unsupported write tool ${op.tool}`);
3885
3998
  }
3886
3999
  }
3887
4000
  async planApiCreate(accountId, payload3, guard) {
@@ -3913,7 +4026,7 @@ var TikTokAdsProvider = class {
3913
4026
  async planApiUpdate(accountId, payload3) {
3914
4027
  const path2 = validateTikTokMutationPath(payload3.path, "update");
3915
4028
  if (containsTikTokBudget(payload3.body)) {
3916
- throw new AdportError21("INVALID_INPUT", "tiktok: budget updates require a typed budget tool for policy checks");
4029
+ throw new AdportError22("INVALID_INPUT", "tiktok: budget updates require a typed budget tool for policy checks");
3917
4030
  }
3918
4031
  const body = { ...payload3.body, advertiser_id: accountId };
3919
4032
  return {
@@ -3943,7 +4056,7 @@ var TikTokAdsProvider = class {
3943
4056
  coercions.push("operation_status coerced to DISABLE (paused) by policy (paused_creation)");
3944
4057
  }
3945
4058
  if (payload3.budget_mode !== "BUDGET_MODE_INFINITE" && !payload3.budget) {
3946
- throw new AdportError21("INVALID_INPUT", `tiktok: budget is required for ${payload3.budget_mode}`);
4059
+ throw new AdportError22("INVALID_INPUT", `tiktok: budget is required for ${payload3.budget_mode}`);
3947
4060
  }
3948
4061
  const budgetDeltas = [];
3949
4062
  if (payload3.budget) {
@@ -3974,7 +4087,7 @@ var TikTokAdsProvider = class {
3974
4087
  }
3975
4088
  async planSetStatus(accountId, payload3) {
3976
4089
  const campaigns = await this.listCampaigns(accountId, payload3.campaign_ids);
3977
- if (payload3.campaign_ids.some((id6) => !campaigns.some((campaign) => campaign.campaign_id === id6 && (campaign.advertiser_id === void 0 || campaign.advertiser_id === accountId)))) throw new AdportError21("INVALID_INPUT", "tiktok: campaign was not found in the selected advertiser");
4090
+ if (payload3.campaign_ids.some((id6) => !campaigns.some((campaign) => campaign.campaign_id === id6 && (campaign.advertiser_id === void 0 || campaign.advertiser_id === accountId)))) throw new AdportError22("INVALID_INPUT", "tiktok: campaign was not found in the selected advertiser");
3978
4091
  const changes = payload3.campaign_ids.map((id6) => {
3979
4092
  const campaign = campaigns.find((c) => c.campaign_id === id6);
3980
4093
  return `~ campaign ${id6} ("${campaign?.campaign_name ?? "?"}") operation_status ${campaign?.operation_status ?? "?"} \u2192 ${payload3.operation_status}`;
@@ -3998,10 +4111,10 @@ var TikTokAdsProvider = class {
3998
4111
  const campaigns = await this.listCampaigns(accountId, [payload3.campaign_id]);
3999
4112
  const campaign = campaigns.find((campaign2) => campaign2.campaign_id === payload3.campaign_id);
4000
4113
  if (!campaign || campaign.advertiser_id !== void 0 && campaign.advertiser_id !== accountId) {
4001
- throw new AdportError21("PROVIDER_ERROR", `tiktok: campaign ${payload3.campaign_id} not found in advertiser ${accountId}`);
4114
+ throw new AdportError22("PROVIDER_ERROR", `tiktok: campaign ${payload3.campaign_id} not found in advertiser ${accountId}`);
4002
4115
  }
4003
4116
  if (campaign.budget_mode === "BUDGET_MODE_INFINITE") {
4004
- throw new AdportError21("PROVIDER_ERROR", `tiktok: campaign "${campaign.campaign_name}" has no budget (BUDGET_MODE_INFINITE)`);
4117
+ throw new AdportError22("PROVIDER_ERROR", `tiktok: campaign "${campaign.campaign_name}" has no budget (BUDGET_MODE_INFINITE)`);
4005
4118
  }
4006
4119
  return {
4007
4120
  summary: `Change TikTok campaign "${campaign.campaign_name}" budget ${campaign.budget} \u2192 ${payload3.budget} (${campaign.budget_mode})`,
@@ -4040,17 +4153,17 @@ function round2(n) {
4040
4153
  function validateTikTokPath(path2) {
4041
4154
  const normalized = path2.replace(/^\/+|\/+$/g, "").trim();
4042
4155
  if (!/^[a-z0-9_/-]{3,160}$/.test(normalized) || normalized.includes("..") || normalized.includes("//")) {
4043
- throw new AdportError21("INVALID_INPUT", `tiktok: invalid Business API path "${path2}"`);
4156
+ throw new AdportError22("INVALID_INPUT", `tiktok: invalid Business API path "${path2}"`);
4044
4157
  }
4045
4158
  return normalized;
4046
4159
  }
4047
4160
  function validateTikTokMutationPath(path2, kind2) {
4048
4161
  const normalized = validateTikTokPath(path2);
4049
4162
  if (normalized.startsWith("optimizer/rule/")) {
4050
- throw new AdportError21("INVALID_INPUT", "tiktok: automated-rule mutations require a verified direct-advertiser workflow with scheduled-action budget and account checks; raw dispatch cannot enforce these limits");
4163
+ throw new AdportError22("INVALID_INPUT", "tiktok: automated-rule mutations require a verified direct-advertiser workflow with scheduled-action budget and account checks; raw dispatch cannot enforce these limits");
4051
4164
  }
4052
4165
  if (!normalized.endsWith(`/${kind2}`)) {
4053
- throw new AdportError21("INVALID_INPUT", `tiktok: ${kind2} tool requires an endpoint ending in /${kind2}`);
4166
+ throw new AdportError22("INVALID_INPUT", `tiktok: ${kind2} tool requires an endpoint ending in /${kind2}`);
4054
4167
  }
4055
4168
  return normalized;
4056
4169
  }
@@ -4111,41 +4224,41 @@ function extractTikTokIds(value) {
4111
4224
 
4112
4225
  // src/tools.ts
4113
4226
  import { defineTool as defineTool9, guardedWriteTool as guardedWriteTool8 } from "@adport/core";
4114
- import { z as z27 } from "zod";
4227
+ import { z as z28 } from "zod";
4115
4228
 
4116
4229
  // src/creative-tools.ts
4117
4230
  import { creativesOutput as creativesOutput2, defineTool as defineTool5, guardedWriteTool as guardedWriteTool4, mediaSourceFields as mediaSourceFields3 } from "@adport/core";
4118
- import { z as z24 } from "zod";
4119
- var id5 = z24.string().regex(/^\d+$/);
4120
- var status2 = z24.enum(["ENABLE", "DISABLE"]);
4121
- var page2 = { page: z24.number().int().positive().default(1), page_size: z24.number().int().positive().max(1e3).default(100) };
4122
- var url = z24.string().url().refine((value) => {
4231
+ import { z as z25 } from "zod";
4232
+ var id5 = z25.string().regex(/^\d+$/);
4233
+ var status2 = z25.enum(["ENABLE", "DISABLE"]);
4234
+ var page2 = { page: z25.number().int().positive().default(1), page_size: z25.number().int().positive().max(1e3).default(100) };
4235
+ var url = z25.string().url().refine((value) => {
4123
4236
  const u = new URL(value);
4124
4237
  return ["https:", "http:"].includes(u.protocol) && !u.username && !u.password;
4125
4238
  });
4126
- var strings2 = z24.array(z24.string().min(1));
4127
- var targetingShape = { location_ids: strings2.optional(), zipcode_ids: strings2.optional(), age_groups: strings2.optional(), gender: z24.string().min(1).optional(), languages: strings2.optional(), operating_systems: strings2.optional(), interest_category_ids: strings2.optional(), interest_keyword_ids: strings2.optional(), audience_ids: strings2.optional(), excluded_audience_ids: strings2.optional(), network_types: strings2.optional(), device_model_ids: strings2.optional(), dayparting: z24.string().regex(/^[01]{336}$/).optional(), smart_audience_enabled: z24.boolean().optional(), smart_interest_behavior_enabled: z24.boolean().optional() };
4128
- var targeting = z24.object(targetingShape).strict();
4129
- var groupPayload = z24.object({ campaign_id: id5, adgroup_name: z24.string().trim().min(1).max(512), promotion_type: z24.string().min(1), placement_type: z24.enum(["PLACEMENT_TYPE_AUTOMATIC", "PLACEMENT_TYPE_NORMAL"]), placements: strings2.min(1).optional(), budget_mode: z24.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL"]), budget: z24.number().positive(), optimization_goal: z24.string().min(1), billing_event: z24.string().min(1), bid_type: z24.enum(["BID_TYPE_CUSTOM", "BID_TYPE_NO_BID"]), bid_price: z24.number().positive().optional(), conversion_bid_price: z24.number().positive().optional(), pacing: z24.enum(["PACING_MODE_SMOOTH", "PACING_MODE_FAST"]), schedule_type: z24.enum(["SCHEDULE_FROM_NOW", "SCHEDULE_START_END"]), schedule_start_time: z24.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/), schedule_end_time: z24.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/).optional(), pixel_id: id5.optional(), optimization_event: z24.string().min(1).optional(), app_id: z24.string().min(1).optional(), targeting, operation_status: status2.default("DISABLE") }).refine((value) => value.placement_type !== "PLACEMENT_TYPE_NORMAL" || Boolean(value.placements?.length), "Manual placement requires placements").refine((value) => value.schedule_type !== "SCHEDULE_START_END" || Boolean(value.schedule_end_time && value.schedule_end_time > value.schedule_start_time), "Scheduled end must be after start");
4130
- var creative = z24.object({ ad_name: z24.string().trim().min(1).max(512), ad_format: z24.enum(["SINGLE_VIDEO", "SINGLE_IMAGE", "CAROUSEL_ADS"]), ad_text: z24.string().min(1).max(100).optional(), identity_type: z24.string().min(1), identity_id: z24.string().min(1), identity_authorized_bc_id: id5.optional(), video_id: z24.string().min(1).optional(), image_ids: strings2.min(1).optional(), tiktok_item_id: id5.optional(), landing_page_url: url.optional(), call_to_action: z24.string().min(1).optional(), display_name: z24.string().min(1).optional(), operation_status: status2.default("DISABLE") }).refine((value) => value.ad_format !== "SINGLE_VIDEO" || Boolean(value.video_id || value.tiktok_item_id), "Video ads require video_id or an authorized tiktok_item_id").refine((value) => value.ad_format === "SINGLE_VIDEO" || Boolean(value.image_ids?.length), "Image/carousel ads require image_ids").refine((value) => !(value.video_id && value.tiktok_item_id), "Choose video_id or tiktok_item_id").refine((value) => Boolean(value.tiktok_item_id || value.ad_text), "Non-Spark ads require ad_text");
4239
+ var strings2 = z25.array(z25.string().min(1));
4240
+ var targetingShape = { location_ids: strings2.optional(), zipcode_ids: strings2.optional(), age_groups: strings2.optional(), gender: z25.string().min(1).optional(), languages: strings2.optional(), operating_systems: strings2.optional(), interest_category_ids: strings2.optional(), interest_keyword_ids: strings2.optional(), audience_ids: strings2.optional(), excluded_audience_ids: strings2.optional(), network_types: strings2.optional(), device_model_ids: strings2.optional(), dayparting: z25.string().regex(/^[01]{336}$/).optional(), smart_audience_enabled: z25.boolean().optional(), smart_interest_behavior_enabled: z25.boolean().optional() };
4241
+ var targeting = z25.object(targetingShape).strict();
4242
+ var groupPayload = z25.object({ campaign_id: id5, adgroup_name: z25.string().trim().min(1).max(512), promotion_type: z25.string().min(1), placement_type: z25.enum(["PLACEMENT_TYPE_AUTOMATIC", "PLACEMENT_TYPE_NORMAL"]), placements: strings2.min(1).optional(), budget_mode: z25.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL"]), budget: z25.number().positive(), optimization_goal: z25.string().min(1), billing_event: z25.string().min(1), bid_type: z25.enum(["BID_TYPE_CUSTOM", "BID_TYPE_NO_BID"]), bid_price: z25.number().positive().optional(), conversion_bid_price: z25.number().positive().optional(), pacing: z25.enum(["PACING_MODE_SMOOTH", "PACING_MODE_FAST"]), schedule_type: z25.enum(["SCHEDULE_FROM_NOW", "SCHEDULE_START_END"]), schedule_start_time: z25.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/), schedule_end_time: z25.string().regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/).optional(), pixel_id: id5.optional(), optimization_event: z25.string().min(1).optional(), app_id: z25.string().min(1).optional(), targeting, operation_status: status2.default("DISABLE") }).refine((value) => value.placement_type !== "PLACEMENT_TYPE_NORMAL" || Boolean(value.placements?.length), "Manual placement requires placements").refine((value) => value.schedule_type !== "SCHEDULE_START_END" || Boolean(value.schedule_end_time && value.schedule_end_time > value.schedule_start_time), "Scheduled end must be after start");
4243
+ var creative = z25.object({ ad_name: z25.string().trim().min(1).max(512), ad_format: z25.enum(["SINGLE_VIDEO", "SINGLE_IMAGE", "CAROUSEL_ADS"]), ad_text: z25.string().min(1).max(100).optional(), identity_type: z25.string().min(1), identity_id: z25.string().min(1), identity_authorized_bc_id: id5.optional(), video_id: z25.string().min(1).optional(), image_ids: strings2.min(1).optional(), tiktok_item_id: id5.optional(), landing_page_url: url.optional(), call_to_action: z25.string().min(1).optional(), display_name: z25.string().min(1).optional(), operation_status: status2.default("DISABLE") }).refine((value) => value.ad_format !== "SINGLE_VIDEO" || Boolean(value.video_id || value.tiktok_item_id), "Video ads require video_id or an authorized tiktok_item_id").refine((value) => value.ad_format === "SINGLE_VIDEO" || Boolean(value.image_ids?.length), "Image/carousel ads require image_ids").refine((value) => !(value.video_id && value.tiktok_item_id), "Choose video_id or tiktok_item_id").refine((value) => Boolean(value.tiktok_item_id || value.ad_text), "Non-Spark ads require ad_text");
4131
4244
  function tiktokCreativeTools(provider) {
4132
4245
  const read = (name3, description, input, handler) => defineTool5({ name: name3, namespace: "tiktok", description, input, annotations: { readOnly: true }, handler });
4133
4246
  const write = (name3, description, payload3, kind2 = "update") => guardedWriteTool4({ name: name3, namespace: "tiktok", provider: "tiktok", description, payload: payload3, kind: kind2 });
4134
4247
  return [
4135
- read("tiktok_ad_groups", "Read native ad-group targeting, budgets, bidding, schedules and statuses with pagination.", z24.object({ account_id: id5, campaign_ids: z24.array(id5).optional(), ad_group_ids: z24.array(id5).optional(), ...page2 }), (input) => provider.creatives.groups(input)),
4136
- defineTool5({ name: "tiktok_ads", namespace: "tiktok", description: "Read native TikTok ad configuration and copy with guarded text/status edit actions. Media previews use URLs returned by TikTok.", input: z24.object({ account_id: id5, ad_group_ids: z24.array(id5).optional(), ad_ids: z24.array(id5).optional(), ...page2 }), output: creativesOutput2.extend({ ads: z24.array(z24.record(z24.string(), z24.unknown())), page_info: z24.unknown().optional() }), presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.creatives.ads(input) }),
4137
- read("tiktok_videos", "Search the advertiser video library with native filtering and pagination.", z24.object({ account_id: id5, filtering: z24.record(z24.string(), z24.unknown()).optional(), ...page2 }), (input) => provider.creatives.read("file/video/ad/search", input)),
4138
- read("tiktok_image_info", "Read advertiser image IDs, dimensions and returned preview URLs.", z24.object({ account_id: id5, image_ids: strings2.min(1).max(100) }), (input) => provider.creatives.read("file/image/ad/info", input)),
4139
- read("tiktok_video_info", "Read advertiser video IDs, processing metadata and returned playback/cover URLs.", z24.object({ account_id: id5, video_ids: strings2.min(1).max(100) }), (input) => provider.creatives.read("file/video/ad/info", input)),
4140
- read("tiktok_search_targeting", "Search location/zip targeting tags using TikTok\u2019s read-only POST endpoint. Targeting eligibility depends on objective, placement and promotion type.", z24.object({ account_id: id5, keywords: strings2.min(1).max(1e3), search_type: z24.enum(["FUZZY_SEARCH", "BATCH_REGION_SEARCH", "BATCH_ZIPCODE_SEARCH"]).default("FUZZY_SEARCH"), objective_type: z24.string().min(1), promotion_type: z24.string().min(1).optional(), placements: strings2.min(1), region_codes: strings2.optional(), geo_types: strings2.optional() }).refine((value) => value.search_type !== "FUZZY_SEARCH" || value.keywords.length === 1, "Fuzzy search takes one keyword"), (input) => provider.creatives.read("tool/targeting/search", input, true)),
4248
+ read("tiktok_ad_groups", "Read native ad-group targeting, budgets, bidding, schedules and statuses with pagination.", z25.object({ account_id: id5, campaign_ids: z25.array(id5).optional(), ad_group_ids: z25.array(id5).optional(), ...page2 }), (input) => provider.creatives.groups(input)),
4249
+ defineTool5({ name: "tiktok_ads", namespace: "tiktok", description: "Read native TikTok ad configuration and copy with guarded text/status edit actions. Media previews use URLs returned by TikTok.", input: z25.object({ account_id: id5, ad_group_ids: z25.array(id5).optional(), ad_ids: z25.array(id5).optional(), ...page2 }), output: creativesOutput2.extend({ ads: z25.array(z25.record(z25.string(), z25.unknown())), page_info: z25.unknown().optional() }), presentation: "creatives", annotations: { readOnly: true }, handler: (input) => provider.creatives.ads(input) }),
4250
+ read("tiktok_videos", "Search the advertiser video library with native filtering and pagination.", z25.object({ account_id: id5, filtering: z25.record(z25.string(), z25.unknown()).optional(), ...page2 }), (input) => provider.creatives.read("file/video/ad/search", input)),
4251
+ read("tiktok_image_info", "Read advertiser image IDs, dimensions and returned preview URLs.", z25.object({ account_id: id5, image_ids: strings2.min(1).max(100) }), (input) => provider.creatives.read("file/image/ad/info", input)),
4252
+ read("tiktok_video_info", "Read advertiser video IDs, processing metadata and returned playback/cover URLs.", z25.object({ account_id: id5, video_ids: strings2.min(1).max(100) }), (input) => provider.creatives.read("file/video/ad/info", input)),
4253
+ read("tiktok_search_targeting", "Search location/zip targeting tags using TikTok\u2019s read-only POST endpoint. Targeting eligibility depends on objective, placement and promotion type.", z25.object({ account_id: id5, keywords: strings2.min(1).max(1e3), search_type: z25.enum(["FUZZY_SEARCH", "BATCH_REGION_SEARCH", "BATCH_ZIPCODE_SEARCH"]).default("FUZZY_SEARCH"), objective_type: z25.string().min(1), promotion_type: z25.string().min(1).optional(), placements: strings2.min(1), region_codes: strings2.optional(), geo_types: strings2.optional() }).refine((value) => value.search_type !== "FUZZY_SEARCH" || value.keywords.length === 1, "Fuzzy search takes one keyword"), (input) => provider.creatives.read("tool/targeting/search", input, true)),
4141
4254
  write("tiktok_create_ad_group", "Create an advertiser-owned ad group with explicit objective-dependent settings. Budgets/bids are whole currency units; schedules use advertiser time. Policy may force DISABLE.", groupPayload, "create"),
4142
- write("tiktok_create_ads", "Create up to 20 standard or Spark ads in an account-owned ad group. Use existing authorized identity and media IDs. Policy may force every creative to DISABLE.", z24.object({ ad_group_id: id5, creatives: z24.array(creative).min(1).max(20) }), "create"),
4143
- ...["ad_group", "ad"].map((entity) => write(`tiktok_set_${entity}_status`, "Enable or pause verified advertiser-owned child entities. Parent serving settings remain independent.", z24.object({ [entity === "ad_group" ? "ad_group_ids" : "ad_ids"]: z24.array(id5).min(1).max(20).refine((value) => new Set(value).size === value.length, "IDs must be unique"), operation_status: status2 }))),
4144
- write("tiktok_update_ad", "Patch supplied ad text/name, landing page or media IDs in its verified ad group. Uses patch_update=true; serving status and omitted creative fields are preserved.", z24.object({ ad_group_id: id5, ad_id: id5, ad_name: z24.string().min(1).max(512).optional(), ad_text: z24.string().min(1).max(100).optional(), landing_page_url: url.optional(), video_id: z24.string().min(1).optional(), image_ids: strings2.min(1).optional() }).refine((value) => ["ad_name", "ad_text", "landing_page_url", "video_id", "image_ids"].some((key2) => value[key2] !== void 0), "Provide a creative field")),
4145
- write("tiktok_update_targeting", "Replace only supplied ad-group targeting dimensions. Omitted targeting and serving settings remain unchanged; supplied arrays replace existing lists.", z24.object({ ad_group_id: id5, targeting: targeting.refine((value) => Object.keys(value).length > 0, "Provide a targeting dimension") })),
4146
- write("tiktok_set_ad_group_budget", "Change a verified ad-group budget in whole account-currency units. Current/proposed amounts are policy-checked; TikTok also enforces spend-based minimums.", z24.object({ ad_group_id: id5, budget: z24.number().positive() })),
4147
- write("tiktok_set_ad_group_bidding", "Edit supplied ad-group bids and target ROAS. Monetary bids use whole account-currency units and current-value policy checks. Serving status remains unchanged.", z24.object({ ad_group_id: id5, bid_price: z24.number().positive().optional(), conversion_bid_price: z24.number().positive().optional(), roas_bid: z24.number().positive().optional() }).refine((value) => ["bid_price", "conversion_bid_price", "roas_bid"].some((key2) => value[key2] !== void 0), "Provide a bid field")),
4148
- ...["image", "video"].map((type) => write(`tiktok_upload_${type}`, `Upload advertiser ${type} bytes with SHA-256-bound approval and TikTok MD5 signature. Hosted calls require media_id; file_path is local-only. Adport limits: images10MiB, videos100MiB.`, z24.object({ ...mediaSourceFields3 }).refine((value) => Number(Boolean(value.file_path)) + Number(Boolean(value.media_id)) === 1, "Choose media_id or file_path"), "create"))
4255
+ write("tiktok_create_ads", "Create up to 20 standard or Spark ads in an account-owned ad group. Use existing authorized identity and media IDs. Policy may force every creative to DISABLE.", z25.object({ ad_group_id: id5, creatives: z25.array(creative).min(1).max(20) }), "create"),
4256
+ ...["ad_group", "ad"].map((entity) => write(`tiktok_set_${entity}_status`, "Enable or pause verified advertiser-owned child entities. Parent serving settings remain independent.", z25.object({ [entity === "ad_group" ? "ad_group_ids" : "ad_ids"]: z25.array(id5).min(1).max(20).refine((value) => new Set(value).size === value.length, "IDs must be unique"), operation_status: status2 }))),
4257
+ write("tiktok_update_ad", "Patch supplied ad text/name, landing page or media IDs in its verified ad group. Uses patch_update=true; serving status and omitted creative fields are preserved.", z25.object({ ad_group_id: id5, ad_id: id5, ad_name: z25.string().min(1).max(512).optional(), ad_text: z25.string().min(1).max(100).optional(), landing_page_url: url.optional(), video_id: z25.string().min(1).optional(), image_ids: strings2.min(1).optional() }).refine((value) => ["ad_name", "ad_text", "landing_page_url", "video_id", "image_ids"].some((key2) => value[key2] !== void 0), "Provide a creative field")),
4258
+ write("tiktok_update_targeting", "Replace only supplied ad-group targeting dimensions. Omitted targeting and serving settings remain unchanged; supplied arrays replace existing lists.", z25.object({ ad_group_id: id5, targeting: targeting.refine((value) => Object.keys(value).length > 0, "Provide a targeting dimension") })),
4259
+ write("tiktok_set_ad_group_budget", "Change a verified ad-group budget in whole account-currency units. Current/proposed amounts are policy-checked; TikTok also enforces spend-based minimums.", z25.object({ ad_group_id: id5, budget: z25.number().positive() })),
4260
+ write("tiktok_set_ad_group_bidding", "Edit supplied ad-group bids and target ROAS. Monetary bids use whole account-currency units and current-value policy checks. Serving status remains unchanged.", z25.object({ ad_group_id: id5, bid_price: z25.number().positive().optional(), conversion_bid_price: z25.number().positive().optional(), roas_bid: z25.number().positive().optional() }).refine((value) => ["bid_price", "conversion_bid_price", "roas_bid"].some((key2) => value[key2] !== void 0), "Provide a bid field")),
4261
+ ...["image", "video"].map((type) => write(`tiktok_upload_${type}`, `Upload advertiser ${type} bytes with SHA-256-bound approval and TikTok MD5 signature. Hosted calls require media_id; file_path is local-only. Adport limits: images10MiB, videos100MiB.`, z25.object({ ...mediaSourceFields3 }).refine((value) => Number(Boolean(value.file_path)) + Number(Boolean(value.media_id)) === 1, "Choose media_id or file_path"), "create"))
4149
4262
  ];
4150
4263
  }
4151
4264
 
@@ -4165,10 +4278,10 @@ function tiktokCustomAudienceTools(provider) {
4165
4278
  }
4166
4279
 
4167
4280
  // src/audience-authoring-tools.ts
4168
- import { z as z25 } from "zod";
4281
+ import { z as z26 } from "zod";
4169
4282
  import { defineTool as defineTool7, guardedWriteTool as guardedWriteTool6 } from "@adport/core";
4170
4283
  function tiktokAudienceAuthoringTools(provider) {
4171
- const catalog = { category: "audiences", exposure: "specialist" }, read = { namespace: "tiktok", catalog, presentation: "records", annotations: { readOnly: true }, output: z25.looseObject({ records: z25.array(z25.record(z25.string(), z25.unknown())) }) }, write = { namespace: "tiktok", provider: "tiktok", catalog };
4284
+ const catalog = { category: "audiences", exposure: "specialist" }, read = { namespace: "tiktok", catalog, presentation: "records", annotations: { readOnly: true }, output: z26.looseObject({ records: z26.array(z26.record(z26.string(), z26.unknown())) }) }, write = { namespace: "tiktok", provider: "tiktok", catalog };
4172
4285
  return [
4173
4286
  defineTool7({ ...read, name: "tiktok_identities", description: "Page identities already linked to the advertiser. Preserves native identity/BC references and availability; BC queries may include other linked identities. Creates no identity or permissions. Exact video source use rechecks identity/info.", input: audienceIdentityList, pagination: { cursorInput: "page", cursorOutput: "next_page" }, handler: (input) => provider.audienceSources.identities(input) }),
4174
4287
  defineTool7({ ...read, name: "tiktok_audience_sources", description: "Discover advertiser-scoped event sources for all nine rule-audience families. Pages apps, pixels, ad groups, stores, offline sets and exact-identity videos. Source filters and cursors stay bound; organic history has a native 500-post window.", input: audienceSourceList, pagination: { cursorInput: "cursor" }, handler: (input) => provider.audienceSources.list(input) }),
@@ -4181,9 +4294,9 @@ function tiktokAudienceAuthoringTools(provider) {
4181
4294
 
4182
4295
  // src/audience-sharing-tools.ts
4183
4296
  import { defineTool as defineTool8, guardedWriteTool as guardedWriteTool7 } from "@adport/core";
4184
- import { z as z26 } from "zod";
4297
+ import { z as z27 } from "zod";
4185
4298
  function tiktokAudienceSharingTools(provider) {
4186
- const shared = { namespace: "tiktok", catalog: { category: "audiences", exposure: "specialist" } }, read = { ...shared, output: z26.looseObject({ records: z26.array(z26.record(z26.string(), z26.unknown())) }), presentation: "records", annotations: { readOnly: true }, additionalAccountInputs: ["shared_advertiser_ids"] }, write = { ...shared, provider: "tiktok", kind: "update", destructive: true };
4299
+ const shared = { namespace: "tiktok", catalog: { category: "audiences", exposure: "specialist" } }, read = { ...shared, output: z27.looseObject({ records: z27.array(z27.record(z27.string(), z27.unknown())) }), presentation: "records", annotations: { readOnly: true }, additionalAccountInputs: ["shared_advertiser_ids"] }, write = { ...shared, provider: "tiktok", kind: "update", destructive: true };
4187
4300
  return [
4188
4301
  defineTool8({ ...read, name: "tiktok_custom_audience_shares", description: "Read owned audience sharing logs for explicit destination accounts. Hosted scope requires source and destinations enabled in this project. Other recipient names/IDs stay hidden. Native status is preserved; missing list data does not prove absence.", input: audienceSharesRead, handler: (input) => provider.audienceSharing.read(input) }),
4189
4302
  defineTool8({ ...read, name: "tiktok_audience_sharing_context", description: "Check selected owned audiences, native authorization, source Admin/Operator role and selected accounts in one Business Center. Returns context_hash for SHARE or singular UNSHARE, with exact existing pairs. No access is changed.", input: audienceSharingContext, handler: (input) => provider.audienceSharing.context(input) }),
@@ -4203,7 +4316,7 @@ var OBJECTIVES = [
4203
4316
  "WEB_CONVERSIONS",
4204
4317
  "PRODUCT_SALES"
4205
4318
  ];
4206
- var operationStatusSchema = z27.enum(["ENABLE", "DISABLE"]);
4319
+ var operationStatusSchema = z28.enum(["ENABLE", "DISABLE"]);
4207
4320
  function tiktokTools(provider, options = {}) {
4208
4321
  return [
4209
4322
  ...tiktokCreativeTools(provider),
@@ -4218,10 +4331,10 @@ function tiktokTools(provider, options = {}) {
4218
4331
  name: "tiktok_api_read",
4219
4332
  namespace: "tiktok",
4220
4333
  description: "Call any documented TikTok Business API v1.3 GET endpoint with advertiser scoping and API-shaped parameters.",
4221
- input: z27.object({
4222
- account_id: z27.string(),
4223
- path: z27.string().min(3).describe("Relative endpoint, e.g. adgroup/get, ad/get, creative/report/get"),
4224
- params: z27.record(z27.string(), z27.unknown()).optional()
4334
+ input: z28.object({
4335
+ account_id: z28.string(),
4336
+ path: z28.string().min(3).describe("Relative endpoint, e.g. adgroup/get, ad/get, creative/report/get"),
4337
+ params: z28.record(z28.string(), z28.unknown()).optional()
4225
4338
  }),
4226
4339
  annotations: { readOnly: true },
4227
4340
  async handler(input) {
@@ -4232,9 +4345,9 @@ function tiktokTools(provider, options = {}) {
4232
4345
  name: "tiktok_campaigns",
4233
4346
  namespace: "tiktok",
4234
4347
  description: "List TikTok campaigns (id, name, operation_status ENABLE/DISABLE, budget, budget_mode, objective).",
4235
- input: z27.object({
4236
- account_id: z27.string().describe("Advertiser id"),
4237
- campaign_ids: z27.array(z27.string()).optional()
4348
+ input: z28.object({
4349
+ account_id: z28.string().describe("Advertiser id"),
4350
+ campaign_ids: z28.array(z28.string()).optional()
4238
4351
  }),
4239
4352
  annotations: { readOnly: true },
4240
4353
  async handler(input) {
@@ -4246,14 +4359,14 @@ function tiktokTools(provider, options = {}) {
4246
4359
  name: "tiktok_report",
4247
4360
  namespace: "tiktok",
4248
4361
  description: "Raw TikTok synchronous reporting (report/integrated). Metric values come back as strings; note total_complete_payment_rate is total purchase VALUE (misleading name), complete_payment_roas is purchase ROAS.",
4249
- input: z27.object({
4250
- account_id: z27.string(),
4251
- data_level: z27.enum(["AUCTION_ADVERTISER", "AUCTION_CAMPAIGN", "AUCTION_ADGROUP", "AUCTION_AD"]).default("AUCTION_CAMPAIGN"),
4252
- dimensions: z27.array(z27.string()).min(1).default(["campaign_id"]),
4253
- metrics: z27.array(z27.string()).min(1).default(["spend", "impressions", "clicks", "conversion"]),
4254
- start_date: z27.string().regex(/^\d{4}-\d{2}-\d{2}$/),
4255
- end_date: z27.string().regex(/^\d{4}-\d{2}-\d{2}$/),
4256
- page_size: z27.number().int().positive().max(1e3).default(200)
4362
+ input: z28.object({
4363
+ account_id: z28.string(),
4364
+ data_level: z28.enum(["AUCTION_ADVERTISER", "AUCTION_CAMPAIGN", "AUCTION_ADGROUP", "AUCTION_AD"]).default("AUCTION_CAMPAIGN"),
4365
+ dimensions: z28.array(z28.string()).min(1).default(["campaign_id"]),
4366
+ metrics: z28.array(z28.string()).min(1).default(["spend", "impressions", "clicks", "conversion"]),
4367
+ start_date: z28.string().regex(/^\d{4}-\d{2}-\d{2}$/),
4368
+ end_date: z28.string().regex(/^\d{4}-\d{2}-\d{2}$/),
4369
+ page_size: z28.number().int().positive().max(1e3).default(200)
4257
4370
  }),
4258
4371
  annotations: { readOnly: true },
4259
4372
  async handler(input) {
@@ -4267,11 +4380,11 @@ function tiktokTools(provider, options = {}) {
4267
4380
  description: "Create a TikTok campaign. Budget is a float in whole account-currency units (min ~20 USD-equivalent for DAY/TOTAL modes). TikTok has no server-side dry run \u2014 the preview is a client-side diff.",
4268
4381
  provider: "tiktok",
4269
4382
  kind: "create",
4270
- payload: z27.object({
4271
- campaign_name: z27.string().min(1).max(512),
4272
- objective_type: z27.enum(OBJECTIVES).default("TRAFFIC"),
4273
- budget_mode: z27.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL", "BUDGET_MODE_INFINITE"]).default("BUDGET_MODE_DAY"),
4274
- budget: z27.number().positive().optional().describe("Whole currency units (float), required unless BUDGET_MODE_INFINITE"),
4383
+ payload: z28.object({
4384
+ campaign_name: z28.string().min(1).max(512),
4385
+ objective_type: z28.enum(OBJECTIVES).default("TRAFFIC"),
4386
+ budget_mode: z28.enum(["BUDGET_MODE_DAY", "BUDGET_MODE_TOTAL", "BUDGET_MODE_INFINITE"]).default("BUDGET_MODE_DAY"),
4387
+ budget: z28.number().positive().optional().describe("Whole currency units (float), required unless BUDGET_MODE_INFINITE"),
4275
4388
  operation_status: operationStatusSchema.optional()
4276
4389
  })
4277
4390
  }),
@@ -4281,8 +4394,8 @@ function tiktokTools(provider, options = {}) {
4281
4394
  description: "Enable or pause (DISABLE) up to 20 TikTok campaigns.",
4282
4395
  provider: "tiktok",
4283
4396
  kind: "update",
4284
- payload: z27.object({
4285
- campaign_ids: z27.array(z27.string()).min(1).max(20),
4397
+ payload: z28.object({
4398
+ campaign_ids: z28.array(z28.string()).min(1).max(20),
4286
4399
  operation_status: operationStatusSchema
4287
4400
  })
4288
4401
  }),
@@ -4292,9 +4405,9 @@ function tiktokTools(provider, options = {}) {
4292
4405
  description: "Change a TikTok campaign's budget (whole currency units). TikTok rejects new budgets below 105% of current spend.",
4293
4406
  provider: "tiktok",
4294
4407
  kind: "update",
4295
- payload: z27.object({
4296
- campaign_id: z27.string(),
4297
- budget: z27.number().positive()
4408
+ payload: z28.object({
4409
+ campaign_id: z28.string(),
4410
+ budget: z28.number().positive()
4298
4411
  })
4299
4412
  }),
4300
4413
  guardedWriteTool8({
@@ -4303,7 +4416,7 @@ function tiktokTools(provider, options = {}) {
4303
4416
  description: "Create through any documented TikTok Business API v1.3 /create endpoint. The advertiser is forced to account_id, campaign creation is paused, and budget fields are policy-checked.",
4304
4417
  provider: "tiktok",
4305
4418
  kind: "create",
4306
- payload: z27.object({ path: z27.string().min(3), body: z27.record(z27.string(), z27.unknown()) })
4419
+ payload: z28.object({ path: z28.string().min(3), body: z28.record(z28.string(), z28.unknown()) })
4307
4420
  }),
4308
4421
  guardedWriteTool8({
4309
4422
  name: "tiktok_api_update",
@@ -4311,7 +4424,7 @@ function tiktokTools(provider, options = {}) {
4311
4424
  description: "Update non-budget/non-bid fields through any documented TikTok Business API v1.3 /update endpoint. Monetary and target-ROAS edits require typed tools.",
4312
4425
  provider: "tiktok",
4313
4426
  kind: "update",
4314
- payload: z27.object({ path: z27.string().min(3), body: z27.record(z27.string(), z27.unknown()) })
4427
+ payload: z28.object({ path: z28.string().min(3), body: z28.record(z28.string(), z28.unknown()) })
4315
4428
  }),
4316
4429
  guardedWriteTool8({
4317
4430
  name: "tiktok_api_delete",
@@ -4320,7 +4433,7 @@ function tiktokTools(provider, options = {}) {
4320
4433
  provider: "tiktok",
4321
4434
  kind: "remove",
4322
4435
  destructive: true,
4323
- payload: z27.object({ path: z27.string().min(3), body: z27.record(z27.string(), z27.unknown()) })
4436
+ payload: z28.object({ path: z28.string().min(3), body: z28.record(z28.string(), z28.unknown()) })
4324
4437
  })
4325
4438
  ];
4326
4439
  }
@@ -4369,8 +4482,10 @@ export {
4369
4482
  catalogScopeKey,
4370
4483
  createTikTokModule,
4371
4484
  creationScope,
4485
+ migrationScope,
4372
4486
  requireCatalogAccess,
4373
4487
  requireCatalogCreationAccess,
4488
+ requireCatalogMigrationAccess,
4374
4489
  resolveTikTokCredentials,
4375
4490
  tiktokCatalogTools,
4376
4491
  tiktokTools