@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":"island-97l5VY8l.mjs","names":[],"sources":["../src/theme/map.ts","../src/theme/types.ts","../src/theme/looks.ts","../src/block-library/island.ts"],"sourcesContent":["import {\n createColorScale,\n DESTRUCTIVE_SCALE_HEX,\n generateColorScale,\n isThemeHex,\n SHADE_STEPS,\n type ColorScale,\n type ColorScaleInclude,\n type ColorScaleState,\n type ShadeStep,\n type ThemeConfig,\n} from \"@bison-lab/tokens\";\n\nimport { SAME_AS_BODY } from \"./fields\";\nimport type { ThemeColorDoc, ThemeDoc } from \"./types\";\n\nfunction pick<T>(value: T | null | undefined, fallback: T): T {\n return value == null ? fallback : value;\n}\n\nfunction headingFromDoc(\n heading: string | null | undefined,\n seed: ThemeConfig[\"fontHeading\"],\n): string | null {\n if (heading === undefined) return seed;\n if (heading === null || heading === SAME_AS_BODY) return null;\n return heading;\n}\n\nfunction hexFromColor(value: ThemeColorDoc | string | null | undefined, fallback: string): string {\n if (typeof value === \"string\") return value || fallback;\n return pick(value?.hex, fallback);\n}\n\nexport function colorDocFromHex(hex: string, sourceStep: ShadeStep = 500): ThemeColorDoc {\n return colorDocFromState(createColorScale(hex, sourceStep));\n}\n\nexport function colorDocFromState(state: ColorScaleState): ThemeColorDoc {\n return {\n hex: state.hex,\n sourceStep: state.sourceStep,\n scale: state.scale,\n stale: state.stale,\n include: Array.isArray(state.include) ? \"custom\" : state.include,\n includedSteps: Array.isArray(state.include) ? [...state.include] : undefined,\n };\n}\n\nexport function stateFromColorDoc(\n doc: ThemeColorDoc | null | undefined,\n fallbackHex = \"#000000\",\n): ColorScaleState {\n const hex = isThemeHex(doc?.hex) ? doc.hex : fallbackHex;\n const sourceStep = (Number(doc?.sourceStep) || 500) as ShadeStep;\n const include = includeFromDoc(doc, sourceStep);\n const scale =\n doc?.scale && typeof doc.scale === \"object\" ? (doc.scale as ColorScale) : generateColorScale(hex, sourceStep);\n return { hex, sourceStep, scale, stale: Boolean(doc?.stale), include };\n}\n\nfunction includeFromDoc(doc: ThemeColorDoc | null | undefined, sourceStep: ShadeStep): ColorScaleInclude {\n if (doc?.include === \"source\") return \"source\";\n if (doc?.include === \"custom\" && Array.isArray(doc.includedSteps)) {\n const steps = doc.includedSteps.map(Number).filter((step): step is ShadeStep => SHADE_STEPS.includes(step as ShadeStep));\n if (!steps.includes(sourceStep)) steps.push(sourceStep);\n return steps;\n }\n return \"all\";\n}\n\n/**\n * Nested Theme document → flat `ThemeConfig`. Null or missing editor\n * fields take the seed; `darkSelector` and `fontWeights` always come from\n * the seed. Reads the BIS-87 groups and the pre-BIS-87 flat fields.\n */\nexport function themeConfigFromDoc(doc: ThemeDoc | null | undefined, seed: ThemeConfig): ThemeConfig {\n const brand = doc?.colors?.brand ?? doc?.brand;\n const typography = doc?.typography ?? doc?.fonts;\n const appearance = doc?.appearance;\n return {\n brandPrimary: hexFromColor(brand?.primary, seed.brandPrimary),\n brandSecondary: hexFromColor(brand?.secondary, seed.brandSecondary),\n brandAccent: hexFromColor(brand?.accent, seed.brandAccent),\n brandHighlight: hexFromColor(brand?.highlight, seed.brandHighlight),\n brandSuccess: hexFromColor(brand?.success, seed.brandSuccess),\n brandDestructive:\n hexFromColor(brand?.destructive, seed.brandDestructive ?? DESTRUCTIVE_SCALE_HEX) ||\n seed.brandDestructive ||\n DESTRUCTIVE_SCALE_HEX,\n greyScale: pick(doc?.colors?.greyScale ?? doc?.greyScale, seed.greyScale),\n radius: pick(appearance?.radius ?? doc?.radius, seed.radius),\n shadow: pick(appearance?.shadow ?? doc?.shadow, seed.shadow),\n motion: pick(appearance?.motion ?? doc?.motion, seed.motion),\n density: pick(appearance?.density ?? doc?.density, seed.density),\n defaultTheme: pick(appearance?.defaultTheme ?? doc?.defaultTheme, seed.defaultTheme),\n fontBody: pick(typography?.body, seed.fontBody),\n fontHeading: headingFromDoc(typography?.heading, seed.fontHeading),\n darkSelector: seed.darkSelector,\n fontWeights: seed.fontWeights,\n };\n}\n\n/** The document `seedTheme` writes so a fresh Global matches the seed config. */\nexport function docFromConfig(config: ThemeConfig, destructive?: string): ThemeDoc {\n const destructiveHex = destructive ?? config.brandDestructive ?? DESTRUCTIVE_SCALE_HEX;\n return {\n colors: {\n brand: {\n primary: colorDocFromHex(config.brandPrimary),\n secondary: colorDocFromHex(config.brandSecondary),\n accent: colorDocFromHex(config.brandAccent),\n highlight: colorDocFromHex(config.brandHighlight),\n success: colorDocFromHex(config.brandSuccess),\n destructive: colorDocFromHex(destructiveHex),\n },\n library: [],\n greyScale: config.greyScale,\n },\n typography: {\n body: config.fontBody,\n heading: config.fontHeading,\n },\n appearance: {\n defaultTheme: config.defaultTheme,\n radius: config.radius,\n shadow: config.shadow,\n motion: config.motion,\n density: config.density,\n },\n };\n}\n\nexport function validateThemeHex(value: unknown): true | string {\n if (!isThemeHex(value)) return \"Enter a six-digit hex colour like #1e3a5f\";\n return true;\n}\n\nexport function validateSourceIncluded(\n value: unknown,\n { siblingData }: { siblingData?: { sourceStep?: unknown; include?: unknown } },\n): true | string {\n const include = siblingData?.include;\n if (include === \"all\" || include === \"source\") return true;\n const source = Number(siblingData?.sourceStep);\n const steps = Array.isArray(value) ? value.map(Number) : [];\n if (!SHADE_STEPS.includes(source as ShadeStep)) return true;\n if (!steps.includes(source)) return \"The source step cannot be excluded\";\n return true;\n}\n","import type { Access } from \"payload\";\nimport type { FontEntry } from \"@bison-lab/fonts\";\nimport type { ColorScale, ColorScaleInclude, ShadeStep, ThemeConfig } from \"@bison-lab/tokens\";\n\nimport type { ColorUsagesOption } from \"./color-usages\";\nimport type { ResolvedThemeIdentity, ThemeIdentityFallback } from \"./identity\";\n\n/**\n * The Theme document a site's generated types will describe. Optional and\n * nullable, no index signature: a generated Global is assignable to this,\n * never the reverse.\n *\n * Legacy flat `brand.*` hexes, `fonts`, and preset fields at the root stay\n * readable so `getPublishedTheme` still maps a pre-BIS-87 row.\n */\nexport interface ThemeColorDoc {\n hex?: string | null;\n sourceStep?: ShadeStep | string | null;\n scale?: ColorScale | null;\n stale?: boolean | null;\n include?: ColorScaleInclude | \"custom\" | null;\n includedSteps?: ShadeStep[] | string[] | null;\n}\n\nexport interface ThemeLibraryColorDoc extends ThemeColorDoc {\n key?: string | null;\n label?: string | null;\n}\n\nexport interface ThemeDoc {\n colors?: {\n brand?: {\n primary?: ThemeColorDoc | string | null;\n secondary?: ThemeColorDoc | string | null;\n accent?: ThemeColorDoc | string | null;\n highlight?: ThemeColorDoc | string | null;\n success?: ThemeColorDoc | string | null;\n destructive?: ThemeColorDoc | string | null;\n } | null;\n library?: ThemeLibraryColorDoc[] | null;\n greyScale?: ThemeConfig[\"greyScale\"] | null;\n } | null;\n typography?: {\n body?: string | null;\n heading?: string | null;\n } | null;\n appearance?: {\n defaultTheme?: ThemeConfig[\"defaultTheme\"] | null;\n radius?: ThemeConfig[\"radius\"] | null;\n shadow?: ThemeConfig[\"shadow\"] | null;\n motion?: ThemeConfig[\"motion\"] | null;\n density?: ThemeConfig[\"density\"] | null;\n } | null;\n /** @deprecated Pre-BIS-87 flat brand hexes. */\n brand?: {\n primary?: ThemeColorDoc | string | null;\n secondary?: ThemeColorDoc | string | null;\n accent?: ThemeColorDoc | string | null;\n highlight?: ThemeColorDoc | string | null;\n success?: ThemeColorDoc | string | null;\n destructive?: ThemeColorDoc | string | null;\n } | null;\n /** @deprecated Pre-BIS-87; now `colors.greyScale`. */\n greyScale?: ThemeConfig[\"greyScale\"] | null;\n /** @deprecated Pre-BIS-87; now `appearance.*`. */\n radius?: ThemeConfig[\"radius\"] | null;\n shadow?: ThemeConfig[\"shadow\"] | null;\n motion?: ThemeConfig[\"motion\"] | null;\n density?: ThemeConfig[\"density\"] | null;\n defaultTheme?: ThemeConfig[\"defaultTheme\"] | null;\n /** @deprecated Pre-BIS-87; now `typography`. */\n fonts?: {\n body?: string | null;\n heading?: string | null;\n } | null;\n logo?: number | string | ThemeUploadDoc | null;\n favicon?: number | string | ThemeUploadDoc | null;\n logoMark?: number | string | ThemeUploadDoc | null;\n}\n\nexport interface ThemeUploadDoc {\n id?: number | string | null;\n url?: string | null;\n alt?: string | null;\n}\n\n/**\n * What an editor can change. `darkSelector` and `fontWeights` stay on the\n * seed — they mean nothing in the admin — and `themeConfigFromDoc` puts\n * them back.\n */\nexport type EditableTheme = Omit<ThemeConfig, \"darkSelector\" | \"fontWeights\">;\n\nexport interface CreateThemeOptions {\n /**\n * `update` defaults to `canUseFeature(\"theme\")` (Designer in the seed).\n * `read` defaults to public; pass a stricter function to tighten it.\n * Omitting `access` still registers the Global.\n */\n access?: { read?: Access; update?: Access };\n /** The site's `bison.config.json`. Every field's `defaultValue`, and the fallback `getPublishedTheme` returns. */\n seed: ThemeConfig;\n /**\n * Destructive seed hex. Falls back to `seed.brandDestructive`, then\n * the library's `DESTRUCTIVE_SCALE_HEX` (`#FF7C6B`).\n */\n destructive?: string;\n /** Default: the whole catalogue. */\n fonts?: readonly FontEntry[];\n /** Where the site's `serveFont` route answers, for the picker's specimens. Default `\"/fonts\"`. */\n fontsBaseUrl?: string;\n /** Fill + automatic label target. Default `7`. Warnings never block save. */\n contrastTarget?: number;\n /**\n * @deprecated Theme has no preview pane (SPI-56 canceled). Kept so a\n * site that still passes it does not fail to boot.\n */\n previewPath?: string;\n /**\n * Adds the Identity page (logo, favicon, mobile-menu mark) when given.\n * Pass `BRAND_ASSETS_SLUG` (or the slug you gave `createBrandAssets`).\n * Save on that page writes only those uploads onto the stored Theme row.\n */\n logo?: { collection: string };\n /**\n * Fallback art when logo, favicon, or mobile-menu mark is empty. The\n * site passes today's files; `--color-primary-mark` is not a Theme field.\n */\n identity?: { fallback?: ThemeIdentityFallback };\n /** Fires from `afterChange` on every save — Theme has no draft mode. */\n onPublish?: (theme: ThemeConfig, doc: ThemeDoc) => void | Promise<void>;\n /**\n * Where Colors Delete looks for `lookField` / `colorTokenField` tokens\n * (drafts included). `true` scans every registered collection and\n * global at request time — Payload internals and Theme itself are\n * skipped, so a later Navigation or Territories global joins without\n * a site change. A list still names slugs. Omit or pass empty: every\n * additional color is unused and deletes immediately.\n */\n colorUsages?: ColorUsagesOption;\n}\n\nexport interface ThemeHeadOptions {\n fontsBaseUrl?: string;\n attribute?: \"class\" | \"data-theme\";\n identity?: ResolvedThemeIdentity;\n /**\n * Custom Colors rows. `themeHead` emits their 50–950 variables and\n * `[data-look]` bindings so a picker key paints without a package bump.\n */\n library?: ThemeLibraryColorDoc[] | null;\n}\n\nexport interface ThemeHead {\n css: string;\n preloads: { href: string; type: \"font/woff2\" }[];\n identity?: ResolvedThemeIdentity;\n}\n\nexport const THEME_SLUG = \"theme\";\nexport const THEME_COLORS_SLUG = \"theme-colors\";\nexport const THEME_TYPOGRAPHY_SLUG = \"theme-typography\";\nexport const THEME_APPEARANCE_SLUG = \"theme-appearance\";\nexport const THEME_IDENTITY_SLUG = \"theme-identity\";\n\nexport const SYSTEM_COLOR_KEYS = [\n \"primary\",\n \"secondary\",\n \"accent\",\n \"highlight\",\n \"success\",\n \"destructive\",\n] as const;\n\nexport type SystemColorKey = (typeof SYSTEM_COLOR_KEYS)[number];\n","import { includedShadeSteps, type ShadeStep } from \"@bison-lab/tokens\";\n\nimport { stateFromColorDoc } from \"./map\";\nimport { THEME_SLUG, type ThemeColorDoc, type ThemeDoc, type ThemeLibraryColorDoc } from \"./types\";\n\n/**\n * System colors Color Settings offers as page-editor fills. Success and\n * Destructive stay off this list — they are theme chrome only.\n */\nexport const PAGE_EDITOR_SYSTEM_KEYS = [\"primary\", \"secondary\", \"accent\", \"highlight\"] as const;\n\nexport type PageEditorSystemKey = (typeof PAGE_EDITOR_SYSTEM_KEYS)[number];\n\nexport interface LookOption {\n label: string;\n value: string;\n}\n\nconst SYSTEM_LABELS: Record<PageEditorSystemKey, string> = {\n primary: \"Primary\",\n secondary: \"Secondary\",\n accent: \"Accent\",\n highlight: \"Highlight\",\n};\n\nfunction brandColor(doc: ThemeDoc | null | undefined, key: PageEditorSystemKey): ThemeColorDoc | null {\n const brand = doc?.colors?.brand ?? doc?.brand;\n const value = brand?.[key];\n if (typeof value === \"string\" || value == null) return value == null ? null : { hex: value };\n return value;\n}\n\nexport function themeLibraryFromDoc(doc: ThemeDoc | null | undefined): ThemeLibraryColorDoc[] {\n return Array.isArray(doc?.colors?.library) ? doc.colors.library : [];\n}\n\nfunction libraryRows(doc: ThemeDoc | null | undefined): ThemeLibraryColorDoc[] {\n return themeLibraryFromDoc(doc);\n}\n\nfunction titleCase(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1);\n}\n\nfunction stepsFor(color: ThemeColorDoc | null | undefined, fallbackHex: string): ShadeStep[] {\n return includedShadeSteps(stateFromColorDoc(color, fallbackHex));\n}\n\n/**\n * Family keys a `lookField()` may offer: the page-editor system scales\n * plus every custom color on Colors. Adding Coral on Theme makes `coral`\n * appear here with no `@bison-lab/*` release.\n */\nexport function pageEditorLooks(doc: ThemeDoc | null | undefined): LookOption[] {\n const system = PAGE_EDITOR_SYSTEM_KEYS.map((value) => ({\n label: SYSTEM_LABELS[value],\n value,\n }));\n const custom = libraryRows(doc)\n .map((row) => {\n const value = row.key?.trim();\n if (!value) return null;\n return { label: row.label?.trim() || titleCase(value), value };\n })\n .filter((option): option is LookOption => option !== null);\n return [...system, ...custom];\n}\n\n/**\n * Included steps as `coral-400`. Excluded steps do not appear. System\n * scales with no stored include list offer the full 50–950 ramp.\n */\nexport function pageEditorTokens(doc: ThemeDoc | null | undefined): LookOption[] {\n const tokens: LookOption[] = [];\n for (const key of PAGE_EDITOR_SYSTEM_KEYS) {\n const label = SYSTEM_LABELS[key];\n for (const step of stepsFor(brandColor(doc, key), \"#000000\")) {\n tokens.push({ label: `${label} ${step}`, value: `${key}-${step}` });\n }\n }\n for (const row of libraryRows(doc)) {\n const key = row.key?.trim();\n if (!key) continue;\n const label = row.label?.trim() || titleCase(key);\n for (const step of stepsFor(row, row.hex ?? \"#000000\")) {\n tokens.push({ label: `${label} ${step}`, value: `${key}-${step}` });\n }\n }\n return tokens;\n}\n\n/** One included step with its stored color, for a picker that draws swatches. */\nexport interface ColorSwatch extends LookOption {\n /** The family key the token starts with (`primary`, `coral`). */\n family: string;\n /** The family's label (`Primary`, `Coral`). */\n familyLabel: string;\n step: ShadeStep;\n /** The step's HSL triplet (`330 100% 43%`), the value its CSS variable holds. */\n hsl: string;\n}\n\n/**\n * `pageEditorTokens` with each step's stored color, grouped by family in\n * the same order, so an admin picker can paint a swatch without the site's\n * Theme stylesheet.\n */\nexport function pageEditorSwatches(doc: ThemeDoc | null | undefined): ColorSwatch[] {\n const swatches: ColorSwatch[] = [];\n const push = (family: string, familyLabel: string, color: ThemeColorDoc | null | undefined, fallbackHex: string) => {\n const state = stateFromColorDoc(color, fallbackHex);\n for (const step of includedShadeSteps(state)) {\n swatches.push({\n label: `${familyLabel} ${step}`,\n value: `${family}-${step}`,\n family,\n familyLabel,\n step,\n hsl: String(state.scale[step] ?? \"\"),\n });\n }\n };\n for (const key of PAGE_EDITOR_SYSTEM_KEYS) push(key, SYSTEM_LABELS[key], brandColor(doc, key), \"#000000\");\n for (const row of libraryRows(doc)) {\n const key = row.key?.trim();\n if (!key) continue;\n push(key, row.label?.trim() || titleCase(key), row, row.hex ?? \"#000000\");\n }\n return swatches;\n}\n\nexport async function themeDocFromRequest(req: {\n payload?: {\n findGlobal?: (args: {\n slug: string;\n depth?: number;\n overrideAccess?: boolean;\n }) => Promise<ThemeDoc | null | undefined>;\n };\n}): Promise<ThemeDoc | null> {\n try {\n const doc = await req.payload?.findGlobal?.({\n slug: THEME_SLUG,\n depth: 0,\n overrideAccess: true,\n });\n return doc ?? null;\n } catch {\n return null;\n }\n}\n","/**\n * How a Block library island tells its card how tall it is (BIS-147).\n * The island (`BlockLibraryIsland`, on `./react`) posts its height to the\n * admin window; the card sizes its iframe from it. No React, no plugin:\n * both halves import this.\n */\n\nexport const ISLAND_HEIGHT_MESSAGE = \"bison-lab:block-library-island-height\" as const;\n\n/** The card's height until its island reports, and for a site whose island never does. */\nexport const ISLAND_FALLBACK_HEIGHT = 720;\n\n/** An empty sample, or a `position: fixed` one (the navbar), still shows as a card. */\nexport const ISLAND_MIN_HEIGHT = 120;\n\n/**\n * The iframe's height is the island's viewport, so a sample sized in `vh`\n * grows when the card does. The ceiling stops that loop.\n */\nexport const ISLAND_MAX_HEIGHT = 960;\n\nexport type IslandHeightMessage = { type: typeof ISLAND_HEIGHT_MESSAGE; height: number };\n\n/** The height a message carries, or `null` when it is not an island's height message. */\nexport function islandHeightOf(data: unknown): number | null {\n if (!data || typeof data !== \"object\") return null;\n const message = data as Partial<IslandHeightMessage>;\n if (message.type !== ISLAND_HEIGHT_MESSAGE) return null;\n const height = message.height;\n return typeof height === \"number\" && Number.isFinite(height) && height >= 0 ? height : null;\n}\n\n/** A reported height, held between the floor and the ceiling and rounded up to a whole pixel. */\nexport function clampIslandHeight(height: number): number {\n return Math.min(ISLAND_MAX_HEIGHT, Math.max(ISLAND_MIN_HEIGHT, Math.ceil(height)));\n}\n"],"mappings":";;;AAgBA,SAAS,KAAQ,OAA6B,UAAgB;AAC5D,QAAO,SAAS,OAAO,WAAW;;AAGpC,SAAS,eACP,SACA,MACe;AACf,KAAI,YAAY,KAAA,EAAW,QAAO;AAClC,KAAI,YAAY,QAAQ,YAAA,GAA0B,QAAO;AACzD,QAAO;;AAGT,SAAS,aAAa,OAAkD,UAA0B;AAChG,KAAI,OAAO,UAAU,SAAU,QAAO,SAAS;AAC/C,QAAO,KAAK,OAAO,KAAK,SAAS;;AAGnC,SAAgB,gBAAgB,KAAa,aAAwB,KAAoB;AACvF,QAAO,kBAAkB,iBAAiB,KAAK,WAAW,CAAC;;AAG7D,SAAgB,kBAAkB,OAAuC;AACvE,QAAO;EACL,KAAK,MAAM;EACX,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,OAAO,MAAM;EACb,SAAS,MAAM,QAAQ,MAAM,QAAQ,GAAG,WAAW,MAAM;EACzD,eAAe,MAAM,QAAQ,MAAM,QAAQ,GAAG,CAAC,GAAG,MAAM,QAAQ,GAAG,KAAA;EACpE;;AAGH,SAAgB,kBACd,KACA,cAAc,WACG;CACjB,MAAM,MAAM,WAAW,KAAK,IAAI,GAAG,IAAI,MAAM;CAC7C,MAAM,aAAc,OAAO,KAAK,WAAW,IAAI;CAC/C,MAAM,UAAU,eAAe,KAA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AS,SAAU,QAAO;CAC9C,MAAM,UAAU;AAChB,KAAI,QAAQ,SAAA,wCAAgC,QAAO;CACnD,MAAM,SAAS,QAAQ;AACvB,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,OAAO,IAAI,UAAU,IAAI,SAAS;;;AAIzF,SAAgB,kBAAkB,QAAwB;AACxD,QAAO,KAAK,IAAA,KAAuB,KAAK,IAAA,KAAuB,KAAK,KAAK,OAAO,CAAC,CAAC"}
1
+ {"version":3,"file":"island-97l5VY8l.mjs","names":[],"sources":["../src/theme/map.ts","../src/theme/types.ts","../src/theme/looks.ts","../src/block-library/island.ts"],"sourcesContent":["import {\n createColorScale,\n DESTRUCTIVE_SCALE_HEX,\n generateColorScale,\n isThemeHex,\n SHADE_STEPS,\n type ColorScale,\n type ColorScaleInclude,\n type ColorScaleState,\n type ShadeStep,\n type ThemeConfig,\n} from \"@bison-lab/tokens\";\n\nimport { SAME_AS_BODY } from \"./fields\";\nimport type { ThemeColorDoc, ThemeDoc } from \"./types\";\n\nfunction pick<T>(value: T | null | undefined, fallback: T): T {\n return value == null ? fallback : value;\n}\n\nfunction headingFromDoc(\n heading: string | null | undefined,\n seed: ThemeConfig[\"fontHeading\"],\n): string | null {\n if (heading === undefined) return seed;\n if (heading === null || heading === SAME_AS_BODY) return null;\n return heading;\n}\n\nfunction hexFromColor(value: ThemeColorDoc | string | null | undefined, fallback: string): string {\n if (typeof value === \"string\") return value || fallback;\n return pick(value?.hex, fallback);\n}\n\nexport function colorDocFromHex(hex: string, sourceStep: ShadeStep = 500): ThemeColorDoc {\n return colorDocFromState(createColorScale(hex, sourceStep));\n}\n\nexport function colorDocFromState(state: ColorScaleState): ThemeColorDoc {\n return {\n hex: state.hex,\n sourceStep: state.sourceStep,\n scale: state.scale,\n stale: state.stale,\n include: Array.isArray(state.include) ? \"custom\" : state.include,\n includedSteps: Array.isArray(state.include) ? [...state.include] : undefined,\n };\n}\n\nexport function stateFromColorDoc(\n doc: ThemeColorDoc | null | undefined,\n fallbackHex = \"#000000\",\n): ColorScaleState {\n const hex = isThemeHex(doc?.hex) ? doc.hex : fallbackHex;\n const sourceStep = (Number(doc?.sourceStep) || 500) as ShadeStep;\n const include = includeFromDoc(doc, sourceStep);\n const scale =\n doc?.scale && typeof doc.scale === \"object\" ? (doc.scale as ColorScale) : generateColorScale(hex, sourceStep);\n return { hex, sourceStep, scale, stale: Boolean(doc?.stale), include };\n}\n\nfunction includeFromDoc(doc: ThemeColorDoc | null | undefined, sourceStep: ShadeStep): ColorScaleInclude {\n if (doc?.include === \"source\") return \"source\";\n if (doc?.include === \"custom\" && Array.isArray(doc.includedSteps)) {\n const steps = doc.includedSteps.map(Number).filter((step): step is ShadeStep => SHADE_STEPS.includes(step as ShadeStep));\n if (!steps.includes(sourceStep)) steps.push(sourceStep);\n return steps;\n }\n return \"all\";\n}\n\n/**\n * Nested Theme document → flat `ThemeConfig`. Null or missing editor\n * fields take the seed; `darkSelector` and `fontWeights` always come from\n * the seed. Reads the BIS-87 groups and the pre-BIS-87 flat fields.\n */\nexport function themeConfigFromDoc(doc: ThemeDoc | null | undefined, seed: ThemeConfig): ThemeConfig {\n const brand = doc?.colors?.brand ?? doc?.brand;\n const typography = doc?.typography ?? doc?.fonts;\n const appearance = doc?.appearance;\n return {\n brandPrimary: hexFromColor(brand?.primary, seed.brandPrimary),\n brandSecondary: hexFromColor(brand?.secondary, seed.brandSecondary),\n brandAccent: hexFromColor(brand?.accent, seed.brandAccent),\n brandHighlight: hexFromColor(brand?.highlight, seed.brandHighlight),\n brandSuccess: hexFromColor(brand?.success, seed.brandSuccess),\n brandDestructive:\n hexFromColor(brand?.destructive, seed.brandDestructive ?? DESTRUCTIVE_SCALE_HEX) ||\n seed.brandDestructive ||\n DESTRUCTIVE_SCALE_HEX,\n greyScale: pick(doc?.colors?.greyScale ?? doc?.greyScale, seed.greyScale),\n radius: pick(appearance?.radius ?? doc?.radius, seed.radius),\n shadow: pick(appearance?.shadow ?? doc?.shadow, seed.shadow),\n motion: pick(appearance?.motion ?? doc?.motion, seed.motion),\n density: pick(appearance?.density ?? doc?.density, seed.density),\n defaultTheme: pick(appearance?.defaultTheme ?? doc?.defaultTheme, seed.defaultTheme),\n fontBody: pick(typography?.body, seed.fontBody),\n fontHeading: headingFromDoc(typography?.heading, seed.fontHeading),\n darkSelector: seed.darkSelector,\n fontWeights: seed.fontWeights,\n };\n}\n\n/** The document `seedTheme` writes so a fresh Global matches the seed config. */\nexport function docFromConfig(config: ThemeConfig, destructive?: string): ThemeDoc {\n const destructiveHex = destructive ?? config.brandDestructive ?? DESTRUCTIVE_SCALE_HEX;\n return {\n colors: {\n brand: {\n primary: colorDocFromHex(config.brandPrimary),\n secondary: colorDocFromHex(config.brandSecondary),\n accent: colorDocFromHex(config.brandAccent),\n highlight: colorDocFromHex(config.brandHighlight),\n success: colorDocFromHex(config.brandSuccess),\n destructive: colorDocFromHex(destructiveHex),\n },\n library: [],\n greyScale: config.greyScale,\n },\n typography: {\n body: config.fontBody,\n heading: config.fontHeading,\n },\n appearance: {\n defaultTheme: config.defaultTheme,\n radius: config.radius,\n shadow: config.shadow,\n motion: config.motion,\n density: config.density,\n },\n };\n}\n\nexport function validateThemeHex(value: unknown): true | string {\n if (!isThemeHex(value)) return \"Enter a six-digit hex colour like #1e3a5f\";\n return true;\n}\n\nexport function validateSourceIncluded(\n value: unknown,\n { siblingData }: { siblingData?: { sourceStep?: unknown; include?: unknown } },\n): true | string {\n const include = siblingData?.include;\n if (include === \"all\" || include === \"source\") return true;\n const source = Number(siblingData?.sourceStep);\n const steps = Array.isArray(value) ? value.map(Number) : [];\n if (!SHADE_STEPS.includes(source as ShadeStep)) return true;\n if (!steps.includes(source)) return \"The source step cannot be excluded\";\n return true;\n}\n","import type { Access } from \"payload\";\nimport type { FontEntry } from \"@bison-lab/fonts\";\nimport type { ColorScale, ColorScaleInclude, ShadeStep, ThemeConfig } from \"@bison-lab/tokens\";\n\nimport type { ColorUsagesOption } from \"./color-usages\";\nimport type { ResolvedThemeIdentity, ThemeIdentityFallback } from \"./identity\";\n\n/**\n * The Theme document a site's generated types will describe. Optional and\n * nullable, no index signature: a generated Global is assignable to this,\n * never the reverse.\n *\n * Legacy flat `brand.*` hexes, `fonts`, and preset fields at the root stay\n * readable so `getPublishedTheme` still maps a pre-BIS-87 row.\n */\nexport interface ThemeColorDoc {\n hex?: string | null;\n sourceStep?: ShadeStep | string | null;\n scale?: ColorScale | null;\n stale?: boolean | null;\n include?: ColorScaleInclude | \"custom\" | null;\n includedSteps?: ShadeStep[] | string[] | null;\n}\n\nexport interface ThemeLibraryColorDoc extends ThemeColorDoc {\n key?: string | null;\n label?: string | null;\n}\n\nexport interface ThemeDoc {\n colors?: {\n brand?: {\n primary?: ThemeColorDoc | string | null;\n secondary?: ThemeColorDoc | string | null;\n accent?: ThemeColorDoc | string | null;\n highlight?: ThemeColorDoc | string | null;\n success?: ThemeColorDoc | string | null;\n destructive?: ThemeColorDoc | string | null;\n } | null;\n library?: ThemeLibraryColorDoc[] | null;\n greyScale?: ThemeConfig[\"greyScale\"] | null;\n } | null;\n typography?: {\n body?: string | null;\n heading?: string | null;\n } | null;\n appearance?: {\n defaultTheme?: ThemeConfig[\"defaultTheme\"] | null;\n radius?: ThemeConfig[\"radius\"] | null;\n shadow?: ThemeConfig[\"shadow\"] | null;\n motion?: ThemeConfig[\"motion\"] | null;\n density?: ThemeConfig[\"density\"] | null;\n } | null;\n /** @deprecated Pre-BIS-87 flat brand hexes. */\n brand?: {\n primary?: ThemeColorDoc | string | null;\n secondary?: ThemeColorDoc | string | null;\n accent?: ThemeColorDoc | string | null;\n highlight?: ThemeColorDoc | string | null;\n success?: ThemeColorDoc | string | null;\n destructive?: ThemeColorDoc | string | null;\n } | null;\n /** @deprecated Pre-BIS-87; now `colors.greyScale`. */\n greyScale?: ThemeConfig[\"greyScale\"] | null;\n /** @deprecated Pre-BIS-87; now `appearance.*`. */\n radius?: ThemeConfig[\"radius\"] | null;\n shadow?: ThemeConfig[\"shadow\"] | null;\n motion?: ThemeConfig[\"motion\"] | null;\n density?: ThemeConfig[\"density\"] | null;\n defaultTheme?: ThemeConfig[\"defaultTheme\"] | null;\n /** @deprecated Pre-BIS-87; now `typography`. */\n fonts?: {\n body?: string | null;\n heading?: string | null;\n } | null;\n logo?: number | string | ThemeUploadDoc | null;\n /** The logo on a dark background; the admin shows it in dark mode. */\n logoDark?: number | string | ThemeUploadDoc | null;\n favicon?: number | string | ThemeUploadDoc | null;\n logoMark?: number | string | ThemeUploadDoc | null;\n}\n\nexport interface ThemeUploadDoc {\n id?: number | string | null;\n url?: string | null;\n alt?: string | null;\n}\n\n/**\n * What an editor can change. `darkSelector` and `fontWeights` stay on the\n * seed — they mean nothing in the admin — and `themeConfigFromDoc` puts\n * them back.\n */\nexport type EditableTheme = Omit<ThemeConfig, \"darkSelector\" | \"fontWeights\">;\n\nexport interface CreateThemeOptions {\n /**\n * `update` defaults to `canUseFeature(\"theme\")` (Designer in the seed).\n * `read` defaults to public; pass a stricter function to tighten it.\n * Omitting `access` still registers the Global.\n */\n access?: { read?: Access; update?: Access };\n /** The site's `bison.config.json`. Every field's `defaultValue`, and the fallback `getPublishedTheme` returns. */\n seed: ThemeConfig;\n /**\n * Destructive seed hex. Falls back to `seed.brandDestructive`, then\n * the library's `DESTRUCTIVE_SCALE_HEX` (`#FF7C6B`).\n */\n destructive?: string;\n /** Default: the whole catalogue. */\n fonts?: readonly FontEntry[];\n /** Where the site's `serveFont` route answers, for the picker's specimens. Default `\"/fonts\"`. */\n fontsBaseUrl?: string;\n /** Fill + automatic label target. Default `7`. Warnings never block save. */\n contrastTarget?: number;\n /**\n * @deprecated Theme has no preview pane (SPI-56 canceled). Kept so a\n * site that still passes it does not fail to boot.\n */\n previewPath?: string;\n /**\n * Adds the Identity page (logo, favicon, mobile-menu mark) when given.\n * Pass `BRAND_ASSETS_SLUG` (or the slug you gave `createBrandAssets`).\n * Save on that page writes only those uploads onto the stored Theme row.\n */\n logo?: { collection: string };\n /**\n * Fallback art when logo, favicon, or mobile-menu mark is empty. The\n * site passes today's files; `--color-primary-mark` is not a Theme field.\n */\n identity?: { fallback?: ThemeIdentityFallback };\n /**\n * The site's name, for the admin's tab titles: `adminNav()` sets\n * `admin.meta.titleSuffix` to `| <siteName> CMS` unless the site set its\n * own. Omit it and Payload's default suffix stays.\n */\n siteName?: string;\n /** Fires from `afterChange` on every save — Theme has no draft mode. */\n onPublish?: (theme: ThemeConfig, doc: ThemeDoc) => void | Promise<void>;\n /**\n * Where Colors Delete looks for `lookField` / `colorTokenField` tokens\n * (drafts included). `true` scans every registered collection and\n * global at request time — Payload internals and Theme itself are\n * skipped, so a later Navigation or Territories global joins without\n * a site change. A list still names slugs. Omit or pass empty: every\n * additional color is unused and deletes immediately.\n */\n colorUsages?: ColorUsagesOption;\n}\n\nexport interface ThemeHeadOptions {\n fontsBaseUrl?: string;\n attribute?: \"class\" | \"data-theme\";\n identity?: ResolvedThemeIdentity;\n /**\n * Custom Colors rows. `themeHead` emits their 50–950 variables and\n * `[data-look]` bindings so a picker key paints without a package bump.\n */\n library?: ThemeLibraryColorDoc[] | null;\n}\n\nexport interface ThemeHead {\n css: string;\n preloads: { href: string; type: \"font/woff2\" }[];\n identity?: ResolvedThemeIdentity;\n}\n\nexport const THEME_SLUG = \"theme\";\nexport const THEME_COLORS_SLUG = \"theme-colors\";\nexport const THEME_TYPOGRAPHY_SLUG = \"theme-typography\";\nexport const THEME_APPEARANCE_SLUG = \"theme-appearance\";\nexport const THEME_IDENTITY_SLUG = \"theme-identity\";\n\nexport const SYSTEM_COLOR_KEYS = [\n \"primary\",\n \"secondary\",\n \"accent\",\n \"highlight\",\n \"success\",\n \"destructive\",\n] as const;\n\nexport type SystemColorKey = (typeof SYSTEM_COLOR_KEYS)[number];\n","import { includedShadeSteps, type ShadeStep } from \"@bison-lab/tokens\";\n\nimport { stateFromColorDoc } from \"./map\";\nimport { THEME_SLUG, type ThemeColorDoc, type ThemeDoc, type ThemeLibraryColorDoc } from \"./types\";\n\n/**\n * System colors Color Settings offers as page-editor fills. Success and\n * Destructive stay off this list — they are theme chrome only.\n */\nexport const PAGE_EDITOR_SYSTEM_KEYS = [\"primary\", \"secondary\", \"accent\", \"highlight\"] as const;\n\nexport type PageEditorSystemKey = (typeof PAGE_EDITOR_SYSTEM_KEYS)[number];\n\nexport interface LookOption {\n label: string;\n value: string;\n}\n\nconst SYSTEM_LABELS: Record<PageEditorSystemKey, string> = {\n primary: \"Primary\",\n secondary: \"Secondary\",\n accent: \"Accent\",\n highlight: \"Highlight\",\n};\n\nfunction brandColor(doc: ThemeDoc | null | undefined, key: PageEditorSystemKey): ThemeColorDoc | null {\n const brand = doc?.colors?.brand ?? doc?.brand;\n const value = brand?.[key];\n if (typeof value === \"string\" || value == null) return value == null ? null : { hex: value };\n return value;\n}\n\nexport function themeLibraryFromDoc(doc: ThemeDoc | null | undefined): ThemeLibraryColorDoc[] {\n return Array.isArray(doc?.colors?.library) ? doc.colors.library : [];\n}\n\nfunction libraryRows(doc: ThemeDoc | null | undefined): ThemeLibraryColorDoc[] {\n return themeLibraryFromDoc(doc);\n}\n\nfunction titleCase(key: string): string {\n return key.charAt(0).toUpperCase() + key.slice(1);\n}\n\nfunction stepsFor(color: ThemeColorDoc | null | undefined, fallbackHex: string): ShadeStep[] {\n return includedShadeSteps(stateFromColorDoc(color, fallbackHex));\n}\n\n/**\n * Family keys a `lookField()` may offer: the page-editor system scales\n * plus every custom color on Colors. Adding Coral on Theme makes `coral`\n * appear here with no `@bison-lab/*` release.\n */\nexport function pageEditorLooks(doc: ThemeDoc | null | undefined): LookOption[] {\n const system = PAGE_EDITOR_SYSTEM_KEYS.map((value) => ({\n label: SYSTEM_LABELS[value],\n value,\n }));\n const custom = libraryRows(doc)\n .map((row) => {\n const value = row.key?.trim();\n if (!value) return null;\n return { label: row.label?.trim() || titleCase(value), value };\n })\n .filter((option): option is LookOption => option !== null);\n return [...system, ...custom];\n}\n\n/**\n * Included steps as `coral-400`. Excluded steps do not appear. System\n * scales with no stored include list offer the full 50–950 ramp.\n */\nexport function pageEditorTokens(doc: ThemeDoc | null | undefined): LookOption[] {\n const tokens: LookOption[] = [];\n for (const key of PAGE_EDITOR_SYSTEM_KEYS) {\n const label = SYSTEM_LABELS[key];\n for (const step of stepsFor(brandColor(doc, key), \"#000000\")) {\n tokens.push({ label: `${label} ${step}`, value: `${key}-${step}` });\n }\n }\n for (const row of libraryRows(doc)) {\n const key = row.key?.trim();\n if (!key) continue;\n const label = row.label?.trim() || titleCase(key);\n for (const step of stepsFor(row, row.hex ?? \"#000000\")) {\n tokens.push({ label: `${label} ${step}`, value: `${key}-${step}` });\n }\n }\n return tokens;\n}\n\n/** One included step with its stored color, for a picker that draws swatches. */\nexport interface ColorSwatch extends LookOption {\n /** The family key the token starts with (`primary`, `coral`). */\n family: string;\n /** The family's label (`Primary`, `Coral`). */\n familyLabel: string;\n step: ShadeStep;\n /** The step's HSL triplet (`330 100% 43%`), the value its CSS variable holds. */\n hsl: string;\n}\n\n/**\n * `pageEditorTokens` with each step's stored color, grouped by family in\n * the same order, so an admin picker can paint a swatch without the site's\n * Theme stylesheet.\n */\nexport function pageEditorSwatches(doc: ThemeDoc | null | undefined): ColorSwatch[] {\n const swatches: ColorSwatch[] = [];\n const push = (family: string, familyLabel: string, color: ThemeColorDoc | null | undefined, fallbackHex: string) => {\n const state = stateFromColorDoc(color, fallbackHex);\n for (const step of includedShadeSteps(state)) {\n swatches.push({\n label: `${familyLabel} ${step}`,\n value: `${family}-${step}`,\n family,\n familyLabel,\n step,\n hsl: String(state.scale[step] ?? \"\"),\n });\n }\n };\n for (const key of PAGE_EDITOR_SYSTEM_KEYS) push(key, SYSTEM_LABELS[key], brandColor(doc, key), \"#000000\");\n for (const row of libraryRows(doc)) {\n const key = row.key?.trim();\n if (!key) continue;\n push(key, row.label?.trim() || titleCase(key), row, row.hex ?? \"#000000\");\n }\n return swatches;\n}\n\nexport async function themeDocFromRequest(req: {\n payload?: {\n findGlobal?: (args: {\n slug: string;\n depth?: number;\n overrideAccess?: boolean;\n }) => Promise<ThemeDoc | null | undefined>;\n };\n}): Promise<ThemeDoc | null> {\n try {\n const doc = await req.payload?.findGlobal?.({\n slug: THEME_SLUG,\n depth: 0,\n overrideAccess: true,\n });\n return doc ?? null;\n } catch {\n return null;\n }\n}\n","/**\n * How a Block library island tells its card how tall it is (BIS-147).\n * The island (`BlockLibraryIsland`, on `./react`) posts its height to the\n * admin window; the card sizes its iframe from it. No React, no plugin:\n * both halves import this.\n */\n\nexport const ISLAND_HEIGHT_MESSAGE = \"bison-lab:block-library-island-height\" as const;\n\n/** The card's height until its island reports, and for a site whose island never does. */\nexport const ISLAND_FALLBACK_HEIGHT = 720;\n\n/** An empty sample, or a `position: fixed` one (the navbar), still shows as a card. */\nexport const ISLAND_MIN_HEIGHT = 120;\n\n/**\n * The iframe's height is the island's viewport, so a sample sized in `vh`\n * grows when the card does. The ceiling stops that loop.\n */\nexport const ISLAND_MAX_HEIGHT = 960;\n\nexport type IslandHeightMessage = { type: typeof ISLAND_HEIGHT_MESSAGE; height: number };\n\n/** The height a message carries, or `null` when it is not an island's height message. */\nexport function islandHeightOf(data: unknown): number | null {\n if (!data || typeof data !== \"object\") return null;\n const message = data as Partial<IslandHeightMessage>;\n if (message.type !== ISLAND_HEIGHT_MESSAGE) return null;\n const height = message.height;\n return typeof height === \"number\" && Number.isFinite(height) && height >= 0 ? height : null;\n}\n\n/** A reported height, held between the floor and the ceiling and rounded up to a whole pixel. */\nexport function clampIslandHeight(height: number): number {\n return Math.min(ISLAND_MAX_HEIGHT, Math.max(ISLAND_MIN_HEIGHT, Math.ceil(height)));\n}\n"],"mappings":";;;AAgBA,SAAS,KAAQ,OAA6B,UAAgB;AAC5D,QAAO,SAAS,OAAO,WAAW;;AAGpC,SAAS,eACP,SACA,MACe;AACf,KAAI,YAAY,KAAA,EAAW,QAAO;AAClC,KAAI,YAAY,QAAQ,YAAA,GAA0B,QAAO;AACzD,QAAO;;AAGT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OAAO,yBAAyB;EACzC,MAAM,QAAQ,cAAc;AAC5B,OAAK,MAAM,QAAQ,SAAS,WAAW,KAAK,IAAI,EAAE,UAAU,CAC1D,QAAO,KAAK;GAAE,OAAO,GAAG,MAAM,GAAG;GAAQ,OAAO,GAAG,IAAI,GAAG;GAAQ,CAAC;;AAGvE,MAAK,MAAM,OAAO,YAAY,IAAI,EAAE;EAClC,MAAM,MAAM,IAAI,KAAK,MAAM;AAC3B,MAAI,CAAC,IAAK;EACV,MAAM,QAAQ,IAAI,OAAO,MAAM,IAAI,UAAU,IAAI;AACjD,OAAK,MAAM,QAAQ,SAAS,KAAK,IAAI,OAAO,UAAU,CACpD,QAAO,KAAK;GAAE,OAAO,GAAG,MAAM,GAAG;GAAQ,OAAO,GAAG,IAAI,GAAG;GAAQ,CAAC;;AAGvE,QAAO;;;;;;;;;;ACjFT,MAAa,wBAAwB;;AAiBrC,SAAgB,eAAe,MAA8B;AAC3D,KAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;CAC9C,MAAM,UAAU;AAChB,KAAI,QAAQ,SAAA,wCAAgC,QAAO;CACnD,MAAM,SAAS,QAAQ;AACvB,QAAO,OAAO,WAAW,YAAY,OAAO,SAAS,OAAO,IAAI,UAAU,IAAI,SAAS;;;AAIzF,SAAgB,kBAAkB,QAAwB;AACxD,QAAO,KAAK,IAAA,KAAuB,KAAK,IAAA,KAAuB,KAAK,KAAK,OAAO,CAAC,CAAC"}
@@ -0,0 +1,179 @@
1
+ //#region src/translate/languages.ts
2
+ /**
3
+ * The languages every Bison site carries. The library owns this list: a new
4
+ * language is a library release that sites take by updating the package
5
+ * (and running the migration it brings). The first entry is the default
6
+ * locale of a site that declares no localization of its own.
7
+ */
8
+ const LIBRARY_LOCALES = [{
9
+ code: "en",
10
+ label: "English"
11
+ }, {
12
+ code: "es",
13
+ label: "Español"
14
+ }];
15
+ const LIBRARY_DEFAULT_LOCALE = "en";
16
+ /** The codes of `LIBRARY_LOCALES`, in order. */
17
+ const LIBRARY_LOCALE_CODES = LIBRARY_LOCALES.map((locale) => locale.code);
18
+ function codeOf(entry) {
19
+ return typeof entry === "string" ? entry : entry.code;
20
+ }
21
+ /**
22
+ * A config's `localization` with every library language in it. A site with
23
+ * none gets the library's (English default, `fallback: true`, so an empty
24
+ * Spanish field reads as English). A site with its own keeps its locales,
25
+ * labels and default, and gains any library language it lacks.
26
+ */
27
+ function withLibraryLocales(localization) {
28
+ if (!localization) return {
29
+ locales: LIBRARY_LOCALES.map((locale) => ({ ...locale })),
30
+ defaultLocale: "en",
31
+ fallback: true
32
+ };
33
+ const own = localization.locales;
34
+ const have = new Set(own.map(codeOf));
35
+ const missing = LIBRARY_LOCALES.filter((locale) => !have.has(locale.code));
36
+ if (missing.length === 0) return localization;
37
+ const locales = [...own.map((entry) => typeof entry === "string" ? {
38
+ code: entry,
39
+ label: entry
40
+ } : entry), ...missing.map((locale) => ({ ...locale }))];
41
+ return {
42
+ ...localization,
43
+ locales
44
+ };
45
+ }
46
+ /** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
47
+ const ACTIVE_LOCALES_CACHE_MS = 6e4;
48
+ const cache = /* @__PURE__ */ new WeakMap();
49
+ /** The last answer read from the database, kept for when a later read fails. */
50
+ const lastGood = /* @__PURE__ */ new WeakMap();
51
+ /** After a failed read, how soon to try the database again. */
52
+ const ACTIVE_LOCALES_RETRY_MS = 5e3;
53
+ /** Drops the cached answer, so the next `activeLocales` reads again. */
54
+ function invalidateActiveLocales(payload) {
55
+ cache.delete(payload);
56
+ }
57
+ /**
58
+ * The ticked target languages, as the Translation screen stores them.
59
+ * `null` or absent (never saved) means the defaults: the target locales the
60
+ * site declared itself before the library's were added.
61
+ */
62
+ function resolveActiveTargets(stored, targets, defaults) {
63
+ const chosen = Array.isArray(stored) ? stored : defaults;
64
+ return targets.filter((code) => chosen.includes(code));
65
+ }
66
+ /**
67
+ * The site's active languages, for routing and middleware: the default
68
+ * locale plus each target language ticked on Settings → Translation. Cached
69
+ * per process for `ttlMs` (60s by default): a request reads memory, and the
70
+ * database is read only when the cache refreshes, or after a save of the
71
+ * screen in the same process. Never throws. When a read fails it answers
72
+ * with the last good read (or, before the first one, the defaults) and
73
+ * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
74
+ * never stands in for the Admin's ticks for a whole cache period, which
75
+ * would send a ticked language's visitors permanent redirects.
76
+ */
77
+ function activeLocales(payload, options = {}) {
78
+ const ttl = options.ttlMs ?? 6e4;
79
+ const hit = cache.get(payload);
80
+ if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;
81
+ const entry = {
82
+ at: Date.now(),
83
+ value: void 0
84
+ };
85
+ entry.value = readActiveLocales(payload).then((read) => {
86
+ if (read.ok) {
87
+ lastGood.set(payload, read.value);
88
+ return read.value;
89
+ }
90
+ entry.ttl = ACTIVE_LOCALES_RETRY_MS;
91
+ return lastGood.get(payload) ?? read.value;
92
+ });
93
+ cache.set(payload, entry);
94
+ return entry.value;
95
+ }
96
+ /** The slug `activeLocales` reads; the Translation screen's. */
97
+ const SETTINGS_SLUG = "translation-settings";
98
+ /** Where `applyTranslation` leaves the default ticks: the site's own target locales. */
99
+ const DEFAULT_ACTIVE_LOCALES = "bisonDefaultActiveLocales";
100
+ async function readActiveLocales(payload) {
101
+ const localization = payload.config.localization;
102
+ const codes = localization ? localization.locales.map(codeOf) : ["en"];
103
+ const defaultLocale = localization ? localization.defaultLocale : "en";
104
+ const targets = codes.filter((code) => code !== defaultLocale);
105
+ const defaults = payload.config.custom?.["bisonDefaultActiveLocales"] ?? targets;
106
+ let stored;
107
+ let ok = true;
108
+ try {
109
+ const doc = await payload.findGlobal({
110
+ slug: SETTINGS_SLUG,
111
+ depth: 0,
112
+ overrideAccess: true
113
+ });
114
+ stored = doc?.languagesChosen ? doc.languages ?? [] : void 0;
115
+ } catch {
116
+ stored = void 0;
117
+ ok = false;
118
+ }
119
+ const ticked = resolveActiveTargets(stored, targets, defaults);
120
+ return {
121
+ ok,
122
+ value: {
123
+ defaultLocale,
124
+ active: codes.filter((code) => code === defaultLocale || ticked.includes(code)),
125
+ inactive: targets.filter((code) => !ticked.includes(code))
126
+ }
127
+ };
128
+ }
129
+ /**
130
+ * Where a request for an inactive language goes: the same path without
131
+ * its locale prefix, for a 308. `null` when the path is not under an
132
+ * inactive locale. In a site's middleware:
133
+ *
134
+ * ```ts
135
+ * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
136
+ * if (to) {
137
+ * const response = NextResponse.redirect(new URL(to + url.search, url), 308);
138
+ * response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
139
+ * return response;
140
+ * }
141
+ * ```
142
+ */
143
+ function inactiveLocaleRedirect(pathname, locales) {
144
+ const [, first, ...rest] = pathname.split("/");
145
+ if (!first || !locales.inactive.includes(first)) return null;
146
+ return pathAfterPrefix(rest);
147
+ }
148
+ /**
149
+ * The path left once a locale prefix is taken off, from the segments after
150
+ * it. Always a path on this site: leading slashes and backslashes collapse
151
+ * to one "/", so "/es//evil.com" or "/es/\\evil.com" can never become a
152
+ * protocol-relative URL to another host.
153
+ */
154
+ function pathAfterPrefix(rest) {
155
+ return `/${rest.join("/").replace(/^[\\/]+/, "")}`;
156
+ }
157
+ /**
158
+ * A page's language alternates (for hreflang and a language switcher),
159
+ * keeping only active languages. `paths` maps each locale to that
160
+ * language's URL for the page.
161
+ */
162
+ function activeAlternates(paths, locales) {
163
+ return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));
164
+ }
165
+ /**
166
+ * A path in a language: the default language's unprefixed, every other one
167
+ * under its prefix (`/about` → `/es/about`, `/` → `/es`). For `pathFor` in
168
+ * `pageMetadata` and `pageSitemap`, and for a language switcher.
169
+ */
170
+ function localePath(path, locale, defaultLocale) {
171
+ const rooted = path.startsWith("/") ? path : `/${path}`;
172
+ if (locale === defaultLocale) return rooted;
173
+ if (rooted === "/" || rooted.startsWith("/?") || rooted.startsWith("/#")) return `/${locale}${rooted.slice(1)}`;
174
+ return `/${locale}${rooted}`;
175
+ }
176
+ //#endregion
177
+ export { LIBRARY_LOCALE_CODES as a, inactiveLocaleRedirect as c, pathAfterPrefix as d, resolveActiveTargets as f, LIBRARY_LOCALES as i, invalidateActiveLocales as l, DEFAULT_ACTIVE_LOCALES as n, activeAlternates as o, withLibraryLocales as p, LIBRARY_DEFAULT_LOCALE as r, activeLocales as s, ACTIVE_LOCALES_CACHE_MS as t, localePath as u };
178
+
179
+ //# sourceMappingURL=languages-B_iiWwxE.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"languages-B_iiWwxE.mjs","names":[],"sources":["../src/translate/languages.ts"],"sourcesContent":["import type { Config, Payload } from \"payload\";\n\n/**\n * The languages every Bison site carries. The library owns this list: a new\n * language is a library release that sites take by updating the package\n * (and running the migration it brings). The first entry is the default\n * locale of a site that declares no localization of its own.\n */\nexport const LIBRARY_LOCALES = [\n { code: \"en\", label: \"English\" },\n { code: \"es\", label: \"Español\" },\n] as const;\n\nexport type LibraryLocaleCode = (typeof LIBRARY_LOCALES)[number][\"code\"];\n\nexport const LIBRARY_DEFAULT_LOCALE: LibraryLocaleCode = \"en\";\n\n/** The codes of `LIBRARY_LOCALES`, in order. */\nexport const LIBRARY_LOCALE_CODES: readonly string[] = LIBRARY_LOCALES.map((locale) => locale.code);\n\ntype LocaleEntry = string | { code: string; label?: unknown };\n\nfunction codeOf(entry: LocaleEntry): string {\n return typeof entry === \"string\" ? entry : entry.code;\n}\n\n/**\n * A config's `localization` with every library language in it. A site with\n * none gets the library's (English default, `fallback: true`, so an empty\n * Spanish field reads as English). A site with its own keeps its locales,\n * labels and default, and gains any library language it lacks.\n */\nexport function withLibraryLocales(\n localization: Config[\"localization\"],\n): Exclude<Config[\"localization\"], false | undefined> {\n if (!localization) {\n return {\n locales: LIBRARY_LOCALES.map((locale) => ({ ...locale })),\n defaultLocale: LIBRARY_DEFAULT_LOCALE,\n fallback: true,\n };\n }\n const own = localization.locales as LocaleEntry[];\n const have = new Set(own.map(codeOf));\n const missing = LIBRARY_LOCALES.filter((locale) => !have.has(locale.code));\n if (missing.length === 0) return localization;\n // Payload reads the list as strings or as objects by its first entry, so\n // the result is all objects: a string entry becomes `{ code, label: code }`.\n const locales = [\n ...own.map((entry) => (typeof entry === \"string\" ? { code: entry, label: entry } : entry)),\n ...missing.map((locale) => ({ ...locale })),\n ];\n return { ...localization, locales: locales as never[] };\n}\n\n// ---------------------------------------------------------------------------\n// Which target languages are switched on\n\n/** What `activeLocales` answers. */\nexport interface ActiveLocales {\n /** The default (source) locale. Always active. */\n defaultLocale: string;\n /** The default locale and every ticked target locale, in config order. */\n active: string[];\n /** Target locales that are not ticked: no translation, no URL, no switcher entry, no hreflang. */\n inactive: string[];\n}\n\n/** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */\nexport const ACTIVE_LOCALES_CACHE_MS = 60_000;\n\ntype SettingsReader = Pick<Payload, \"findGlobal\" | \"config\">;\n\nconst cache = new WeakMap<object, { at: number; ttl?: number; value: Promise<ActiveLocales> }>();\n\n/** The last answer read from the database, kept for when a later read fails. */\nconst lastGood = new WeakMap<object, ActiveLocales>();\n\n/** After a failed read, how soon to try the database again. */\nexport const ACTIVE_LOCALES_RETRY_MS = 5_000;\n\n/** Drops the cached answer, so the next `activeLocales` reads again. */\nexport function invalidateActiveLocales(payload: object): void {\n cache.delete(payload);\n}\n\n/**\n * The ticked target languages, as the Translation screen stores them.\n * `null` or absent (never saved) means the defaults: the target locales the\n * site declared itself before the library's were added.\n */\nexport function resolveActiveTargets(\n stored: readonly string[] | null | undefined,\n targets: readonly string[],\n defaults: readonly string[],\n): string[] {\n const chosen = Array.isArray(stored) ? stored : defaults;\n return targets.filter((code) => chosen.includes(code));\n}\n\n/**\n * The site's active languages, for routing and middleware: the default\n * locale plus each target language ticked on Settings → Translation. Cached\n * per process for `ttlMs` (60s by default): a request reads memory, and the\n * database is read only when the cache refreshes, or after a save of the\n * screen in the same process. Never throws. When a read fails it answers\n * with the last good read (or, before the first one, the defaults) and\n * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout\n * never stands in for the Admin's ticks for a whole cache period, which\n * would send a ticked language's visitors permanent redirects.\n */\nexport function activeLocales(payload: SettingsReader, options: { ttlMs?: number } = {}): Promise<ActiveLocales> {\n const ttl = options.ttlMs ?? ACTIVE_LOCALES_CACHE_MS;\n const hit = cache.get(payload);\n if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;\n const entry: { at: number; ttl?: number; value: Promise<ActiveLocales> } = { at: Date.now(), value: undefined as never };\n entry.value = readActiveLocales(payload).then((read) => {\n if (read.ok) {\n lastGood.set(payload, read.value);\n return read.value;\n }\n entry.ttl = ACTIVE_LOCALES_RETRY_MS;\n return lastGood.get(payload) ?? read.value;\n });\n cache.set(payload, entry);\n return entry.value;\n}\n\n/** The slug `activeLocales` reads; the Translation screen's. */\nconst SETTINGS_SLUG = \"translation-settings\";\n\n/** Where `applyTranslation` leaves the default ticks: the site's own target locales. */\nexport const DEFAULT_ACTIVE_LOCALES = \"bisonDefaultActiveLocales\";\n\nasync function readActiveLocales(payload: SettingsReader): Promise<{ ok: boolean; value: ActiveLocales }> {\n const localization = payload.config.localization;\n const codes = localization ? (localization.locales as LocaleEntry[]).map(codeOf) : [LIBRARY_DEFAULT_LOCALE];\n const defaultLocale = localization ? localization.defaultLocale : LIBRARY_DEFAULT_LOCALE;\n const targets = codes.filter((code) => code !== defaultLocale);\n const defaults = ((payload.config.custom as Record<string, unknown> | undefined)?.[DEFAULT_ACTIVE_LOCALES] ??\n targets) as string[];\n let stored: string[] | null | undefined;\n let ok = true;\n try {\n const doc = (await payload.findGlobal({ slug: SETTINGS_SLUG as never, depth: 0, overrideAccess: true })) as {\n languages?: string[] | null;\n languagesChosen?: boolean | null;\n };\n stored = doc?.languagesChosen ? (doc.languages ?? []) : undefined;\n } catch {\n stored = undefined;\n ok = false;\n }\n const ticked = resolveActiveTargets(stored, targets, defaults);\n return {\n ok,\n value: {\n defaultLocale,\n active: codes.filter((code) => code === defaultLocale || ticked.includes(code)),\n inactive: targets.filter((code) => !ticked.includes(code)),\n },\n };\n}\n\n/**\n * Where a request for an inactive language goes: the same path without\n * its locale prefix, for a 308. `null` when the path is not under an\n * inactive locale. In a site's middleware:\n *\n * ```ts\n * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));\n * if (to) {\n * const response = NextResponse.redirect(new URL(to + url.search, url), 308);\n * response.headers.set(\"Cache-Control\", \"no-store\"); // so ticking the language again works for these visitors\n * return response;\n * }\n * ```\n */\nexport function inactiveLocaleRedirect(\n pathname: string,\n locales: Pick<ActiveLocales, \"inactive\" | \"defaultLocale\">,\n): string | null {\n const [, first, ...rest] = pathname.split(\"/\");\n if (!first || !locales.inactive.includes(first)) return null;\n return pathAfterPrefix(rest);\n}\n\n/**\n * The path left once a locale prefix is taken off, from the segments after\n * it. Always a path on this site: leading slashes and backslashes collapse\n * to one \"/\", so \"/es//evil.com\" or \"/es/\\\\evil.com\" can never become a\n * protocol-relative URL to another host.\n */\nexport function pathAfterPrefix(rest: readonly string[]): string {\n return `/${rest.join(\"/\").replace(/^[\\\\/]+/, \"\")}`;\n}\n\n/**\n * A page's language alternates (for hreflang and a language switcher),\n * keeping only active languages. `paths` maps each locale to that\n * language's URL for the page.\n */\nexport function activeAlternates(\n paths: Readonly<Record<string, string>>,\n locales: Pick<ActiveLocales, \"active\">,\n): Record<string, string> {\n return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));\n}\n\n/**\n * A path in a language: the default language's unprefixed, every other one\n * under its prefix (`/about` → `/es/about`, `/` → `/es`). For `pathFor` in\n * `pageMetadata` and `pageSitemap`, and for a language switcher.\n */\nexport function localePath(\n path: string,\n locale: string,\n defaultLocale: string,\n): string {\n const rooted = path.startsWith(\"/\") ? path : `/${path}`;\n if (locale === defaultLocale) return rooted;\n if (rooted === \"/\" || rooted.startsWith(\"/?\") || rooted.startsWith(\"/#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C3D;EACF;;;;;;;;;;;;;;;;AAiBH,SAAgB,uBACd,UACA,SACe;CACf,MAAM,GAAG,OAAO,GAAG,QAAQ,SAAS,MAAM,IAAI;AAC9C,KAAI,CAAC,SAAS,CAAC,QAAQ,SAAS,SAAS,MAAM,CAAE,QAAO;AACxD,QAAO,gBAAgB,KAAK;;;;;;;;AAS9B,SAAgB,gBAAgB,MAAiC;AAC/D,QAAO,IAAI,KAAK,KAAK,IAAI,CAAC,QAAQ,WAAW,GAAG;;;;;;;AAQlD,SAAgB,iBACd,OACA,SACwB;AACxB,QAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC,QAAQ,CAAC,UAAU,QAAQ,OAAO,SAAS,KAAK,CAAC,CAAC;;;;;;;AAQpG,SAAgB,WACd,MACA,QACA,eACQ;CACR,MAAM,SAAS,KAAK,WAAW,IAAI,GAAG,OAAO,IAAI;AACjD,KAAI,WAAW,cAAe,QAAO;AACrC,KAAI,WAAW,OAAO,OAAO,WAAW,KAAK,IAAI,OAAO,WAAW,KAAK,CACtE,QAAO,IAAI,SAAS,OAAO,MAAM,EAAE;AACrC,QAAO,IAAI,SAAS"}
@@ -0,0 +1,86 @@
1
+ import { Config, Payload } from "payload";
2
+
3
+ //#region src/translate/languages.d.ts
4
+ /**
5
+ * The languages every Bison site carries. The library owns this list: a new
6
+ * language is a library release that sites take by updating the package
7
+ * (and running the migration it brings). The first entry is the default
8
+ * locale of a site that declares no localization of its own.
9
+ */
10
+ declare const LIBRARY_LOCALES: readonly [{
11
+ readonly code: "en";
12
+ readonly label: "English";
13
+ }, {
14
+ readonly code: "es";
15
+ readonly label: "Español";
16
+ }];
17
+ type LibraryLocaleCode = (typeof LIBRARY_LOCALES)[number]["code"];
18
+ declare const LIBRARY_DEFAULT_LOCALE: LibraryLocaleCode;
19
+ /** The codes of `LIBRARY_LOCALES`, in order. */
20
+ declare const LIBRARY_LOCALE_CODES: readonly string[];
21
+ /**
22
+ * A config's `localization` with every library language in it. A site with
23
+ * none gets the library's (English default, `fallback: true`, so an empty
24
+ * Spanish field reads as English). A site with its own keeps its locales,
25
+ * labels and default, and gains any library language it lacks.
26
+ */
27
+ declare function withLibraryLocales(localization: Config["localization"]): Exclude<Config["localization"], false | undefined>;
28
+ /** What `activeLocales` answers. */
29
+ interface ActiveLocales {
30
+ /** The default (source) locale. Always active. */
31
+ defaultLocale: string;
32
+ /** The default locale and every ticked target locale, in config order. */
33
+ active: string[];
34
+ /** Target locales that are not ticked: no translation, no URL, no switcher entry, no hreflang. */
35
+ inactive: string[];
36
+ }
37
+ /** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
38
+ declare const ACTIVE_LOCALES_CACHE_MS = 60000;
39
+ type SettingsReader = Pick<Payload, "findGlobal" | "config">;
40
+ /** After a failed read, how soon to try the database again. */
41
+ /** Drops the cached answer, so the next `activeLocales` reads again. */
42
+ declare function invalidateActiveLocales(payload: object): void;
43
+ /**
44
+ * The site's active languages, for routing and middleware: the default
45
+ * locale plus each target language ticked on Settings → Translation. Cached
46
+ * per process for `ttlMs` (60s by default): a request reads memory, and the
47
+ * database is read only when the cache refreshes, or after a save of the
48
+ * screen in the same process. Never throws. When a read fails it answers
49
+ * with the last good read (or, before the first one, the defaults) and
50
+ * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
51
+ * never stands in for the Admin's ticks for a whole cache period, which
52
+ * would send a ticked language's visitors permanent redirects.
53
+ */
54
+ declare function activeLocales(payload: SettingsReader, options?: {
55
+ ttlMs?: number;
56
+ }): Promise<ActiveLocales>;
57
+ /**
58
+ * Where a request for an inactive language goes: the same path without
59
+ * its locale prefix, for a 308. `null` when the path is not under an
60
+ * inactive locale. In a site's middleware:
61
+ *
62
+ * ```ts
63
+ * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
64
+ * if (to) {
65
+ * const response = NextResponse.redirect(new URL(to + url.search, url), 308);
66
+ * response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
67
+ * return response;
68
+ * }
69
+ * ```
70
+ */
71
+ declare function inactiveLocaleRedirect(pathname: string, locales: Pick<ActiveLocales, "inactive" | "defaultLocale">): string | null;
72
+ /**
73
+ * A page's language alternates (for hreflang and a language switcher),
74
+ * keeping only active languages. `paths` maps each locale to that
75
+ * language's URL for the page.
76
+ */
77
+ declare function activeAlternates(paths: Readonly<Record<string, string>>, locales: Pick<ActiveLocales, "active">): Record<string, string>;
78
+ /**
79
+ * A path in a language: the default language's unprefixed, every other one
80
+ * under its prefix (`/about` → `/es/about`, `/` → `/es`). For `pathFor` in
81
+ * `pageMetadata` and `pageSitemap`, and for a language switcher.
82
+ */
83
+ declare function localePath(path: string, locale: string, defaultLocale: string): string;
84
+ //#endregion
85
+ export { LIBRARY_LOCALE_CODES as a, activeLocales as c, localePath as d, withLibraryLocales as f, LIBRARY_LOCALES as i, inactiveLocaleRedirect as l, ActiveLocales as n, LibraryLocaleCode as o, LIBRARY_DEFAULT_LOCALE as r, activeAlternates as s, ACTIVE_LOCALES_CACHE_MS as t, invalidateActiveLocales as u };
86
+ //# sourceMappingURL=languages-cDe9Lznx.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"languages-cDe9Lznx.d.mts","names":[],"sources":["../src/translate/languages.ts"],"mappings":";;;;;AAQA;;;;cAAa,eAAA;EAAA;;;;;;KAKD,iBAAA,WAA4B,eAAA;AAAA,cAE3B,sBAAA,EAAwB,iBAAA;;cAGxB,oBAAA;AAHb;;;;;AAGA;AAHA,iBAiBgB,kBAAA,CACd,YAAA,EAAc,MAAA,mBACb,OAAA,CAAQ,MAAA;;UAyBM,aAAA;EAzCkF;EA2CjG,aAAA;EA7BgC;EA+BhC,MAAA;EA9Bc;EAgCd,QAAA;AAAA;;cAIW,uBAAA;AAAA,KAER,cAAA,GAAiB,IAAA,CAAK,OAAA;;;iBAWX,uBAAA,CAAwB,OAAA;;;;;AAbxC;;;;;AAA8C;;iBA0C9B,aAAA,CAAc,OAAA,EAAS,cAAA,EAAgB,OAAA;EAAW,KAAA;AAAA,IAAwB,OAAA,CAAQ,aAAA;;;;AAAlG;;;;;;;;;;;iBAmEgB,sBAAA,CACd,QAAA,UACA,OAAA,EAAS,IAAA,CAAK,aAAA;;;;;;iBAsBA,gBAAA,CACd,KAAA,EAAO,QAAA,CAAS,MAAA,mBAChB,OAAA,EAAS,IAAA,CAAK,aAAA,cACb,MAAA;;AAHH;;;;iBAYgB,UAAA,CACd,IAAA,UACA,MAAA,UACA,aAAA"}
@@ -13,4 +13,4 @@ interface LocaleRead {
13
13
  }
