@symbo.ls/brender 3.14.662 → 3.14.663

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/render.js CHANGED
@@ -10,6 +10,7 @@ import { extractMetadata, generateHeadHtml } from './metadata.js'
10
10
  import { hydrate } from './hydrate.js'
11
11
  import { composeIntoShell } from './shell.js'
12
12
  import { prefetchPageData, injectPrefetchedState, fetchSSRTranslations } from './prefetch.js'
13
+ import { createEarlySeedScript } from '@symbo.ls/fetch'
13
14
 
14
15
  // funcql plugin — enables evaluation of funcql schemas as property values
15
16
  // during SSR. Async-imported to avoid polluting non-funcql codepaths.
@@ -111,19 +112,6 @@ const structuredCloneDeep = (obj, seen = new WeakMap()) => {
111
112
  return clone
112
113
  }
113
114
 
114
- // JSON replacer that drops functions, circular refs, and non-serializable values
115
- const safeJsonReplacer = () => {
116
- const seen = new WeakSet()
117
- return (key, value) => {
118
- if (typeof value === 'function') return undefined
119
- if (typeof value === 'object' && value !== null) {
120
- if (seen.has(value)) return undefined
121
- seen.add(value)
122
- }
123
- return value
124
- }
125
- }
126
-
127
115
  // ── Workspace detection ──────────────────────────────────────────────────────
128
116
  // Detect whether brender is running inside the monorepo or as an installed
129
117
  // npm package, and resolve paths accordingly.
