@bison-lab/payload-core 5.10.0 → 5.13.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.
Files changed (109) hide show
  1. package/README.md +125 -10
  2. package/dist/admin-branding-CEKdfYah.mjs +178 -0
  3. package/dist/admin-branding-CEKdfYah.mjs.map +1 -0
  4. package/dist/admin-head-CcpH7P4C.mjs +187 -0
  5. package/dist/admin-head-CcpH7P4C.mjs.map +1 -0
  6. package/dist/admin-head-QfW81bDy.d.mts +63 -0
  7. package/dist/admin-head-QfW81bDy.d.mts.map +1 -0
  8. package/dist/admin-server.d.mts +52 -0
  9. package/dist/admin-server.d.mts.map +1 -0
  10. package/dist/admin-server.mjs +94 -0
  11. package/dist/admin-server.mjs.map +1 -0
  12. package/dist/admin.d.mts.map +1 -1
  13. package/dist/admin.mjs +97 -6
  14. package/dist/admin.mjs.map +1 -1
  15. package/dist/{alternates-DxBTUXHh.mjs → alternates-Tv5-ccza.mjs} +1 -1
  16. package/dist/{alternates-DxBTUXHh.mjs.map → alternates-Tv5-ccza.mjs.map} +1 -1
  17. package/dist/{alternates-DlRTsaVe.d.mts → alternates-aRncEUBI.d.mts} +1 -1
  18. package/dist/{alternates-DlRTsaVe.d.mts.map → alternates-aRncEUBI.d.mts.map} +1 -1
  19. package/dist/block-library.d.mts +1 -1
  20. package/dist/block-library.mjs +1 -1
  21. package/dist/{block-thumbnails-DC34uFtE.mjs → block-thumbnails-DvILqW_e.mjs} +1 -1
  22. package/dist/{block-thumbnails-DC34uFtE.mjs.map → block-thumbnails-DvILqW_e.mjs.map} +1 -1
  23. package/dist/block-thumbnails-cli.mjs +1 -1
  24. package/dist/block-thumbnails.mjs +1 -1
  25. package/dist/{capability-Kd5LgQpm.mjs → capability-B4FLx4OX.mjs} +4 -159
  26. package/dist/capability-B4FLx4OX.mjs.map +1 -0
  27. package/dist/{capability-NlorUIta.d.mts → capability-DonuHSPG.d.mts} +1 -1
  28. package/dist/{capability-NlorUIta.d.mts.map → capability-DonuHSPG.d.mts.map} +1 -1
  29. package/dist/{catalogue-CJ0RlTg4.d.mts → catalogue-tVovXWp9.d.mts} +1 -1
  30. package/dist/{catalogue-CJ0RlTg4.d.mts.map → catalogue-tVovXWp9.d.mts.map} +1 -1
  31. package/dist/{facet-field-DO3VT_Cz.mjs → facet-field-7p6_MhsT.mjs} +1 -1
  32. package/dist/{facet-field-DO3VT_Cz.mjs.map → facet-field-7p6_MhsT.mjs.map} +1 -1
  33. package/dist/{facet-field-Cd6lffed.d.mts → facet-field-Dbcu1L91.d.mts} +1 -1
  34. package/dist/{facet-field-Cd6lffed.d.mts.map → facet-field-Dbcu1L91.d.mts.map} +1 -1
  35. package/dist/{types-B1MmE-L3.d.mts → identity-B4Lew8Fu.d.mts} +40 -24
  36. package/dist/identity-B4Lew8Fu.d.mts.map +1 -0
  37. package/dist/{identity-CN6EOeDM.mjs → identity-CkUE_uN2.mjs} +11 -3
  38. package/dist/{identity-CN6EOeDM.mjs.map → identity-CkUE_uN2.mjs.map} +1 -1
  39. package/dist/index.d.mts +58 -16
  40. package/dist/index.d.mts.map +1 -1
  41. package/dist/index.mjs +150 -60
  42. package/dist/index.mjs.map +1 -1
  43. package/dist/island-97l5VY8l.mjs.map +1 -1
  44. package/dist/languages-B_iiWwxE.mjs +179 -0
  45. package/dist/languages-B_iiWwxE.mjs.map +1 -0
  46. package/dist/languages-cDe9Lznx.d.mts +86 -0
  47. package/dist/languages-cDe9Lznx.d.mts.map +1 -0
  48. package/dist/{locale-tnKLkutC.d.mts → locale-CTT3nn6T.d.mts} +1 -1
  49. package/dist/locale-CTT3nn6T.d.mts.map +1 -0
  50. package/dist/{locale-B6rUVwpg.mjs → locale-DaEJ1d2O.mjs} +1 -1
  51. package/dist/{locale-B6rUVwpg.mjs.map → locale-DaEJ1d2O.mjs.map} +1 -1
  52. package/dist/locale-routing.d.mts +129 -0
  53. package/dist/locale-routing.d.mts.map +1 -0
  54. package/dist/locale-routing.mjs +256 -0
  55. package/dist/locale-routing.mjs.map +1 -0
  56. package/dist/lookup-DiOCro-_.mjs +165 -0
  57. package/dist/lookup-DiOCro-_.mjs.map +1 -0
  58. package/dist/lookup-uyEKHlLX.d.mts +41 -0
  59. package/dist/lookup-uyEKHlLX.d.mts.map +1 -0
  60. package/dist/{messages-XFoL9RtF.mjs → messages-Bv6JIEiG.mjs} +2 -2
  61. package/dist/{messages-XFoL9RtF.mjs.map → messages-Bv6JIEiG.mjs.map} +1 -1
  62. package/dist/metadata.d.mts +2 -2
  63. package/dist/metadata.mjs +1 -1
  64. package/dist/navigation.d.mts +2 -2
  65. package/dist/navigation.mjs +1 -1
  66. package/dist/og.d.mts +2 -2
  67. package/dist/og.mjs +2 -2
  68. package/dist/{preview-Br1SQCKn.mjs → preview-BE7P1ezl.mjs} +5 -120
  69. package/dist/preview-BE7P1ezl.mjs.map +1 -0
  70. package/dist/{preview-B69Dhi8T.d.mts → preview-DSQN4uYa.d.mts} +2 -2
  71. package/dist/{preview-B69Dhi8T.d.mts.map → preview-DSQN4uYa.d.mts.map} +1 -1
  72. package/dist/{published-Vu_QX2Vv.mjs → published-BF2F3od_.mjs} +2 -2
  73. package/dist/{published-Vu_QX2Vv.mjs.map → published-BF2F3od_.mjs.map} +1 -1
  74. package/dist/{published-hqtvmVUD.mjs → published-BzihgcSf.mjs} +1 -1
  75. package/dist/{published-hqtvmVUD.mjs.map → published-BzihgcSf.mjs.map} +1 -1
  76. package/dist/{published-B80KqlcU.mjs → published-C8bW5jvC.mjs} +3 -3
  77. package/dist/{published-B80KqlcU.mjs.map → published-C8bW5jvC.mjs.map} +1 -1
  78. package/dist/{published-2I-k6zEo.d.mts → published-DYpXTy84.d.mts} +3 -3
  79. package/dist/{published-2I-k6zEo.d.mts.map → published-DYpXTy84.d.mts.map} +1 -1
  80. package/dist/{published-BhYTEAK_.d.mts → published-VTz_aYaQ.d.mts} +2 -2
  81. package/dist/{published-BhYTEAK_.d.mts.map → published-VTz_aYaQ.d.mts.map} +1 -1
  82. package/dist/{root-page-key-kx3C1eyp.mjs → root-page-key-ywNz2k4L.mjs} +1 -1
  83. package/dist/{root-page-key-kx3C1eyp.mjs.map → root-page-key-ywNz2k4L.mjs.map} +1 -1
  84. package/dist/seo.d.mts +1 -1
  85. package/dist/seo.mjs +2 -2
  86. package/dist/{strings-Fd7kUCT7.mjs → strings-_9n8BefX.mjs} +1 -1
  87. package/dist/{strings-Fd7kUCT7.mjs.map → strings-_9n8BefX.mjs.map} +1 -1
  88. package/dist/taxonomy.d.mts +1 -1
  89. package/dist/taxonomy.mjs +1 -1
  90. package/dist/theme.d.mts +6 -5
  91. package/dist/theme.d.mts.map +1 -1
  92. package/dist/theme.mjs +6 -63
  93. package/dist/{title-BVV3o329.d.mts → title-DBSLJfrW.d.mts} +1 -1
  94. package/dist/{title-BVV3o329.d.mts.map → title-DBSLJfrW.d.mts.map} +1 -1
  95. package/dist/translate-messages-cli.mjs +2 -2
  96. package/dist/translate.d.mts +2 -77
  97. package/dist/translate.d.mts.map +1 -1
  98. package/dist/translate.mjs +4 -3
  99. package/dist/translate.mjs.map +1 -1
  100. package/dist/{wireframe-Ba65SOj8.mjs → wireframe-DjPHSACa.mjs} +1 -1
  101. package/dist/{wireframe-Ba65SOj8.mjs.map → wireframe-DjPHSACa.mjs.map} +1 -1
  102. package/dist/wireframe-cli.mjs +1 -1
  103. package/dist/wireframe.mjs +1 -1
  104. package/package.json +13 -5
  105. package/dist/capability-Kd5LgQpm.mjs.map +0 -1
  106. package/dist/locale-tnKLkutC.d.mts.map +0 -1
  107. package/dist/preview-Br1SQCKn.mjs.map +0 -1
  108. package/dist/theme.mjs.map +0 -1
  109. package/dist/types-B1MmE-L3.d.mts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"root-page-key-kx3C1eyp.mjs","names":[],"sources":["../src/collections/root-page-key.ts"],"sourcesContent":["/**\n * The home page is the row whose `pageKey` is `/`. That key is the identifier.\n * The stored slug is an internal token so an unaddressed draft can keep an\n * empty slug without colliding with home. Editors see `/`, never the token.\n */\nexport const ROOT_PAGE_KEY = \"/\";\n\nexport const ROOT_PAGE_SLUG = \"__root__\";\n\nexport const REQUIRED_PAGE_CELL =\n \"@bison-lab/payload-core/admin#RequiredPageCell\";\n\nexport const REQUIRED_PAGE_FIELD =\n \"@bison-lab/payload-core/admin#RequiredPageField\";\n\nexport const PAGE_SLUG_CELL = \"@bison-lab/payload-core/admin#PageSlugCell\";\n\nexport const REQUIRED_PAGE_DELETE_MESSAGE =\n \"This page is required by the site and cannot be deleted.\";\n\nexport const REQUIRED_PAGE_UNPUBLISH_MESSAGE =\n \"This page is required by the site and cannot be unpublished.\";\n\nexport function isRootPageKey(value: unknown): value is typeof ROOT_PAGE_KEY {\n return value === ROOT_PAGE_KEY;\n}\n\nexport function isRequiredPageKey(\n value: unknown,\n requiredKeys: readonly string[],\n): boolean {\n return typeof value === \"string\" && requiredKeys.includes(value);\n}\n\n/** `/` is always required. Extras are site keys, not paths, and cannot be the root token. */\nexport function requiredPageKeys(extra: readonly string[] = []): string[] {\n const keys = [ROOT_PAGE_KEY];\n for (const key of extra) {\n if (key === ROOT_PAGE_KEY || key === ROOT_PAGE_SLUG || key.trim() === \"\") {\n throw new Error(\n `createPages requiredKeys cannot include ${JSON.stringify(key)}. The home page is always \"/\".`,\n );\n }\n if (!keys.includes(key)) keys.push(key);\n }\n return keys;\n}\n"],"mappings":";;;;;;AAKA,MAAa,gBAAgB;AAE7B,MAAa,iBAAiB;AAE9B,MAAa,qBACX;AAEF,MAAa,sBACX;AAEF,MAAa,iBAAiB;AAE9B,MAAa,+BACX;AAEF,MAAa,kCACX;AAEF,SAAgB,cAAc,OAA+C;AAC3E,QAAO,UAAA;;AAGT,SAAgB,kBACd,OACA,cACS;AACT,QAAO,OAAO,UAAU,YAAY,aAAa,SAAS,MAAM;;;AAIlE,SAAgB,iBAAiB,QAA2B,EAAE,EAAY;CACxE,MAAM,OAAO,CAAA,IAAe;AAC5B,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,QAAA,OAAyB,QAAA,cAA0B,IAAI,MAAM,KAAK,GACpE,OAAM,IAAI,MACR,2CAA2C,KAAK,UAAU,IAAI,CAAC,gCAChE;AAEH,MAAI,CAAC,KAAK,SAAS,IAAI,CAAE,MAAK,KAAK,IAAI;;AAEzC,QAAO"}
1
+ {"version":3,"file":"root-page-key-ywNz2k4L.mjs","names":[],"sources":["../src/collections/root-page-key.ts"],"sourcesContent":["/**\n * The home page is the row whose `pageKey` is `/`. That key is the identifier.\n * The stored slug is an internal token so an unaddressed draft can keep an\n * empty slug without colliding with home. Editors see `/`, never the token.\n */\nexport const ROOT_PAGE_KEY = \"/\";\n\nexport const ROOT_PAGE_SLUG = \"__root__\";\n\nexport const REQUIRED_PAGE_CELL =\n \"@bison-lab/payload-core/admin#RequiredPageCell\";\n\nexport const REQUIRED_PAGE_FIELD =\n \"@bison-lab/payload-core/admin#RequiredPageField\";\n\nexport const PAGE_SLUG_CELL = \"@bison-lab/payload-core/admin#PageSlugCell\";\n\nexport const REQUIRED_PAGE_DELETE_MESSAGE =\n \"This page is required by the site and cannot be deleted.\";\n\nexport const REQUIRED_PAGE_UNPUBLISH_MESSAGE =\n \"This page is required by the site and cannot be unpublished.\";\n\nexport function isRootPageKey(value: unknown): value is typeof ROOT_PAGE_KEY {\n return value === ROOT_PAGE_KEY;\n}\n\nexport function isRequiredPageKey(\n value: unknown,\n requiredKeys: readonly string[],\n): boolean {\n return typeof value === \"string\" && requiredKeys.includes(value);\n}\n\n/** `/` is always required. Extras are site keys, not paths, and cannot be the root token. */\nexport function requiredPageKeys(extra: readonly string[] = []): string[] {\n const keys = [ROOT_PAGE_KEY];\n for (const key of extra) {\n if (key === ROOT_PAGE_KEY || key === ROOT_PAGE_SLUG || key.trim() === \"\") {\n throw new Error(\n `createPages requiredKeys cannot include ${JSON.stringify(key)}. The home page is always \"/\".`,\n );\n }\n if (!keys.includes(key)) keys.push(key);\n }\n return keys;\n}\n"],"mappings":";;;;;;AAKA,MAAa,gBAAgB;AAE7B,MAAa,iBAAiB;AAE9B,MAAa,qBACX;AAEF,MAAa,sBACX;AAEF,MAAa,iBAAiB;AAE9B,MAAa,+BACX;AAEF,MAAa,kCACX;AAEF,SAAgB,cAAc,OAA+C;AAC3E,QAAO,UAAA;;AAGT,SAAgB,kBACd,OACA,cACS;AACT,QAAO,OAAO,UAAU,YAAY,aAAa,SAAS,MAAM;;;AAIlE,SAAgB,iBAAiB,QAA2B,EAAE,EAAY;CACxE,MAAM,OAAO,CAAA,IAAe;AAC5B,MAAK,MAAM,OAAO,OAAO;AACvB,MAAI,QAAA,OAAyB,QAAA,cAA0B,IAAI,MAAM,KAAK,GACpE,OAAM,IAAI,MACR,2CAA2C,KAAK,UAAU,IAAI,CAAC,gCAChE;AAEH,MAAI,CAAC,KAAK,SAAS,IAAI,CAAE,MAAK,KAAK,IAAI;;AAEzC,QAAO"}
package/dist/seo.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { t as LocaleAlternatesOptions } from "./alternates-DlRTsaVe.mjs";
1
+ import { t as LocaleAlternatesOptions } from "./alternates-aRncEUBI.mjs";
2
2
  import { Payload } from "payload";
3
3
  import { ReactElement } from "react";
4
4
 
package/dist/seo.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { l as isRootPageKey } from "./root-page-key-kx3C1eyp.mjs";
2
- import { t as languageAlternates } from "./alternates-DxBTUXHh.mjs";
1
+ import { l as isRootPageKey } from "./root-page-key-ywNz2k4L.mjs";
2
+ import { t as languageAlternates } from "./alternates-Tv5-ccza.mjs";
3
3
  import { createElement } from "react";