14
14
  //#endregion
15
15
  export { LocaleRead as t };
16
- //# sourceMappingURL=locale-tnKLkutC.d.mts.map
16
+ //# sourceMappingURL=locale-CTT3nn6T.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"locale-CTT3nn6T.d.mts","names":[],"sources":["../src/locale.ts"],"mappings":";;AAQA;;;;;;;UAAiB,UAAA;EACf,MAAA;EACA,cAAA;AAAA"}
@@ -9,4 +9,4 @@ function localeArgs({ locale, fallbackLocale } = {}) {
9
9
  //#endregion
10
10
  export { localeArgs as t };
11
11
 
12
- //# sourceMappingURL=locale-B6rUVwpg.mjs.map
12
+ //# sourceMappingURL=locale-DaEJ1d2O.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"locale-B6rUVwpg.mjs","names":[],"sources":["../src/locale.ts"],"sourcesContent":["/**\n * Which locale a read returns, as Payload's Local API takes it. Pass the\n * request's locale (every site carries the library's languages), or a\n * Spanish page renders the default locale's copy; omitted reads the\n * default locale.\n * `fallbackLocale: false` returns empty where the locale has no value\n * instead of the default locale's.\n */\nexport interface LocaleRead {\n locale?: string;\n fallbackLocale?: string | false;\n}\n\n/** The `locale` / `fallbackLocale` arguments to spread into a read, only when set. */\nexport function localeArgs({ locale, fallbackLocale }: LocaleRead = {}): LocaleRead {\n return {\n ...(locale !== undefined ? { locale } : {}),\n ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),\n };\n}\n"],"mappings":";;AAcA,SAAgB,WAAW,EAAE,QAAQ,mBAA+B,EAAE,EAAc;AAClF,QAAO;EACL,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,GAAG,EAAE;EAC1C,GAAI,mBAAmB,KAAA,IAAY,EAAE,gBAAgB,GAAG,EAAE;EAC3D"}
1
+ {"version":3,"file":"locale-DaEJ1d2O.mjs","names":[],"sources":["../src/locale.ts"],"sourcesContent":["/**\n * Which locale a read returns, as Payload's Local API takes it. Pass the\n * request's locale (every site carries the library's languages), or a\n * Spanish page renders the default locale's copy; omitted reads the\n * default locale.\n * `fallbackLocale: false` returns empty where the locale has no value\n * instead of the default locale's.\n */\nexport interface LocaleRead {\n locale?: string;\n fallbackLocale?: string | false;\n}\n\n/** The `locale` / `fallbackLocale` arguments to spread into a read, only when set. */\nexport function localeArgs({ locale, fallbackLocale }: LocaleRead = {}): LocaleRead {\n return {\n ...(locale !== undefined ? { locale } : {}),\n ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),\n };\n}\n"],"mappings":";;AAcA,SAAgB,WAAW,EAAE,QAAQ,mBAA+B,EAAE,EAAc;AAClF,QAAO;EACL,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,GAAG,EAAE;EAC1C,GAAI,mBAAmB,KAAA,IAAY,EAAE,gBAAgB,GAAG,EAAE;EAC3D"}
@@ -0,0 +1,129 @@
1
+ import { t as REDIRECTS_SLUG } from "./lookup-uyEKHlLX.mjs";
2
+ import { a as LIBRARY_LOCALE_CODES, c as activeLocales, d as localePath, l as inactiveLocaleRedirect, n as ActiveLocales, r as LIBRARY_DEFAULT_LOCALE, s as activeAlternates, t as ACTIVE_LOCALES_CACHE_MS, u as invalidateActiveLocales } from "./languages-cDe9Lznx.mjs";
3
+ import { Payload } from "payload";
4
+ import { NextRequest, NextResponse } from "next/server";
5
+
6
+ //#region src/locale-routing.d.ts
7
+ /**
8
+ * The request header `localeProxy` passes the language in. It is set (or
9
+ * removed) on every request the proxy sees, so a value a visitor sends
10
+ * never reaches the page.
11
+ */
12
+ declare const LOCALE_HEADER = "x-bison-locale";
13
+ /** What a request needs from the live list. */
14
+ type LocaleSet = Pick<ActiveLocales, "defaultLocale" | "active" | "inactive">;
15
+ interface LocaleRoutingOptions {
16
+ /**
17
+ * Paths the helper leaves alone, on top of its own (`/admin`, `/api`,
18
+ * `/_next`, `/_vercel`, and a file outside a language prefix). Called
19
+ * with the request's path, and with the path after a live language's
20
+ * prefix.
21
+ */
22
+ skip?: (pathname: string) => boolean;
23
+ }
24
+ /**
25
+ * What to do with a request:
26
+ * - `skip`: not a page (admin, API, a file); pass it through untouched.
27
+ * - `serve`: an unprefixed URL, in the default language.
28
+ * - `rewrite`: a live language's URL; serve `pathname` (the site's existing
29
+ * route) in `locale`.
30
+ * - `redirect`: 308 to `pathname`: an unticked language's URL to the default
31
+ * language's page, the default language's own prefix to its unprefixed
32
+ * URL, or a prefix in the wrong case to the language's own spelling.
33
+ */
34
+ type LocaleRoute = {
35
+ action: "skip";
36
+ } | {
37
+ action: "serve";
38
+ locale: string;
39
+ pathname: string;
40
+ } | {
41
+ action: "rewrite";
42
+ locale: string;
43
+ pathname: string;
44
+ } | {
45
+ action: "redirect";
46
+ pathname: string;
47
+ };
48
+ /**
49
+ * The routing decision for a path, from the live list. Pure, so a site can
50
+ * run its own lookup (a Redirects row in the request's language) on the
51
+ * same answer before `localeProxy` builds the response. Every path under a
52
+ * language's prefix is handled, files included; a file anywhere else is
53
+ * skipped.
54
+ */
55
+ declare function routeLocale(pathname: string, locales: LocaleSet, options?: LocaleRoutingOptions): LocaleRoute;
56
+ /**
57
+ * The proxy helper a site calls once, from `proxy.ts` (Next 16) or
58
+ * `middleware.ts`, after any lookup of its own:
59
+ *
60
+ * ```ts
61
+ * return localeProxy(request, async () => activeLocales(await getPayload({ config })));
62
+ * ```
63
+ *
64
+ * The default language stays unprefixed. A live language's prefix is
65
+ * rewritten to the site's existing routes, the language passed in
66
+ * `LOCALE_HEADER` for `getRequestLocale`. An unticked language's prefix
67
+ * 308s to the default language's page, uncached, so ticking it again
68
+ * reaches every visitor. `locales` is the live list or a function that
69
+ * reads it, which is not called for a path the helper skips.
70
+ */
71
+ declare function localeProxy(request: NextRequest, locales: LocaleSet | (() => LocaleSet | Promise<LocaleSet>), options?: LocaleRoutingOptions): Promise<NextResponse>;
72
+ /**
73
+ * The request's language from the header `localeProxy` set. The default
74
+ * language when it is missing, or not in `locales.active` (the library's
75
+ * languages when no list is given). Pass the live list on a site with
76
+ * languages of its own.
77
+ */
78
+ declare function localeFromHeaders(headers: Pick<Headers, "get">, locales?: Pick<LocaleSet, "defaultLocale" | "active">): string;
79
+ /**
80
+ * The request's language, for a Server Component, `generateMetadata` or a
81
+ * route handler. Pass it to the readers (`getNavigation`,
82
+ * `getPublishedIdentity`, a page read) as `locale`. Reading request headers
83
+ * makes the route render per request, which a page served in more than
84
+ * one language at one route needs.
85
+ */
86
+ declare function getRequestLocale(locales?: Pick<LocaleSet, "defaultLocale" | "active">): Promise<string>;
87
+ interface MatchRedirectOptions extends LocaleRoutingOptions {
88
+ /** The site's Payload, or anything with its `find`. Read only for a path that could match. */
89
+ payload: Pick<Payload, "find">;
90
+ /** The request's path (`request.nextUrl.pathname`). */
91
+ pathname: string;
92
+ /** The request's query string (`request.nextUrl.search`), kept on the redirect when the row's destination has none. */
93
+ search?: string;
94
+ /** The live list, the same one `localeProxy` is given. */
95
+ locales: LocaleSet;
96
+ /**
97
+ * The site's reserved-slug predicate, the one `createPages` and
98
+ * `createRedirects` take. A path that is reserved, before or after its
99
+ * language prefix, is never redirected, whatever row exists.
100
+ */
101
+ isReservedSlug?: (slug: string) => boolean;
102
+ /** The site's page path, for a site whose pages are not at `/<slug>`. Answer null for a page a visitor cannot open. */
103
+ pagePath?: (page: unknown) => string | null;
104
+ /** The site's origin, so a row's absolute URL on this site still counts. */
105
+ origin?: string;
106
+ }
107
+ /**
108
+ * The Redirects row for a request, in the request's language, as the
109
+ * `Location` of a 308; null when no row answers. Call it in the site's proxy
110
+ * before `localeProxy`, with the same live list:
111
+ *
112
+ * ```ts
113
+ * const locales = await activeLocales(payload);
114
+ * const redirect = await matchRedirect({ payload, pathname, search, locales, isReservedSlug });
115
+ * if (redirect) return NextResponse.redirect(new URL(redirect.location, request.url), 308);
116
+ * return localeProxy(request, locales);
117
+ * ```
118
+ *
119
+ * A page reference resolves to the page's path in the visitor's language. A
120
+ * row in a language that is not ticked never answers. Every destination is a
121
+ * path on this site. A failed read answers null, so a database outage never
122
+ * turns into an error page.
123
+ */
124
+ declare function matchRedirect(options: MatchRedirectOptions): Promise<{
125
+ location: string;
126
+ } | null>;
127
+ //#endregion
128
+ export { ACTIVE_LOCALES_CACHE_MS, type ActiveLocales, LIBRARY_DEFAULT_LOCALE, LIBRARY_LOCALE_CODES, LOCALE_HEADER, LocaleRoute, LocaleRoutingOptions, LocaleSet, MatchRedirectOptions, REDIRECTS_SLUG, activeAlternates, activeLocales, getRequestLocale, inactiveLocaleRedirect, invalidateActiveLocales, localeFromHeaders, localePath, localeProxy, matchRedirect, routeLocale };
129
+ //# sourceMappingURL=locale-routing.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"locale-routing.d.mts","names":[],"sources":["../src/locale-routing.ts"],"mappings":";;;;;;;AAuDA;;;;cAAa,aAAA;AAGb;AAAA,KAAY,SAAA,GAAY,IAAA,CACtB,aAAA;AAAA,UAIe,oBAAA;EALO;;AAKxB;;;;EAOE,IAAA,IAAQ,QAAA;AAAA;;;;;;;;;;;KAaE,WAAA;EACN,MAAA;AAAA;EACA,MAAA;EAAiB,MAAA;EAAgB,QAAA;AAAA;EACjC,MAAA;EAAmB,MAAA;EAAgB,QAAA;AAAA;EACnC,MAAA;EAAoB,QAAA;AAAA;;;;;;;AAyE1B;iBA7CgB,WAAA,CACd,QAAA,UACA,OAAA,EAAS,SAAA,EACT,OAAA,GAAS,oBAAA,GACR,WAAA;;;;;;;;;;;;;;;;iBAyCmB,WAAA,CACpB,OAAA,EAAS,WAAA,EACT,OAAA,EAAS,SAAA,UAAmB,SAAA,GAAY,OAAA,CAAQ,SAAA,IAChD,OAAA,GAAS,oBAAA,GACR,OAAA,CAAQ,YAAA;;;;;;;iBA+CK,iBAAA,CACd,OAAA,EAAS,IAAA,CAAK,OAAA,UACd,OAAA,GAAU,IAAA,CAAK,SAAA;;AAFjB;;;;;;iBAiBsB,gBAAA,CACpB,OAAA,GAAU,IAAA,CAAK,SAAA,gCACd,OAAA;AAAA,UAOc,oBAAA,SAA6B,oBAAA;EAxB9B;EA0Bd,OAAA,EAAS,IAAA,CAAK,OAAA;EA3BA;EA6Bd,QAAA;EA5BU;EA8BV,MAAA;EA9BA;EAgCA,OAAA,EAAS,SAAA;EAhC4C;AAevD;;;;EAuBE,cAAA,IAAkB,IAAA;EArBjB;EAuBD,QAAA,IAAY,IAAA;EAvBJ;EAyBR,MAAA;AAAA;;;;;AAlBF;;;;;;;;;;;;;iBAsFsB,aAAA,CAAc,OAAA,EAAS,oBAAA,GAAuB,OAAA;EAAU,QAAA;AAAA"}