@@ -678,6 +666,116 @@ const buildPathRegistry = (element, path = '') => {
678
666
  * @param {object} [options.context] - Additional context overrides
679
667
  * @returns {Promise<{ html: string, metadata: object, registry: object, element: object }>}
680
668
  */
669
+ // ── In-flight request tracking (the post-create flush) ──────────────────────
670
+ // The render's flush waits for the requests a page starts while it renders
671
+ // (fetch plugin, SDK, project code — all end in globalThis.fetch). One
672
+ // counting wrapper is installed around whatever globalThis.fetch is at render
673
+ // time and left in place: it returns the inner call's own promise untouched,
674
+ // and re-installing per render would nest wrappers across concurrent renders
675
+ // in one isolate. A host that swaps globalThis.fetch later gets wrapped again
676
+ // on its next render. The count is process-wide — a concurrent render's
677
+ // request can only make a flush wait longer, never cut one short, and the
678
+ // flush is capped.
679
+ let _inFlight = 0
680
+ const FETCH_TRACKED = Symbol.for('brender.fetchTracked')
681
+ const inFlightRequests = () => _inFlight
682
+ // ── Recorded answers (the fetch seed, phase B) ──────────────────────────────
683
+ // While exactly ONE render is running, the anonymous GETs it makes are
684
+ // recorded — url, Accept-Language, status, content type, body — so the page
685
+ // can carry them (@symbo.ls/fetch createEarlySeedScript) and the hydrating
686
+ // client adopts them instead of asking again. A second render overlapping
687
+ // in the same isolate taints the recording: another project's answers must
688
+ // never land in this page, so an overlapped render carries none.
689
+ // Only a GET whose headers are Accept-Language / Accept at most is recorded
690
+ // (never a signed-in or keyed call), only an ok JSON or text answer, at most
691
+ // SEED_ENTRY_MAX bytes each and SEED_TOTAL_MAX per page.
692
+ const SEED_ENTRY_MAX = 256 * 1024
693
+ const SEED_TOTAL_MAX = 1024 * 1024
694
+ const SEED_HEADERS_OK = new Set(['accept-language', 'accept'])
695
+ let _activeRenders = 0
696
+ let _seed = null
697
+
698
+ const requestShape = (args) => {
699
+ const [input, init] = args
700
+ const isRequest = input && typeof input === 'object' && typeof input.url === 'string'
701
+ const url = isRequest ? input.url : String(input)
702
+ const method = String((init && init.method) || (isRequest && input.method) || 'GET').toUpperCase()
703
+ const headers = {}
704
+ const add = (h) => {
705
+ if (!h) return
706
+ if (typeof h.forEach === 'function' && !Array.isArray(h)) h.forEach((v, k) => { headers[String(k).toLowerCase()] = String(v) })
707
+ else if (Array.isArray(h)) for (const [k, v] of h) headers[String(k).toLowerCase()] = String(v)
708
+ else for (const k in h) if (h[k] != null) headers[k.toLowerCase()] = String(h[k])
709
+ }
710
+ if (isRequest) add(input.headers)
711
+ if (init) add(init.headers)
712
+ return { url, method, headers }
713
+ }
714
+
715
+ const recordAnswer = (seed, shape, response, track) => {
716
+ if (!response || !response.ok || typeof response.clone !== 'function') return
717
+ const type = (response.headers && response.headers.get && response.headers.get('content-type')) || ''
718
+ if (!/json|^text\//i.test(type)) return
719
+ let copy
720
+ try { copy = response.clone() } catch { return }
721
+ track(copy.text().then((body) => {
722
+ if (seed.tainted || body.length > SEED_ENTRY_MAX || seed.bytes + body.length > SEED_TOTAL_MAX) return
723
+ seed.bytes += body.length
724
+ seed.entries.push({ url: shape.url, lang: shape.headers['accept-language'] || '', status: response.status, type, body })
725
+ }, () => {}))
726
+ }
727
+
728
+ const trackFetches = () => {
729
+ const inner = globalThis.fetch
730
+ if (typeof inner !== 'function' || inner[FETCH_TRACKED]) return
731
+ const tracked = function (...args) {
732
+ _inFlight++
733
+ let settled = false
734
+ const done = () => { if (!settled) { settled = true; _inFlight-- } }
735
+ // a pending body read counts as in flight: the flush waits for it too
736
+ const track = (promise) => { _inFlight++; promise.then(() => { _inFlight-- }, () => { _inFlight-- }) }
737
+ const seed = _seed && !_seed.tainted ? _seed : null
738
+ let shape = null
739
+ if (seed) {
740
+ try {
741
+ shape = requestShape(args)
742
+ if (shape.method !== 'GET' || !/^https?:/i.test(shape.url) ||
743
+ Object.keys(shape.headers).some((h) => !SEED_HEADERS_OK.has(h))) shape = null
744
+ } catch { shape = null }
745
+ }
746
+ let result
747
+ try {
748
+ result = inner.apply(this, args)
749
+ } catch (err) {
750
+ done()
751
+ throw err
752
+ }
753
+ if (result && typeof result.then === 'function') {
754
+ result.then((response) => {
755
+ if (shape) recordAnswer(seed, shape, response, track)
756
+ done()
757
+ }, done)
758
+ } else done()
759
+ return result
760
+ }
761
+ tracked[FETCH_TRACKED] = true
762
+ globalThis.fetch = tracked
763
+ }
764
+
765
+ // ── Opt-in hydration boot scripts (phase B) ────────────────────────────────
766
+ // What a page needs for the client to ADOPT the server DOM instead of
767
+ // replacing it (smbls createDomql hydrateRender): the element-path registry,
768
+ // the opt-in flag, and the recorded anonymous answers for the fetch plugin
769
+ // (@symbo.ls/fetch createEarlySeedScript). Default off everywhere — a page
770
+ // without these keeps the fresh client render.
771
+ // FW-BRENDER-HYDRATION-AND-CF-DEPLOY-PROVIDER-1.
772
+ export const adoptionScripts = ({ brRegistry, fetchSeed } = {}) => {
773
+ if (!brRegistry || !Object.keys(brRegistry).length) return ''
774
+ const registry = JSON.stringify(brRegistry).replace(/</g, '\\u003c')
775
+ return `<script>window.__BR_REGISTRY__=${registry};window.__BRENDER_HYDRATE__=true</script>` +
776
+ (fetchSeed && fetchSeed.length ? '\n' + createEarlySeedScript(fetchSeed) : '')
777
+ }
778
+
681
779
  export const render = async (data, options = {}) => {
682
780
  const { route = '/', pathname, state: stateOverrides, context: contextOverrides, prefetch = false } = options
683
781
  // pathname is the actual URL path (e.g. /podcast/abc-123), route is the page pattern (e.g. /podcast/:id)
@@ -773,7 +871,7 @@ export const render = async (data, options = {}) => {
773
871
  if (data.polyglot && !config.polyglot) config.polyglot = data.polyglot
774
872
  if (data.fetch && !config.fetch) config.fetch = data.fetch
775
873
  if (data.router && !config.router) config.router = data.router
776
- for (const k of ['useReset', 'useVariable', 'useFontImport', 'useIconSprite', 'useSvgSprite', 'useDefaultConfig', 'useDocumentTheme']) {
874
+ for (const k of SCRATCH_CONFIG_FLAGS) {
777
875
  if (data[k] != null && config[k] == null) config[k] = data[k]
778
876
  }
779
877
 
@@ -804,7 +902,25 @@ export const render = async (data, options = {}) => {
804
902
  // Reset the atomic CSS engine for this render pass
805
903
  resetCss()
806
904
 
905
+ // Every other top-level key of the payload, as the client gets it: the
906
+ // client boots with the WHOLE published payload as its context (mermaid
907
+ // bundle.js), so `globalScope` (frank's hoisted helpers behind `__scope.X`)
908
+ // and project-level context keys (`catalog`, `imageBase`, `siteUrl`, …)
909
+ // must be there on the server too — without them docs.symbols.app threw
910
+ // "__scope.isViewNavRoute is not a function" and shaker.ge read
911
+ // `this.context.catalog` as undefined (FW-BRENDER-HYDRATION-AND-CF-DEPLOY-
912
+ // PROVIDER-1). Cloned: a render must not write into a payload a multi-page
913
+ // build reuses. The explicit keys below still win.
914
+ const projectContext = {}
915
+ for (const key in data) {
916
+ if (key === 'app' || key === 'config' || key === 'pages' || key === 'components' ||
917
+ key === 'state' || key === 'snippets' || key === 'designSystem' || key === 'dependencies') continue
918
+ const value = data[key]
919
+ projectContext[key] = value && typeof value === 'object' ? structuredCloneDeep(value) : value
920
+ }
921
+
807
922
  const ctx = {
923
+ ...projectContext,
808
924
  state: baseState,
809
925
  ...(stateOverrides ? { state: { ...baseState, ...stateOverrides } } : {}),
810
926
  dependencies: structuredCloneDeep(data.dependencies || {}),
@@ -857,14 +973,42 @@ export const render = async (data, options = {}) => {
857
973
 
858
974
  resetKeys()
859
975
 
860
- const element = await createDomqlElement(app, ctx)
861
-
862
- // Allow async operations (fetch callbacks, state updates, re-renders) to flush.
863
- // DOMQL's fetch plugin fires on element creation and updates state asynchronously.
864
- // With prefetch enabled, data is pre-injected but DOMQL's fetch may also fire
865
- // and trigger state updates. Give enough time for these to complete.
866
- const flushDelay = prefetch ? 2000 : 50
867
- await new Promise(r => setTimeout(r, flushDelay))
976
+ trackFetches()
977
+ // the recording of this render's answers (see `_seed`): tainted the moment
978
+ // another render overlaps it
979
+ _activeRenders++
980
+ if (_activeRenders === 1) _seed = { entries: [], bytes: 0, tainted: false }
981
+ else if (_seed) _seed.tainted = true
982
+ const seed = _seed
983
+ let element
984
+ try {
985
+ element = await createDomqlElement(app, ctx)
986
+
987
+ // Allow async operations (fetch callbacks, state updates, re-renders) to flush.
988
+ // DOMQL's fetch plugin fires on element creation and updates state asynchronously.
989
+ // With prefetch enabled, data is pre-injected but DOMQL's fetch may also fire
990
+ // and trigger state updates. Give enough time for these to complete.
991
+ //
992
+ // It used to sleep a flat 2000 ms with prefetch — measured in workerd on
993
+ // six published projects, `flush` was 2000 ms on every route, 40–90 % of
994
+ // each platform pre-render. Now: a 50 ms quiet period, then — with
995
+ // prefetch — keep waiting while requests are in flight (the answers the
996
+ // flush exists for), each settled batch followed by another quiet period
997
+ // for the state updates and follow-up requests it triggers. The old
998
+ // 2000 ms stays the cap (FW-BRENDER-HYDRATION-AND-CF-DEPLOY-PROVIDER-1).
999
+ const flushStart = Date.now()
1000
+ const flushCap = prefetch ? 2000 : 50
1001
+ const sleep = (ms) => new Promise(r => setTimeout(r, ms))
1002
+ await sleep(Math.min(50, flushCap))
1003
+ while (prefetch && inFlightRequests() > 0 && Date.now() - flushStart < flushCap) {
1004
+ while (inFlightRequests() > 0 && Date.now() - flushStart < flushCap) await sleep(10)
1005
+ await sleep(Math.max(0, Math.min(50, flushCap - (Date.now() - flushStart))))
1006
+ }
1007
+ } finally {
1008
+ _activeRenders--
1009
+ if (_seed === seed) _seed = null
1010
+ }
1011
+ const fetchSeed = seed && !seed.tainted ? seed.entries.slice() : []
868
1012
 
869
1013
  // Assign data-br keys for hydration
870
1014
  assignKeys(body)
@@ -882,20 +1026,30 @@ export const render = async (data, options = {}) => {
882
1026
 
883
1027
  // Extract CSS from style tags in virtual head (atomic CSS engine writes here)
884
1028
  const emotionCSS = []
1029
+ const capturedRules = []
885
1030
  const head = document.head || document.querySelector('head')
886
1031
  if (head) {
887
1032
  for (const style of head.querySelectorAll('style')) {
888
1033
  if (style.sheet && style.sheet.cssRules) {
889
1034
  for (const rule of style.sheet.cssRules) {
890
- if (rule.cssText) emotionCSS.push(rule.cssText)
1035
+ if (rule.cssText) {
1036
+ emotionCSS.push(rule.cssText)
1037
+ capturedRules.push(rule)
1038
+ }
891
1039
  }
892
1040
  }
893
1041
  if (!emotionCSS.length) {
894
1042
  const content = style.textContent || ''
895
- if (content) emotionCSS.push(content)
1043
+ if (content) {
1044
+ emotionCSS.push(content)
1045
+ capturedRules.push({ cssText: content })
1046
+ }
896
1047
  }
897
1048
  }
898
1049
  }
1050
+ // globalCSS: the init-injected globals; classRules: everything else, in
1051
+ // capture order (see splitCapturedCSS).
1052
+ const { globalCSS, classRules } = splitCapturedCSS(capturedRules)
899
1053
 
900
1054
  let html = fixSvgContent(body.innerHTML)
901
1055
 
@@ -916,7 +1070,7 @@ export const render = async (data, options = {}) => {
916
1070
  if (_prevLoc !== undefined) globalThis.location = _prevLoc
917
1071
  else delete globalThis.location
918
1072
 
919
- return { html, metadata, registry, brRegistry, element, emotionCSS, document, window, ssrTranslations, prefetchedPages }
1073
+ return { html, metadata, registry, brRegistry, element, emotionCSS, globalCSS, classRules, fetchSeed, document, window, ssrTranslations, prefetchedPages }
920
1074
  }
921
1075
 
922
1076
  /**
@@ -990,46 +1144,18 @@ const fixSvgContent = (html) => {
990
1144
  )
991
1145
  }
992
1146
 
993
- // ── Global CSS generation ─────────────────────────────────────────────────────
994
-
995
- /**
996
- * Runs the scratch design-system pipeline (via esbuild bundling to work around
997
- * bare-import issues) to produce CSS variables and reset styles — the same
998
- * globals that the SPA runtime injects via emotion.injectGlobal.
999
- */
1000
- let _cachedGlobalCSS = null
1001
-
1002
1147
  // Frank serializes a project's `config.js` exports at the TOP LEVEL of the
1003
1148
  // data payload (not under `data.config`), so `globalTheme` / `themeStorageKey`
1004
1149
  // / `useReset` / etc. live alongside `components` / `pages` / `designSystem`.
1005
- // Both renderRoute and renderPage used to call `generateGlobalCSS(ds,
1006
- // data.config || data.settings)` which resolved to undefined for any project
1007
- // pushed through frank — every config flag silently dropped, including
1008
- // `globalTheme: 'light'`. The hardcoded `globalTheme: 'auto'` default in
1009
- // generateGlobalCSS then won, prod always rendered in matchMedia-detected
1010
- // theme regardless of what the project declared. Helper picks the config
1011
- // flags from `data` whichever shape they arrive in.
1150
+ // render() lifts these into the render context, as the client's context
1151
+ // carries them — the global CSS is captured from that render, so a project's
1152
+ // `globalTheme: 'light'` decides which scheme lands in the :root fallback.
1012
1153
  const SCRATCH_CONFIG_FLAGS = [
1013
1154
  'globalTheme', 'themeStorageKey', 'themeRoot',
1014
1155
  'useReset', 'useVariable', 'useFontImport', 'useIconSprite', 'useSvgSprite',
1015
1156
  'useDocumentTheme', 'useDefaultConfig', 'useDefaultIcons',
1016
1157
  'useThemeSuffixedVars', 'verbose', 'semanticIcons',
1017
1158
  ]
1018
- const pickProjectConfig = (data) => {
1019
- if (!data || typeof data !== 'object') return null
1020
- if (data.config && typeof data.config === 'object') return data.config
1021
- const out = {}
1022
- let any = false
1023
- for (const flag of SCRATCH_CONFIG_FLAGS) {
1024
- if (Object.prototype.hasOwnProperty.call(data, flag)) {
1025
- out[flag] = data[flag]
1026
- any = true
1027
- }
1028
- }
1029
- if (any) return out
1030
- return data.settings || null
1031
- }
1032
-
1033
1159
  // Serialise scratch `buildSkinVarStyles` output — `{ selector: { var: value },
1034
1160
  // '@media …': { selector: { var: value } } }` — as CSS text
1035
1161
  // (FW-SCRATCH-SKINS-DIMENSION-1).
@@ -1052,206 +1178,79 @@ export const skinRulesToCSS = (rules) => Object.entries(rules || {})
1052
1178
  .filter(Boolean)
1053
1179
  .join('\n\n')
1054
1180
 
1055
- const generateGlobalCSS = async (ds, config) => {
1056
- if (_cachedGlobalCSS) return _cachedGlobalCSS
1057
-
1058
- try {
1059
- const { existsSync, writeFileSync, unlinkSync } = await import('fs')
1060
- const { tmpdir } = await import('os')
1061
- const { randomBytes } = await import('crypto')
1062
-
1063
- // Guard: skip if filesystem APIs aren't available (e.g. CF Workers)
1064
- try { tmpdir() } catch { return {} }
1065
-
1066
- const esbuild = await import('esbuild')
1067
-
1068
- // Write a temporary script that imports scratch, runs set(), and
1069
- // serialises the CSS_VARS + RESET objects as JSON.
1070
- const dsJson = JSON.stringify(ds || {}, safeJsonReplacer())
1071
- // Config may contain non-serializable values (e.g. a DB client with
1072
- // circular refs, functions). Strip those for the CSS generation script.
1073
- const cfgJson = JSON.stringify(config || {}, safeJsonReplacer())
1074
- const tmpEntry = join(tmpdir(), `br_global_${randomBytes(6).toString('hex')}.mjs`)
1075
- const tmpOut = join(tmpdir(), `br_global_${randomBytes(6).toString('hex')}_out.mjs`)
1076
-
1077
- writeFileSync(tmpEntry, `
1078
- import { set, getActiveConfig, getFontFaceString } from '@symbo.ls/scratch'
1079
- // Namespace access for the skin builder: a scratch without it (version
1080
- // skew) gives an empty skin block instead of failing this whole bundle
1081
- // and, with it, every global rule.
1082
- import * as scratchNs from '@symbo.ls/scratch'
1083
- import { DEFAULT_CONFIG } from '@symbo.ls/default-config'
1084
-
1085
- const ds = ${dsJson}
1086
- const cfg = ${cfgJson}
1087
-
1088
- // Merge with defaults (same as initEmotion)
1089
- const merged = {}
1090
- for (const k in DEFAULT_CONFIG) merged[k] = DEFAULT_CONFIG[k]
1091
- for (const k in ds) {
1092
- if (typeof ds[k] === 'object' && !Array.isArray(ds[k]) && typeof merged[k] === 'object' && !Array.isArray(merged[k])) {
1093
- merged[k] = { ...merged[k], ...ds[k] }
1094
- } else {
1095
- merged[k] = ds[k]
1096
- }
1097
- }
1098
-
1099
- const conf = set({
1100
- useReset: true,
1101
- useVariable: true,
1102
- useFontImport: true,
1103
- useDocumentTheme: true,
1104
- useDefaultConfig: true,
1105
- globalTheme: 'auto',
1106
- ...merged,
1107
- ...cfg
1108
- }, { newConfig: {} })
1109
-
1110
- const result = {
1111
- CSS_VARS: conf.CSS_VARS || {},
1112
- CSS_MEDIA_VARS: conf.CSS_MEDIA_VARS || {},
1113
- // Skin rules — the same builder smbls init() injects on the client
1114
- // (FW-SCRATCH-SKINS-DIMENSION-1).
1115
- CSS_SKIN_RULES: typeof scratchNs.buildSkinVarStyles === 'function'
1116
- ? scratchNs.buildSkinVarStyles(conf.cssSkinVars, conf.cssSkinFallback, ':root')
1117
- : {},
1118
- reset: conf.reset || {},
1119
- animation: conf.animation || {}
1120
- }
1121
- // Export as globalThis so we can read it
1122
- globalThis.__BR_GLOBAL_CSS__ = result
1123
- export default result
1124
- `)
1125
-
1126
- // Detect workspace layout (monorepo vs npm install)
1127
- const ws = detectWorkspace()
1128
-
1129
- // Workspace resolve plugin: maps @symbo.ls/* and @symbo.ls/* to source paths
1130
- const workspacePlugin = {
1131
- name: 'workspace-resolve',
1132
- setup (build) {
1133
- build.onResolve({ filter: /^@symbo\.ls\// }, args => {
1134
- const pkg = args.path.replace('@symbo.ls/', '')
1135
- if (ws.isMonorepo) {
1136
- for (const dir of ['packages', 'plugins']) {
1137
- const src = resolve(ws.monorepoRoot, dir, pkg, 'src', 'index.js')
1138
- if (existsSync(src)) return { path: src }
1139
- const dist = resolve(ws.monorepoRoot, dir, pkg, 'index.js')
1140
- if (existsSync(dist)) return { path: dist }
1141
- }
1142
- const blank = resolve(ws.monorepoRoot, 'packages', 'default-config', 'blank', 'index.js')
1143
- if (pkg === 'default-config' && existsSync(blank)) return { path: blank }
1144
- }
1145
- // An npm install: no override — esbuild resolves the package's
1146
- // published `exports` (dist/esm). Forcing the root index.js here
1147
- // broke every npm consumer: published @symbo.ls/scratch and
1148
- // @symbo.ls/default-config ship a root index.js that re-exports
1149
- // ./src/… and ./designSystem/…, which their tarballs do not
1150
- // contain, so this bundle failed ("Could not resolve
1151
- // ./src/index.js") and every page lost its :root variables, reset
1152
- // and @keyframes (found with the xma.info report item 1 repro).
1153
- })
1154
- build.onResolve({ filter: /^@domql\// }, args => {
1155
- const pkg = args.path.replace('@symbo.ls/', '')
1156
- if (ws.isMonorepo) {
1157
- const src = resolve(ws.monorepoRoot, 'packages', 'domql', 'packages', pkg, 'src', 'index.js')
1158
- if (existsSync(src)) return { path: src }
1159
- } else {
1160
- const resolved = resolveDomqlPackage(ws, pkg, 'src', 'index.js')
1161
- if (resolved && existsSync(resolved)) return { path: resolved }
1162
- const resolvedIdx = resolveDomqlPackage(ws, pkg, 'index.js')
1163
- if (resolvedIdx && existsSync(resolvedIdx)) return { path: resolvedIdx }
1164
- }
1165
- })
1166
- }
1167
- }
1168
-
1169
- await esbuild.build({
1170
- entryPoints: [tmpEntry],
1171
- bundle: true,
1172
- format: 'esm',
1173
- platform: 'node',
1174
- outfile: tmpOut,
1175
- write: true,
1176
- logLevel: 'silent',
1177
- plugins: [workspacePlugin],
1178
- nodePaths: ws.isMonorepo
1179
- ? [resolve(ws.monorepoRoot, 'node_modules')]
1180
- : [
1181
- ...(ws.smblsRoot ? [resolve(ws.smblsRoot, 'node_modules')] : []),
1182
- ...(ws.projectRoot ? [resolve(ws.projectRoot, 'node_modules')] : []),
1183
- ...(ws.smblsRoot ? [resolve(ws.smblsRoot, '..', '..', 'node_modules')] : [])
1184
- ].filter(p => existsSync(p)),
1185
- external: ['fs', 'path', 'os', 'crypto', 'url', 'http', 'https', 'stream', 'util', 'events', 'buffer', 'child_process', 'worker_threads', 'net', 'tls', 'dns', 'dgram', 'zlib', 'assert', 'querystring', 'string_decoder', 'readline', 'perf_hooks', 'async_hooks', 'v8', 'vm', 'cluster', 'inspector', 'module', 'process', 'tty', 'color-contrast-checker']
1186
- })
1187
-
1188
- const mod = await import(`file://${tmpOut}`)
1189
- const data = mod.default || {}
1190
- try { unlinkSync(tmpEntry) } catch {} // cleanup: ignore if temp file already removed
1191
- try { unlinkSync(tmpOut) } catch {} // cleanup: ignore if temp file already removed
1192
-
1193
- const cssVars = data.CSS_VARS || {}
1194
- const cssMediaVars = data.CSS_MEDIA_VARS || {}
1195
- const reset = data.RESET || {}
1196
- const animations = data.ANIMATION || {}
1197
-
1198
- // ── :root CSS variables ──
1199
- const varDecls = Object.entries(cssVars)
1200
- .map(([k, v]) => ` ${k}: ${v}`)
1201
- .join(';\n')
1202
- let rootRule = varDecls ? `:root {\n${varDecls};\n}` : ''
1203
-
1204
- // ── Theme-switching CSS vars (media queries + data-theme selectors) ──
1205
- const themeVarRules = Object.entries(cssMediaVars)
1206
- .map(([key, vars]) => {
1207
- const decls = Object.entries(vars)
1208
- .map(([k, v]) => ` ${k}: ${v}`)
1209
- .join(';\n')
1210
- if (!decls) return ''
1211
- if (key.startsWith('@media')) {
1212
- // Media query — only when no data-theme forces a theme
1213
- return `${key} {\n :root:not([data-theme]) {\n${decls};\n }\n}`
1214
- }
1215
- // Selector ([data-theme="..."]) — apply directly
1216
- return `${key} {\n${decls};\n}`
1217
- })
1218
- .filter(Boolean)
1219
- .join('\n\n')
1220
- if (themeVarRules) rootRule += '\n\n' + themeVarRules
1221
-
1222
- // ── Skin rules ([data-skin] selectors + the reduced-transparency block) ──
1223
- // After the scheme blocks: on an equal specificity the skin wins, as it
1224
- // does in the hydrated page (smbls init injects them in the same order).
1225
- const skinRules = skinRulesToCSS(data.CSS_SKIN_RULES)
1226
- if (skinRules) rootRule += (rootRule ? '\n\n' : '') + skinRules
1227
-
1228
- // ── Reset styles ──
1229
- const resetRules = generateResetCSS(reset)
1230
-
1231
- // ── @keyframes animations ──
1232
- const keyframeRules = []
1233
- for (const name in animations) {
1234
- const frames = animations[name]
1235
- if (!frames || typeof frames !== 'object') continue
1236
- const frameRules = Object.entries(frames).map(([step, p]) => {
1237
- if (typeof p !== 'object') return ''
1238
- const decls = Object.entries(p).map(([k, v]) => `${camelToKebab(k)}: ${v}`).join('; ')
1239
- return ` ${step} { ${decls}; }`
1240
- }).join('\n')
1241
- keyframeRules.push(`@keyframes ${name} {\n${frameRules}\n}`)
1242
- }
1181
+ // ── Global CSS: the render's own capture, split ────────────────────────────
1182
+ // The rules smbls init injects into the virtual <head> during render() ARE
1183
+ // the page's global CSS — the :root variables, scheme and skin blocks, the
1184
+ // processed reset and every @keyframes — exactly what the client injects,
1185
+ // for THIS project and render. They are split off the captured sheet so a
1186
+ // page emits them once, ahead of the atomic classes, and so renderPage's
1187
+ // cross-page accumulation keeps only the classes.
1188
+ //
1189
+ // This replaced generateGlobalCSS, which re-derived the same CSS by bundling
1190
+ // a temp module with esbuild into tmpdir. It read data.RESET/data.ANIMATION
1191
+ // where the module exported reset/animation (resetRules and keyframeRules
1192
+ // were always '', and renderRoute fell back to the RAW design-system reset,
1193
+ // tokens unresolved); it threw on every cold Cloudflare isolate ("[unenv]
1194
+ // fs.writeFileSync is not implemented yet"); and its result was cached per
1195
+ // PROCESS, keyed on nothing, so a server rendering two projects gave the
1196
+ // second one the first one's :root (FW-BRENDER-HYDRATION-AND-CF-DEPLOY-PROVIDER-1).
1197
+
1198
+ // A selector is global when no selector in its list targets a class — the
1199
+ // atomic engine's every rule does (`._p-a`, `.c1x:hover`, `[data-theme] .c2`).
1200
+ // Quoted strings and attribute brackets are masked first: a dot inside
1201
+ // `[href$=".pdf"]` is not a class.
1202
+ const CLASS_IN_SELECTOR = /\.[A-Za-z_\\-]/
1203
+ const isGlobalSelector = (selectorText) => {
1204
+ if (typeof selectorText !== 'string' || !selectorText) return false
1205
+ const masked = selectorText
1206
+ .replace(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g, '""')
1207
+ .replace(/\[[^\]]*\]/g, '[]')
1208
+ return !CLASS_IN_SELECTOR.test(masked)
1209
+ }
1210
+ const VARIABLE_SCOPE = /^\s*(:root|\[data-theme|\[data-skin)/
1211
+
1212
+ // Classify one CSSOM rule: 'root' (variables, scheme and skin blocks),
1213
+ // 'keyframes', 'reset' (any other global rule), or null (stays with the
1214
+ // atomic classes).
1215
+ const classifyRule = (rule) => {
1216
+ const text = rule && rule.cssText
1217
+ if (typeof text !== 'string') return null
1218
+ if (/^@(-webkit-)?keyframes\b/.test(text)) return 'keyframes'
1219
+ // @font-face stays in the class stream (`css` / data-emotion), where every
1220
+ // consumer — including a mermaid that predates this split and emits only
1221
+ // rootRule/resetCss/keyframeRules + css — has always found it.
1222
+ if (text.startsWith('@font-face')) return null
1223
+ if (typeof rule.selectorText === 'string') {
1224
+ if (!isGlobalSelector(rule.selectorText)) return null
1225
+ return VARIABLE_SCOPE.test(rule.selectorText) ? 'root' : 'reset'
1226
+ }
1227
+ // A grouping rule (@media/@supports/@container) is global when all of its
1228
+ // rules are; it joins the group its rules agree on.
1229
+ const inner = rule.cssRules && Array.from(rule.cssRules)
1230
+ if (inner && inner.length && /^@(media|supports|container)\b/.test(text)) {
1231
+ const kinds = new Set(inner.map(classifyRule))
1232
+ if (kinds.has(null) || kinds.size !== 1) return kinds.has(null) ? null : 'reset'
1233
+ return [...kinds][0]
1234
+ }
1235
+ return null
1236
+ }
1243
1237
 
1244
- _cachedGlobalCSS = {
1245
- rootRule,
1246
- resetRules,
1247
- fontFaceCSS: '',
1248
- keyframeRules: keyframeRules.join('\n')
1249
- }
1250
- return _cachedGlobalCSS
1251
- } catch (err) {
1252
- console.warn('generateGlobalCSS failed:', err.message, err.stack)
1253
- _cachedGlobalCSS = { rootRule: '', resetRules: '', fontFaceCSS: '', keyframeRules: '' }
1254
- return _cachedGlobalCSS
1238
+ export const splitCapturedCSS = (rules) => {
1239
+ const groups = { root: [], reset: [], keyframes: [] }
1240
+ const rest = []
1241
+ for (const rule of rules || []) {
1242
+ const kind = classifyRule(rule)
1243
+ if (kind) groups[kind].push(rule.cssText)
1244
+ else if (rule && rule.cssText) rest.push(rule.cssText)
1245
+ }
1246
+ return {
1247
+ globalCSS: {
1248
+ rootRule: groups.root.join('\n'),
1249
+ resetRules: groups.reset.join('\n'),
1250
+ keyframeRules: groups.keyframes.join('\n'),
1251
+ fontFaceCSS: ''
1252
+ },
1253
+ classRules: rest
1255
1254
  }
1256
1255
  }
1257
1256
 
@@ -1265,7 +1264,7 @@ let _accumulatedEmotionCSS = new Set()
1265
1264
  /**
1266
1265
  * Reset the cached global CSS and emotion CSS (useful when rendering multiple projects).
1267
1266
  */
1268
- export const resetGlobalCSSCache = () => { _cachedGlobalCSS = null; _accumulatedEmotionCSS = new Set() }
1267
+ export const resetGlobalCSSCache = () => { _accumulatedEmotionCSS = new Set() }
1269
1268
 
1270
1269
  /**
1271
1270
  * Returns the complete accumulated emotion CSS from all renders so far.
@@ -1297,15 +1296,17 @@ export const replaceEmotionCSS = (html, newCSS) => {
1297
1296
  * @returns {Promise<{ html: string, css: string, resetCss: string, fontLinks: string, metadata: object, brKeyCount: number }>}
1298
1297
  */
1299
1298
  export const renderRoute = async (data, options = {}) => {
1300
- const { route = '/', pathname } = options
1299
+ // `prefetch: false` renders without the DB prefetch and translation fetch
1300
+ // — the publish-time pre-render (smbls publish → ssrCache) renders data-free.
1301
+ const { route = '/', pathname, prefetch = true } = options
1301
1302
 
1302
1303
  // Use the full render pipeline which handles polyglot, prefetch, emotion, etc.
1303
1304
  // Pass pathname so the virtual DOM location reflects the actual URL (for dynamic routes)
1304
- const result = await render(data, { route, pathname, prefetch: true })
1305
+ const result = await render(data, { route, pathname, prefetch })
1305
1306
  if (!result) return null
1306
1307
 
1307
1308
  const ds = data.designSystem || {}
1308
- const globalCSS = await generateGlobalCSS(ds, pickProjectConfig(data))
1309
+ const globalCSS = result.globalCSS
1309
1310
 
1310
1311
  // Extract prefetched state and language for metadata resolution
1311
1312
  let prefetchedState = null
@@ -1343,13 +1344,18 @@ export const renderRoute = async (data, options = {}) => {
1343
1344
 
1344
1345
  return {
1345
1346
  html: result.html,
1346
- css: result.emotionCSS ? result.emotionCSS.join('\n') : '',
1347
+ css: result.classRules.join('\n'),
1348
+ // the same rules as a list — a caller that unions several routes' CSS
1349
+ // (the publish-time ssrCache) dedupes by rule
1350
+ classRules: result.classRules.slice(),
1347
1351
  globalCSS,
1348
- resetCss: globalCSS.resetRules || generateResetCSS(ds.reset),
1352
+ resetCss: globalCSS.resetRules,
1349
1353
  fontLinks: generateFontLinks(ds),
1350
1354
  metadata: result.metadata || extractMetadata(data, route),
1351
1355
  brKeyCount: result.registry ? Object.keys(result.registry).length : 0,
1352
1356
  brRegistry: result.brRegistry || {},
1357
+ // anonymous GET answers this render got (see `_seed`) — for adoptionScripts
1358
+ fetchSeed: result.fetchSeed || [],
1353
1359
  ssrTranslations: result.ssrTranslations,
1354
1360
  prefetchedState,
1355
1361
  activeLang
@@ -1371,7 +1377,12 @@ export const renderRoute = async (data, options = {}) => {
1371
1377
  * @param {string} [options.lang='en'] - HTML lang attribute
1372
1378
  * @param {string} [options.themeColor] - theme-color meta
1373
1379
  * @param {object} [options.isr] - ISR options with clientScript path
1374
- * @param {boolean} [options.hydrate=true] - Use true hydration (attach to existing DOM) instead of full SPA re-render
1380
+ * @param {boolean} [options.hydrate=true] - With `isr`: boot the client over the
1381
+ * pre-rendered markup (`__BRENDER__`; the client replaces it with a fresh
1382
+ * render) instead of the legacy swap script
1383
+ * @param {boolean} [options.adoptDom=false] - Opt-in hydration: also ship the
1384
+ * element-path registry, `__BRENDER_HYDRATE__` and the recorded anonymous
1385
+ * fetch answers, so the client ADOPTS the server DOM (smbls hydrateRender)
1375
1386
  * @param {boolean} [options.prefetch=true] - Whether to prefetch data via DB adapter
1376
1387
  * @param {string} [options.shell] - A built app document (e.g. dist/index.html)
1377
1388
  * to render INTO instead of emitting a standalone document (see shell.js).
@@ -1382,7 +1393,7 @@ export const renderRoute = async (data, options = {}) => {
1382
1393
  * @returns {Promise<{ html: string, route: string, brKeyCount: number, shell?: true }>}
1383
1394
  */
1384
1395
  export const renderPage = async (data, route = '/', options = {}) => {
1385
- const { lang, themeColor, isr, hydrate = true, prefetch = true, shell } = options
1396
+ const { lang, themeColor, isr, hydrate = true, prefetch = true, shell, adoptDom = false } = options
1386
1397
 
1387
1398
  // Detect lang from project config, app metadata, or default
1388
1399
  const htmlLang = lang || data.state?.lang || data.app?.metadata?.lang || 'en'
@@ -1414,16 +1425,16 @@ export const renderPage = async (data, route = '/', options = {}) => {
1414
1425
  // Each page may introduce unique CSS classes not seen on previous pages.
1415
1426
  // Emotion's singleton cache only emits NEW classes per render, so we
1416
1427
  // collect all rules across renders to build the complete stylesheet.
1417
- if (result.emotionCSS && result.emotionCSS.length) {
1418
- for (const rule of result.emotionCSS) {
1419
- if (rule) _accumulatedEmotionCSS.add(rule)
1420
- }
1428
+ // Only the classes accumulate: the globals are this page's own (one :root,
1429
+ // one copy of each @keyframes — they used to pile up across pages).
1430
+ for (const rule of result.classRules) {
1431
+ if (rule) _accumulatedEmotionCSS.add(rule)
1421
1432
  }
1422
1433
  const emotionCSS = Array.from(_accumulatedEmotionCSS).join('\n')
1423
1434
 
1424
- // Generate global CSS (variables, reset, keyframes) via scratch pipeline
1435
+ // Global CSS (variables, reset, keyframes): this render's own init output
1425
1436
  const ds = data.designSystem || {}
1426
- const globalCSS = await generateGlobalCSS(ds, pickProjectConfig(data))
1437
+ const globalCSS = result.globalCSS
1427
1438
 
1428
1439
  // Generate font links from design system
1429
1440
  const fontLinks = generateFontLinks(ds)
@@ -1473,9 +1484,11 @@ export const renderPage = async (data, route = '/', options = {}) => {
1473
1484
  const brRegistryJson = result.brRegistry && Object.keys(result.brRegistry).length
1474
1485
  ? JSON.stringify(result.brRegistry)
1475
1486
  : null
1476
- const brRegistryScript = brRegistryJson
1477
- ? `<script>window.__BR_REGISTRY__=${brRegistryJson}</script>\n`
1478
- : ''
1487
+ const brRegistryScript = adoptDom
1488
+ ? (adoptionScripts(result) ? adoptionScripts(result) + '\n' : '')
1489
+ : brRegistryJson
1490
+ ? `<script>window.__BR_REGISTRY__=${brRegistryJson}</script>\n`
1491
+ : ''
1479
1492
  isrBody = `${translationSeed}${brRegistryScript}<script>window.__BRENDER__=true</script>
1480
1493
  <script type="module" src="${prefix}${isr.clientScript}"></script>`
1481
1494
  } else {
@@ -1526,15 +1539,16 @@ export const renderPage = async (data, route = '/', options = {}) => {
1526
1539
  // pages that never booted.
1527
1540
  if (typeof shell === 'string') {
1528
1541
  const styles = [
1529
- globalCSS.fontFaceCSS ? `<style>${globalCSS.fontFaceCSS}</style>` : '',
1530
- `<style>\n${globalCSS.rootRule || ''}\n${globalCSS.resetRules || ''}\n${globalCSS.keyframeRules || ''}\n</style>`,
1542
+ globalCSS.fontFaceCSS ? `<style data-brender>${globalCSS.fontFaceCSS}</style>` : '',
1543
+ `<style data-brender>\n${globalCSS.rootRule || ''}\n${globalCSS.resetRules || ''}\n${globalCSS.keyframeRules || ''}\n</style>`,
1531
1544
  emotionCSS ? `<style data-emotion="smbls">\n${emotionCSS}\n</style>` : ''
1532
1545
  ]
1533
1546
  const html = composeIntoShell(shell, {
1534
1547
  headTags: resolvedHeadTags,
1535
1548
  headEnd: [fontLinks, ...styles].filter(Boolean).join('\n'),
1536
1549
  body: result.html,
1537
- depth: Number.isInteger(options.depth) ? options.depth : 0
1550
+ depth: Number.isInteger(options.depth) ? options.depth : 0,
1551
+ bootScripts: adoptDom ? adoptionScripts(result) : ''
1538
1552
  })
1539
1553
  return { html, route, brKeyCount, shell: true }
1540
1554
  }
@@ -1544,8 +1558,8 @@ export const renderPage = async (data, route = '/', options = {}) => {
1544
1558
  <head>
1545
1559
  ${resolvedHeadTags}
1546
1560
  ${fontLinks}
1547
- ${globalCSS.fontFaceCSS ? `<style>${globalCSS.fontFaceCSS}</style>` : ''}
1548
- <style>
1561
+ ${globalCSS.fontFaceCSS ? `<style data-brender>${globalCSS.fontFaceCSS}</style>` : ''}
1562
+ <style data-brender>
1549
1563
  ${globalCSS.rootRule || ''}
1550
1564
  ${globalCSS.resetRules || ''}
1551
1565
  ${globalCSS.keyframeRules || ''}
@@ -1953,33 +1967,6 @@ const extractCSS = (element, ds) => {
1953
1967
  return [...keyframes, ...rules].join('\n')
1954
1968
  }
1955
1969
 
1956
- const generateResetCSS = (reset) => {
1957
- if (!reset) return ''
1958
- const rules = []
1959
- for (const [selector, props] of Object.entries(reset)) {
1960
- if (!props || typeof props !== 'object') continue
1961
- const baseDecls = []
1962
- const mediaRules = []
1963
- for (const [k, v] of Object.entries(props)) {
1964
- if (typeof v === 'object' && v !== null) {
1965
- // Nested object: @media query or sub-selector
1966
- if (k.startsWith('@media') || k.startsWith('@')) {
1967
- const inner = Object.entries(v)
1968
- .filter(([, iv]) => typeof iv !== 'object')
1969
- .map(([ik, iv]) => `${camelToKebab(ik)}: ${iv}`)
1970
- .join('; ')
1971
- if (inner) mediaRules.push(`${k} { ${selector} { ${inner}; } }`)
1972
- }
1973
- continue
1974
- }
1975
- baseDecls.push(`${camelToKebab(k)}: ${v}`)
1976
- }
1977
- if (baseDecls.length) rules.push(`${selector} { ${baseDecls.join('; ')}; }`)
1978
- rules.push(...mediaRules)
1979
- }
1980
- return rules.join('\n')
1981
- }
1982
-
1983
1970
  const generateFontLinks = (ds) => {
1984
1971
  if (!ds) return ''
1985
1972
  const families = ds.font_family || ds.fontFamily || {}