4
4
  //#region src/seo/sitemap.ts
5
5
  /** A page with no address yet has nothing to list. Home is keyed, not slugged. */
@@ -264,4 +264,4 @@ function isTranslatorConfigured(translator) {
264
264
  //#endregion
265
265
  export { TRANSLATE_MODEL_PRICES as a, estimateCost as c, translationSystemPrompt as d, verifyAnthropicKey as f, ECONOMY_TRANSLATE_MODEL as i, modelPrice as l, translateStrings as n, anthropicTranslator as o, classifyAnthropicError as p, DEFAULT_TRANSLATE_MODEL as r, containsWord as s, isTranslatorConfigured as t, parseJsonArray as u };
266
266
 
267
- //# sourceMappingURL=strings-Fd7kUCT7.mjs.map
267
+ //# sourceMappingURL=strings-_9n8BefX.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"strings-Fd7kUCT7.mjs","names":[],"sources":["../src/translate/errors.ts","../src/translate/anthropic.ts","../src/translate/strings.ts"],"sourcesContent":["/**\n * Why a translation call failed, in the terms an Admin can act on.\n *\n * - `out-of-credit`: the Anthropic account has no credit or a billing\n * problem (402 `billing_error`, or the older 400 \"credit balance is too\n * low\").\n * - `key-rejected`: the key is wrong, revoked or lacks permission (401, 403).\n * - `rate-limited`: 429, after the SDK's own retry.\n * - `unreachable`: no answer, a timeout, or a 5xx / 529 from Anthropic.\n * - `other`: anything else (a malformed reply, a refusal).\n */\nexport type TranslationFailureKind = \"out-of-credit\" | \"key-rejected\" | \"rate-limited\" | \"unreachable\" | \"other\";\n\nfunction errorType(error: { error?: unknown; type?: unknown }): string | undefined {\n if (typeof error.type === \"string\") return error.type;\n const body = error.error as { type?: unknown; error?: { type?: unknown } } | undefined;\n if (typeof body?.error?.type === \"string\") return body.error.type;\n if (typeof body?.type === \"string\") return body.type;\n return undefined;\n}\n\n/** Sorts an error thrown by the Anthropic SDK (or a network failure) into a `TranslationFailureKind`. */\nexport function classifyAnthropicError(error: unknown): TranslationFailureKind {\n if (!error || typeof error !== \"object\") return \"other\";\n const candidate = error as { status?: unknown; message?: unknown; error?: unknown; type?: unknown };\n const status = typeof candidate.status === \"number\" ? candidate.status : undefined;\n const type = errorType(candidate);\n const message = typeof candidate.message === \"string\" ? candidate.message : \"\";\n if (status === 402 || type === \"billing_error\") return \"out-of-credit\";\n if (status === 400 && /credit balance/i.test(message)) return \"out-of-credit\";\n if (status === 401 || status === 403 || type === \"authentication_error\" || type === \"permission_error\") {\n return \"key-rejected\";\n }\n if (status === 429 || type === \"rate_limit_error\") return \"rate-limited\";\n if (status === undefined || status >= 500) return \"unreachable\";\n return \"other\";\n}\n","import { classifyAnthropicError, type TranslationFailureKind } from \"./errors\";\nimport type { TranslateRequest, TranslateSite, Translator } from \"./types\";\n\n/**\n * The library's default model. Translating marketing copy does not need the\n * most capable model; a current Sonnet handles it well at a fraction of the\n * price. A site overrides it per environment (`ANTHROPIC_TRANSLATE_MODEL`).\n */\nexport const DEFAULT_TRANSLATE_MODEL = \"claude-sonnet-5-5\";\n\n/** \"Economy (Haiku)\" on Settings → Translation: a fraction of Sonnet's price for plainer copy. */\nexport const ECONOMY_TRANSLATE_MODEL = \"claude-haiku-5-5\";\n\n/** USD per million tokens, for the cost estimates on Settings → Translation. */\nexport interface ModelPrice {\n input: number;\n output: number;\n}\n\n/**\n * Anthropic's list prices for the two models the screen offers. A model\n * not listed (an `ANTHROPIC_TRANSLATE_MODEL` override) is estimated at\n * Sonnet's price, so an estimate errs high rather than reading as free.\n */\nexport const TRANSLATE_MODEL_PRICES: Record<string, ModelPrice> = {\n [DEFAULT_TRANSLATE_MODEL]: { input: 2, output: 10 },\n [ECONOMY_TRANSLATE_MODEL]: { input: 0.1, output: 0.5 },\n};\n\nexport function modelPrice(model: string): ModelPrice {\n return TRANSLATE_MODEL_PRICES[model] ?? TRANSLATE_MODEL_PRICES[DEFAULT_TRANSLATE_MODEL]!;\n}\n\n/** Estimated USD for one call's tokens on `model`. */\nexport function estimateCost(model: string, inputTokens: number, outputTokens: number): number {\n const price = modelPrice(model);\n return (inputTokens * price.input + outputTokens * price.output) / 1_000_000;\n}\n\n/** What one translator call did, for usage, cost and failure reporting. */\nexport type TranslatorCallEvent =\n | { ok: true; model: string; strings: number; inputTokens: number; outputTokens: number }\n | { ok: false; model: string; strings: number; failure: TranslationFailureKind; status?: number; message: string };\n\n/**\n * True when `text` contains `word` as a whole word, case-sensitively: \"ProtectIQ\"\n * is in \"Get ProtectIQ today\" but not in \"protectiq\" or \"ProtectIQs\". A\n * frozen word is only kept where it appears this way.\n */\nexport function containsWord(text: string, word: string): boolean {\n if (!word) return false;\n const escaped = word.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?<![\\\\p{L}\\\\p{N}_])${escaped}(?![\\\\p{L}\\\\p{N}_])`, \"u\").test(text);\n}\n\n/**\n * The SDK's defaults are a 10-minute timeout with retries. A translation\n * must stay bounded to seconds, not minutes: the manual endpoint awaits it\n * while an editor waits, and a deferred run must finish inside the host's\n * `waitUntil` window. One retry, 90s cap, then the target stays as it was.\n */\nconst TIMEOUT_MS = 90_000;\nconst MAX_RETRIES = 1;\n\n/** The slice of the Anthropic client this translator calls. */\nexport interface AnthropicMessagesClient {\n messages: {\n create(\n body: Record<string, unknown>,\n options?: { timeout?: number; maxRetries?: number },\n ): Promise<{\n content: Array<{ type: string; text?: string }>;\n usage?: { input_tokens?: number | null; output_tokens?: number | null } | null;\n }>;\n };\n}\n\nexport interface AnthropicTranslatorOptions {\n /**\n * The API key, usually `process.env.ANTHROPIC_API_KEY`. Without one the\n * translator reports `configured: false`: publishes still work, a\n * warning is logged, and \"Translate now\" is hidden.\n */\n apiKey?: string | null;\n /** The model id; omitted or blank uses `DEFAULT_TRANSLATE_MODEL`. */\n model?: string | null;\n /** The site facts the prompt carries. The plugin's own `site`, when given, wins. */\n site?: TranslateSite;\n /** A client to use instead of constructing one (tests, a proxied client). */\n client?: AnthropicMessagesClient;\n /**\n * Called once per API call with its token usage, or with why it failed.\n * Settings → Translation records usage and failures through it. A throw\n * here is ignored.\n */\n onCall?: (event: TranslatorCallEvent) => void | Promise<void>;\n}\n\nfunction languageName(code: string, site: TranslateSite | undefined): string {\n const named = site?.languages?.[code];\n if (named) return named;\n try {\n return new Intl.DisplayNames([\"en\"], { type: \"language\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/**\n * The system prompt: the library's generic rules plus the site's own facts.\n * Exported so a site can read exactly what the model is told.\n */\nexport function translationSystemPrompt(request: Pick<TranslateRequest, \"from\" | \"to\" | \"site\">): string {\n const { site } = request;\n const from = languageName(request.from, site);\n const to = languageName(request.to, site);\n const who = site?.name\n ? `You are a professional translator for ${site.name}${site.about ? `, ${site.about}` : \"\"}.`\n : \"You are a professional translator for a business website.\";\n const voice = site?.voice ? ` Keep the ${site.voice} brand voice.` : \" Keep the brand voice.\";\n const verbatim = [site?.name, ...(site?.keepVerbatim ?? [])].filter(\n (value, index, all): value is string => Boolean(value) && all.indexOf(value) === index,\n );\n const keep = verbatim.length\n ? `- Keep these EXACTLY as written, untranslated: ${verbatim.join(\n \", \",\n )}. Also keep URLs, email addresses and phone numbers as written.`\n : \"- Keep URLs, email addresses and phone numbers exactly as written.\";\n\n return `${who} Translate website and UI copy from ${from} into clear, natural ${to}.${voice}\n\nHard rules:\n- You receive a JSON array of strings. Return ONLY a JSON array of the translated strings, in the SAME ORDER and SAME LENGTH. No prose, no markdown, no code fences.\n${keep}\n- Preserve any ICU/message placeholders such as {year}, {count}, {name} verbatim, including the braces.\n- Preserve any HTML tags (e.g. <em>...</em>, <strong>...</strong>) and their positions; translate only the text between them.\n- For legal, regulatory or compliance copy, translate faithfully and literally. This output is a first-pass draft for a native speaker to review, not final compliance copy.\n- If a string is empty or is only a placeholder/URL/number, return it unchanged.`;\n}\n\n/** Tolerant JSON-array parse: strips accidental ``` fences and prose around the array, and checks the shape. */\nexport function parseJsonArray(text: string): string[] | null {\n let candidate = text.trim();\n const fenced = candidate.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced?.[1] !== undefined) candidate = fenced[1].trim();\n // If the model wrapped the array in prose, take the outermost [ ... ].\n const start = candidate.indexOf(\"[\");\n const end = candidate.lastIndexOf(\"]\");\n if (start !== -1 && end > start) candidate = candidate.slice(start, end + 1);\n try {\n const value: unknown = JSON.parse(candidate);\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value as string[];\n } catch {\n // fall through\n }\n return null;\n}\n\n/**\n * The provided `Translator`: one Anthropic Messages call per batch, the\n * strings as a JSON array in and out. `@anthropic-ai/sdk` is a peer,\n * imported on the first call, so a site that never translates never loads\n * it. Every failure (no key, the SDK missing, a network error, a\n * refusal, a malformed or wrong-length reply) returns `null` and is logged\n * by the caller; it never throws.\n */\nexport function anthropicTranslator(options: AnthropicTranslatorOptions): Translator {\n const apiKey = options.apiKey || undefined;\n const model = options.model?.trim() || DEFAULT_TRANSLATE_MODEL;\n let client: AnthropicMessagesClient | undefined = options.client;\n\n const getClient = async (): Promise<AnthropicMessagesClient | null> => {\n if (client) return client;\n if (!apiKey) return null;\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n return client;\n };\n\n const report = async (event: TranslatorCallEvent): Promise<void> => {\n try {\n await options.onCall?.(event);\n } catch {\n // Reporting must never change the translation's outcome.\n }\n };\n\n const translate = async (strings: string[], request: TranslateRequest): Promise<string[] | null> => {\n if (strings.length === 0) return [];\n let anthropic: AnthropicMessagesClient | null;\n try {\n anthropic = await getClient();\n } catch {\n return null;\n }\n if (!anthropic) return null;\n try {\n const given = request.site ?? options.site;\n // Only the frozen words this batch actually contains (whole word,\n // case-sensitive), so \"protectiq\" in English is never told to stay\n // \"ProtectIQ\".\n const site = given?.keepVerbatim\n ? {\n ...given,\n keepVerbatim: given.keepVerbatim.filter((word) => strings.some((value) => containsWord(value, word))),\n }\n : given;\n const to = languageName(request.to, site);\n const content =\n (request.context ? `Context: ${request.context}\\n\\n` : \"\") +\n `Translate this JSON array of ${strings.length} strings to ${to}:\\n${JSON.stringify(strings)}`;\n const response = await anthropic.messages.create(\n {\n model,\n max_tokens: 16000,\n // A batch of copy is routine work; low effort keeps it fast and\n // inside the timeout without changing the result.\n output_config: { effort: \"low\" },\n system: translationSystemPrompt({ from: request.from, to: request.to, site }),\n messages: [{ role: \"user\", content }],\n },\n { timeout: TIMEOUT_MS, maxRetries: MAX_RETRIES },\n );\n const text = response.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\")\n .trim();\n const parsed = parseJsonArray(text);\n const usable = parsed && parsed.length === strings.length ? parsed : null;\n if (usable) {\n await report({\n ok: true,\n model,\n strings: strings.length,\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n });\n } else {\n await report({ ok: false, model, strings: strings.length, failure: \"other\", message: \"The reply was not a usable JSON array.\" });\n }\n return usable;\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n await report({\n ok: false,\n model,\n strings: strings.length,\n failure: classifyAnthropicError(error),\n ...(typeof status === \"number\" ? { status } : {}),\n message: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n };\n\n return Object.assign(translate, { configured: Boolean(apiKey || options.client) });\n}\n\n/** What a key check found. */\nexport type KeyCheck = \"valid\" | \"rejected\" | \"out-of-credit\" | \"unreachable\";\n\n/**\n * Checks a key with the smallest call that proves both the key and the\n * account's credit: one Haiku message with a few output tokens (a fraction\n * of a cent). A 401 is `rejected`; a billing error `out-of-credit`; no\n * answer, a 5xx or a rate limit `unreachable`, meaning \"check again on\n * first use\". Never throws.\n */\nexport async function verifyAnthropicKey(\n apiKey: string,\n options: { client?: AnthropicMessagesClient } = {},\n): Promise<KeyCheck> {\n try {\n let client = options.client;\n if (!client) {\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n }\n await client.messages.create(\n {\n model: ECONOMY_TRANSLATE_MODEL,\n max_tokens: 16,\n output_config: { effort: \"low\" },\n messages: [{ role: \"user\", content: \"Reply with OK.\" }],\n },\n { timeout: 20_000, maxRetries: 0 },\n );\n return \"valid\";\n } catch (error) {\n const kind = classifyAnthropicError(error);\n if (kind === \"key-rejected\") return \"rejected\";\n if (kind === \"out-of-credit\") return \"out-of-credit\";\n return \"unreachable\";\n }\n}\n","import type { TranslateRequest, Translator } from \"./types\";\n\n/**\n * Translates `strings` with `translator` in one batch, preserving order.\n * Repeated strings are sent once. Returns `null` when the translator throws,\n * returns `null`, or returns anything but one string per string sent, so a\n * caller can leave the target as it was. Never throws.\n */\nexport async function translateStrings(\n strings: readonly string[],\n options: TranslateRequest & { translator: Translator },\n): Promise<string[] | null> {\n if (strings.length === 0) return [];\n const { translator, ...request } = options;\n const unique = [...new Set(strings)];\n let result: unknown;\n try {\n result = await translator(unique, request);\n } catch {\n return null;\n }\n if (!Array.isArray(result) || result.length !== unique.length) return null;\n if (!result.every((value) => typeof value === \"string\")) return null;\n const byString = new Map(unique.map((value, index) => [value, result[index] as string]));\n return strings.map((value) => byString.get(value) ?? value);\n}\n\n/** True unless the translator says it cannot run (an Anthropic translator with no API key). */\nexport function isTranslatorConfigured(translator: Translator | undefined): translator is Translator {\n return translator !== undefined && translator.configured !== false;\n}\n"],"mappings":";AAaA,SAAS,UAAU,OAAgE;AACjF,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,MAAM;CACjD,MAAM,OAAO,MAAM;AACnB,KAAI,OAAO,MAAM,OAAO,SAAS,SAAU,QAAO,KAAK,MAAM;AAC7D,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,KAAK;;;AAKlD,SAAgB,uBAAuB,OAAwC;AAC7E,KAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;CAChD,MAAM,YAAY;CAClB,MAAM,SAAS,OAAO,UAAU,WAAW,WAAW,UAAU,SAAS,KAAA;CACzE,MAAM,OAAO,UAAU,UAAU;CACjC,MAAM,UAAU,OAAO,UAAU,YAAY,WAAW,UAAU,UAAU;AAC5E,KAAI,WAAW,OAAO,SAAS,gBAAiB,QAAO;AACvD,KAAI,WAAW,OAAO,kBAAkB,KAAK,QAAQ,CAAE,QAAO;AAC9D,KAAI,WAAW,OAAO,WAAW,OAAO,SAAS,0BAA0B,SAAS,mBAClF,QAAO;AAET,KAAI,WAAW,OAAO,SAAS,mBAAoB,QAAO;AAC1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MAAM,IAAI,MAAM;;;AAI7D,SAAgB,uBAAuB,YAA8D;AACnG,QAAO,eAAe,KAAA,KAAa,WAAW,eAAe"}
1
+ {"version":3,"file":"strings-_9n8BefX.mjs","names":[],"sources":["../src/translate/errors.ts","../src/translate/anthropic.ts","../src/translate/strings.ts"],"sourcesContent":["/**\n * Why a translation call failed, in the terms an Admin can act on.\n *\n * - `out-of-credit`: the Anthropic account has no credit or a billing\n * problem (402 `billing_error`, or the older 400 \"credit balance is too\n * low\").\n * - `key-rejected`: the key is wrong, revoked or lacks permission (401, 403).\n * - `rate-limited`: 429, after the SDK's own retry.\n * - `unreachable`: no answer, a timeout, or a 5xx / 529 from Anthropic.\n * - `other`: anything else (a malformed reply, a refusal).\n */\nexport type TranslationFailureKind = \"out-of-credit\" | \"key-rejected\" | \"rate-limited\" | \"unreachable\" | \"other\";\n\nfunction errorType(error: { error?: unknown; type?: unknown }): string | undefined {\n if (typeof error.type === \"string\") return error.type;\n const body = error.error as { type?: unknown; error?: { type?: unknown } } | undefined;\n if (typeof body?.error?.type === \"string\") return body.error.type;\n if (typeof body?.type === \"string\") return body.type;\n return undefined;\n}\n\n/** Sorts an error thrown by the Anthropic SDK (or a network failure) into a `TranslationFailureKind`. */\nexport function classifyAnthropicError(error: unknown): TranslationFailureKind {\n if (!error || typeof error !== \"object\") return \"other\";\n const candidate = error as { status?: unknown; message?: unknown; error?: unknown; type?: unknown };\n const status = typeof candidate.status === \"number\" ? candidate.status : undefined;\n const type = errorType(candidate);\n const message = typeof candidate.message === \"string\" ? candidate.message : \"\";\n if (status === 402 || type === \"billing_error\") return \"out-of-credit\";\n if (status === 400 && /credit balance/i.test(message)) return \"out-of-credit\";\n if (status === 401 || status === 403 || type === \"authentication_error\" || type === \"permission_error\") {\n return \"key-rejected\";\n }\n if (status === 429 || type === \"rate_limit_error\") return \"rate-limited\";\n if (status === undefined || status >= 500) return \"unreachable\";\n return \"other\";\n}\n","import { classifyAnthropicError, type TranslationFailureKind } from \"./errors\";\nimport type { TranslateRequest, TranslateSite, Translator } from \"./types\";\n\n/**\n * The library's default model. Translating marketing copy does not need the\n * most capable model; a current Sonnet handles it well at a fraction of the\n * price. A site overrides it per environment (`ANTHROPIC_TRANSLATE_MODEL`).\n */\nexport const DEFAULT_TRANSLATE_MODEL = \"claude-sonnet-5-5\";\n\n/** \"Economy (Haiku)\" on Settings → Translation: a fraction of Sonnet's price for plainer copy. */\nexport const ECONOMY_TRANSLATE_MODEL = \"claude-haiku-5-5\";\n\n/** USD per million tokens, for the cost estimates on Settings → Translation. */\nexport interface ModelPrice {\n input: number;\n output: number;\n}\n\n/**\n * Anthropic's list prices for the two models the screen offers. A model\n * not listed (an `ANTHROPIC_TRANSLATE_MODEL` override) is estimated at\n * Sonnet's price, so an estimate errs high rather than reading as free.\n */\nexport const TRANSLATE_MODEL_PRICES: Record<string, ModelPrice> = {\n [DEFAULT_TRANSLATE_MODEL]: { input: 2, output: 10 },\n [ECONOMY_TRANSLATE_MODEL]: { input: 0.1, output: 0.5 },\n};\n\nexport function modelPrice(model: string): ModelPrice {\n return TRANSLATE_MODEL_PRICES[model] ?? TRANSLATE_MODEL_PRICES[DEFAULT_TRANSLATE_MODEL]!;\n}\n\n/** Estimated USD for one call's tokens on `model`. */\nexport function estimateCost(model: string, inputTokens: number, outputTokens: number): number {\n const price = modelPrice(model);\n return (inputTokens * price.input + outputTokens * price.output) / 1_000_000;\n}\n\n/** What one translator call did, for usage, cost and failure reporting. */\nexport type TranslatorCallEvent =\n | { ok: true; model: string; strings: number; inputTokens: number; outputTokens: number }\n | { ok: false; model: string; strings: number; failure: TranslationFailureKind; status?: number; message: string };\n\n/**\n * True when `text` contains `word` as a whole word, case-sensitively: \"ProtectIQ\"\n * is in \"Get ProtectIQ today\" but not in \"protectiq\" or \"ProtectIQs\". A\n * frozen word is only kept where it appears this way.\n */\nexport function containsWord(text: string, word: string): boolean {\n if (!word) return false;\n const escaped = word.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?<![\\\\p{L}\\\\p{N}_])${escaped}(?![\\\\p{L}\\\\p{N}_])`, \"u\").test(text);\n}\n\n/**\n * The SDK's defaults are a 10-minute timeout with retries. A translation\n * must stay bounded to seconds, not minutes: the manual endpoint awaits it\n * while an editor waits, and a deferred run must finish inside the host's\n * `waitUntil` window. One retry, 90s cap, then the target stays as it was.\n */\nconst TIMEOUT_MS = 90_000;\nconst MAX_RETRIES = 1;\n\n/** The slice of the Anthropic client this translator calls. */\nexport interface AnthropicMessagesClient {\n messages: {\n create(\n body: Record<string, unknown>,\n options?: { timeout?: number; maxRetries?: number },\n ): Promise<{\n content: Array<{ type: string; text?: string }>;\n usage?: { input_tokens?: number | null; output_tokens?: number | null } | null;\n }>;\n };\n}\n\nexport interface AnthropicTranslatorOptions {\n /**\n * The API key, usually `process.env.ANTHROPIC_API_KEY`. Without one the\n * translator reports `configured: false`: publishes still work, a\n * warning is logged, and \"Translate now\" is hidden.\n */\n apiKey?: string | null;\n /** The model id; omitted or blank uses `DEFAULT_TRANSLATE_MODEL`. */\n model?: string | null;\n /** The site facts the prompt carries. The plugin's own `site`, when given, wins. */\n site?: TranslateSite;\n /** A client to use instead of constructing one (tests, a proxied client). */\n client?: AnthropicMessagesClient;\n /**\n * Called once per API call with its token usage, or with why it failed.\n * Settings → Translation records usage and failures through it. A throw\n * here is ignored.\n */\n onCall?: (event: TranslatorCallEvent) => void | Promise<void>;\n}\n\nfunction languageName(code: string, site: TranslateSite | undefined): string {\n const named = site?.languages?.[code];\n if (named) return named;\n try {\n return new Intl.DisplayNames([\"en\"], { type: \"language\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/**\n * The system prompt: the library's generic rules plus the site's own facts.\n * Exported so a site can read exactly what the model is told.\n */\nexport function translationSystemPrompt(request: Pick<TranslateRequest, \"from\" | \"to\" | \"site\">): string {\n const { site } = request;\n const from = languageName(request.from, site);\n const to = languageName(request.to, site);\n const who = site?.name\n ? `You are a professional translator for ${site.name}${site.about ? `, ${site.about}` : \"\"}.`\n : \"You are a professional translator for a business website.\";\n const voice = site?.voice ? ` Keep the ${site.voice} brand voice.` : \" Keep the brand voice.\";\n const verbatim = [site?.name, ...(site?.keepVerbatim ?? [])].filter(\n (value, index, all): value is string => Boolean(value) && all.indexOf(value) === index,\n );\n const keep = verbatim.length\n ? `- Keep these EXACTLY as written, untranslated: ${verbatim.join(\n \", \",\n )}. Also keep URLs, email addresses and phone numbers as written.`\n : \"- Keep URLs, email addresses and phone numbers exactly as written.\";\n\n return `${who} Translate website and UI copy from ${from} into clear, natural ${to}.${voice}\n\nHard rules:\n- You receive a JSON array of strings. Return ONLY a JSON array of the translated strings, in the SAME ORDER and SAME LENGTH. No prose, no markdown, no code fences.\n${keep}\n- Preserve any ICU/message placeholders such as {year}, {count}, {name} verbatim, including the braces.\n- Preserve any HTML tags (e.g. <em>...</em>, <strong>...</strong>) and their positions; translate only the text between them.\n- For legal, regulatory or compliance copy, translate faithfully and literally. This output is a first-pass draft for a native speaker to review, not final compliance copy.\n- If a string is empty or is only a placeholder/URL/number, return it unchanged.`;\n}\n\n/** Tolerant JSON-array parse: strips accidental ``` fences and prose around the array, and checks the shape. */\nexport function parseJsonArray(text: string): string[] | null {\n let candidate = text.trim();\n const fenced = candidate.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced?.[1] !== undefined) candidate = fenced[1].trim();\n // If the model wrapped the array in prose, take the outermost [ ... ].\n const start = candidate.indexOf(\"[\");\n const end = candidate.lastIndexOf(\"]\");\n if (start !== -1 && end > start) candidate = candidate.slice(start, end + 1);\n try {\n const value: unknown = JSON.parse(candidate);\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value as string[];\n } catch {\n // fall through\n }\n return null;\n}\n\n/**\n * The provided `Translator`: one Anthropic Messages call per batch, the\n * strings as a JSON array in and out. `@anthropic-ai/sdk` is a peer,\n * imported on the first call, so a site that never translates never loads\n * it. Every failure (no key, the SDK missing, a network error, a\n * refusal, a malformed or wrong-length reply) returns `null` and is logged\n * by the caller; it never throws.\n */\nexport function anthropicTranslator(options: AnthropicTranslatorOptions): Translator {\n const apiKey = options.apiKey || undefined;\n const model = options.model?.trim() || DEFAULT_TRANSLATE_MODEL;\n let client: AnthropicMessagesClient | undefined = options.client;\n\n const getClient = async (): Promise<AnthropicMessagesClient | null> => {\n if (client) return client;\n if (!apiKey) return null;\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n return client;\n };\n\n const report = async (event: TranslatorCallEvent): Promise<void> => {\n try {\n await options.onCall?.(event);\n } catch {\n // Reporting must never change the translation's outcome.\n }\n };\n\n const translate = async (strings: string[], request: TranslateRequest): Promise<string[] | null> => {\n if (strings.length === 0) return [];\n let anthropic: AnthropicMessagesClient | null;\n try {\n anthropic = await getClient();\n } catch {\n return null;\n }\n if (!anthropic) return null;\n try {\n const given = request.site ?? options.site;\n // Only the frozen words this batch actually contains (whole word,\n // case-sensitive), so \"protectiq\" in English is never told to stay\n // \"ProtectIQ\".\n const site = given?.keepVerbatim\n ? {\n ...given,\n keepVerbatim: given.keepVerbatim.filter((word) => strings.some((value) => containsWord(value, word))),\n }\n : given;\n const to = languageName(request.to, site);\n const content =\n (request.context ? `Context: ${request.context}\\n\\n` : \"\") +\n `Translate this JSON array of ${strings.length} strings to ${to}:\\n${JSON.stringify(strings)}`;\n const response = await anthropic.messages.create(\n {\n model,\n max_tokens: 16000,\n // A batch of copy is routine work; low effort keeps it fast and\n // inside the timeout without changing the result.\n output_config: { effort: \"low\" },\n system: translationSystemPrompt({ from: request.from, to: request.to, site }),\n messages: [{ role: \"user\", content }],\n },\n { timeout: TIMEOUT_MS, maxRetries: MAX_RETRIES },\n );\n const text = response.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\")\n .trim();\n const parsed = parseJsonArray(text);\n const usable = parsed && parsed.length === strings.length ? parsed : null;\n if (usable) {\n await report({\n ok: true,\n model,\n strings: strings.length,\n inputTokens: response.usage?.input_tokens ?? 0,\n outputTokens: response.usage?.output_tokens ?? 0,\n });\n } else {\n await report({ ok: false, model, strings: strings.length, failure: \"other\", message: \"The reply was not a usable JSON array.\" });\n }\n return usable;\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n await report({\n ok: false,\n model,\n strings: strings.length,\n failure: classifyAnthropicError(error),\n ...(typeof status === \"number\" ? { status } : {}),\n message: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n };\n\n return Object.assign(translate, { configured: Boolean(apiKey || options.client) });\n}\n\n/** What a key check found. */\nexport type KeyCheck = \"valid\" | \"rejected\" | \"out-of-credit\" | \"unreachable\";\n\n/**\n * Checks a key with the smallest call that proves both the key and the\n * account's credit: one Haiku message with a few output tokens (a fraction\n * of a cent). A 401 is `rejected`; a billing error `out-of-credit`; no\n * answer, a 5xx or a rate limit `unreachable`, meaning \"check again on\n * first use\". Never throws.\n */\nexport async function verifyAnthropicKey(\n apiKey: string,\n options: { client?: AnthropicMessagesClient } = {},\n): Promise<KeyCheck> {\n try {\n let client = options.client;\n if (!client) {\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n }\n await client.messages.create(\n {\n model: ECONOMY_TRANSLATE_MODEL,\n max_tokens: 16,\n output_config: { effort: \"low\" },\n messages: [{ role: \"user\", content: \"Reply with OK.\" }],\n },\n { timeout: 20_000, maxRetries: 0 },\n );\n return \"valid\";\n } catch (error) {\n const kind = classifyAnthropicError(error);\n if (kind === \"key-rejected\") return \"rejected\";\n if (kind === \"out-of-credit\") return \"out-of-credit\";\n return \"unreachable\";\n }\n}\n","import type { TranslateRequest, Translator } from \"./types\";\n\n/**\n * Translates `strings` with `translator` in one batch, preserving order.\n * Repeated strings are sent once. Returns `null` when the translator throws,\n * returns `null`, or returns anything but one string per string sent, so a\n * caller can leave the target as it was. Never throws.\n */\nexport async function translateStrings(\n strings: readonly string[],\n options: TranslateRequest & { translator: Translator },\n): Promise<string[] | null> {\n if (strings.length === 0) return [];\n const { translator, ...request } = options;\n const unique = [...new Set(strings)];\n let result: unknown;\n try {\n result = await translator(unique, request);\n } catch {\n return null;\n }\n if (!Array.isArray(result) || result.length !== unique.length) return null;\n if (!result.every((value) => typeof value === \"string\")) return null;\n const byString = new Map(unique.map((value, index) => [value, result[index] as string]));\n return strings.map((value) => byString.get(value) ?? value);\n}\n\n/** True unless the translator says it cannot run (an Anthropic translator with no API key). */\nexport function isTranslatorConfigured(translator: Translator | undefined): translator is Translator {\n return translator !== undefined && translator.configured !== false;\n}\n"],"mappings":";AAaA,SAAS,UAAU,OAAgE;AACjF,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,MAAM;CACjD,MAAM,OAAO,MAAM;AACnB,KAAI,OAAO,MAAM,OAAO,SAAS,SAAU,QAAO,KAAK,MAAM;AAC7D,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,KAAK;;;AAKlD,SAAgB,uBAAuB,OAAwC;AAC7E,KAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;CAChD,MAAM,YAAY;CAClB,MAAM,SAAS,OAAO,UAAU,WAAW,WAAW,UAAU,SAAS,KAAA;CACzE,MAAM,OAAO,UAAU,UAAU;CACjC,MAAM,UAAU,OAAO,UAAU,YAAY,WAAW,UAAU,UAAU;AAC5E,KAAI,WAAW,OAAO,SAAS,gBAAiB,QAAO;AACvD,KAAI,WAAW,OAAO,kBAAkB,KAAK,QAAQ,CAAE,QAAO;AAC9D,KAAI,WAAW,OAAO,WAAW,OAAO,SAAS,0BAA0B,SAAS,mBAClF,QAAO;AAET,KAAI,WAAW,OAAO,SAAS,mBAAoB,QAAO;AAC1D,KAAI,WAAW,KAAA,KAAa,UAAU,IAAK,QAAO;AAClD,QAAO;;;;;;;;;AC3BT,MAAa,0BAA0B;;AAGvC,MAAa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,2 +1,2 @@
1
- import { n as facetField, t as FacetEntry } from "./facet-field-Cd6lffed.mjs";
1
+ import { n as facetField, t as FacetEntry } from "./facet-field-Dbcu1L91.mjs";
2
2
  export { type FacetEntry, facetField };
package/dist/taxonomy.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as facetField } from "./facet-field-DO3VT_Cz.mjs";
1
+ import { t as facetField } from "./facet-field-7p6_MhsT.mjs";
2
2
  export { facetField };
package/dist/theme.d.mts CHANGED
@@ -1,7 +1,8 @@
1
- import { _ as ThemeIdentityFallback, c as THEME_SLUG, d as ThemeDoc, f as ThemeHead, g as ResolvedThemeIdentity, h as ThemeUploadDoc, i as SystemColorKey, m as ThemeLibraryColorDoc, n as EditableTheme, p as ThemeHeadOptions, r as SYSTEM_COLOR_KEYS, t as CreateThemeOptions, u as ThemeColorDoc, v as resolveThemeIdentity } from "./types-B1MmE-L3.mjs";
2
- import { _ as deleteLibraryColor, a as PageEditorSystemKey, c as pageEditorTokens, f as colorTokenField, g as rewriteColorTokens, h as findColorTokens, i as PAGE_EDITOR_SYSTEM_KEYS, l as themeLibraryFromDoc, m as ColorTokenHit, n as ColorSwatch, o as pageEditorLooks, p as lookField, r as LookOption, s as pageEditorSwatches, t as THEME_PREVIEW_BREAKPOINTS, v as rewriteColorToken, y as themeColorKeys } from "./preview-B69Dhi8T.mjs";
3
- import { t as LocaleRead } from "./locale-tnKLkutC.mjs";
4
- import { n as getPublishedIdentity, r as getPublishedTheme } from "./published-2I-k6zEo.mjs";
1
+ import { _ as ThemeHeadOptions, a as CreateThemeOptions, c as SystemColorKey, f as THEME_SLUG, g as ThemeHead, h as ThemeDoc, i as resolveThemeIdentity, m as ThemeColorDoc, n as ThemeIdentityAsset, o as EditableTheme, r as ThemeIdentityFallback, s as SYSTEM_COLOR_KEYS, t as ResolvedThemeIdentity, v as ThemeLibraryColorDoc, y as ThemeUploadDoc } from "./identity-B4Lew8Fu.mjs";
2
+ import { t as LocaleRead } from "./locale-CTT3nn6T.mjs";
3
+ import { n as getPublishedIdentity, r as getPublishedTheme } from "./published-DYpXTy84.mjs";
4
+ import { a as getAdminHead, i as adminAuthCss, n as AdminHeadData, o as getAdminIdentity, r as AdminHeadOptions, t as AdminBrandingPayload } from "./admin-head-QfW81bDy.mjs";
5
+ import { _ as deleteLibraryColor, a as PageEditorSystemKey, c as pageEditorTokens, f as colorTokenField, g as rewriteColorTokens, h as findColorTokens, i as PAGE_EDITOR_SYSTEM_KEYS, l as themeLibraryFromDoc, m as ColorTokenHit, n as ColorSwatch, o as pageEditorLooks, p as lookField, r as LookOption, s as pageEditorSwatches, t as THEME_PREVIEW_BREAKPOINTS, v as rewriteColorToken, y as themeColorKeys } from "./preview-DSQN4uYa.mjs";
5
6
  import { ShadeStep, ThemeConfig } from "@bison-lab/tokens";
6
7
 
7
8
  //#region src/theme/map.d.ts
@@ -30,5 +31,5 @@ declare function themeHead(config: ThemeConfig, options?: ThemeHeadOptions): The
30
31
  */
31
32
  declare function themeHeadFromDoc(doc: ThemeDoc | null | undefined, seed: ThemeConfig, options?: Omit<ThemeHeadOptions, "library">): ThemeHead;
32
33
  //#endregion
33
- export { type ColorSwatch, type ColorTokenHit, type CreateThemeOptions, type EditableTheme, type LocaleRead, type LookOption, PAGE_EDITOR_SYSTEM_KEYS, type PageEditorSystemKey, type ResolvedThemeIdentity, SYSTEM_COLOR_KEYS, type SystemColorKey, THEME_PREVIEW_BREAKPOINTS, THEME_SLUG, type ThemeColorDoc, type ThemeDoc, type ThemeHead, type ThemeHeadOptions, type ThemeIdentityFallback, type ThemeLibraryColorDoc, type ThemeUploadDoc, colorTokenField, deleteLibraryColor, findColorTokens, getPublishedIdentity, getPublishedTheme, lookField, pageEditorLooks, pageEditorSwatches, pageEditorTokens, resolveThemeIdentity, rewriteColorToken, rewriteColorTokens, themeColorKeys, themeConfigFromDoc, themeHead, themeHeadFromDoc, themeLibraryFromDoc };
34
+ export { type AdminBrandingPayload, type AdminHeadData, type AdminHeadOptions, type ColorSwatch, type ColorTokenHit, type CreateThemeOptions, type EditableTheme, type LocaleRead, type LookOption, PAGE_EDITOR_SYSTEM_KEYS, type PageEditorSystemKey, type ResolvedThemeIdentity, SYSTEM_COLOR_KEYS, type SystemColorKey, THEME_PREVIEW_BREAKPOINTS, THEME_SLUG, type ThemeColorDoc, type ThemeDoc, type ThemeHead, type ThemeHeadOptions, type ThemeIdentityAsset, type ThemeIdentityFallback, type ThemeLibraryColorDoc, type ThemeUploadDoc, adminAuthCss, colorTokenField, deleteLibraryColor, findColorTokens, getAdminHead, getAdminIdentity, getPublishedIdentity, getPublishedTheme, lookField, pageEditorLooks, pageEditorSwatches, pageEditorTokens, resolveThemeIdentity, rewriteColorToken, rewriteColorTokens, themeColorKeys, themeConfigFromDoc, themeHead, themeHeadFromDoc, themeLibraryFromDoc };
34
35
  //# sourceMappingURL=theme.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"theme.d.mts","names":[],"sources":["../src/theme/map.ts","../src/theme/head.ts"],"mappings":";;;;;;;;;AA4EA;;;iBAAgB,kBAAA,CAAmB,GAAA,EAAK,QAAA,qBAA6B,IAAA,EAAM,WAAA,GAAc,WAAA;;;;;;;;AAAzF;;;;iBC3DgB,SAAA,CAAU,MAAA,EAAQ,WAAA,EAAa,OAAA,GAAS,gBAAA,GAAwB,SAAA;;;;;;iBAmBhE,gBAAA,CACd,GAAA,EAAK,QAAA,qBACL,IAAA,EAAM,WAAA,EACN,OAAA,GAAS,IAAA,CAAK,gBAAA,eACb,SAAA"}
1
+ {"version":3,"file":"theme.d.mts","names":[],"sources":["../src/theme/map.ts","../src/theme/head.ts"],"mappings":";;;;;;;;;;;AA4EA;;iBAAgB,kBAAA,CAAmB,GAAA,EAAK,QAAA,qBAA6B,IAAA,EAAM,WAAA,GAAc,WAAA;;;;;;;;;AAAzF;;;iBC3DgB,SAAA,CAAU,MAAA,EAAQ,WAAA,EAAa,OAAA,GAAS,gBAAA,GAAwB,SAAA;;;;;;iBAmBhE,gBAAA,CACd,GAAA,EAAK,QAAA,qBACL,IAAA,EAAM,WAAA,EACN,OAAA,GAAS,IAAA,CAAK,gBAAA,eACb,SAAA"}
package/dist/theme.mjs CHANGED
@@ -1,63 +1,6 @@
1
- import { l as stateFromColorDoc, n as SYSTEM_COLOR_KEYS, o as THEME_SLUG, t as resolveThemeIdentity, u as themeConfigFromDoc } from "./identity-CN6EOeDM.mjs";
2
- import { a as pageEditorLooks, c as themeLibraryFromDoc, d as deleteLibraryColor, f as rewriteColorToken, i as PAGE_EDITOR_SYSTEM_KEYS, l as findColorTokens, n as colorTokenField, o as pageEditorSwatches, p as themeColorKeys, r as lookField, s as pageEditorTokens, t as THEME_PREVIEW_BREAKPOINTS, u as rewriteColorTokens } from "./preview-Br1SQCKn.mjs";
3
- import { n as getPublishedTheme, t as getPublishedIdentity } from "./published-B80KqlcU.mjs";
4
- import { fontFaceCss, fontPreloads } from "@bison-lab/fonts";
5
- import { buildThemeCss, generateNamedScaleCSS, lookBindingCss, themeFontIds } from "@bison-lab/tokens";
6
- //#region src/theme/look-css.ts
7
- /**
8
- * Custom `--coral-*` variables plus `[data-look]` bindings for every
9
- * page-editor family. System bindings always ship so a look key paints
10
- * before anyone adds a custom scale.
11
- */
12
- function themeLookCss(library) {
13
- const rows = Array.isArray(library) ? library : [];
14
- const customKeys = [];
15
- const scaleLines = [];
16
- for (const row of rows) {
17
- const key = row.key?.trim();
18
- if (!key) continue;
19
- customKeys.push(key);
20
- const state = stateFromColorDoc(row, row.hex ?? "#000000");
21
- scaleLines.push(generateNamedScaleCSS(key, state.scale));
22
- }
23
- return [scaleLines.length ? `:root {\n${scaleLines.join("\n")}\n}` : "", lookBindingCss([...PAGE_EDITOR_SYSTEM_KEYS, ...customKeys])].filter(Boolean).join("\n\n");
24
- }
25
- //#endregion
26
- //#region src/theme/head.ts
27
- /**
28
- * `@font-face` plus `buildThemeCss` as one stylesheet, and the preload
29
- * list for the families the config names. A root layout (and the admin
30
- * layout, if it should restyle too) renders `css` in a `<style>` and
31
- * each preload as `<link rel="preload" as="font">`.
32
- *
33
- * `library` adds custom `--coral-*` variables and `[data-look]` bindings
34
- * so a Color Settings scale paints the moment it is published.
35
- */
36
- function themeHead(config, options = {}) {
37
- const fontsBaseUrl = options.fontsBaseUrl ?? "/fonts";
38
- const ids = themeFontIds(config);
39
- const faces = fontFaceCss(ids, fontsBaseUrl);
40
- const theme = buildThemeCss(config, { attribute: options.attribute });
41
- const looks = themeLookCss(options.library);
42
- const body = looks ? `${theme}\n\n${looks}` : theme;
43
- return {
44
- css: faces ? `${faces}\n\n${body}` : body,
45
- preloads: fontPreloads(ids, fontsBaseUrl),
46
- identity: options.identity
47
- };
48
- }
49
- /**
50
- * `themeHead` plus the custom scales on the Theme document. Sites that
51
- * still call `themeHead(getPublishedTheme())` keep working; they miss
52
- * `--coral-*` until they pass `library` or switch here.
53
- */
54
- function themeHeadFromDoc(doc, seed, options = {}) {
55
- return themeHead(themeConfigFromDoc(doc, seed), {
56
- ...options,
57
- library: themeLibraryFromDoc(doc)
58
- });
59
- }
60
- //#endregion
61
- export { PAGE_EDITOR_SYSTEM_KEYS, SYSTEM_COLOR_KEYS, THEME_PREVIEW_BREAKPOINTS, THEME_SLUG, colorTokenField, deleteLibraryColor, findColorTokens, getPublishedIdentity, getPublishedTheme, lookField, pageEditorLooks, pageEditorSwatches, pageEditorTokens, resolveThemeIdentity, rewriteColorToken, rewriteColorTokens, themeColorKeys, themeConfigFromDoc, themeHead, themeHeadFromDoc, themeLibraryFromDoc };
62
-
63
- //# sourceMappingURL=theme.mjs.map
1
+ import { n as SYSTEM_COLOR_KEYS, o as THEME_SLUG, t as resolveThemeIdentity, u as themeConfigFromDoc } from "./identity-CkUE_uN2.mjs";
2
+ import { a as rewriteColorTokens, c as themeColorKeys, i as findColorTokens, n as colorTokenField, o as deleteLibraryColor, r as lookField, s as rewriteColorToken, t as THEME_PREVIEW_BREAKPOINTS } from "./preview-BE7P1ezl.mjs";
3
+ import { a as PAGE_EDITOR_SYSTEM_KEYS, c as pageEditorTokens, o as pageEditorLooks, s as pageEditorSwatches, u as themeLibraryFromDoc } from "./admin-branding-CEKdfYah.mjs";
4
+ import { n as getPublishedTheme, t as getPublishedIdentity } from "./published-C8bW5jvC.mjs";
5
+ import { a as themeHeadFromDoc, i as themeHead, n as getAdminHead, r as getAdminIdentity, t as adminAuthCss } from "./admin-head-CcpH7P4C.mjs";
6
+ export { PAGE_EDITOR_SYSTEM_KEYS, SYSTEM_COLOR_KEYS, THEME_PREVIEW_BREAKPOINTS, THEME_SLUG, adminAuthCss, colorTokenField, deleteLibraryColor, findColorTokens, getAdminHead, getAdminIdentity, getPublishedIdentity, getPublishedTheme, lookField, pageEditorLooks, pageEditorSwatches, pageEditorTokens, resolveThemeIdentity, rewriteColorToken, rewriteColorTokens, themeColorKeys, themeConfigFromDoc, themeHead, themeHeadFromDoc, themeLibraryFromDoc };
@@ -52,4 +52,4 @@ declare function documentTitle(siteName: string, pageTitle: string): string;
52
52
  declare function titleTemplate(siteName: string): string;
53
53
  //#endregion
54
54
  export { SeoImageSize as a, SeoImageDoc as i, titleTemplate as n, SeoImageValue as o, MediaId as r, SeoMeta as s, documentTitle as t };
55
- //# sourceMappingURL=title-BVV3o329.d.mts.map
55
+ //# sourceMappingURL=title-DBSLJfrW.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"title-BVV3o329.d.mts","names":[],"sources":["../src/seo/types.ts","../src/seo/title.ts"],"mappings":";;KACY,OAAA;;UAGK,YAAA;EACf,GAAA;EACA,KAAA;EACA,MAAA;AAAA;;;;;;;;AAWF;UAAiB,WAAA;EACf,GAAA;EACA,GAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;IAAA,CAAW,IAAA,WAAe,YAAA;EAAA;AAAA;;KAIhB,aAAA,GAAgB,OAAA,GAAU,WAAA;;AAAtC;;;UAMiB,OAAA;EACf,KAAA;EACA,WAAA;EACA,KAAA,GAAQ,aAAA;EACR,OAAA;AAAA;;;;AApCF;;;;;iBCKgB,aAAA,CAAc,QAAA,UAAkB,SAAA;;;;;iBAQhC,aAAA,CAAc,QAAA"}
1
+ {"version":3,"file":"title-DBSLJfrW.d.mts","names":[],"sources":["../src/seo/types.ts","../src/seo/title.ts"],"mappings":";;KACY,OAAA;;UAGK,YAAA;EACf,GAAA;EACA,KAAA;EACA,MAAA;AAAA;;;;;;;;AAWF;UAAiB,WAAA;EACf,GAAA;EACA,GAAA;EACA,KAAA;EACA,MAAA;EACA,KAAA;IAAA,CAAW,IAAA,WAAe,YAAA;EAAA;AAAA;;KAIhB,aAAA,GAAgB,OAAA,GAAU,WAAA;;AAAtC;;;UAMiB,OAAA;EACf,KAAA;EACA,WAAA;EACA,KAAA,GAAQ,aAAA;EACR,OAAA;AAAA;;;;AApCF;;;;;iBCKgB,aAAA,CAAc,QAAA,UAAkB,SAAA;;;;;iBAQhC,aAAA,CAAc,QAAA"}
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { o as anthropicTranslator } from "./strings-Fd7kUCT7.mjs";
3
- import { t as fillMessages } from "./messages-XFoL9RtF.mjs";
2
+ import { o as anthropicTranslator } from "./strings-_9n8BefX.mjs";
3
+ import { t as fillMessages } from "./messages-Bv6JIEiG.mjs";
4
4
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { basename, resolve } from "node:path";
6
6
  import { parseArgs } from "node:util";
@@ -1,4 +1,5 @@
1
- import { $ as BisonTranslationKind, A as usageThisMonth, B as KeyCheck, C as RATE_LIMIT_STREAK, D as monthKey, E as UsageMonth, F as resolveApiKey, G as containsWord, H as TRANSLATE_MODEL_PRICES, I as AnthropicMessagesClient, J as parseJsonArray, K as estimateCost, L as AnthropicTranslatorOptions, M as ResolvedKey, N as decryptApiKey, O as recordUsage, P as encryptApiKey, Q as BISON_TRANSLATION_CONTEXT, R as DEFAULT_TRANSLATE_MODEL, S as FAILURE_ADVICE, T as TRANSLATION_USAGE_SLUG, U as TranslatorCallEvent, V as ModelPrice, W as anthropicTranslator, X as verifyAnthropicKey, Y as translationSystemPrompt, Z as AutoTranslateOptions, _ as TranslationSettingsDoc, a as translation, at as TranslatedEntity, b as resolveModel, c as KeyStatus, ct as classifyAnthropicError, d as TRANSLATION_GRANT, et as BisonTranslationMarker, f as TRANSLATION_KEY_PANEL, g as TranslationModelChoice, h as TRANSLATION_STATUS_BAR, i as hasLocalizedFields, it as TranslateSite, j as KeySource, k as usageHistory, l as ResolvedTranslationSettings, m as TRANSLATION_STATE_SLUG, n as TranslationOptions, nt as TranslateLocaleResult, o as TranslationStatus, ot as Translator, p as TRANSLATION_SETTINGS_SLUG, q as modelPrice, r as applyTranslation, rt as TranslateRequest, s as translationSettingsEndpoints, st as TranslationFailureKind, t as TranslationEntityHint, tt as Doc, u as TRANSLATION_ACTIVITY_PANEL, v as invalidateTranslationSettings, w as RecordedFailure, x as siteFromInstructions, y as readTranslationSettings, z as ECONOMY_TRANSLATE_MODEL } from "./capability-NlorUIta.mjs";
1
+ import { $ as BisonTranslationKind, A as usageThisMonth, B as KeyCheck, C as RATE_LIMIT_STREAK, D as monthKey, E as UsageMonth, F as resolveApiKey, G as containsWord, H as TRANSLATE_MODEL_PRICES, I as AnthropicMessagesClient, J as parseJsonArray, K as estimateCost, L as AnthropicTranslatorOptions, M as ResolvedKey, N as decryptApiKey, O as recordUsage, P as encryptApiKey, Q as BISON_TRANSLATION_CONTEXT, R as DEFAULT_TRANSLATE_MODEL, S as FAILURE_ADVICE, T as TRANSLATION_USAGE_SLUG, U as TranslatorCallEvent, V as ModelPrice, W as anthropicTranslator, X as verifyAnthropicKey, Y as translationSystemPrompt, Z as AutoTranslateOptions, _ as TranslationSettingsDoc, a as translation, at as TranslatedEntity, b as resolveModel, c as KeyStatus, ct as classifyAnthropicError, d as TRANSLATION_GRANT, et as BisonTranslationMarker, f as TRANSLATION_KEY_PANEL, g as TranslationModelChoice, h as TRANSLATION_STATUS_BAR, i as hasLocalizedFields, it as TranslateSite, j as KeySource, k as usageHistory, l as ResolvedTranslationSettings, m as TRANSLATION_STATE_SLUG, n as TranslationOptions, nt as TranslateLocaleResult, o as TranslationStatus, ot as Translator, p as TRANSLATION_SETTINGS_SLUG, q as modelPrice, r as applyTranslation, rt as TranslateRequest, s as translationSettingsEndpoints, st as TranslationFailureKind, t as TranslationEntityHint, tt as Doc, u as TRANSLATION_ACTIVITY_PANEL, v as invalidateTranslationSettings, w as RecordedFailure, x as siteFromInstructions, y as readTranslationSettings, z as ECONOMY_TRANSLATE_MODEL } from "./capability-DonuHSPG.mjs";
2
+ import { a as LIBRARY_LOCALE_CODES, c as activeLocales, f as withLibraryLocales, i as LIBRARY_LOCALES, l as inactiveLocaleRedirect, n as ActiveLocales, o as LibraryLocaleCode, r as LIBRARY_DEFAULT_LOCALE, s as activeAlternates, t as ACTIVE_LOCALES_CACHE_MS, u as invalidateActiveLocales } from "./languages-cDe9Lznx.mjs";
2
3
  import { Block, CollectionAfterChangeHook, CollectionConfig, Config, Endpoint, Field, GlobalConfig, Payload, PayloadRequest, Plugin, SanitizedConfig } from "payload";
3
4
 
4
5
  //#region src/translate/plugin.d.ts
@@ -15,82 +16,6 @@ import { Block, CollectionAfterChangeHook, CollectionConfig, Config, Endpoint, F
15
16
  */
16
17
  declare function autoTranslate(options: AutoTranslateOptions): Plugin;
17
18
  //#endregion
18
- //#region src/translate/languages.d.ts
19
- /**
20
- * The languages every Bison site carries. The library owns this list: a new
21
- * language is a library release that sites take by updating the package
22
- * (and running the migration it brings). The first entry is the default
23
- * locale of a site that declares no localization of its own.
24
- */
25
- declare const LIBRARY_LOCALES: readonly [{
26
- readonly code: "en";
27
- readonly label: "English";
28
- }, {
29
- readonly code: "es";
30
- readonly label: "Español";
31
- }];
32
- type LibraryLocaleCode = (typeof LIBRARY_LOCALES)[number]["code"];
33
- declare const LIBRARY_DEFAULT_LOCALE: LibraryLocaleCode;
34
- /** The codes of `LIBRARY_LOCALES`, in order. */
35
- declare const LIBRARY_LOCALE_CODES: readonly string[];
36
- /**
37
- * A config's `localization` with every library language in it. A site with
38
- * none gets the library's (English default, `fallback: true`, so an empty
39
- * Spanish field reads as English). A site with its own keeps its locales,
40
- * labels and default, and gains any library language it lacks.
41
- */
42
- declare function withLibraryLocales(localization: Config["localization"]): Exclude<Config["localization"], false | undefined>;
43
- /** What `activeLocales` answers. */
44
- interface ActiveLocales {
45
- /** The default (source) locale. Always active. */
46
- defaultLocale: string;
47
- /** The default locale and every ticked target locale, in config order. */
48
- active: string[];
49
- /** Target locales that are not ticked: no translation, no URL, no switcher entry, no hreflang. */
50
- inactive: string[];
51
- }
52
- /** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
53
- declare const ACTIVE_LOCALES_CACHE_MS = 60000;
54
- type SettingsReader = Pick<Payload, "findGlobal" | "config">;
55
- /** After a failed read, how soon to try the database again. */
56
- /** Drops the cached answer, so the next `activeLocales` reads again. */
57
- declare function invalidateActiveLocales(payload: object): void;
58
- /**
59
- * The site's active languages, for routing and middleware: the default
60
- * locale plus each target language ticked on Settings → Translation. Cached
61
- * per process for `ttlMs` (60s by default): a request reads memory, and the
62
- * database is read only when the cache refreshes, or after a save of the
63
- * screen in the same process. Never throws. When a read fails it answers
64
- * with the last good read (or, before the first one, the defaults) and
65
- * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
66
- * never stands in for the Admin's ticks for a whole cache period, which
67
- * would send a ticked language's visitors permanent redirects.
68
- */
69
- declare function activeLocales(payload: SettingsReader, options?: {
70
- ttlMs?: number;
71
- }): Promise<ActiveLocales>;
72
- /**
73
- * Where a request for an inactive language goes: the same path without
74
- * its locale prefix, for a 308. `null` when the path is not under an
75
- * inactive locale. In a site's middleware:
76
- *
77
- * ```ts
78
- * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
79
- * if (to) {
80
- * const response = NextResponse.redirect(new URL(to + url.search, url), 308);
81
- * response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
82
- * return response;
83
- * }
84
- * ```
85
- */
86
- declare function inactiveLocaleRedirect(pathname: string, locales: Pick<ActiveLocales, "inactive" | "defaultLocale">): string | null;
87
- /**
88
- * A page's language alternates (for hreflang and a language switcher),
89
- * keeping only active languages. `paths` maps each locale to that
90
- * language's URL for the page.
91
- */
92
- declare function activeAlternates(paths: Readonly<Record<string, string>>, locales: Pick<ActiveLocales, "active">): Record<string, string>;
93
- //#endregion
94
19
  //#region src/translate/migrate-locales.d.ts
95
20
  /**
96
21
  * The data migration for a Postgres site going from one locale to several.
@@ -1 +1 @@
1
- {"version":3,"file":"translate.d.mts","names":[],"sources":["../src/translate/plugin.ts","../src/translate/languages.ts","../src/translate/migrate-locales.ts","../src/translate/jobs.ts","../src/translate/interface-text.ts","../src/translate/fields.ts","../src/translate/hooks.ts","../src/translate/document.ts","../src/translate/strings.ts","../src/translate/guards.ts","../src/translate/after-commit.ts","../src/translate/state.ts","../src/translate/endpoint.ts","../src/translate/messages.ts"],"mappings":";;;;;;AAsBA;;;;;;;;;iBAAgB,aAAA,CAAc,OAAA,EAAS,oBAAA,GAAuB,MAAA;;;;;;AAA9D;;;cCda,eAAA;EAAA;;;;;;KAKD,iBAAA,WAA4B,eAAA;AAAA,cAE3B,sBAAA,EAAwB,iBAAA;AAPrC;AAAA,cAUa,oBAAA;;;;;;;iBAcG,kBAAA,CACd,YAAA,EAAc,MAAA,mBACb,OAAA,CAAQ,MAAA;;UAyBM,aAAA;EA9CY;EAgD3B,aAAA;EAhDsC;EAkDtC,MAAA;EAhDW;EAkDX,QAAA;AAAA;;cAIW,uBAAA;AAAA,KAER,cAAA,GAAiB,IAAA,CAAK,OAAA;;;iBAWX,uBAAA,CAAwB,OAAA;;;;;;;;;AAvBxC;;;iBAoDgB,aAAA,CAAc,OAAA,EAAS,cAAA,EAAgB,OAAA;EAAW,KAAA;AAAA,IAAwB,OAAA,CAAQ,aAAA;;AA1ClG;;;;;AAA8C;;;;;AAa9C;;;iBAgGgB,sBAAA,CACd,QAAA,UACA,OAAA,EAAS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AA,EACL,KAAA,UACA,IAAA,QAAY,OAAA,QACZ,SAAA,IAAa,OAAA,EAAS,OAAA,qBACrB,OAAA;;;UCpDc,kBAAA;EXWa;;;;;EWL5B,UAAA,GAAa,UAAA;;EAEb,IAAA,GAAO,aAAA;EACP,SAAA,IAAa,OAAA,EAAS,OAAA;EACtB,YAAA;EACA,aAAA;;EAEA,WAAA,EAAa,MAAA;IAAiB,OAAA,IAAW,GAAA,EAAK,GAAA;EAAA;;EAE9C,OAAA,EAAS,MAAA;IAAiB,OAAA,IAAW,GAAA,EAAK,GAAA;EAAA;AAAA;;AVX5C;;;;;iBUyBgB,kBAAA,CACd,MAAA,EAAQ,MAAA,GAAS,eAAA,GAAkB,OAAA,aAClC,QAAA,CAAS,kBAAA;;;;;AVVZ;;iBUoBgB,cAAA,WAAyB,MAAA,GAAS,eAAA,CAAA,CAAiB,MAAA,EAAQ,CAAA,EAAG,UAAA,EAAY,UAAA,GAAa,CAAA;;;;cC5C1F,aAAA;;;;KCJD,YAAA,sCAAkD,YAAA;EAAA,CAAoB,GAAA,WAAc,YAAA;AAAA;AAAA,UAgE/E,kBAAA;Eb9CsB;EagDrC,QAAA,EAAU,YAAA;EbhDkD;EakD5D,UAAA;EblDkE;;;;ACdpE;;EYuEE,QAAA;AAAA;;;;;;;AZlEF;iBY4EsB,YAAA,CAAa,OAAA;EACjC,MAAA,EAAQ,YAAA;EACR,MAAA,GAAS,YAAA;EACT,UAAA,EAAY,UAAA;EACZ,IAAA;EACA,EAAA;EACA,KAAA;EACA,OAAA;EACA,IAAA,GAAO,aAAA;EACP,UAAA,IAAc,IAAA,UAAc,KAAA;AAAA,IAC1B,OAAA,CAAQ,kBAAA"}
1
+ {"version":3,"file":"translate.d.mts","names":[],"sources":["../src/translate/plugin.ts","../src/translate/migrate-locales.ts","../src/translate/jobs.ts","../src/translate/interface-text.ts","../src/translate/fields.ts","../src/translate/hooks.ts","../src/translate/document.ts","../src/translate/strings.ts","../src/translate/guards.ts","../src/translate/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AO,aAAA;EACP,SAAA,IAAa,OAAA,EAAS,OAAA;EACtB,YAAA;EACA,aAAA;ETW8B;EST9B,WAAA,EAAa,MAAA;IAAiB,OAAA,IAAW,GAAA,EAAK,GAAA;EAAA;ETShB;ESP9B,OAAA,EAAS,MAAA;IAAiB,OAAA,IAAW,GAAA,EAAK,GAAA;EAAA;AAAA;;ATgB5C;;;;;iBSFgB,kBAAA,CACd,MAAA,EAAQ,MAAA,GAAS,eAAA,GAAkB,OAAA,aAClC,QAAA,CAAS,kBAAA;;;;;;;iBAUI,cAAA,WAAyB,MAAA,GAAS,eAAA,CAAA,CAAiB,MAAA,EAAQ,CAAA,EAAG,UAAA,EAAY,UAAA,GAAa,CAAA;;;;cC5C1F,aAAA;;;;KCJD,YAAA,sCAAkD,YAAA;EAAA,CAAoB,GAAA,WAAc,YAAA;AAAA;AAAA,UAgE/E,kBAAA;EZ9CmD;EYgDlE,QAAA,EAAU,YAAA;EZhDkB;EYkD5B,UAAA;EZlDkE;;;;;ACOpE;EWkDE,QAAA;AAAA;;;;;;;AX1CF;iBWoDsB,YAAA,CAAa,OAAA;EACjC,MAAA,EAAQ,YAAA;EACR,MAAA,GAAS,YAAA;EACT,UAAA,EAAY,UAAA;EACZ,IAAA;EACA,EAAA;EACA,KAAA;EACA,OAAA;EACA,IAAA,GAAO,aAAA;EACP,UAAA,IAAc,IAAA,UAAc,KAAA;AAAA,IAC1B,OAAA,CAAQ,kBAAA"}
@@ -1,6 +1,7 @@
1
- import { $ as LIBRARY_DEFAULT_LOCALE, A as TRANSLATE_NOW, B as TRANSLATION_STATUS_BAR, C as isAutosave, D as shouldSkipUndraftedTranslation, E as shouldSkipDraftedTranslation, F as TRANSLATION_ACTIVITY_PANEL, G as FAILURE_ADVICE, H as readTranslationSettings, I as TRANSLATION_GRANT, J as monthKey, K as RATE_LIMIT_STREAK, L as TRANSLATION_KEY_PANEL, M as BISON_TRANSLATION_CONTEXT, N as readTranslateState, O as TRANSACTION_TIMEOUT_MS, P as withTranslator, Q as ACTIVE_LOCALES_CACHE_MS, R as TRANSLATION_SETTINGS_SLUG, S as startJob, T as localizedCopyUnchanged, U as resolveModel, V as invalidateTranslationSettings, W as siteFromInstructions, X as usageHistory, Y as recordUsage, Z as usageThisMonth, _ as frozenWordForce, a as MESSAGES_CACHE_MS, at as invalidateActiveLocales, b as runJobSlice, c as importMessages, ct as encryptApiKey, d as unflattenMessages, dt as sameRow, et as LIBRARY_LOCALES, f as translationSettingsEndpoints, ft as translationJob, g as estimateJob, h as claimJob, i as INTERFACE_TEXT_SLUG, it as inactiveLocaleRedirect, j as translateDocument, k as runAfterCommit, l as interfaceTextGlobal, lt as resolveApiKey, m as TRANSLATION_JOBS_SLUG, n as hasLocalizedFields, nt as activeAlternates, o as flattenMessages, ot as withLibraryLocales, p as LEASE_MS, q as TRANSLATION_USAGE_SLUG, r as translation, rt as activeLocales, s as getMessages, st as decryptApiKey, t as applyTranslation, tt as LIBRARY_LOCALE_CODES, u as invalidateMessages, ut as collectLocalizedStrings, v as jobView, w as draftedTranslationDecision, x as startBackfill, y as resumeStaleJobs, z as TRANSLATION_STATE_SLUG } from "./capability-Kd5LgQpm.mjs";
2
- import { a as TRANSLATE_MODEL_PRICES, c as estimateCost, d as translationSystemPrompt, f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, l as modelPrice, n as translateStrings, o as anthropicTranslator, p as classifyAnthropicError, r as DEFAULT_TRANSLATE_MODEL, s as containsWord, t as isTranslatorConfigured, u as parseJsonArray } from "./strings-Fd7kUCT7.mjs";
3
- import { t as fillMessages } from "./messages-XFoL9RtF.mjs";
1
+ import { $ as encryptApiKey, A as TRANSLATE_NOW, B as TRANSLATION_STATUS_BAR, C as isAutosave, D as shouldSkipUndraftedTranslation, E as shouldSkipDraftedTranslation, F as TRANSLATION_ACTIVITY_PANEL, G as FAILURE_ADVICE, H as readTranslationSettings, I as TRANSLATION_GRANT, J as monthKey, K as RATE_LIMIT_STREAK, L as TRANSLATION_KEY_PANEL, M as BISON_TRANSLATION_CONTEXT, N as readTranslateState, O as TRANSACTION_TIMEOUT_MS, P as withTranslator, Q as decryptApiKey, R as TRANSLATION_SETTINGS_SLUG, S as startJob, T as localizedCopyUnchanged, U as resolveModel, V as invalidateTranslationSettings, W as siteFromInstructions, X as usageHistory, Y as recordUsage, Z as usageThisMonth, _ as frozenWordForce, a as MESSAGES_CACHE_MS, b as runJobSlice, c as importMessages, d as unflattenMessages, et as resolveApiKey, f as translationSettingsEndpoints, g as estimateJob, h as claimJob, i as INTERFACE_TEXT_SLUG, j as translateDocument, k as runAfterCommit, l as interfaceTextGlobal, m as TRANSLATION_JOBS_SLUG, n as hasLocalizedFields, nt as sameRow, o as flattenMessages, p as LEASE_MS, q as TRANSLATION_USAGE_SLUG, r as translation, rt as translationJob, s as getMessages, t as applyTranslation, tt as collectLocalizedStrings, u as invalidateMessages, v as jobView, w as draftedTranslationDecision, x as startBackfill, y as resumeStaleJobs, z as TRANSLATION_STATE_SLUG } from "./capability-B4FLx4OX.mjs";
2
+ import { a as LIBRARY_LOCALE_CODES, c as inactiveLocaleRedirect, i as LIBRARY_LOCALES, l as invalidateActiveLocales, o as activeAlternates, p as withLibraryLocales, r as LIBRARY_DEFAULT_LOCALE, s as activeLocales, t as ACTIVE_LOCALES_CACHE_MS } from "./languages-B_iiWwxE.mjs";
3
+ import { a as TRANSLATE_MODEL_PRICES, c as estimateCost, d as translationSystemPrompt, f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, l as modelPrice, n as translateStrings, o as anthropicTranslator, p as classifyAnthropicError, r as DEFAULT_TRANSLATE_MODEL, s as containsWord, t as isTranslatorConfigured, u as parseJsonArray } from "./strings-_9n8BefX.mjs";
4
+ import { t as fillMessages } from "./messages-Bv6JIEiG.mjs";
4
5
  //#region src/translate/plugin.ts
5
6
  function hints(list) {
6
7
  return (list ?? []).map((entry) => typeof entry === "string" ? [entry, {}] : [entry.slug, entry.context ? { context: entry.context } : {}]);
@@ -1 +1 @@
1
- {"version":3,"file":"translate.mjs","names":[],"sources":["../src/translate/plugin.ts","../src/translate/migrate-locales.ts"],"sourcesContent":["import type { Config, Plugin } from \"payload\";\n\nimport { applyTranslation, type TranslationEntityHint } from \"./capability\";\nimport type { AutoTranslateOptions, TranslatedEntity } from \"./types\";\n\nfunction hints(list: TranslatedEntity[] | undefined): Array<[string, TranslationEntityHint]> {\n return (list ?? []).map((entry) =>\n typeof entry === \"string\" ? [entry, {}] : [entry.slug, entry.context ? { context: entry.context } : {}],\n );\n}\n\n/**\n * @deprecated Every site now has translation through `adminNav()` (or\n * `translation()`), switched on by an Admin in Settings → Translation, and\n * it covers every collection and global with localized fields. This keeps\n * an existing `autoTranslate({ ... })` line working: `enabled: false`\n * returns the config untouched; `enabled: true` applies the capability with\n * its `site` (the instructions' first values), `waitUntil`, the listed\n * entities' `context` hints, and `translator`, which then replaces the\n * screen's key and model (tests). The listed slugs must exist. The screen's\n * switch governs it either way.\n */\nexport function autoTranslate(options: AutoTranslateOptions): Plugin {\n return (config: Config): Config => {\n if (!options.enabled) return config;\n for (const [slug] of hints(options.collections)) {\n if (!config.collections?.some((collection) => collection.slug === slug)) {\n throw new Error(`autoTranslate: no collection \"${slug}\" in the config`);\n }\n }\n for (const [slug] of hints(options.globals)) {\n if (!config.globals?.some((global) => global.slug === slug)) {\n throw new Error(`autoTranslate: no global \"${slug}\" in the config`);\n }\n }\n return applyTranslation(config, {\n translator: options.translator,\n ...(options.site ? { site: options.site } : {}),\n ...(options.waitUntil ? { waitUntil: options.waitUntil } : {}),\n hints: Object.fromEntries([...hints(options.collections), ...hints(options.globals)]),\n });\n };\n}\n","/**\n * The data migration for a Postgres site going from one locale to several.\n *\n * Turning localization on moves every localized column out of its table\n * into a `<table>_locales` table (one row per locale). `payload\n * migrate:create` writes that as SQL that creates the new tables and then\n * drops the old columns, which throws the copy away. This runs the same\n * SQL with one step in between: after everything else and before any column\n * or type is dropped, each column that moves is copied into its locale\n * table as the default locale's row. Nothing else changes, so the result is\n * exactly the schema Payload generated, holding the content it held before.\n *\n * In the generated migration, replace the body of `up`:\n *\n * ```ts\n * import { localizeExistingContent } from \"@bison-lab/payload-core/translate\";\n *\n * export async function up({ db, payload }: MigrateUpArgs): Promise<void> {\n * await localizeExistingContent({ db, payload, sql, statements: `\n * ...the SQL migrate:create wrote inside sql`...`, unchanged...\n * ` });\n * }\n * ```\n *\n * Postgres only. The migration has no `down`: going back to one locale\n * would drop every other locale's copy.\n */\n\n/** The slice of Payload's `db` (Drizzle) this uses. */\nexport interface MigrationDb {\n // Method syntax on purpose: its parameter is checked bivariantly, so\n // Payload's `PostgresDB` (whose `execute` takes `SQLWrapper | string`)\n // is accepted as it is, with no cast in the site's migration.\n execute(query: never): Promise<unknown>;\n}\n\n/** `sql` from `@payloadcms/db-postgres`, for `sql.raw`. */\nexport interface MigrationSql {\n raw: (text: string) => unknown;\n}\n\n/** The slice of the site's Payload config the relationship step reads (`payload` from the migration's `up`). */\nexport interface MigrationPayload {\n /** The adapter's table-name suffixes, when a site changed them (`postgresAdapter({ localesSuffix })`). */\n db?: { localesSuffix?: string; relationshipsSuffix?: string; versionsSuffix?: string };\n config: {\n collections?: ReadonlyArray<{ slug: string; dbName?: unknown; fields: readonly unknown[] }>;\n globals?: ReadonlyArray<{ slug: string; dbName?: unknown; fields: readonly unknown[] }>;\n /** Config-level blocks, for blocks fields that use `blockReferences`. */\n blocks?: ReadonlyArray<{ slug: string; fields: readonly unknown[] }>;\n };\n}\n\nexport interface LocalizeExistingContentOptions {\n db: MigrationDb;\n sql: MigrationSql;\n /**\n * The migration's `payload`. Needed when a localized relationship, upload\n * or hasMany text/number field already holds rows: Payload keeps those in\n * shared `_rels` / `_texts` / `_numbers` tables with a `locale` column it\n * adds now, and only the config says which rows belong to a localized\n * field. Without it, such rows make the migration stop with an error\n * rather than lose them.\n */\n payload?: MigrationPayload;\n /** The SQL `migrate:create` generated for this change, as text. */\n statements: string;\n /** The locale existing content is in. Defaults to `en`. */\n locale?: string;\n /** The Postgres schema Payload's tables are in. Defaults to `public`. */\n schema?: string;\n /** Progress lines; defaults to `console.log`. */\n log?: (line: string) => void;\n}\n\nexport interface LocalizedTableCopy {\n table: string;\n into: string;\n columns: string[];\n rows: number;\n}\n\n/**\n * Splits generated SQL into statements at a `;` that ends a line, keeping a\n * `DO $$ ... $$;` block whole.\n */\nexport function splitStatements(text: string): string[] {\n const out: string[] = [];\n let current: string[] = [];\n let inDollar = false;\n for (const line of text.split(\"\\n\")) {\n if (line.trim() === \"\" && current.length === 0) continue;\n current.push(line);\n const dollars = line.match(/\\$\\$/g)?.length ?? 0;\n if (dollars % 2 === 1) inDollar = !inDollar;\n if (!inDollar && /;\\s*$/.test(line)) {\n out.push(current.join(\"\\n\").trim());\n current = [];\n }\n }\n const rest = current.join(\"\\n\").trim();\n if (rest) out.push(rest);\n return out;\n}\n\nconst DROP_COLUMN = /^ALTER TABLE\\s+(?:\"[^\"]+\"\\.)?\"([^\"]+)\"\\s+DROP COLUMN\\s+(?:IF EXISTS\\s+)?\"([^\"]+)\"/i;\nconst DROP_TYPE = /^DROP TYPE\\b/i;\n/** The bare name of a type in `DROP TYPE` / `CREATE TYPE` (`\"public\".\"enum_x\"` → `enum_x`). */\nconst TYPE_NAME = /^(?:DROP|CREATE) TYPE\\s+(?:IF EXISTS\\s+)?(?:\"[^\"]+\"\\.)?\"?([^\"\\s(]+)\"?/i;\nconst ADD_LOCALE = /^ALTER TABLE\\s+(?:\"[^\"]+\"\\.)?\"([^\"]+)\"\\s+ADD COLUMN\\s+\"locale\"\\s/i;\n/**\n * A NOT NULL locale column added to a table that already has rows: `_locale`\n * on a localized array or blocks table, or `locale` on a localized hasMany\n * select's own table. Either would fail on the first existing row.\n */\nconst ADD_LOCALE_NOT_NULL =\n /^(ALTER TABLE\\s+((?:\"[^\"]+\"\\.)?\"[^\"]+\")\\s+ADD COLUMN\\s+\"(_?locale)\"\\s+(\\S+)\\s+NOT NULL)(\\s*;)$/i;\n\nexport interface PartitionedStatements {\n /** Everything that does not drop: creates, adds, indexes, constraints. */\n first: string[];\n /** Tables that gain a nullable `locale` column (shared relationship / hasMany tables). */\n localeColumns: string[];\n /** The columns dropped, by table. */\n drops: Map<string, string[]>;\n /** The drops themselves, run last. */\n last: string[];\n}\n\n/**\n * Sorts statements into what runs before the copy and the drops that run\n * after it. A `_locale NOT NULL` column added to an existing table (a\n * localized array or blocks field) gets the default locale as a default\n * while it is added, so existing rows are kept as that locale's.\n */\nexport function partitionStatements(statements: readonly string[], locale = \"en\"): PartitionedStatements {\n const first: string[] = [];\n const last: string[] = [];\n const localeColumns: string[] = [];\n const drops = new Map<string, string[]>();\n // drizzle-kit drops and re-creates a type under the same name when an\n // enum loses a value; that drop must stay where it is, before its CREATE.\n const recreated = new Set(\n statements\n .filter((statement) => /^CREATE TYPE\\b/i.test(statement))\n .map((statement) => statement.match(TYPE_NAME)?.[1])\n .filter((name): name is string => Boolean(name)),\n );\n for (const statement of statements) {\n const addLocaleColumn = statement.match(ADD_LOCALE);\n if (addLocaleColumn) localeColumns.push(addLocaleColumn[1]!);\n const drop = statement.match(DROP_COLUMN);\n if (drop) {\n const [, table, column] = drop as unknown as [string, string, string];\n drops.set(table, [...(drops.get(table) ?? []), column]);\n last.push(statement);\n continue;\n }\n if (DROP_TYPE.test(statement)) {\n const name = statement.match(TYPE_NAME)?.[1];\n if (name && recreated.has(name)) first.push(statement);\n else last.push(statement);\n continue;\n }\n const addLocale = statement.match(ADD_LOCALE_NOT_NULL);\n if (addLocale && !/DEFAULT/i.test(statement)) {\n const [, head, table, columnName, type] = addLocale as unknown as [string, string, string, string, string];\n first.push(`${head} DEFAULT '${locale}'::text::${type};`);\n first.push(`ALTER TABLE ${table} ALTER COLUMN \"${columnName}\" DROP DEFAULT;`);\n continue;\n }\n first.push(statement);\n }\n return { first, localeColumns, drops, last };\n}\n\n// ---------------------------------------------------------------------------\n// Rows of localized relationships, uploads and hasMany fields\n\ninterface ConfigField {\n type?: string;\n name?: string;\n localized?: boolean;\n fields?: ConfigField[];\n tabs?: Array<{ name?: string; localized?: boolean; fields: ConfigField[] }>;\n blocks?: Array<{ slug: string; fields: ConfigField[] }>;\n blockReferences?: Array<string | { slug: string; fields: ConfigField[] }>;\n}\n\n/** Payload's default table name for a slug (`toSnakeCase`). */\nfunction snake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\n/** Named fields at this level, looking through rows, collapsibles, unnamed groups and unnamed tabs. */\nfunction named(fields: readonly ConfigField[]): ConfigField[] {\n return fields.flatMap((field) => {\n if (field.type === \"tabs\") {\n return (field.tabs ?? []).flatMap((tab) =>\n tab.name ? [{ type: \"group\", name: tab.name, localized: tab.localized, fields: tab.fields }] : named(tab.fields),\n );\n }\n if (!field.name && field.fields) return named(field.fields);\n return field.name ? [field] : [];\n });\n}\n\n/**\n * Whether the stored `path` of a relationship / hasMany row (`related`,\n * `layout.1.items.0.ref`) is a localized field, or sits inside one.\n * `undefined` when the path is not in the config. Throws when blocks\n * disagree (two block types with the same sub-path, one localized).\n */\nexport function isLocalizedPath(\n fields: readonly ConfigField[],\n segments: readonly string[],\n inherited = false,\n configBlocks: ReadonlyArray<{ slug: string; fields: readonly unknown[] }> = [],\n): boolean | undefined {\n const [head, ...rest] = segments;\n const field = named(fields).find((candidate) => candidate.name === head);\n if (!field) return undefined;\n const localized = inherited || field.localized === true;\n if (rest.length === 0) return localized;\n if (field.type === \"array\") return isLocalizedPath(field.fields ?? [], rest.slice(1), localized, configBlocks);\n if (field.type === \"blocks\") {\n // Inline blocks, plus blocks named by slug in `blockReferences` and declared once in `config.blocks`.\n const referenced = (field.blockReferences ?? []).flatMap((ref) =>\n typeof ref === \"string\" ? configBlocks.filter((block) => block.slug === ref) : [ref],\n ) as Array<{ slug: string; fields: ConfigField[] }>;\n const answers = [...(field.blocks ?? []), ...referenced]\n .map((block) => isLocalizedPath(block.fields, rest.slice(1), localized, configBlocks))\n .filter((answer): answer is boolean => answer !== undefined);\n if (answers.length === 0) return undefined;\n if (answers.some((answer) => answer !== answers[0])) {\n throw new Error(`localizeExistingContent: \"${segments.join(\".\")}\" is localized in one block type and not another`);\n }\n return answers[0];\n }\n return isLocalizedPath(field.fields ?? [], rest, localized, configBlocks);\n}\n\n/** The adapter's table suffixes: Payload's defaults unless the site set its own. */\nfunction suffixes(payload: MigrationPayload | undefined) {\n return {\n locales: payload?.db?.localesSuffix ?? \"_locales\",\n rels: payload?.db?.relationshipsSuffix ?? \"_rels\",\n versions: payload?.db?.versionsSuffix ?? \"_v\",\n };\n}\n\nconst escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** A shared relationship / hasMany table: `<base><relationshipsSuffix>`, `<base>_texts`, `<base>_numbers`. */\nfunction sharedSuffix(payload: MigrationPayload | undefined): RegExp {\n return new RegExp(`(${escapeRegExp(suffixes(payload).rels)}|_texts|_numbers)$`);\n}\n\nfunction entityFor(payload: MigrationPayload, table: string): { fields: readonly ConfigField[]; version: boolean } | null {\n const { versions } = suffixes(payload);\n const base = table.replace(sharedSuffix(payload), \"\");\n const version = base.startsWith(\"_\") && base.endsWith(versions);\n const name = version ? base.slice(1, -versions.length) : base;\n const entities = [...(payload.config.collections ?? []), ...(payload.config.globals ?? [])];\n const entity = entities.find((candidate) =>\n (typeof candidate.dbName === \"string\" ? candidate.dbName : snake(candidate.slug)) === name,\n );\n return entity ? { fields: entity.fields as readonly ConfigField[], version } : null;\n}\n\nconst quote = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst literal = (value: string) => `'${value.replace(/'/g, \"''\")}'`;\n\nfunction rowsOf(result: unknown): Array<Record<string, unknown>> {\n if (Array.isArray(result)) return result as Array<Record<string, unknown>>;\n const rows = (result as { rows?: unknown } | null)?.rows;\n return Array.isArray(rows) ? (rows as Array<Record<string, unknown>>) : [];\n}\n\ninterface ColumnInfo {\n column_name: string;\n data_type: string;\n udt_schema: string;\n udt_name: string;\n}\n\n/**\n * Runs a localization migration without losing content: see the module\n * comment. Returns what it copied. Throws (and Payload rolls the migration\n * back) on any SQL error.\n */\nexport async function localizeExistingContent(options: LocalizeExistingContentOptions): Promise<LocalizedTableCopy[]> {\n const { db, sql } = options;\n const locale = options.locale ?? \"en\";\n const schema = options.schema ?? \"public\";\n const log = options.log ?? ((line: string) => console.log(line));\n const run = (text: string) => db.execute(sql.raw(text) as never);\n\n const { first, localeColumns, drops, last } = partitionStatements(splitStatements(options.statements), locale);\n for (const statement of first) await run(statement);\n\n // Relationship, upload and hasMany rows: the new `locale` column is the\n // default locale on rows of a localized field, and stays empty on the\n // rest (Payload reads a non-localized row only when it has no locale).\n for (const table of localeColumns) {\n const qualifiedTable = `${quote(schema)}.${quote(table)}`;\n const tableColumns = rowsOf(\n await run(\n `SELECT column_name, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(schema)} AND table_name = ${literal(table)} AND column_name IN ('locale', 'path')`,\n ),\n ) as unknown as ColumnInfo[];\n const localeInfo = tableColumns.find((info) => info.column_name === \"locale\");\n const value = localeInfo\n ? `${literal(locale)}::text::${quote(localeInfo.udt_schema)}.${quote(localeInfo.udt_name)}`\n : literal(locale);\n // Shared by structure, not by name: a relationship / hasMany table keeps\n // each row's field `path`; a hasMany select's own table (which may well be\n // called `pages_phone_numbers`) has none.\n const shared = tableColumns.some((info) => info.column_name === \"path\");\n if (!shared) {\n // A hasMany select keeps its own table, which gains `locale` only when the field is localized.\n const result = await run(`UPDATE ${qualifiedTable} SET \"locale\" = ${value} WHERE \"locale\" IS NULL`);\n log(`[localize] ${table}: locale set on ${(result as { rowCount?: number } | null)?.rowCount ?? \"?\"} rows`);\n continue;\n }\n const paths = rowsOf(await run(`SELECT DISTINCT \"path\" FROM ${qualifiedTable} WHERE \"locale\" IS NULL`)).map((row) =>\n String(row.path),\n );\n if (paths.length === 0) continue;\n if (!options.payload) {\n throw new Error(\n `localizeExistingContent: ${table} holds relationship or hasMany rows that may belong to localized fields. Pass the migration's payload ({ db, payload, sql, statements }) so they keep their content.`,\n );\n }\n const entity = entityFor(options.payload, table);\n if (!entity) {\n throw new Error(\n `localizeExistingContent: no collection or global stores its relationships in ${table}. If one does under a custom table name, give that collection or global a dbName matching ${table.replace(sharedSuffix(options.payload), \"\")}.`,\n );\n }\n const localized = paths.filter((path) => {\n const segments = path.split(\".\");\n const own = entity.version && segments[0] === \"version\" ? segments.slice(1) : segments;\n const answer = isLocalizedPath(entity.fields, own, false, options.payload!.config.blocks ?? []);\n // A row the config cannot place may be exactly the content this exists\n // to keep: stop rather than guess.\n if (answer === undefined) {\n throw new Error(`localizeExistingContent: ${table} has rows at \"${path}\", which is not a field in the config passed`);\n }\n return answer;\n });\n if (localized.length === 0) continue;\n const result = await run(\n `UPDATE ${qualifiedTable} SET \"locale\" = ${value} WHERE \"locale\" IS NULL AND \"path\" IN (${localized.map(literal).join(\", \")})`,\n );\n log(`[localize] ${table}: locale set on ${(result as { rowCount?: number } | null)?.rowCount ?? \"?\"} rows (${localized.join(\", \")})`);\n }\n\n const columnsOf = async (table: string): Promise<ColumnInfo[]> =>\n rowsOf(\n await run(\n `SELECT column_name, data_type, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(\n schema,\n )} AND table_name = ${literal(table)}`,\n ),\n ) as unknown as ColumnInfo[];\n\n const copies: LocalizedTableCopy[] = [];\n for (const [table, dropped] of drops) {\n const into = `${table}${suffixes(options.payload).locales}`;\n const target = await columnsOf(into);\n if (target.length === 0) {\n log(`[localize] ${table}: ${dropped.join(\", \")} dropped with no locale table to keep them; not copied`);\n continue;\n }\n const byName = new Map(target.map((column) => [column.column_name, column]));\n const moving = dropped.filter((column) => byName.has(column));\n const lost = dropped.filter((column) => !byName.has(column));\n if (lost.length) log(`[localize] ${table}: ${lost.join(\", \")} dropped, not localized; not copied`);\n if (moving.length === 0) continue;\n const cast = (column: string) => {\n const info = byName.get(column)!;\n return info.data_type === \"USER-DEFINED\"\n ? `${quote(column)}::text::${quote(info.udt_schema)}.${quote(info.udt_name)}`\n : quote(column);\n };\n const localeColumn = byName.get(\"_locale\");\n if (!localeColumn || !byName.has(\"_parent_id\")) {\n throw new Error(`localizeExistingContent: ${into} has no _locale / _parent_id column`);\n }\n const localeValue = `${literal(locale)}::text::${quote(localeColumn.udt_schema)}.${quote(localeColumn.udt_name)}`;\n const qualified = (name: string) => `${quote(schema)}.${quote(name)}`;\n const statement = `INSERT INTO ${qualified(into)} (${[...moving.map(quote), '\"_locale\"', '\"_parent_id\"'].join(\", \")})\nSELECT ${[...moving.map((column) => `p.${cast(column)}`), localeValue, 'p.\"id\"'].join(\", \")}\nFROM ${qualified(table)} p\nWHERE NOT EXISTS (SELECT 1 FROM ${qualified(into)} l WHERE l.\"_parent_id\" = p.\"id\" AND l.\"_locale\"::text = ${literal(\n locale,\n )})`;\n // A locale row that already exists (a site that had localization makes\n // another field localized) gets the moved values; any other parent gets\n // a new English row.\n const updated = await run(`UPDATE ${qualified(into)} l SET ${moving\n .map((column) => `${quote(column)} = p.${cast(column)}`)\n .join(\", \")}\nFROM ${qualified(table)} p\nWHERE l.\"_parent_id\" = p.\"id\" AND l.\"_locale\"::text = ${literal(locale)}`);\n const result = await run(statement);\n const rows =\n ((result as { rowCount?: number } | null)?.rowCount ?? 0) + ((updated as { rowCount?: number } | null)?.rowCount ?? 0);\n copies.push({ table, into, columns: moving, rows });\n log(`[localize] ${table} -> ${into}: ${moving.join(\", \")} (${rows} rows)`);\n }\n\n for (const statement of last) await run(statement);\n return copies;\n}\n"],"mappings":";;;;AAKA,SAAS,MAAM,MAA8E;AAC3F,SAAQ,QAAQ,EAAE,EAAE,KAAK,UACvB,OAAO,UAAU,WAAW,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,MAAM,MAAM,MAAM,UAAU,EAAE,SAAS,MAAM,SAAS,GAAG,EAAE,CAAC,CACxG;;;;;;;;;;;;;AAcH,SAAgB,cAAc,SAA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0C,YAAY;AACtH,SAAO,KAAK;GAAE;GAAO;GAAM,SAAS;GAAQ;GAAM,CAAC;AACnD,MAAI,cAAc,MAAM,MAAM,KAAK,IAAI,OAAO,KAAK,KAAK,CAAC,IAAI,KAAK,QAAQ;;AAG5E,MAAK,MAAM,aAAa,KAAM,OAAM,IAAI,UAAU;AAClD,QAAO"}
1
+ {"version":3,"file":"translate.mjs","names":[],"sources":["../src/translate/plugin.ts","../src/translate/migrate-locales.ts"],"sourcesContent":["import type { Config, Plugin } from \"payload\";\n\nimport { applyTranslation, type TranslationEntityHint } from \"./capability\";\nimport type { AutoTranslateOptions, TranslatedEntity } from \"./types\";\n\nfunction hints(list: TranslatedEntity[] | undefined): Array<[string, TranslationEntityHint]> {\n return (list ?? []).map((entry) =>\n typeof entry === \"string\" ? [entry, {}] : [entry.slug, entry.context ? { context: entry.context } : {}],\n );\n}\n\n/**\n * @deprecated Every site now has translation through `adminNav()` (or\n * `translation()`), switched on by an Admin in Settings → Translation, and\n * it covers every collection and global with localized fields. This keeps\n * an existing `autoTranslate({ ... })` line working: `enabled: false`\n * returns the config untouched; `enabled: true` applies the capability with\n * its `site` (the instructions' first values), `waitUntil`, the listed\n * entities' `context` hints, and `translator`, which then replaces the\n * screen's key and model (tests). The listed slugs must exist. The screen's\n * switch governs it either way.\n */\nexport function autoTranslate(options: AutoTranslateOptions): Plugin {\n return (config: Config): Config => {\n if (!options.enabled) return config;\n for (const [slug] of hints(options.collections)) {\n if (!config.collections?.some((collection) => collection.slug === slug)) {\n throw new Error(`autoTranslate: no collection \"${slug}\" in the config`);\n }\n }\n for (const [slug] of hints(options.globals)) {\n if (!config.globals?.some((global) => global.slug === slug)) {\n throw new Error(`autoTranslate: no global \"${slug}\" in the config`);\n }\n }\n return applyTranslation(config, {\n translator: options.translator,\n ...(options.site ? { site: options.site } : {}),\n ...(options.waitUntil ? { waitUntil: options.waitUntil } : {}),\n hints: Object.fromEntries([...hints(options.collections), ...hints(options.globals)]),\n });\n };\n}\n","/**\n * The data migration for a Postgres site going from one locale to several.\n *\n * Turning localization on moves every localized column out of its table\n * into a `<table>_locales` table (one row per locale). `payload\n * migrate:create` writes that as SQL that creates the new tables and then\n * drops the old columns, which throws the copy away. This runs the same\n * SQL with one step in between: after everything else and before any column\n * or type is dropped, each column that moves is copied into its locale\n * table as the default locale's row. Nothing else changes, so the result is\n * exactly the schema Payload generated, holding the content it held before.\n *\n * In the generated migration, replace the body of `up`:\n *\n * ```ts\n * import { localizeExistingContent } from \"@bison-lab/payload-core/translate\";\n *\n * export async function up({ db, payload }: MigrateUpArgs): Promise<void> {\n * await localizeExistingContent({ db, payload, sql, statements: `\n * ...the SQL migrate:create wrote inside sql`...`, unchanged...\n * ` });\n * }\n * ```\n *\n * Postgres only. The migration has no `down`: going back to one locale\n * would drop every other locale's copy.\n */\n\n/** The slice of Payload's `db` (Drizzle) this uses. */\nexport interface MigrationDb {\n // Method syntax on purpose: its parameter is checked bivariantly, so\n // Payload's `PostgresDB` (whose `execute` takes `SQLWrapper | string`)\n // is accepted as it is, with no cast in the site's migration.\n execute(query: never): Promise<unknown>;\n}\n\n/** `sql` from `@payloadcms/db-postgres`, for `sql.raw`. */\nexport interface MigrationSql {\n raw: (text: string) => unknown;\n}\n\n/** The slice of the site's Payload config the relationship step reads (`payload` from the migration's `up`). */\nexport interface MigrationPayload {\n /** The adapter's table-name suffixes, when a site changed them (`postgresAdapter({ localesSuffix })`). */\n db?: { localesSuffix?: string; relationshipsSuffix?: string; versionsSuffix?: string };\n config: {\n collections?: ReadonlyArray<{ slug: string; dbName?: unknown; fields: readonly unknown[] }>;\n globals?: ReadonlyArray<{ slug: string; dbName?: unknown; fields: readonly unknown[] }>;\n /** Config-level blocks, for blocks fields that use `blockReferences`. */\n blocks?: ReadonlyArray<{ slug: string; fields: readonly unknown[] }>;\n };\n}\n\nexport interface LocalizeExistingContentOptions {\n db: MigrationDb;\n sql: MigrationSql;\n /**\n * The migration's `payload`. Needed when a localized relationship, upload\n * or hasMany text/number field already holds rows: Payload keeps those in\n * shared `_rels` / `_texts` / `_numbers` tables with a `locale` column it\n * adds now, and only the config says which rows belong to a localized\n * field. Without it, such rows make the migration stop with an error\n * rather than lose them.\n */\n payload?: MigrationPayload;\n /** The SQL `migrate:create` generated for this change, as text. */\n statements: string;\n /** The locale existing content is in. Defaults to `en`. */\n locale?: string;\n /** The Postgres schema Payload's tables are in. Defaults to `public`. */\n schema?: string;\n /** Progress lines; defaults to `console.log`. */\n log?: (line: string) => void;\n}\n\nexport interface LocalizedTableCopy {\n table: string;\n into: string;\n columns: string[];\n rows: number;\n}\n\n/**\n * Splits generated SQL into statements at a `;` that ends a line, keeping a\n * `DO $$ ... $$;` block whole.\n */\nexport function splitStatements(text: string): string[] {\n const out: string[] = [];\n let current: string[] = [];\n let inDollar = false;\n for (const line of text.split(\"\\n\")) {\n if (line.trim() === \"\" && current.length === 0) continue;\n current.push(line);\n const dollars = line.match(/\\$\\$/g)?.length ?? 0;\n if (dollars % 2 === 1) inDollar = !inDollar;\n if (!inDollar && /;\\s*$/.test(line)) {\n out.push(current.join(\"\\n\").trim());\n current = [];\n }\n }\n const rest = current.join(\"\\n\").trim();\n if (rest) out.push(rest);\n return out;\n}\n\nconst DROP_COLUMN = /^ALTER TABLE\\s+(?:\"[^\"]+\"\\.)?\"([^\"]+)\"\\s+DROP COLUMN\\s+(?:IF EXISTS\\s+)?\"([^\"]+)\"/i;\nconst DROP_TYPE = /^DROP TYPE\\b/i;\n/** The bare name of a type in `DROP TYPE` / `CREATE TYPE` (`\"public\".\"enum_x\"` → `enum_x`). */\nconst TYPE_NAME = /^(?:DROP|CREATE) TYPE\\s+(?:IF EXISTS\\s+)?(?:\"[^\"]+\"\\.)?\"?([^\"\\s(]+)\"?/i;\nconst ADD_LOCALE = /^ALTER TABLE\\s+(?:\"[^\"]+\"\\.)?\"([^\"]+)\"\\s+ADD COLUMN\\s+\"locale\"\\s/i;\n/**\n * A NOT NULL locale column added to a table that already has rows: `_locale`\n * on a localized array or blocks table, or `locale` on a localized hasMany\n * select's own table. Either would fail on the first existing row.\n */\nconst ADD_LOCALE_NOT_NULL =\n /^(ALTER TABLE\\s+((?:\"[^\"]+\"\\.)?\"[^\"]+\")\\s+ADD COLUMN\\s+\"(_?locale)\"\\s+(\\S+)\\s+NOT NULL)(\\s*;)$/i;\n\nexport interface PartitionedStatements {\n /** Everything that does not drop: creates, adds, indexes, constraints. */\n first: string[];\n /** Tables that gain a nullable `locale` column (shared relationship / hasMany tables). */\n localeColumns: string[];\n /** The columns dropped, by table. */\n drops: Map<string, string[]>;\n /** The drops themselves, run last. */\n last: string[];\n}\n\n/**\n * Sorts statements into what runs before the copy and the drops that run\n * after it. A `_locale NOT NULL` column added to an existing table (a\n * localized array or blocks field) gets the default locale as a default\n * while it is added, so existing rows are kept as that locale's.\n */\nexport function partitionStatements(statements: readonly string[], locale = \"en\"): PartitionedStatements {\n const first: string[] = [];\n const last: string[] = [];\n const localeColumns: string[] = [];\n const drops = new Map<string, string[]>();\n // drizzle-kit drops and re-creates a type under the same name when an\n // enum loses a value; that drop must stay where it is, before its CREATE.\n const recreated = new Set(\n statements\n .filter((statement) => /^CREATE TYPE\\b/i.test(statement))\n .map((statement) => statement.match(TYPE_NAME)?.[1])\n .filter((name): name is string => Boolean(name)),\n );\n for (const statement of statements) {\n const addLocaleColumn = statement.match(ADD_LOCALE);\n if (addLocaleColumn) localeColumns.push(addLocaleColumn[1]!);\n const drop = statement.match(DROP_COLUMN);\n if (drop) {\n const [, table, column] = drop as unknown as [string, string, string];\n drops.set(table, [...(drops.get(table) ?? []), column]);\n last.push(statement);\n continue;\n }\n if (DROP_TYPE.test(statement)) {\n const name = statement.match(TYPE_NAME)?.[1];\n if (name && recreated.has(name)) first.push(statement);\n else last.push(statement);\n continue;\n }\n const addLocale = statement.match(ADD_LOCALE_NOT_NULL);\n if (addLocale && !/DEFAULT/i.test(statement)) {\n const [, head, table, columnName, type] = addLocale as unknown as [string, string, string, string, string];\n first.push(`${head} DEFAULT '${locale}'::text::${type};`);\n first.push(`ALTER TABLE ${table} ALTER COLUMN \"${columnName}\" DROP DEFAULT;`);\n continue;\n }\n first.push(statement);\n }\n return { first, localeColumns, drops, last };\n}\n\n// ---------------------------------------------------------------------------\n// Rows of localized relationships, uploads and hasMany fields\n\ninterface ConfigField {\n type?: string;\n name?: string;\n localized?: boolean;\n fields?: ConfigField[];\n tabs?: Array<{ name?: string; localized?: boolean; fields: ConfigField[] }>;\n blocks?: Array<{ slug: string; fields: ConfigField[] }>;\n blockReferences?: Array<string | { slug: string; fields: ConfigField[] }>;\n}\n\n/** Payload's default table name for a slug (`toSnakeCase`). */\nfunction snake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\n/** Named fields at this level, looking through rows, collapsibles, unnamed groups and unnamed tabs. */\nfunction named(fields: readonly ConfigField[]): ConfigField[] {\n return fields.flatMap((field) => {\n if (field.type === \"tabs\") {\n return (field.tabs ?? []).flatMap((tab) =>\n tab.name ? [{ type: \"group\", name: tab.name, localized: tab.localized, fields: tab.fields }] : named(tab.fields),\n );\n }\n if (!field.name && field.fields) return named(field.fields);\n return field.name ? [field] : [];\n });\n}\n\n/**\n * Whether the stored `path` of a relationship / hasMany row (`related`,\n * `layout.1.items.0.ref`) is a localized field, or sits inside one.\n * `undefined` when the path is not in the config. Throws when blocks\n * disagree (two block types with the same sub-path, one localized).\n */\nexport function isLocalizedPath(\n fields: readonly ConfigField[],\n segments: readonly string[],\n inherited = false,\n configBlocks: ReadonlyArray<{ slug: string; fields: readonly unknown[] }> = [],\n): boolean | undefined {\n const [head, ...rest] = segments;\n const field = named(fields).find((candidate) => candidate.name === head);\n if (!field) return undefined;\n const localized = inherited || field.localized === true;\n if (rest.length === 0) return localized;\n if (field.type === \"array\") return isLocalizedPath(field.fields ?? [], rest.slice(1), localized, configBlocks);\n if (field.type === \"blocks\") {\n // Inline blocks, plus blocks named by slug in `blockReferences` and declared once in `config.blocks`.\n const referenced = (field.blockReferences ?? []).flatMap((ref) =>\n typeof ref === \"string\" ? configBlocks.filter((block) => block.slug === ref) : [ref],\n ) as Array<{ slug: string; fields: ConfigField[] }>;\n const answers = [...(field.blocks ?? []), ...referenced]\n .map((block) => isLocalizedPath(block.fields, rest.slice(1), localized, configBlocks))\n .filter((answer): answer is boolean => answer !== undefined);\n if (answers.length === 0) return undefined;\n if (answers.some((answer) => answer !== answers[0])) {\n throw new Error(`localizeExistingContent: \"${segments.join(\".\")}\" is localized in one block type and not another`);\n }\n return answers[0];\n }\n return isLocalizedPath(field.fields ?? [], rest, localized, configBlocks);\n}\n\n/** The adapter's table suffixes: Payload's defaults unless the site set its own. */\nfunction suffixes(payload: MigrationPayload | undefined) {\n return {\n locales: payload?.db?.localesSuffix ?? \"_locales\",\n rels: payload?.db?.relationshipsSuffix ?? \"_rels\",\n versions: payload?.db?.versionsSuffix ?? \"_v\",\n };\n}\n\nconst escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** A shared relationship / hasMany table: `<base><relationshipsSuffix>`, `<base>_texts`, `<base>_numbers`. */\nfunction sharedSuffix(payload: MigrationPayload | undefined): RegExp {\n return new RegExp(`(${escapeRegExp(suffixes(payload).rels)}|_texts|_numbers)$`);\n}\n\nfunction entityFor(payload: MigrationPayload, table: string): { fields: readonly ConfigField[]; version: boolean } | null {\n const { versions } = suffixes(payload);\n const base = table.replace(sharedSuffix(payload), \"\");\n const version = base.startsWith(\"_\") && base.endsWith(versions);\n const name = version ? base.slice(1, -versions.length) : base;\n const entities = [...(payload.config.collections ?? []), ...(payload.config.globals ?? [])];\n const entity = entities.find((candidate) =>\n (typeof candidate.dbName === \"string\" ? candidate.dbName : snake(candidate.slug)) === name,\n );\n return entity ? { fields: entity.fields as readonly ConfigField[], version } : null;\n}\n\nconst quote = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst literal = (value: string) => `'${value.replace(/'/g, \"''\")}'`;\n\nfunction rowsOf(result: unknown): Array<Record<string, unknown>> {\n if (Array.isArray(result)) return result as Array<Record<string, unknown>>;\n const rows = (result as { rows?: unknown } | null)?.rows;\n return Array.isArray(rows) ? (rows as Array<Record<string, unknown>>) : [];\n}\n\ninterface ColumnInfo {\n column_name: string;\n data_type: string;\n udt_schema: string;\n udt_name: string;\n}\n\n/**\n * Runs a localization migration without losing content: see the module\n * comment. Returns what it copied. Throws (and Payload rolls the migration\n * back) on any SQL error.\n */\nexport async function localizeExistingContent(options: LocalizeExistingContentOptions): Promise<LocalizedTableCopy[]> {\n const { db, sql } = options;\n const locale = options.locale ?? \"en\";\n const schema = options.schema ?? \"public\";\n const log = options.log ?? ((line: string) => console.log(line));\n const run = (text: string) => db.execute(sql.raw(text) as never);\n\n const { first, localeColumns, drops, last } = partitionStatements(splitStatements(options.statements), locale);\n for (const statement of first) await run(statement);\n\n // Relationship, upload and hasMany rows: the new `locale` column is the\n // default locale on rows of a localized field, and stays empty on the\n // rest (Payload reads a non-localized row only when it has no locale).\n for (const table of localeColumns) {\n const qualifiedTable = `${quote(schema)}.${quote(table)}`;\n const tableColumns = rowsOf(\n await run(\n `SELECT column_name, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(schema)} AND table_name = ${literal(table)} AND column_name IN ('locale', 'path')`,\n ),\n ) as unknown as ColumnInfo[];\n const localeInfo = tableColumns.find((info) => info.column_name === \"locale\");\n const value = localeInfo\n ? `${literal(locale)}::text::${quote(localeInfo.udt_schema)}.${quote(localeInfo.udt_name)}`\n : literal(locale);\n // Shared by structure, not by name: a relationship / hasMany table keeps\n // each row's field `path`; a hasMany select's own table (which may well be\n // called `pages_phone_numbers`) has none.\n const shared = tableColumns.some((info) => info.column_name === \"path\");\n if (!shared) {\n // A hasMany select keeps its own table, which gains `locale` only when the field is localized.\n const result = await run(`UPDATE ${qualifiedTable} SET \"locale\" = ${value} WHERE \"locale\" IS NULL`);\n log(`[localize] ${table}: locale set on ${(result as { rowCount?: number } | null)?.rowCount ?? \"?\"} rows`);\n continue;\n }\n const paths = rowsOf(await run(`SELECT DISTINCT \"path\" FROM ${qualifiedTable} WHERE \"locale\" IS NULL`)).map((row) =>\n String(row.path),\n );\n if (paths.length === 0) continue;\n if (!options.payload) {\n throw new Error(\n `localizeExistingContent: ${table} holds relationship or hasMany rows that may belong to localized fields. Pass the migration's payload ({ db, payload, sql, statements }) so they keep their content.`,\n );\n }\n const entity = entityFor(options.payload, table);\n if (!entity) {\n throw new Error(\n `localizeExistingContent: no collection or global stores its relationships in ${table}. If one does under a custom table name, give that collection or global a dbName matching ${table.replace(sharedSuffix(options.payload), \"\")}.`,\n );\n }\n const localized = paths.filter((path) => {\n const segments = path.split(\".\");\n const own = entity.version && segments[0] === \"version\" ? segments.slice(1) : segments;\n const answer = isLocalizedPath(entity.fields, own, false, options.payload!.config.blocks ?? []);\n // A row the config cannot place may be exactly the content this exists\n // to keep: stop rather than guess.\n if (answer === undefined) {\n throw new Error(`localizeExistingContent: ${table} has rows at \"${path}\", which is not a field in the config passed`);\n }\n return answer;\n });\n if (localized.length === 0) continue;\n const result = await run(\n `UPDATE ${qualifiedTable} SET \"locale\" = ${value} WHERE \"locale\" IS NULL AND \"path\" IN (${localized.map(literal).join(\", \")})`,\n );\n log(`[localize] ${table}: locale set on ${(result as { rowCount?: number } | null)?.rowCount ?? \"?\"} rows (${localized.join(\", \")})`);\n }\n\n const columnsOf = async (table: string): Promise<ColumnInfo[]> =>\n rowsOf(\n await run(\n `SELECT column_name, data_type, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(\n schema,\n )} AND table_name = ${literal(table)}`,\n ),\n ) as unknown as ColumnInfo[];\n\n const copies: LocalizedTableCopy[] = [];\n for (const [table, dropped] of drops) {\n const into = `${table}${suffixes(options.payload).locales}`;\n const target = await columnsOf(into);\n if (target.length === 0) {\n log(`[localize] ${table}: ${dropped.join(\", \")} dropped with no locale table to keep them; not copied`);\n continue;\n }\n const byName = new Map(target.map((column) => [column.column_name, column]));\n const moving = dropped.filter((column) => byName.has(column));\n const lost = dropped.filter((column) => !byName.has(column));\n if (lost.length) log(`[localize] ${table}: ${lost.join(\", \")} dropped, not localized; not copied`);\n if (moving.length === 0) continue;\n const cast = (column: string) => {\n const info = byName.get(column)!;\n return info.data_type === \"USER-DEFINED\"\n ? `${quote(column)}::text::${quote(info.udt_schema)}.${quote(info.udt_name)}`\n : quote(column);\n };\n const localeColumn = byName.get(\"_locale\");\n if (!localeColumn || !byName.has(\"_parent_id\")) {\n throw new Error(`localizeExistingContent: ${into} has no _locale / _parent_id column`);\n }\n const localeValue = `${literal(locale)}::text::${quote(localeColumn.udt_schema)}.${quote(localeColumn.udt_name)}`;\n const qualified = (name: string) => `${quote(schema)}.${quote(name)}`;\n const statement = `INSERT INTO ${qualified(into)} (${[...moving.map(quote), '\"_locale\"', '\"_parent_id\"'].join(\", \")})\nSELECT ${[...moving.map((column) => `p.${cast(column)}`), localeValue, 'p.\"id\"'].join(\", \")}\nFROM ${qualified(table)} p\nWHERE NOT EXISTS (SELECT 1 FROM ${qualified(into)} l WHERE l.\"_parent_id\" = p.\"id\" AND l.\"_locale\"::text = ${literal(\n locale,\n )})`;\n // A locale row that already exists (a site that had localization makes\n // another field localized) gets the moved values; any other parent gets\n // a new English row.\n const updated = await run(`UPDATE ${qualified(into)} l SET ${moving\n .map((column) => `${quote(column)} = p.${cast(column)}`)\n .join(\", \")}\nFROM ${qualified(table)} p\nWHERE l.\"_parent_id\" = p.\"id\" AND l.\"_locale\"::text = ${literal(locale)}`);\n const result = await run(statement);\n const rows =\n ((result as { rowCount?: number } | null)?.rowCount ?? 0) + ((updated as { rowCount?: number } | null)?.rowCount ?? 0);\n copies.push({ table, into, columns: moving, rows });\n log(`[localize] ${table} -> ${into}: ${moving.join(\", \")} (${rows} rows)`);\n }\n\n for (const statement of last) await run(statement);\n return copies;\n}\n"],"mappings":";;;;;AAKA,SAAS,MAA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U,KAAK,CAAC,SAAS,OAC1D,KAAK,WAAW,GAAG,MAAM,OAAO,CAAC,OAAO,KAAK,OAAO,GAAG,CACvD,KAAK,KAAK,CAAC;OACX,UAAU,MAAM,CAAC;wDACgC,QAAQ,OAAO,GAAG;EAEtE,MAAM,SADS,MAAM,IAAI,UAAU,GAEU,YAAY,MAAO,SAA0C,YAAY;AACtH,SAAO,KAAK;GAAE;GAAO;GAAM,SAAS;GAAQ;GAAM,CAAC;AACnD,MAAI,cAAc,MAAM,MAAM,KAAK,IAAI,OAAO,KAAK,KAAK,CAAC,IAAI,KAAK,QAAQ;;AAG5E,MAAK,MAAM,aAAa,KAAM,OAAM,IAAI,UAAU;AAClD,QAAO"}
@@ -300,4 +300,4 @@ async function captureWireframes(page, previews, { selector = WIREFRAME_ROOT } =
300
300
  //#endregion
301
301
  export { captureWireframes as a, wireframeSvg as c, WIREFRAME_WIDTH as i, WIREFRAME_ROOT as n, extractWireframe as o, WIREFRAME_VIEWPORT as r, svgDataUri as s, WIREFRAME_HEIGHT as t };
302
302
 
303
- //# sourceMappingURL=wireframe-Ba65SOj8.mjs.map
303
+ //# sourceMappingURL=wireframe-DjPHSACa.mjs.map