@markless/bundler 0.4.0 → 0.6.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.
@@ -0,0 +1,2744 @@
1
+ import { joinURL, parsePath, withQuery, withoutLeadingSlash } from "ufo";
2
+ import { MARKLESS_COMPONENT_PART_BRAND } from "@markless/web/render-to-string";
3
+ import { ASYNC_PROTOCOL_VERSION, PROTOCOL_EVENT_ACTION_KIND, protocolEventActionKind } from "@markless/serializer";
4
+ import { isAbsolute, resolve } from "pathe";
5
+ import { emitSymbolResolverModule } from "@markless/compiler";
6
+ //#region src/build/preload-plan.ts
7
+ const DEFAULT_MIN_PROBABILITY = 0;
8
+ const JAVASCRIPT_MODULE_RE = /\.(?:mjs|js)(?:[?#].*)?$/;
9
+ const PRIORITY_RANK = {
10
+ high: 2,
11
+ auto: 1,
12
+ low: 0
13
+ };
14
+ function planModulePreloadUrls(input) {
15
+ return planModulePreloads(input).map((preload) => preload.href);
16
+ }
17
+ function planModulePreloads(input) {
18
+ const minProbability = input.minProbability ?? DEFAULT_MIN_PROBABILITY;
19
+ const maxPreloads = input.maxPreloads ?? Number.POSITIVE_INFINITY;
20
+ const graph = parseBundleGraph(input.bundleGraph);
21
+ const planned = /* @__PURE__ */ new Map();
22
+ const bestVisitByNode = /* @__PURE__ */ new Map();
23
+ let order = 0;
24
+ const addModule = (name, probability, priority, fetchPriority) => {
25
+ if (!isPreloadableModuleName(name)) return;
26
+ const href = preloadHref(input.base, name);
27
+ const existing = planned.get(href);
28
+ const nextRank = PRIORITY_RANK[priority];
29
+ const existingRank = existing ? PRIORITY_RANK[existing.priority] : -1;
30
+ if (existing && (existingRank > nextRank || existingRank === nextRank && existing.probability >= probability)) return;
31
+ planned.set(href, {
32
+ fetchPriority,
33
+ href,
34
+ name,
35
+ order: existing?.order ?? order++,
36
+ priority,
37
+ probability
38
+ });
39
+ };
40
+ const visit = (name, probability, priority, fetchPriority, seen, suppressed = false, suppressRootOnly = false) => {
41
+ if (probability < minProbability || planned.size >= maxPreloads) return;
42
+ if (!suppressed) {
43
+ const priorityRank = PRIORITY_RANK[priority];
44
+ const previousBest = bestVisitByNode.get(name);
45
+ if (previousBest && (previousBest.priorityRank > priorityRank || previousBest.priorityRank === priorityRank && previousBest.probability >= probability)) return;
46
+ bestVisitByNode.set(name, {
47
+ priorityRank,
48
+ probability
49
+ });
50
+ }
51
+ if (seen.has(name)) return;
52
+ const nextSeen = new Set(seen);
53
+ nextSeen.add(name);
54
+ const record = graph.get(name);
55
+ if (!record) {
56
+ if (!suppressed) addModule(name, probability, priority, fetchPriority);
57
+ return;
58
+ }
59
+ for (const dep of record.deps.filter((item) => item.kind === "static")) visit(dep.name, probability * dep.probability, priority, fetchPriority, nextSeen, suppressed && !suppressRootOnly);
60
+ if (!suppressed) addModule(name, probability, priority, fetchPriority);
61
+ for (const dep of record.deps.filter((item) => item.kind === "dynamic")) {
62
+ if (input.lazyChunks?.has(dep.name)) continue;
63
+ const edgeProbability = JAVASCRIPT_MODULE_RE.test(name) ? dep.probability : 1;
64
+ visit(dep.name, probability * edgeProbability, priority, fetchPriority, nextSeen, false);
65
+ }
66
+ };
67
+ for (const root of input.roots) {
68
+ const normalized = normalizeRoot(root);
69
+ visit(normalized.name, 1, normalized.priority, normalized.fetchPriority, /* @__PURE__ */ new Set(), normalized.edges === "dynamic-only" || normalized.edges === "dependencies-only", normalized.edges === "dependencies-only");
70
+ }
71
+ return [...planned.values()].sort((left, right) => {
72
+ const priority = PRIORITY_RANK[right.priority] - PRIORITY_RANK[left.priority];
73
+ if (priority !== 0) return priority;
74
+ return left.order - right.order;
75
+ }).slice(0, maxPreloads).map(({ order: _order, ...preload }) => preload);
76
+ }
77
+ function parseBundleGraph(graph) {
78
+ const records = /* @__PURE__ */ new Map();
79
+ if (!graph) return records;
80
+ let index = 0;
81
+ while (index < graph.length) {
82
+ const name = graph[index++];
83
+ if (typeof name !== "string") continue;
84
+ const deps = [];
85
+ let probability = 1;
86
+ let kind = "static";
87
+ while (typeof graph[index] === "number") {
88
+ const marker = graph[index++];
89
+ if (marker < 0) {
90
+ probability = -marker / 10;
91
+ kind = "dynamic";
92
+ continue;
93
+ }
94
+ const dep = graph[marker];
95
+ if (typeof dep === "string") deps.push({
96
+ name: dep,
97
+ kind,
98
+ probability
99
+ });
100
+ }
101
+ records.set(name, {
102
+ name,
103
+ deps
104
+ });
105
+ }
106
+ return records;
107
+ }
108
+ function preloadHref(base, name) {
109
+ if (!base || /^(?:[a-z]+:)?\/\//i.test(name)) return name;
110
+ return joinURL(base, name);
111
+ }
112
+ function isPreloadableModuleName(name) {
113
+ return JAVASCRIPT_MODULE_RE.test(name) || isViteDevModuleUrl(name);
114
+ }
115
+ function isViteDevModuleUrl(name) {
116
+ return (name.startsWith("/") || name.startsWith("@id/")) && /(?:^|[?&])import(?:[&#]|$)/.test(name);
117
+ }
118
+ function normalizeRoot(root) {
119
+ if (typeof root === "string") return {
120
+ name: root,
121
+ priority: "auto",
122
+ fetchPriority: "auto"
123
+ };
124
+ const priority = root.priority ?? "auto";
125
+ return {
126
+ name: root.name,
127
+ priority,
128
+ edges: root.edges,
129
+ fetchPriority: root.fetchPriority ?? priorityToFetchPriority(priority)
130
+ };
131
+ }
132
+ function priorityToFetchPriority(priority) {
133
+ if (priority === "auto") return "auto";
134
+ return priority;
135
+ }
136
+ //#endregion
137
+ //#region src/execution-log.ts
138
+ const MARKLESS_EXECUTION_LOG_MODULE_ID = "virtual:markless:dev-log";
139
+ const MARKLESS_EXECUTION_LOG_GLOBAL = "__mxLog";
140
+ const EXECUTION_LOG_CHUNK_MODULE_PATTERN = /virtual:markless:dev-log|[/\\]web[/\\]src[/\\]dev-log\.ts(?:[?#].*)?$/;
141
+ function isExecutionLogChunk(chunk) {
142
+ return !!chunk.moduleIds?.length && chunk.moduleIds.every((id) => EXECUTION_LOG_CHUNK_MODULE_PATTERN.test(id));
143
+ }
144
+ const EXECUTION_LOG_DISPATCH_MODULE_IDS = ["web:render-csr", "web:resume-events"];
145
+ const MARKLESS_EXECUTION_LEDGER_GLOBAL = "__marklessExecutionLedger";
146
+ const MARKLESS_EXECUTION_LEDGER_INIT = "{ unit: 'chunk-raw-bytes', load: { app: 0, framework: 0, instrument: 0, inline: 0, modules: [] }, total: { app: 0, framework: 0, instrument: 0, inline: 0 }, turns: [], incomplete: null }";
147
+ const EXECUTION_LOG_GESTURE_EVENTS = [
148
+ "pointerdown",
149
+ "touchstart",
150
+ "keydown"
151
+ ];
152
+ const EXECUTION_LOG_FRAMEWORK_ID_PATTERN = "/^(?:web|runtime|serializer|router|core|analyzer):/";
153
+ function normalizeExecutionLogMode(mode) {
154
+ return mode ?? "auto";
155
+ }
156
+ function injectExecutionLogModuleHook(source, moduleId, mode) {
157
+ if (normalizeExecutionLogMode(mode) === "never") return source;
158
+ return `globalThis.__mxLog?.add(${JSON.stringify(moduleId)});\n${source}`;
159
+ }
160
+ const EXECUTION_LOG_HOOK_LINE = /^globalThis\.__mxLog\?\.add\("(?:[^"\\]|\\.)*"\);\n/;
161
+ function hasExecutionLogModuleHook(source) {
162
+ return EXECUTION_LOG_HOOK_LINE.test(source);
163
+ }
164
+ function requalifyExecutionLogModuleHook(source, moduleId) {
165
+ if (!EXECUTION_LOG_HOOK_LINE.test(source)) return source;
166
+ return source.replace(EXECUTION_LOG_HOOK_LINE, `globalThis.__mxLog?.add(${JSON.stringify(moduleId)});\n`);
167
+ }
168
+ function executionLogVirtualModuleSource(options = {}) {
169
+ if (!options.moduleSizes) return executionLogVirtualModuleSourceWithOwnSize(options, null);
170
+ return executionLogVirtualModuleSourceWithOwnSize(options, executionLogVirtualModuleSourceWithOwnSize(options, 0).length);
171
+ }
172
+ function executionLogVirtualModuleSourceWithOwnSize(options, ownRawSize) {
173
+ const moduleSizes = options.moduleSizes ? Object.fromEntries([...[...options.moduleSizes].map(([id, raw]) => [id, {
174
+ raw,
175
+ estimated: true
176
+ }]), [MARKLESS_EXECUTION_LOG_MODULE_ID, {
177
+ raw: ownRawSize ?? 0,
178
+ estimated: true,
179
+ instrument: true
180
+ }]]) : null;
181
+ return `
182
+ globalThis.__mxLog?.add(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)});
183
+ const marklessDefaultModuleSizes = ${JSON.stringify(moduleSizes)};
184
+ const marklessDefaultAttribution = ${JSON.stringify(options.attribution ?? null)};
185
+ const marklessSizesUrl = ${JSON.stringify(options.sizesUrl ?? null)};
186
+ let marklessSizesPromise;
187
+ let marklessAttribution;
188
+ let marklessInstallPromise;
189
+ let marklessRenderSummaryTurn;
190
+ function modules(log) { return log ? [...log] : []; }
191
+ function sizeRecord(input) { return !input ? undefined : typeof input === 'number' ? { raw: input, estimated: true } : input; }
192
+ function normalizeSizes(input) { if (!input) return undefined; const map = new Map(); for (const id of Object.keys(input)) if (id !== 'attribution' && id !== 'unshipped') map.set(id, sizeRecord(input[id])); return map; }
193
+ async function loadModuleSizes(input) {
194
+ if (input.moduleSizes) return normalizeSizes(input.moduleSizes);
195
+ if (marklessDefaultModuleSizes) { marklessAttribution = marklessDefaultAttribution; return normalizeSizes(marklessDefaultModuleSizes); }
196
+ if (!marklessSizesUrl) return undefined;
197
+ marklessSizesPromise ||= fetch(marklessSizesUrl).then((response) => response.ok ? response.json() : undefined).then((payload) => { marklessAttribution = payload && payload.attribution; return normalizeSizes(payload); }).catch(() => undefined);
198
+ return marklessSizesPromise;
199
+ }
200
+ function symbolParts(id) { const match = /^virtual:markless:symbol:([^:]+):([^:]+)$/.exec(id); if (!match) return null; try { return { source: decodeURIComponent(match[1]), symbolId: decodeURIComponent(match[2]) }; } catch { return null; } }
201
+ function baseSymbolId(id) { if (!id.startsWith('bound:')) return null; const separator = id.indexOf(':', 'bound:'.length); if (separator < 0) return null; try { return decodeURIComponent(id.slice('bound:'.length, separator)); } catch { return null; } }
202
+ function routeFile() { const text = document.querySelector?.('script[type="@markless/core/route"]')?.textContent; if (!text) return null; try { const value = JSON.parse(text).file; return typeof value === 'string' ? value : null; } catch { return null; } }
203
+ // Attribution tables are keyed by the bare path this lookup can name: the
204
+ // document's route file, or — for a routeless page — the build's single root,
205
+ // which is the only page it can be.
206
+ function attributionScopes(tables) { if (!tables) return undefined; const route = routeFile(); if (route) { if (route.includes('..') || route.includes('\\\\')) return undefined; const canonical = route.replace(/^\\/+/, ''); return Object.prototype.hasOwnProperty.call(tables, canonical) ? tables[canonical] : undefined; } const roots = Object.keys(tables); return roots.length === 1 ? tables[roots[0]] : undefined; }
207
+ // A handler renders inside one component but is owned by whichever component
208
+ // created the closure — a prop-passed onClick renders at the child's scope and
209
+ // belongs to the parent. The owner is therefore somewhere on the host's render
210
+ // ancestry, so once the host's OWN scope is one the table names, the chain is
211
+ // walked outward and the first scope holding exactly one candidate wins. Never a
212
+ // guess: a host in a scope the table does not name is refused outright, a scope
213
+ // with zero or several candidates is skipped, and an id nobody owns uniquely
214
+ // stays unmapped.
215
+ function scopeChain(scope) { const chain = []; for (let current = scope; ; ) { chain.push(current); if (!current) return chain; const next = current.replace(/c\\d+:$/, ''); if (next === current) return chain; current = next; } }
216
+ function qualifySymbolIds(ids, hostNodeId, sizes, tables) { const scopes = attributionScopes(tables); if (!scopes) return ids; const host = /^((?:c\\d+:)*)[^:]+$/.exec(hostNodeId); const hostScope = host && host[1]; return ids.map((id) => { const own = /^((?:c\\d+:)+)(.*)$/.exec(id); const scope = own ? own[1] : hostScope; if (scope === null || scope === undefined || !Object.prototype.hasOwnProperty.call(scopes, scope)) return id; const local = own ? own[2] : id; const base = baseSymbolId(local); const sizeSymbolId = base || local; if (!sizeSymbolId.startsWith('symbol:')) return id; for (const candidate of scopeChain(scope)) { if (!Object.prototype.hasOwnProperty.call(scopes, candidate)) continue; const matches = [...(sizes?.keys() || [])].filter((key) => { const match = /^virtual:markless:symbol:([^:]+):([^:]+)$/.exec(key); if (!match || match[1] !== scopes[candidate]) return false; try { return decodeURIComponent(match[2]) === sizeSymbolId; } catch { return false; } }); if (matches.length !== 1) continue; if (!base) return matches[0]; const match = /^virtual:markless:symbol:([^:]+):/.exec(matches[0]); return match ? 'virtual:markless:symbol:' + match[1] + ':' + encodeURIComponent(local) : id; } return id; }); }
217
+ function canonicalId(id, sizes) {
218
+ if (!sizes || sizes.has(id)) return id;
219
+ const qualified = symbolParts(id); const local = qualified ? qualified.symbolId : id.replace(/^(?:c\\d+:)+/, ''); const sizeSymbolId = baseSymbolId(local) || local;
220
+ if (!sizeSymbolId.startsWith('symbol:')) return id;
221
+ const matches = [...sizes.keys()].filter((key) => { const parts = symbolParts(key); return !!parts && parts.symbolId === sizeSymbolId && (!qualified || parts.source === qualified.source); });
222
+ return matches.length === 1 ? matches[0] : id;
223
+ }
224
+ function displayId(id) { const parts = symbolParts(id); return parts ? parts.symbolId + ' (' + (parts.source.split('/').pop() || parts.source) + ')' : id; }
225
+ function displayObservedId(id, sizes) { const parts = symbolParts(id); return displayId(baseSymbolId(parts ? parts.symbolId : id) ? id : canonicalId(id, sizes)); }
226
+ function accounting(items, sizes) {
227
+ const ids = [...new Set(items.map((id) => canonicalId(id, sizes)))];
228
+ if (!sizes) return { appBytes: ids.length ? null : 0, instrumentBytes: 0, appModules: ids.length, instrumentModules: 0, estimated: { app: false, instrument: false }, unmappedIds: [] };
229
+ let appBytes = 0, instrumentBytes = 0, appModules = 0, instrumentModules = 0, appEstimated = false, instrumentEstimated = false; const unmappedIds = [];
230
+ for (const id of ids) { const record = sizes.get(id); if (!record) { appModules++; unmappedIds.push(id); continue; } const bytes = record.raw; instrumentBytes += record.instrumentRaw || 0; if (record.instrument) { instrumentModules++; instrumentBytes += bytes; instrumentEstimated ||= !!record.estimated; } else { appModules++; appBytes += bytes; appEstimated ||= !!record.estimated; } }
231
+ return { appBytes: unmappedIds.length ? null : appBytes, instrumentBytes, appModules, instrumentModules, estimated: { app: appEstimated, instrument: instrumentEstimated }, unmappedIds };
232
+ }
233
+ function rowKb(items, sizes) { const a = accounting(items, sizes); if (a.unmappedIds.length) return 'bytes unknown'; const total = (a.appBytes || 0) + (a.instrumentBytes || 0); return (total / 1024).toFixed(1) + ' KB' + (a.estimated.app || a.estimated.instrument ? ' est. source' : ''); }
234
+ // One cumulative ledger owns every number the console prints. A module's charge is its own share
235
+ // of its chunk's raw bytes when the build map carries one, else the whole chunk; unit says which.
236
+ function marklessLedger() { return (globalThis.${MARKLESS_EXECUTION_LEDGER_GLOBAL} ||= ${MARKLESS_EXECUTION_LEDGER_INIT}); }
237
+ function ledgerCategory(id, record) { return record && record.instrument ? 'instrument' : ${EXECUTION_LOG_FRAMEWORK_ID_PATTERN}.test(id) ? 'framework' : 'app'; }
238
+ function ledgerCharge(l, ids, sizes) {
239
+ const seen = (l.chargedIds ||= new Set());
240
+ const seenChunks = (l.chargedChunks ||= new Set());
241
+ const delta = { app: 0, framework: 0, instrument: 0, gzip: 0, modules: [], unmapped: [] };
242
+ const charge = (raw, viaAlias) => {
243
+ const id = canonicalId(raw, sizes);
244
+ const record = sizes && sizes.get(id);
245
+ // A name several modules answer to charges each of them, once.
246
+ if (record && record.alias) { if (!viaAlias) for (const member of record.alias) charge(member, true); return; }
247
+ // The dedupe unit is the unit charged: the module when the map splits its chunk, else the
248
+ // chunk, so one chunk reached under two names is one charge. Dev estimates dedupe by id.
249
+ const chunk = record && !record.module && record.chunk;
250
+ if (chunk ? seenChunks.has(chunk) : seen.has(id)) return;
251
+ if (chunk) seenChunks.add(chunk); else seen.add(id);
252
+ if (!record) { delta.unmapped.push(id); return; }
253
+ if (record.estimated) l.unit = 'estimated-source-bytes'; else if (record.module && l.unit !== 'estimated-source-bytes') l.unit = 'module-raw-bytes';
254
+ delta[ledgerCategory(id, record)] += record.raw; delta.instrument += record.instrumentRaw || 0; delta.gzip += record.gzip || 0; delta.modules.push(id);
255
+ };
256
+ for (const raw of ids) charge(raw, false);
257
+ if (delta.unmapped.length) l.incomplete = { reason: 'unmapped-id', ids: [...new Set([...(l.incomplete ? l.incomplete.ids : []), ...delta.unmapped])] };
258
+ return delta;
259
+ }
260
+ // Load is everything charged before the FIRST USER GESTURE, which the activation
261
+ // script latches on the gesture itself (loadClosed) rather than on the kind of
262
+ // whichever turn reports first. On an SSR page nothing runs until the click, and
263
+ // the instrument and the wake entry both arrive with it; their render/resume
264
+ // turns are work that gesture caused, so their charge joins the gesture's turn —
265
+ // merged into it if it already exists, carried until it does if it does not.
266
+ function ledgerApply(l, kind, label, delta) {
267
+ const gesture = kind !== 'render' && kind !== 'resume';
268
+ if (gesture) l.loadClosed = true;
269
+ for (const name of ['app', 'framework', 'instrument']) { l.total[name] += delta[name]; if (!l.loadClosed) l.load[name] += delta[name]; }
270
+ l.totalGzip = (l.totalGzip || 0) + delta.gzip;
271
+ if (!l.loadClosed) { l.loadGzip = (l.loadGzip || 0) + delta.gzip; for (const id of delta.modules) l.load.modules.push(id); }
272
+ if (!gesture && l.loadClosed) {
273
+ const open = l.open;
274
+ if (open) { open.delta.app += delta.app; open.delta.framework += delta.framework; open.delta.instrument += delta.instrument; for (const id of delta.modules) open.modules.push(id); return open; }
275
+ const held = (l.carry ||= { app: 0, framework: 0, instrument: 0, modules: [] });
276
+ held.app += delta.app; held.framework += delta.framework; held.instrument += delta.instrument; for (const id of delta.modules) held.modules.push(id);
277
+ delta = { app: 0, framework: 0, instrument: 0, modules: [] };
278
+ }
279
+ const carry = gesture ? l.carry : undefined;
280
+ if (carry) l.carry = undefined;
281
+ const turn = { kind, label, delta: { app: delta.app + (carry ? carry.app : 0), framework: delta.framework + (carry ? carry.framework : 0), instrument: delta.instrument + (carry ? carry.instrument : 0) }, modules: carry ? [...carry.modules, ...delta.modules] : delta.modules };
282
+ l.turns.push(turn); if (gesture) l.open = turn;
283
+ return turn;
284
+ }
285
+ function ledgerKb(bytes) { return (bytes / 1024).toFixed(1) + ' KB'; }
286
+ // The instrument is dev-only weight, so it stays out of the headline totals and
287
+ // keeps its own category, exactly as the pre-ledger lines did.
288
+ function ledgerVisible(part) { return part.app + part.framework + part.inline; }
289
+ function ledgerLine(l, turn) {
290
+ let line = 'markless: ' + ledgerKb(ledgerVisible(l.load)) + ' executed at load';
291
+ if (turn && turn.kind !== 'render' && turn.kind !== 'resume') line += ' · this ' + turn.kind + ' +' + ledgerKb(turn.delta.app + turn.delta.framework);
292
+ line += ' · total ' + ledgerKb(ledgerVisible(l.total));
293
+ if (l.totalGzip) line += ' (gzip ' + ledgerKb(l.totalGzip) + ')';
294
+ if (l.incomplete) line += ' · ' + l.incomplete.ids.length + ' unmapped (excluded)';
295
+ return line;
296
+ }
297
+ function ledgerMirror(l, turn, text, attribute) {
298
+ const root = document.documentElement; if (!root) return;
299
+ root.setAttribute(attribute, text);
300
+ root.setAttribute('data-markless-log-unit', l.unit);
301
+ root.setAttribute('data-markless-log-load-bytes', String(ledgerVisible(l.load)));
302
+ root.setAttribute('data-markless-log-total-bytes', String(ledgerVisible(l.total)));
303
+ root.setAttribute('data-markless-log-inline-bytes', String(l.total.inline));
304
+ if (turn) {
305
+ root.setAttribute('data-markless-log-app-bytes', String(turn.delta.app));
306
+ root.setAttribute('data-markless-log-framework-bytes', String(turn.delta.framework));
307
+ root.setAttribute('data-markless-log-instrument-bytes', String(turn.delta.instrument));
308
+ root.setAttribute('data-markless-log-turn-bytes', String(turn.delta.app + turn.delta.framework));
309
+ root.setAttribute('data-markless-log-turn-modules', turn.modules.join(' '));
310
+ // The headline carries no selector, so the turn's identity lives here.
311
+ root.setAttribute('data-markless-log-turn-label', turn.kind + (turn.label ? ' ' + turn.label : ''));
312
+ }
313
+ if (l.incomplete) root.setAttribute('data-markless-log-incomplete', String(l.incomplete.ids.length)); else root.removeAttribute('data-markless-log-incomplete');
314
+ }
315
+ function warmIds(event) { return [...new Set([event.dispatchModuleId, ...((event.eventRecord && event.eventRecord.symbolIds) || [])].filter(Boolean))]; }
316
+ function causeRows(input) {
317
+ const before = input.before || new Set(); const after = input.after || new Set(); const woken = [...after].filter((id) => !before.has(id)); const record = input.eventRecord;
318
+ const cause = record ? input.eventName + ' matched event record ' + record.hostNodeId : input.eventName + ' matched runtime records';
319
+ const label = (id) => displayObservedId(id, input.moduleSizes) + (input.moduleSizes ? ' (' + rowKb([id], input.moduleSizes) + (input.moduleSizes.get(canonicalId(id, input.moduleSizes))?.instrument ? ' instrument' : '') + ')' : '');
320
+ const rows = woken.map((id) => 'woke ' + label(id) + ' <- ' + cause);
321
+ if (record) for (const id of warmIds(input)) rows.push('ran warm ' + label(id) + ' <- ' + cause);
322
+ if (record && !(input.view?.behaviors || []).some((b) => b.hostNodeId === record.hostNodeId)) rows.push('skip behavior — no matching record touched');
323
+ return rows;
324
+ }
325
+ function mirrorInteraction(l, turn, text) {
326
+ const root = document.documentElement; if (!root) return;
327
+ root.setAttribute('data-markless-log-interactions', String(Number(root.getAttribute('data-markless-log-interactions') || '0') + 1));
328
+ ledgerMirror(l, turn, text, 'data-markless-log-last');
329
+ }
330
+ export async function installMarklessExecutionLog(input = {}) {
331
+ const log = globalThis.__mxLog; if (!log || globalThis.__mxLogInteraction) return;
332
+ if (marklessInstallPromise) return marklessInstallPromise;
333
+ marklessInstallPromise = (async () => {
334
+ const moduleSizes = await loadModuleSizes(input); const current = modules(log);
335
+ if (input.printResumeSummary !== false) {
336
+ const l = marklessLedger(); const turn = ledgerApply(l, 'resume', undefined, ledgerCharge(l, current, moduleSizes)); const summary = ledgerLine(l, turn);
337
+ // This summary publishes into the ledger and mirrors; it never prints. The
338
+ // ledger's turn line is the one printed line, and a resume that lands
339
+ // beside a render turn would otherwise print the same load figure twice.
340
+ // A turn merged into an open gesture belongs to that gesture, so it mirrors
341
+ // onto the interaction attribute instead of the load one.
342
+ ledgerMirror(l, turn, summary, turn.kind === 'resume' ? 'data-markless-log-summary' : 'data-markless-log-last');
343
+ }
344
+ globalThis.__mxLogInteraction = (event) => {
345
+ const capturedAfter = modules(event.after || log);
346
+ const symbolIds = qualifySymbolIds((event.eventRecord && event.eventRecord.symbolIds) || [], event.eventRecord && event.eventRecord.hostNodeId, moduleSizes, marklessAttribution);
347
+ if (event.eventRecord) event = { ...event, eventRecord: { ...event.eventRecord, symbolIds } };
348
+ const after = capturedAfter; const before = event.before || new Set(); if (log.has(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)}) && !after.includes(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)})) after.push(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)}); const woken = after.filter((id) => !before.has(id)); const warm = warmIds(event);
349
+ const l = marklessLedger(); const label = '[' + (event.selector || 'event target') + ']';
350
+ if (event.noMatch) {
351
+ const turn = ledgerApply(l, event.eventName, label, ledgerCharge(l, [], moduleSizes)); const line = ledgerLine(l, turn) + ' · no event record matched ' + label;
352
+ console.info(line); mirrorInteraction(l, turn, line); return;
353
+ }
354
+ const turn = ledgerApply(l, event.eventName, label, ledgerCharge(l, [...woken, ...warm], moduleSizes)); const header = ledgerLine(l, turn);
355
+ console.groupCollapsed(header);
356
+ console.log(event.eventName + ' ' + label + ' · woke ' + woken.length + ' modules · ran warm ' + warm.length + ' modules');
357
+ for (const row of causeRows({ ...event, after: new Set(after), moduleSizes })) console.log(row);
358
+ console.groupEnd(); mirrorInteraction(l, turn, header);
359
+ };
360
+ log.__marklessInstalled = true;
361
+ })();
362
+ return marklessInstallPromise;
363
+ }
364
+ export async function logMarklessInteraction(event) { await installMarklessExecutionLog({ printResumeSummary: false }); globalThis.__mxLogInteraction?.(event); }
365
+ // The inline resumer wakes the runtime with no event (self-wake at load, overlay
366
+ // primer on pointerdown). That is a resume, not a gesture: counting it would
367
+ // close load early and charge one user click as two interactions.
368
+ export async function logMarklessSpecializedInteraction(input, before) {
369
+ if (!input.event) return logMarklessSpecializedWake();
370
+ const target = input.element ?? input.event.target;
371
+ const tag = typeof target?.tagName === 'string' ? target.tagName.toLowerCase() : 'element';
372
+ await logMarklessInteraction({ eventName: input.event.type ?? 'event', eventRecord: input.eventRecord, before, selector: tag + (target?.id ? '#' + target.id : ''), after: new Set(globalThis.__mxLog) });
373
+ }
374
+ async function logMarklessSpecializedWake() {
375
+ await installMarklessExecutionLog({ printResumeSummary: false });
376
+ const log = globalThis.__mxLog; if (!log) return;
377
+ const moduleSizes = await loadModuleSizes({}); const l = marklessLedger();
378
+ const turn = ledgerApply(l, 'resume', undefined, ledgerCharge(l, modules(log), moduleSizes));
379
+ ledgerMirror(l, turn, ledgerLine(l, turn), turn.kind === 'resume' ? 'data-markless-log-summary' : 'data-markless-log-last');
380
+ }
381
+ function marklessRenderSummaryTurnEnd() {
382
+ // Each injected entry module calls in from its own dynamic-import
383
+ // resolution, so a microtask window closes between callers of one render;
384
+ // a frame holds them all. The timeout is the backstop for a document that
385
+ // never paints, and whichever lands first ends the turn.
386
+ if (typeof requestAnimationFrame !== 'function') return Promise.resolve();
387
+ return new Promise((resolve) => { let ended; const end = () => { if (ended) return; ended = true; resolve(); }; requestAnimationFrame(end); setTimeout(end, 50); });
388
+ }
389
+ // Only the console line coalesces: the attribute mirror keeps its per-call
390
+ // last-wins timing, which the interaction mirror interleaves with.
391
+ function coalesceMarklessRenderSummaryLine(summary) {
392
+ if (marklessRenderSummaryTurn) { marklessRenderSummaryTurn.summary = summary; return marklessRenderSummaryTurn.printed; }
393
+ const turn = { summary };
394
+ turn.printed = marklessRenderSummaryTurnEnd().then(() => { marklessRenderSummaryTurn = undefined; console.log(turn.summary); });
395
+ marklessRenderSummaryTurn = turn;
396
+ return turn.printed;
397
+ }
398
+ export async function logMarklessRenderSummary(input = {}) {
399
+ const log = globalThis.__mxLog; if (!log) return;
400
+ const moduleSizes = await loadModuleSizes(input); const l = marklessLedger();
401
+ const turn = ledgerApply(l, 'render', undefined, ledgerCharge(l, modules(log), moduleSizes));
402
+ const summary = ledgerLine(l, turn);
403
+ if (turn.kind !== 'render') { ledgerMirror(l, turn, summary, 'data-markless-log-last'); return; }
404
+ ledgerMirror(l, turn, summary, 'data-markless-log-summary');
405
+ return coalesceMarklessRenderSummaryLine(summary);
406
+ }
407
+ `;
408
+ }
409
+ function executionLogActivationInjection(mode) {
410
+ if (normalizeExecutionLogMode(mode) === "never") return null;
411
+ return {
412
+ tag: "script",
413
+ location: "head",
414
+ children: `(() => { const l = location; if (${mode === "always" ? "true" : "/^https?:\\/\\/(?:localhost|127\\.0\\.0\\.1|\\[::1\\])(?::|$)/.test(l.origin) || new URLSearchParams(l.search).has('markless-log') || (() => { try { return localStorage.getItem('marklessLog') === '1'; } catch { return false; } })()"}) { globalThis.__mxLog = globalThis.__mxLog || new Set(); const g = globalThis.${MARKLESS_EXECUTION_LEDGER_GLOBAL} = globalThis.${MARKLESS_EXECUTION_LEDGER_GLOBAL} || ${MARKLESS_EXECUTION_LEDGER_INIT}; const s = document.currentScript && document.currentScript.textContent; if (s) { g.total.inline += s.length; if (!g.loadClosed) g.load.inline += s.length; } const c = (e) => { if (e.isTrusted) g.loadClosed = true; }; for (const t of ${JSON.stringify(EXECUTION_LOG_GESTURE_EVENTS)}) addEventListener(t, c, { capture: true, passive: true }); } })();`
415
+ };
416
+ }
417
+ //#endregion
418
+ //#region src/scalar-plan-loader.ts
419
+ function emitScalarPlanLoader(actions, routes) {
420
+ const ordered = routes.filter((route) => route.prefix.length > 0).toSorted((left, right) => right.prefix.length - left.prefix.length);
421
+ const scalarActions = actions.filter((action) => action.recordKind === "event" && action.plan?.kind === "scalar");
422
+ if (scalarActions.length === 0 && ordered.length === 0) return "";
423
+ return [
424
+ "export function loadScalarActionPlan(symbolId) {",
425
+ ...scalarActions.map((action) => `\tif (symbolId === ${JSON.stringify(action.plan.symbolId)}) return ${JSON.stringify({
426
+ hostNodeId: action.hostNodeId,
427
+ eventName: action.eventName,
428
+ scope: "",
429
+ plan: action.plan
430
+ })};`),
431
+ ...ordered.flatMap((route) => [
432
+ `\tif (symbolId.startsWith(${JSON.stringify(route.prefix)})) {`,
433
+ "importSource" in route ? `\t\treturn import(${JSON.stringify(route.importSource)}).then(module => module.loadScalarActionPlan?.(symbolId.slice(${route.prefix.length}))).then(action => action && ({ ...action, scope: ${JSON.stringify(route.prefix)} + action.scope }));` : `\t\treturn Promise.resolve(loadScalarActionPlan(symbolId.slice(${route.prefix.length}))).then(action => action && ({ ...action, scope: ${JSON.stringify(route.prefix)} + action.scope }));`,
434
+ " }"
435
+ ]),
436
+ "}"
437
+ ].join("\n");
438
+ }
439
+ //#endregion
440
+ //#region src/scalar-plan-source.ts
441
+ const MARKLESS_SCALAR_PLAN_SOURCE_QUERY = "markless-scalar-plans";
442
+ function scalarPlanSourceReference(source) {
443
+ return withQuery(source, {
444
+ "markless-symbols": null,
445
+ [MARKLESS_SCALAR_PLAN_SOURCE_QUERY]: null
446
+ });
447
+ }
448
+ //#endregion
449
+ //#region src/rebound-symbol-route.ts
450
+ function emitReboundSymbolImport(routes, reboundName) {
451
+ return routes.some(hasBoundSymbols) ? `import { marklessReboundSymbol as ${reboundName} } from '@markless/web/fns/rebound-symbol';` : "";
452
+ }
453
+ function hasBoundSymbols(route) {
454
+ return route.boundSymbols !== void 0 && Object.keys(route.boundSymbols).length > 0;
455
+ }
456
+ /**
457
+ * One loader for every composed child route, driven by a table: a page with many
458
+ * instances of a child adds a row per instance, not a copy of the loader.
459
+ */
460
+ function emitSymbolRouteTable(input) {
461
+ const { routes, functionName, fallbackName, reboundName } = input;
462
+ const sources = [...new Set(routes.flatMap((route) => route.importSource ? [route.importSource] : []))];
463
+ const keyLists = [];
464
+ const table = routes.map((route) => `[${JSON.stringify(route.prefix)}, ${route.importSource ? sources.indexOf(route.importSource) : -1}, ${hasBoundSymbols(route) ? boundEntry(route.boundSymbols, keyLists) : 0}]`);
465
+ return [
466
+ emitReboundSymbolImport(routes, reboundName),
467
+ `const ${functionName}Imports = [${sources.map((source) => `() => import(${JSON.stringify(source)})`).join(", ")}];`,
468
+ keyLists.length > 0 ? `const ${functionName}BoundKeys = [${keyLists.join(", ")}];` : "",
469
+ `const ${functionName}Routes = [${table.join(", ")}];`,
470
+ `${input.exported ? "export " : ""}function ${functionName}(symbolId) {`,
471
+ `\tfor (const [prefix, at, bound] of ${functionName}Routes) {`,
472
+ " if (!symbolId.startsWith(prefix)) continue;",
473
+ " const rest = symbolId.slice(prefix.length);",
474
+ `\t\tconst unbound = () => at < 0 ? (prefix ? ${functionName}(rest) : ${fallbackName}(rest)) : ${functionName}Imports[at]().then((mod) => mod.loadSymbol ? mod.loadSymbol(rest) : Promise.reject(new Error(\`Unknown child async symbol \${symbolId}\`)));`,
475
+ hasAnyBound(routes) ? [keyLists.length > 0 ? `\t\tconst boundId = !bound ? undefined : Array.isArray(bound) ? (${functionName}BoundKeys[bound[1]].includes(rest) ? \`bound:\${encodeURIComponent(rest)}:\${bound[0]}\` : undefined) : Object.hasOwn(bound, rest) ? bound[rest] : undefined;` : " const boundId = bound && Object.hasOwn(bound, rest) ? bound[rest] : undefined;", `\t\tif (boundId) return ${reboundName}(${fallbackName}(boundId), prefix, unbound);`].join("\n") : "",
476
+ " return unbound();",
477
+ " }",
478
+ `\treturn ${fallbackName}(symbolId);`,
479
+ "}"
480
+ ].filter((line) => line !== "").join("\n");
481
+ }
482
+ function boundEntry(boundSymbols, keyLists) {
483
+ const entries = Object.entries(boundSymbols);
484
+ const [firstKey, firstId] = entries[0];
485
+ const head = `bound:${encodeURIComponent(firstKey)}:`;
486
+ const suffix = firstId.startsWith(head) ? firstId.slice(head.length) : void 0;
487
+ if (suffix === void 0 || entries.some(([key, id]) => id !== `bound:${encodeURIComponent(key)}:${suffix}`)) return JSON.stringify(boundSymbols);
488
+ const keys = JSON.stringify(entries.map(([key]) => key));
489
+ let index = keyLists.indexOf(keys);
490
+ if (index < 0) index = keyLists.push(keys) - 1;
491
+ return `[${JSON.stringify(suffix)}, ${index}]`;
492
+ }
493
+ function hasAnyBound(routes) {
494
+ return routes.some(hasBoundSymbols);
495
+ }
496
+ //#endregion
497
+ //#region src/source-module.ts
498
+ const MARKLESS_VIRTUAL_PREFIX = "virtual:markless:";
499
+ const MARKLESS_BOUND_SYMBOLS_EXPORT = "marklessBoundSymbols";
500
+ const RESUME_ENTRY_SPECIFIER = "@markless/core/web/resume";
501
+ const STORAGE_FREE_RESUME_ENTRY_SPECIFIER = "@markless/core/web/resume-storage-free";
502
+ const SYMBOL_VIRTUAL_PREFIX = `${MARKLESS_VIRTUAL_PREFIX}symbol:`;
503
+ function symbolVirtualModuleId(filename, symbolId) {
504
+ return `${SYMBOL_VIRTUAL_PREFIX}${encodeURIComponent(filename)}:${encodeURIComponent(symbolId)}`;
505
+ }
506
+ function symbolEntryVirtualModuleId(filename, symbolId) {
507
+ return `${symbolVirtualModuleId(filename, symbolId)}:entry`;
508
+ }
509
+ function encodedSymbolSource(filename) {
510
+ return encodeURIComponent(filename);
511
+ }
512
+ function symbolVirtualModuleSourceFile(moduleId) {
513
+ const bare = moduleId.startsWith("\0") ? moduleId.slice(1) : moduleId;
514
+ if (!bare.startsWith(SYMBOL_VIRTUAL_PREFIX)) return null;
515
+ const encoded = bare.slice(SYMBOL_VIRTUAL_PREFIX.length);
516
+ const separator = encoded.indexOf(":");
517
+ if (separator <= 0 || separator === encoded.length - 1) return null;
518
+ if (encoded.includes(":", separator + 1)) return null;
519
+ try {
520
+ return decodeURIComponent(encoded.slice(0, separator));
521
+ } catch {
522
+ return null;
523
+ }
524
+ }
525
+ function resumeVirtualModuleId(filename) {
526
+ return `${MARKLESS_VIRTUAL_PREFIX}resume:${encodeURIComponent(filename)}`;
527
+ }
528
+ function prerenderWakeVirtualModuleId(filename) {
529
+ return `${MARKLESS_VIRTUAL_PREFIX}prerender-wake:${encodeURIComponent(filename)}`;
530
+ }
531
+ function settleVirtualModuleId(filename) {
532
+ return `${MARKLESS_VIRTUAL_PREFIX}settle:${encodeURIComponent(filename)}`;
533
+ }
534
+ /**
535
+ * The settle module: import targets and data, no logic. It carries the DOM
536
+ * filler, each boundary's async runner keyed by graph node, and each bound
537
+ * symbol's compiled derive function keyed by the id the fill plan references.
538
+ * Rolldown resolves the real chunk urls, so nothing here is a url the document
539
+ * has to carry, and a page that never settles an arm never loads it.
540
+ */
541
+ function emitSettleModule(input) {
542
+ const imports = [...input.runners, ...input.derives].map((entry) => entry.symbol);
543
+ const seen = /* @__PURE__ */ new Map();
544
+ const lines = ["export { marklessApplySettlePlan as f } from '@markless/web/fns/settle-plan';"];
545
+ for (const symbol of imports) {
546
+ if (seen.has(symbol.id)) continue;
547
+ seen.set(symbol.id, symbol.exportName);
548
+ lines.push(`import { ${symbol.exportName} } from ${JSON.stringify(symbol.chunk)};`);
549
+ }
550
+ const entries = (rows) => `{${rows.map((row) => `${JSON.stringify(row.key)}: ${seen.get(row.symbolId)}`).join(",")}}`;
551
+ lines.push(`export const r = ${entries(input.runners.map((entry) => ({
552
+ key: entry.node,
553
+ symbolId: entry.symbol.id
554
+ })))};`);
555
+ lines.push(`export const d = ${entries(input.derives.map((entry) => ({
556
+ key: entry.id,
557
+ symbolId: entry.symbol.id
558
+ })))};`);
559
+ return `${lines.join("\n")}\n`;
560
+ }
561
+ function prerenderWakeVirtualModuleSourceFile(moduleId) {
562
+ const bare = moduleId.startsWith("\0") ? moduleId.slice(1) : moduleId;
563
+ const prefix = `${MARKLESS_VIRTUAL_PREFIX}prerender-wake:`;
564
+ if (!bare.startsWith(prefix)) return null;
565
+ try {
566
+ return decodeURIComponent(bare.slice(prefix.length));
567
+ } catch {
568
+ return null;
569
+ }
570
+ }
571
+ function scopedSymbolExportName(moduleId, exportName) {
572
+ return `${exportName}_${stringHash(moduleId)}`;
573
+ }
574
+ function rewriteSymbolModuleExport(source, fromExportName, toExportName) {
575
+ return source.replace(`export function ${fromExportName}`, `export function ${toExportName}`).replace(`export async function ${fromExportName}`, `export async function ${toExportName}`);
576
+ }
577
+ function payloadModule(payload) {
578
+ return [
579
+ `export const state = ${JSON.stringify(payload.state, null, " ")};`,
580
+ `export const runtimeDemandMap = ${JSON.stringify(withoutFirstUse(payload.runtimeDemandMap), null, " ")};`,
581
+ `export const view = ${JSON.stringify(payload.view, null, " ")};`,
582
+ ""
583
+ ].join("\n");
584
+ }
585
+ function withoutFirstUse(runtimeDemandMap) {
586
+ const map = runtimeDemandMap;
587
+ if (!map?.actions?.some((action) => "firstUse" in action) && !(map && ("firstUsePage" in map || "armActions" in map))) return runtimeDemandMap;
588
+ const { firstUsePage: _firstUsePage, armActions: _armActions, ...rest } = map;
589
+ return {
590
+ ...rest,
591
+ ...map.actions ? { actions: map.actions.map((action) => {
592
+ const { firstUse: _firstUse, ...fields } = action;
593
+ return fields;
594
+ }) } : {}
595
+ };
596
+ }
597
+ /** The module-local name a direct-CSR module's root renders under. */
598
+ function csrRootLocalName(rootExportName) {
599
+ return `marklessCsr${rootExportName}`;
600
+ }
601
+ function emitPublicRenderModule(source, input) {
602
+ if (!input.rootExportName) return source;
603
+ const declaration = `export function ${input.rootExportName}()`;
604
+ if (!source.includes(declaration)) throw new Error(`MARKLESS_CSR_ROOT_DECLARATION_MISSING: ${input.rootExportName}`);
605
+ const localName = csrRootLocalName(input.rootExportName);
606
+ if (!input.executionLogEnabled) return source.replace(declaration, `function ${localName}()`);
607
+ const implementationName = `marklessRender${input.rootExportName}`;
608
+ return [
609
+ source.replace(declaration, `function ${implementationName}()`),
610
+ `function ${localName}() {`,
611
+ `\tconst output = ${implementationName}();`,
612
+ " if (globalThis.__mxLog) globalThis.__mxLoadLog().then(log => log.logMarklessRenderSummary());",
613
+ " return output;",
614
+ "}"
615
+ ].join("\n");
616
+ }
617
+ function emitSourceModule(input) {
618
+ if (input.directCsr && input.prerenderRecords) input = {
619
+ ...input,
620
+ prerenderRecords: false
621
+ };
622
+ const symbolsOnly = input.environment === "client" && input.clientOutput === "symbols-only";
623
+ const routeSymbols = input.environment === "client" && input.symbolRoutes.length > 0;
624
+ const canonicalRenderData = input.environment === "client" && !symbolsOnly && !input.prerenderRecords && input.canonicalRenderData === true && input.publicRenderRootExportName === null && !!input.publicSsrModuleSource && !!input.renderDataId;
625
+ const emitsSsrBody = !!input.publicSsrModuleSource && !(input.environment === "client" && (symbolsOnly || !input.prerenderRecords && !input.dev));
626
+ const csrRootName = input.environment !== "server" && !symbolsOnly && !input.prerenderRecords && input.publicRenderRootExportName ? csrRootLocalName(input.publicRenderRootExportName) : null;
627
+ return [
628
+ !input.publicSsrModuleSource && !input.publicRenderModuleSource || symbolsOnly || !input.renderDataId || input.environment === "client" && !input.publicRenderModuleSource && !input.prerenderRecords && !input.dev && !canonicalRenderData ? "" : canonicalRenderData ? emitsSsrBody ? `import { marklessPrerenderData, marklessRenderData } from '${input.renderDataId}';` : `import { marklessPrerenderData } from '${input.renderDataId}';` : `import { marklessRenderData } from '${input.renderDataId}';`,
629
+ symbolsOnly ? "" : `import { state as payloadState, view as payloadView, runtimeDemandMap as payloadRuntimeDemandMap } from '${input.payloadId}';`,
630
+ input.environment === "client" && input.directCsr === true && input.hasComputedState === true ? ["import { installMarklessDerivedReconcile } from '@markless/web/fns/reconcile-plane';", "installMarklessDerivedReconcile();"].join("\n") : null,
631
+ input.environment === "client" && input.hasComputedState === true ? emitRosterResumeLoaderInstall() : null,
632
+ input.environment === "client" && input.hasOverlayMarks === true ? emitOverlayLoaderInstall() : null,
633
+ input.environment === "client" && input.hasIdleEvents === true && !symbolsOnly ? emitIdleTriggerInstall() : null,
634
+ input.environment === "client" ? clientRowMintLoader(input) : null,
635
+ "",
636
+ emitLoadSymbol(input),
637
+ symbolsOnly && input.scalarActions ? emitScalarPlanLoader(input.scalarActions, input.symbolRoutes.map((route) => "importSource" in route ? {
638
+ ...route,
639
+ importSource: scalarPlanSourceReference(route.importSource)
640
+ } : route)) : "",
641
+ symbolsOnly && input.closureActions && emitsClosurePlanLoader(input.closureActions, input.closurePlanRoutes ?? []) ? `${emitClosurePlanRoute(input.closurePlanRoutes ?? [], "loadClosureActionPlan", input.closureActions)}\nexport { loadClosureActionPlan };` : null,
642
+ input.behaviorSymbols?.length ? emitDirectSourceSymbolLoader(input.behaviorSymbols, "readMarklessBehaviorSourceSymbol").replace("function loadSymbol(", "function loadBehaviorSymbol(") : "",
643
+ input.environment === "client" && input.executionLog !== "never" ? emitExecutionLogLoader() : "",
644
+ routeSymbols ? "const marklessLoadLocalSymbol = loadSymbol;" : "",
645
+ (symbolsOnly || input.publicRenderRootExportName === null) && !routeSymbols ? "export { loadSymbol };" : "",
646
+ symbolsOnly ? "" : "export { payloadView };",
647
+ symbolsOnly ? "" : "export { payloadRuntimeDemandMap };",
648
+ input.devResumeReexport && input.environment === "client" ? `export { resumeContainerEvent } from '${resumeVirtualModuleId(input.filename)}';` : "",
649
+ "",
650
+ input.environment === "server" || symbolsOnly || input.prerenderRecords ? "" : emitPublicRenderModule(input.publicRenderModuleSource, {
651
+ executionLogEnabled: input.executionLog !== "never",
652
+ rootExportName: input.publicRenderRootExportName
653
+ }),
654
+ emitsSsrBody ? input.publicSsrModuleSource : "",
655
+ routeSymbols ? emitLazySymbolRouteFunction(input.symbolRoutes, "marklessSsrLoadSymbolRoute", "marklessLoadLocalSymbol", input.scalarActions !== void 0) : "",
656
+ routeSymbols && !symbolsOnly && input.directCsr === true ? emitComposedArmRecordsInstall() : null,
657
+ symbolsOnly && routeSymbols ? "export { marklessSsrLoadSymbolRoute as loadSymbol };" : "",
658
+ symbolsOnly ? "" : emitCompiledAppDefault({
659
+ environment: input.environment,
660
+ executionLog: input.executionLog,
661
+ headInjections: input.headInjections,
662
+ storageSeeds: input.storageSeeds,
663
+ inlineResumerSources: input.inlineResumerSources,
664
+ prerenderBoot: input.prerenderBoot,
665
+ resumeModuleUrl: input.resumeModuleUrl,
666
+ prerenderWakeModuleUrl: input.prerenderWakeModuleUrl,
667
+ rootExportName: input.publicRenderRootExportName,
668
+ csrRootName,
669
+ symbolLoaderName: routeSymbols ? "marklessSsrLoadSymbolRoute" : "loadSymbol",
670
+ ssrExportName: input.publicRenderSsrExportName,
671
+ ssrComponents: input.publicRenderSsrComponentExports ?? [],
672
+ canonicalRenderData,
673
+ prerenderRecords: input.prerenderRecords,
674
+ dev: input.dev
675
+ }),
676
+ ...emitSharedDefinitionExports(input.sharedDefinitionExports ?? [], input.publicRenderSsrComponentExports ?? []),
677
+ ""
678
+ ].filter((line) => line !== null).join("\n");
679
+ }
680
+ const MARKLESS_SHARED_CALL_UNCOMPILED = "MARKLESS_SHARED_CALL_UNCOMPILED";
681
+ /**
682
+ * One real ES named export per authored shared definition, bound to a callable
683
+ * that only ever throws.
684
+ *
685
+ * The export exists for two reasons, and neither is "run the definition".
686
+ * Linking first: a `.ts` barrel writing `export { nscShared as state } from
687
+ * './family.tsrx'` is resolved before anything runs, and the emitted module
688
+ * replacing the authored one wholesale made that a SyntaxError. Failing closed
689
+ * second: a compiled consumer's `family.state()` is lowered by the compiler and
690
+ * never reaches this binding, so anything that DOES reach it is an uncompiled
691
+ * call site, which cannot be served correctly — a shared instance resolves
692
+ * against the widget the caller renders under, and an uncompiled call has no
693
+ * such caller. It throws by name rather than quietly becoming a second,
694
+ * unratified runtime API.
695
+ */
696
+ function emitSharedDefinitionExports(sharedExports, ssrComponents) {
697
+ if (sharedExports.length === 0) return [];
698
+ const taken = /* @__PURE__ */ new Set([...RESERVED_MODULE_BINDINGS, ...ssrComponents.map((component) => component.exportName)]);
699
+ return sharedExports.map((name) => {
700
+ if (taken.has(name)) throw new Error(`MARKLESS_SHARED_EXPORT_NAME_RESERVED: ${name}`);
701
+ taken.add(name);
702
+ const message = `${MARKLESS_SHARED_CALL_UNCOMPILED}: ${name} — a shared definition can only be called from a compiled module; this call site was not compiled.`;
703
+ return `export const ${name} = () => { throw new Error(${JSON.stringify(message)}); };`;
704
+ });
705
+ }
706
+ /**
707
+ * Whether this app's serialized state defines any computed node. Computed
708
+ * definitions are what `createRuntimeGraph` turns into derived graph nodes on
709
+ * resume, so they are exactly the apps derived reconciliation can act on.
710
+ */
711
+ function payloadHasComputed(payloadState) {
712
+ const computed = payloadState?.computed;
713
+ return Array.isArray(computed) && computed.length > 0;
714
+ }
715
+ function emitIdleTriggerInstall() {
716
+ return ["import { installMarklessIdle } from '@markless/web/fns/idle-trigger';", "installMarklessIdle();"].join("\n");
717
+ }
718
+ /**
719
+ * The one line that makes elevation cost nothing until it is used.
720
+ *
721
+ * Writing the `import()` specifier HERE rather than in the runtime is the whole
722
+ * mechanism: a module every app loads cannot name the behaviour without making
723
+ * every app ship its chunk. The handoff is a global rather than a slot module
724
+ * for the same reason - a slot module is bytes every app pays for a capability
725
+ * most of them do not have. Nothing is fetched until the runtime calls it.
726
+ */
727
+ function emitOverlayLoaderInstall() {
728
+ return [
729
+ "globalThis.__marklessOverlay = (root) =>",
730
+ " root.querySelector('[overlay]')",
731
+ " ? import('@markless/web/fns/overlay').then((m) => m.installOverlayBehavior(root))",
732
+ " : undefined;"
733
+ ].join("\n");
734
+ }
735
+ /**
736
+ * The same one line for the live roster, gated on the same fact the reconcile
737
+ * plane is gated on: a payload with no computed nodes can hold no roster
738
+ * derivation, so it never names the module and never emits its chunk.
739
+ *
740
+ * Both call sites (the start-up wiring and a sync computed's re-derive) sit in
741
+ * modules every resumed page runs, which is why neither may write the specifier.
742
+ * A composed MDX route writes it too: it cannot see its islands' computeds.
743
+ */
744
+ function emitRosterResumeLoaderInstall() {
745
+ return "globalThis.__marklessRosterResume ??= () => import('@markless/web/fns/roster-resume');";
746
+ }
747
+ /**
748
+ * The same one line for the row mint, and for the same reason.
749
+ *
750
+ * `resume-keyed-repeats` is loaded by EVERY repeat, so it cannot name the
751
+ * building half: doing so makes an app whose rows only reorder emit the mint
752
+ * chunk anyway. Written here, the specifier exists only in a build the compiler
753
+ * recorded a mintable repeat for; the repeat runtime reads the loader off the
754
+ * global and refuses to build without one.
755
+ */
756
+ function emitRowMintLoaderInstall() {
757
+ return "globalThis.__marklessRowMint ??= () => import('@markless/web/fns/row-mint');";
758
+ }
759
+ /**
760
+ * The same one line for per-enclosing-row wiring: only a page holding a `@for`
761
+ * inside another `@for`'s rows names the module, so no other app emits its chunk.
762
+ */
763
+ function nestedRepeatsLoader(runtimeDemandMap, linked = false) {
764
+ return linked || demandsKeyedRepeatModule(runtimeDemandMap, NESTED_REPEATS_RUNTIME_MODULE_ID) ? ["globalThis.__marklessNestedRepeats ??= (...input) =>", " import('@markless/web/fns/nested-repeats').then((nested) => nested.wireNestedRepeats(...input));"].join("\n") : null;
765
+ }
766
+ /**
767
+ * True when the compiler folded the mint into a keyed-repeat record - which it
768
+ * does exactly for a record carrying `rowTemplate` or `emptyArm`, the two fields
769
+ * that make a repeat able to build nodes.
770
+ */
771
+ function demandsRowMint(runtimeDemandMap) {
772
+ const records = runtimeDemandMap?.payloadRecords;
773
+ return Array.isArray(records) && records.some((record) => record.kind === "keyed-repeat" && record.runtimeModuleIds?.includes(ROW_MINT_RUNTIME_MODULE_ID) === true);
774
+ }
775
+ /**
776
+ * The component-rooted mint, which also needs this page's render-data surface.
777
+ *
778
+ * It answers the SAME global as the template mint, whose builders it re-exports:
779
+ * the repeat runtime carries no second loader, so a page with no component row
780
+ * ships not one byte of this path. Nothing page-specific is written here - every
781
+ * page emits this same line - because one document can hold several modules that
782
+ * install a mint, and the one that builds every kind of row must keep the global
783
+ * whichever is evaluated last. The surface travels on the runtime input instead
784
+ * and arrives as the loader's first argument.
785
+ */
786
+ function emitRowComponentMintLoaderInstall() {
787
+ return [
788
+ "globalThis.__marklessRowMint = Object.assign(",
789
+ " (...input) => import('@markless/web/fns/row-component-mint').then((mint) => mint.marklessRowComponentMint(...input)),",
790
+ " { components: true },",
791
+ ");"
792
+ ].join("\n");
793
+ }
794
+ function componentRowLoader(input) {
795
+ if (!input.renderDataId) return void 0;
796
+ if (input.linkedRowComponents || demandsKeyedRepeatModule(input.runtimeDemandMap, ROW_COMPONENT_MINT_RUNTIME_MODULE_ID)) return emitRowComponentMintLoaderInstall();
797
+ return input.linkedRowSlotReaders || demandsKeyedRepeatModule(input.runtimeDemandMap, ROW_SLOT_MINT_RUNTIME_MODULE_ID) ? emitRowSlotMintLoaderInstall() : void 0;
798
+ }
799
+ function clientRowMintLoader(input) {
800
+ const mint = demandsRowComponentMint(input.runtimeDemandMap) ? emitRowComponentMintLoaderInstall() : componentRowLoader(input) ?? (input.linkedRowTemplates || demandsRowMint(input.runtimeDemandMap) ? emitRowMintLoaderInstall() : null);
801
+ const nested = nestedRepeatsLoader(input.runtimeDemandMap, input.linkedNestedRepeats);
802
+ return mint && nested ? `${mint}\n${nested}` : mint ?? nested;
803
+ }
804
+ function emitRowSlotMintLoaderInstall() {
805
+ return ["if (!globalThis.__marklessRowMint?.components) globalThis.__marklessRowMint = (...input) =>", " import('@markless/web/fns/row-slot-mint').then((mint) => mint.marklessRowSlotMint(...input));"].join("\n");
806
+ }
807
+ /**
808
+ * True when the compiler folded the component mint into a keyed-repeat record -
809
+ * which it does exactly for a record carrying `rowComponent`.
810
+ */
811
+ function demandsRowComponentMint(runtimeDemandMap) {
812
+ return demandsKeyedRepeatModule(runtimeDemandMap, ROW_COMPONENT_MINT_RUNTIME_MODULE_ID);
813
+ }
814
+ function demandsKeyedRepeatModule(runtimeDemandMap, moduleId) {
815
+ const records = runtimeDemandMap?.payloadRecords;
816
+ return Array.isArray(records) && records.some((record) => record.kind === "keyed-repeat" && record.runtimeModuleIds?.includes(moduleId) === true);
817
+ }
818
+ const ROW_MINT_RUNTIME_MODULE_ID = "web/fns/row-mint";
819
+ const NESTED_REPEATS_RUNTIME_MODULE_ID = "web/fns/nested-repeats";
820
+ const ROW_COMPONENT_MINT_RUNTIME_MODULE_ID = "web/fns/row-component-mint";
821
+ const ROW_SLOT_MINT_RUNTIME_MODULE_ID = "web/fns/row-slot-mint";
822
+ /** True when the compiler recorded an `overlay` mark for this module. */
823
+ function demandsOverlay(runtimeDemandMap) {
824
+ const records = runtimeDemandMap?.payloadRecords;
825
+ return Array.isArray(records) && records.some((record) => record.kind === "overlay");
826
+ }
827
+ function emitResumeModule(input) {
828
+ const routeSymbols = input.symbolRoutes.length > 0;
829
+ const resumeSymbolLoader = routeSymbols ? "marklessSsrLoadSymbolRoute" : "loadSymbol";
830
+ const servedPlansOnly = leanResumeMode(input.runtimeDemandMap) === "none" && leanResumeMode(input.servedScalarPlans) !== "none";
831
+ const scalarSpecializations = scalarDispatcherSpecializations(servedPlansOnly ? {
832
+ ...input,
833
+ runtimeDemandMap: input.servedScalarPlans
834
+ } : input);
835
+ const stagedPrerender = (input.prerenderTriggerGroups?.length ?? 0) > 0;
836
+ const resumeContainerEvent = emitQueuedResumeContainerEvent(emitResumeContainerEvent(resumeSymbolLoader, input.needsFullResume ?? false, input.storageCells !== true && input.payloadState?.version === ASYNC_PROTOCOL_VERSION, servedPlansOnly ? "scalar" : composedLeanMode(input.symbolRoutes.length > 0, leanResumeMode(input.runtimeDemandMap)), scalarSpecializations, input.runtimeDemandMap, input.executionLog !== "never", input.prerenderDataId, stagedPrerender, componentRowLoader(input) ? input.lazyRenderDataId ?? input.renderDataId : void 0, input.symbolRoutes.length > 0 || servedPlansOnly, (input.closurePlanRoutes ?? []).some((route) => "importSource" in route) && scalarSpecializations.length > 0 && !input.prerenderDataId, input.streamsArms === true));
837
+ const closureImports = [
838
+ "marklessClosureRouted",
839
+ "marklessPrimeClosure",
840
+ "marklessPrimeRoutedClosure",
841
+ "marklessRunClosureAction",
842
+ "marklessRunRoutedClosure"
843
+ ].filter((name) => resumeContainerEvent.includes(name));
844
+ return [
845
+ input.boundSymbolDescriptors ? `export const ${MARKLESS_BOUND_SYMBOLS_EXPORT} = ${emitBoundSymbolDescriptors(input.boundSymbolDescriptors)};` : null,
846
+ input.prerenderDataId && !stagedPrerender && resumeContainerEvent.includes("marklessPrerenderData") ? `import { marklessPrerenderData } from '${input.prerenderDataId}';` : null,
847
+ stagedPrerender && input.prerenderDataId ? `async function marklessLoadPrerenderData() { const module = await import('${input.lazyRenderDataId ?? input.prerenderDataId}'); return module.marklessPrerenderData; }` : null,
848
+ `import { runtimeDemandMap as payloadRuntimeDemandMap } from '${input.payloadId}';`,
849
+ payloadHasComputed(input.payloadState) ? [
850
+ "import { installMarklessDerivedReconcile } from '@markless/web/fns/reconcile-plane';",
851
+ "installMarklessDerivedReconcile();",
852
+ emitRosterResumeLoaderInstall()
853
+ ].join("\n") : input.rosterDerivation === true ? emitRosterResumeLoaderInstall() : null,
854
+ demandsOverlay(input.runtimeDemandMap) ? emitOverlayLoaderInstall() : null,
855
+ input.hasIdleEvents ? emitIdleTriggerInstall() : null,
856
+ componentRowLoader(input) ?? (input.linkedRowTemplates || demandsRowMint(input.runtimeDemandMap) ? emitRowMintLoaderInstall() : null),
857
+ nestedRepeatsLoader(input.runtimeDemandMap, input.linkedNestedRepeats),
858
+ scalarSpecializations.length > 0 ? [
859
+ "import { marklessDecodeScalarCell, marklessReadScalarCell, marklessScalarSpecializedError } from '@markless/web/fns/scalar-specialized';",
860
+ resumeContainerEvent.includes("marklessScalarServedOwner") ? `import { marklessScalarLocate, marklessScalarServedOwner, marklessScalarServedPrime${resumeContainerEvent.includes("marklessScalarServedRecord") ? ", marklessScalarServedRecord" : ""} } from '@markless/web/fns/scalar-served';` : "",
861
+ ...closureImports.length > 0 ? [`import { ${closureImports.join(", ")} } from '@markless/web/fns/closure-action';`] : [],
862
+ "import { marklessWriteScalar } from '@markless/web/fns/write-scalar';",
863
+ "import { marklessUpdateText } from '@markless/web/fns/update-text';"
864
+ ].join("\n") : "",
865
+ scalarSpecializations.length > 0 || stagedPrerender ? "import { marklessFindElementAtDomOrderIndex } from '@markless/web/fns/dom-order';" : "",
866
+ "",
867
+ input.executionLog === "never" ? "" : emitExecutionLogLoader(),
868
+ input.installResumeSummary && input.executionLog !== "never" ? "if (globalThis.__mxLog) globalThis.__mxLoadLog().then(log => log.installMarklessExecutionLog());" : null,
869
+ "",
870
+ emitLoadSymbol(input, stagedPrerender ? "readMarklessWakeSourceSymbol" : void 0),
871
+ routeSymbols ? "const marklessLoadLocalSymbol = loadSymbol;" : "",
872
+ routeSymbols ? emitLazySymbolRouteFunction(input.symbolRoutes, "marklessSsrLoadSymbolRoute", "marklessLoadLocalSymbol") : "",
873
+ routeSymbols ? "export { marklessSsrLoadSymbolRoute as loadSymbol };" : "",
874
+ routeSymbols ? emitComposedArmRecordsInstall() : null,
875
+ stagedPrerender ? emitPrerenderTriggerGroupLoader(input.prerenderTriggerGroups ?? []) : "",
876
+ resumeContainerEvent.includes("marklessClosurePlanRoute") ? emitClosurePlanRoute(input.closurePlanRoutes ?? [], "marklessClosurePlanRoute", []) : null,
877
+ resumeContainerEvent,
878
+ ""
879
+ ].filter((line) => line !== null).join("\n");
880
+ }
881
+ function emitBoundSymbolDescriptors(descriptors) {
882
+ return JSON.stringify(Object.fromEntries(Object.keys(descriptors).sort().map((boundaryId) => [boundaryId, descriptors[boundaryId]])));
883
+ }
884
+ function emitQueuedResumeContainerEvent(source, { censusRepair = true } = {}) {
885
+ const implementation = source.replace("export async function resumeContainerEvent", "async function marklessResumeContainerEvent");
886
+ if (implementation === source) throw new Error("MARKLESS_RESUME_DISPATCH_EXPORT_MISSING");
887
+ return [
888
+ implementation,
889
+ "export function resumeContainerEvent(input) {",
890
+ " const root = input.root;",
891
+ censusRepair ? " if (root.__marklessShifted) return import('@markless/web/fns/served-census-repair').then((census) => (census.marklessRepairCensus(root), resumeContainerEvent(input)));" : "",
892
+ " if (!root.__marklessDispatch) {",
893
+ " let handler = marklessResumeContainerEvent, tail = Promise.resolve(), done = tail, lastEvent = null, lastEventTime = undefined, seen = new WeakMap();",
894
+ " root.__marklessRegisterDispatch = next => {",
895
+ " const fallback = handler;",
896
+ " handler = input => next(input, fallback);",
897
+ " };",
898
+ " root.__marklessDispatch = next => {",
899
+ " const event = next.event, eventTime = event?.timeStamp;",
900
+ " if (event && next.eventRecord && next.element) event.__marklessPressHost ??= next.element;",
901
+ " if ((event === lastEvent && eventTime === lastEventTime) || (seen.has(event) && seen.get(event) === eventTime)) return done;",
902
+ " if (Object(event) === event) seen.set(event, eventTime);",
903
+ " lastEvent = event;",
904
+ " lastEventTime = eventTime;",
905
+ " let release;",
906
+ " const started = new Promise(resolve => release = resolve);",
907
+ " const run = () => (root.__marklessReleaseDispatch = release, handler(next));",
908
+ " done = tail.then(run, run);",
909
+ " done.then(release, release);",
910
+ " tail = started;",
911
+ " return done;",
912
+ " };",
913
+ " }",
914
+ " return root.__marklessDispatch(input);",
915
+ "}"
916
+ ].join("\n");
917
+ }
918
+ function emitComposedArmRecordsInstall() {
919
+ return ["import { installMarklessComposedArmRecords } from '@markless/web/fns/instance-scope';", "installMarklessComposedArmRecords();"].join("\n");
920
+ }
921
+ function emitLazySymbolRouteFunction(routes, functionName, fallbackName = "loadSymbol", includeScalarActionPlans = false) {
922
+ if (routes.length === 0) return "";
923
+ return emitSymbolRouteTable({
924
+ routes: [...routes].sort((left, right) => right.prefix.length - left.prefix.length).map((route) => "importSource" in route ? {
925
+ ...route,
926
+ importSource: symbolRouteImportSource$1(route.importSource, includeScalarActionPlans)
927
+ } : route),
928
+ functionName,
929
+ fallbackName,
930
+ reboundName: `${functionName}Rebound`
931
+ });
932
+ }
933
+ function emitsClosurePlanLoader(actions, routes) {
934
+ return routes.some((route) => "importSource" in route) || actions.some((action) => action.plan?.kind === "closure");
935
+ }
936
+ function emitClosurePlanRoute(routes, functionName, actions) {
937
+ const shapes = [];
938
+ const local = actions.filter((action) => action.recordKind === "event" && action.plan?.kind === "closure").map((action) => {
939
+ const { symbolId, cells, computed, updates } = action.plan;
940
+ const shape = JSON.stringify({
941
+ cells,
942
+ computed,
943
+ updates
944
+ });
945
+ if (!shapes.includes(shape)) shapes.push(shape);
946
+ return `\t${JSON.stringify(symbolId)}: { symbolId: ${JSON.stringify(symbolId)}, ...marklessLocalClosureShapes[${shapes.indexOf(shape)}] },`;
947
+ });
948
+ const ordered = [...routes].sort((left, right) => right.prefix.length - left.prefix.length);
949
+ const localLookup = local.length > 0 ? "Object.hasOwn(marklessLocalClosurePlans, symbolId) ? marklessLocalClosurePlans[symbolId] : undefined" : "undefined";
950
+ return [
951
+ local.length > 0 ? [
952
+ `const marklessLocalClosureShapes = [${shapes.join(", ")}];`,
953
+ "const marklessLocalClosurePlans = {",
954
+ ...local,
955
+ "};"
956
+ ].join("\n") : "",
957
+ `function ${functionName}(symbolId) {`,
958
+ ...ordered.flatMap((route) => [
959
+ ` if (symbolId.startsWith(${JSON.stringify(route.prefix)})) {`,
960
+ "importSource" in route ? ` return import(${JSON.stringify(symbolRouteImportSource$1(route.importSource))}).then((mod) => mod.loadClosureActionPlan?.(symbolId.slice(${route.prefix.length})));` : route.prefix.length > 0 ? ` return ${functionName}(symbolId.slice(${route.prefix.length}));` : ` return ${localLookup};`,
961
+ " }"
962
+ ]),
963
+ ` return ${localLookup};`,
964
+ "}"
965
+ ].filter(Boolean).join("\n");
966
+ }
967
+ function symbolRouteImportSource$1(importSource, includeScalarActionPlans = false) {
968
+ if (includeScalarActionPlans) return scalarPlanSourceReference(importSource);
969
+ return importSource.includes("?") ? `${importSource}&markless-symbols` : `${importSource}?markless-symbols`;
970
+ }
971
+ function emitCompiledAppDefault(input) {
972
+ const renderCsrEntry = input.csrRootName ? [` renderCsr: ${input.csrRootName},`] : [];
973
+ const symbolLoaderEntry = input.environment !== "server" && input.rootExportName === null ? [`\tloadSymbol: ${input.symbolLoaderName},`] : input.prerenderRecords === true ? [`\tloadSymbol: ${input.symbolLoaderName},`] : [];
974
+ const renderDataEntry = input.canonicalRenderData ? [" renderData: marklessPrerenderData,"] : [];
975
+ const servesSsr = !!input.ssrExportName && (input.environment !== "client" || input.prerenderRecords || input.dev);
976
+ const renderSsrEntry = servesSsr ? [
977
+ " renderSsr(props, marklessRenderContext) {",
978
+ ` return ${input.ssrExportName}(props, marklessRenderContext);`,
979
+ " },"
980
+ ] : [];
981
+ const renderSsrComponentsEntry = servesSsr && input.ssrComponents.length > 0 ? [` renderSsrComponents: { ${input.ssrComponents.map((component) => `${JSON.stringify(component.exportName)}: { renderSsr: ${component.ssrFunctionName} }`).join(", ")} },`] : [];
982
+ const resumeModuleEntry = input.resumeModuleUrl && input.environment !== "client" ? [` resumeModuleUrl: ${JSON.stringify(input.resumeModuleUrl)},`] : [];
983
+ const prerenderWakeModuleEntry = input.prerenderWakeModuleUrl && input.environment !== "client" ? [`\tprerenderWakeModuleUrl: ${JSON.stringify(input.prerenderWakeModuleUrl)},`] : [];
984
+ const inlineResumerEntry = input.inlineResumerSources && input.environment !== "client" ? [`\tinlineResumerSources: ${JSON.stringify(input.inlineResumerSources)},`] : [];
985
+ const prerenderBootEntry = input.prerenderBoot && input.environment !== "client" ? [`\tprerenderBoot: ${JSON.stringify(input.prerenderBoot)},`] : [];
986
+ const headInjectionEntry = input.headInjections?.length && input.environment !== "client" ? [` headInjections: ${JSON.stringify(input.headInjections)},`] : [];
987
+ const storageSeedEntry = input.storageSeeds?.length && input.environment !== "client" ? [`\tstorageSeeds: ${JSON.stringify(input.storageSeeds)},`] : [];
988
+ const modulePreloadEntry = input.resumeModuleUrl && input.environment === "server" ? [` modulePreloads: [{ href: ${JSON.stringify(input.resumeModuleUrl)}, fetchPriority: "high" }],`] : [];
989
+ const metadataEntries = input.environment === "client" ? [] : [
990
+ ...headInjectionEntry,
991
+ ...storageSeedEntry,
992
+ ...resumeModuleEntry,
993
+ ...prerenderWakeModuleEntry,
994
+ ...inlineResumerEntry,
995
+ ...prerenderBootEntry,
996
+ ...modulePreloadEntry,
997
+ input.executionLog && input.executionLog !== "never" ? ` executionLog: ${JSON.stringify(input.executionLog)},` : "",
998
+ " payloadView,"
999
+ ];
1000
+ return [
1001
+ "const marklessCompiledApp = {",
1002
+ ...renderCsrEntry,
1003
+ ...renderDataEntry,
1004
+ ...symbolLoaderEntry,
1005
+ ...renderSsrEntry,
1006
+ ...renderSsrComponentsEntry,
1007
+ ...metadataEntries,
1008
+ "};",
1009
+ "export default marklessCompiledApp;",
1010
+ ...emitComponentExports({
1011
+ ssrComponents: input.ssrComponents,
1012
+ rootExportName: input.ssrComponents.find((component) => component.ssrFunctionName === input.ssrExportName)?.exportName,
1013
+ servesSsr: !!servesSsr
1014
+ })
1015
+ ].join("\n");
1016
+ }
1017
+ const RESERVED_MODULE_BINDINGS = /* @__PURE__ */ new Set([
1018
+ "loadBehaviorSymbol",
1019
+ "loadClosureActionPlan",
1020
+ "loadScalarActionPlan",
1021
+ "loadSymbol",
1022
+ "marklessCompiledApp",
1023
+ "marklessLoadLocalSymbol",
1024
+ "marklessLocalClosurePlans",
1025
+ "marklessLocalClosureShapes",
1026
+ "marklessPrerenderData",
1027
+ "marklessRenderData",
1028
+ "marklessRenderSsr",
1029
+ "marklessSsrLoadSymbolRoute",
1030
+ "payloadRuntimeDemandMap",
1031
+ "payloadState",
1032
+ "payloadView",
1033
+ "readMarklessBehaviorSourceSymbol",
1034
+ "resumeContainerEvent"
1035
+ ]);
1036
+ /**
1037
+ * One real ES named export per component the module serves, so plain ESM reaches
1038
+ * them: a `.ts` barrel writing `export { CheckboxRoot as root } from
1039
+ * './checkbox.tsrx'`, and an app writing `import { Gallery } from
1040
+ * './Gallery.tsrx'`, are both named reads the bundler resolves at LINK time.
1041
+ * Publishing components only on the default export's map answered neither
1042
+ * (MISSING_EXPORT at build, "does not provide an export named" in the browser).
1043
+ *
1044
+ * The root is published merged - the module surface plus its own part's
1045
+ * `renderSsr` - because both consumers reach it by that one name: `render(Gallery,
1046
+ * { target })` reads the surface (`renderCsr`/`renderData`/`loadSymbol`), while a
1047
+ * barrel re-export composed as a member tag reads the part. Every other component
1048
+ * is published as the part `marklessSsrComponentPart` hands a composed child,
1049
+ * carrying nothing of the module surface. A part rendered AS A PAGE would
1050
+ * therefore be served inert, so the export is branded and `renderSsrOutput`
1051
+ * refuses it; composition reads the unbranded map entry and is untouched.
1052
+ */
1053
+ function emitComponentExports(input) {
1054
+ return input.ssrComponents.map((component) => {
1055
+ if (RESERVED_MODULE_BINDINGS.has(component.exportName)) throw new Error(`MARKLESS_COMPONENT_EXPORT_NAME_RESERVED: ${component.exportName}`);
1056
+ const part = `marklessCompiledApp.renderSsrComponents[${JSON.stringify(component.exportName)}]`;
1057
+ const isRoot = component.exportName === input.rootExportName;
1058
+ const brand = `${MARKLESS_COMPONENT_PART_BRAND}: ${JSON.stringify(component.exportName)}`;
1059
+ if (input.servesSsr) return `export const ${component.exportName} = ${isRoot ? `{ ...marklessCompiledApp, renderSsr: ${part}.renderSsr }` : `{ ...${part}, ${brand} }`};`;
1060
+ return isRoot ? `export const ${component.exportName} = marklessCompiledApp;` : `export const ${component.exportName} = { marklessCsrOnlyPart: ${JSON.stringify(component.exportName)}, ${brand} };`;
1061
+ });
1062
+ }
1063
+ function emitResumeContainerEvent(loadSymbolName, needsFullResume, storageFreePayload, leanMode, scalarSpecializations, runtimeDemandMap, executionLogEnabled, prerenderDataId, stagedPrerender = false, componentRowRenderDataId, servedOnly = false, routedClosures = false, streamsArms = false) {
1064
+ const armsOpen = (indent) => streamsArms ? [`${indent}const marklessArms = (await import('@markless/web/fns/streamed-arms')).marklessStreamedArms(handoff.root, ${loadSymbolName});`] : [];
1065
+ const armsStarted = (indent) => streamsArms ? [`${indent}marklessArms.started();`] : [];
1066
+ const wakeLoadSymbol = streamsArms ? "marklessArms.loadSymbol" : loadSymbolName;
1067
+ const resumeEntry = storageFreePayload ? STORAGE_FREE_RESUME_ENTRY_SPECIFIER : RESUME_ENTRY_SPECIFIER;
1068
+ const renderDataEntry = (indent, expression) => componentRowRenderDataId ? [`${indent}renderData: () => ${expression},`] : [];
1069
+ const fullResumeHandoff = stagedPrerender && prerenderDataId ? [
1070
+ "async function marklessFullResumeHandoff(handoff) {",
1071
+ " handoff.root.__asyncResumeRuntimeStarted = true;",
1072
+ " const group = await marklessLoadPrerenderTriggerGroup(handoff);",
1073
+ " const { mergePrerenderPayloadRecords, resumePrerenderTriggerGroup } = await import('@markless/web/fns/prerender-trigger-resume');",
1074
+ " if (!group) {",
1075
+ " const { derivePrerenderResumeRecords, renderPrerenderBoundary, resumeFromPrerenderRecords } = await import('@markless/web/fns/prerender-resume');",
1076
+ " handoff.root.__marklessFullResumeRuntime ??= (async () => {",
1077
+ " const marklessPrerenderData = await marklessLoadPrerenderData();",
1078
+ `\t\t\tconst fallbackRecords = mergePrerenderPayloadRecords(await derivePrerenderResumeRecords(marklessPrerenderData, ${loadSymbolName}), handoff.root);`,
1079
+ " return (await resumeFromPrerenderRecords({",
1080
+ " ...fallbackRecords,",
1081
+ " root: handoff.root,",
1082
+ `\t\t\t\tloadSymbol: ${loadSymbolName},`,
1083
+ `\t\t\t\trenderAsyncBoundary: (boundaryId, status, graph) => renderPrerenderBoundary(marklessPrerenderData, boundaryId, status, graph, ${loadSymbolName}),`,
1084
+ ...renderDataEntry(" ", "marklessPrerenderData"),
1085
+ " })).runtime;",
1086
+ " })();",
1087
+ " const marklessFullRuntime = await handoff.root.__marklessFullResumeRuntime;",
1088
+ " await marklessFullRuntime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
1089
+ " return;",
1090
+ " }",
1091
+ " const records = mergePrerenderPayloadRecords({ state: group.state, view: group.view }, handoff.root);",
1092
+ " const { runtime } = await resumePrerenderTriggerGroup({",
1093
+ " ...records, groupId: group.groupId, graphNodeIds: group.graphNodeIds,",
1094
+ " root: handoff.root, loadSymbol: group.loadSymbol, prepareBoundaryArm: group.prepareBoundaryArm, renderBoundaryArm: group.renderBoundaryArm,",
1095
+ " });",
1096
+ " await runtime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
1097
+ "}"
1098
+ ].join("\n") : prerenderDataId ? [
1099
+ "async function marklessFullResumeHandoff(handoff) {",
1100
+ " handoff.root.__marklessLinkedRenderDataBoot = true;",
1101
+ " handoff.root.__asyncResumeRuntimeStarted = true;",
1102
+ " const runtime = await (handoff.root.__marklessFullResumeRuntime ??= (async () => {",
1103
+ " const { derivePrerenderResumeRecords, mergePrerenderPayloadRecords, renderPrerenderBoundary, resumeFromPrerenderRecords } = await import('@markless/web/fns/prerender-resume');",
1104
+ `\t\tconst records = await derivePrerenderResumeRecords(marklessPrerenderData, ${loadSymbolName});`,
1105
+ " const mergedRecords = mergePrerenderPayloadRecords(records, handoff.root);",
1106
+ ...armsOpen(" "),
1107
+ streamsArms ? " const resumed = await resumeFromPrerenderRecords({" : " return (await resumeFromPrerenderRecords({",
1108
+ " ...mergedRecords,",
1109
+ " root: handoff.root,",
1110
+ `\t\t\tloadSymbol: ${wakeLoadSymbol},`,
1111
+ `\t\t\trenderAsyncBoundary: (boundaryId, status, graph) => renderPrerenderBoundary(marklessPrerenderData, boundaryId, status, graph, ${loadSymbolName}),`,
1112
+ ...renderDataEntry(" ", "marklessPrerenderData"),
1113
+ ...streamsArms ? [
1114
+ " });",
1115
+ ...armsStarted(" "),
1116
+ " return resumed.runtime;"
1117
+ ] : [" })).runtime;"],
1118
+ " })());",
1119
+ " await runtime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
1120
+ "}"
1121
+ ].join("\n") : [
1122
+ "async function marklessFullResumeHandoff(handoff) {",
1123
+ " handoff.root.__asyncResumeRuntimeStarted = true;",
1124
+ ...armsOpen(" "),
1125
+ ` const { resumeFromPayloadDocument } = await import('${resumeEntry}');`,
1126
+ " const { runtime } = await resumeFromPayloadDocument({",
1127
+ " document: handoff.document,",
1128
+ " root: handoff.root,",
1129
+ ` loadSymbol: ${wakeLoadSymbol},`,
1130
+ ...renderDataEntry(" ", `import('${componentRowRenderDataId}').then((data) => data.marklessPrerenderData)`),
1131
+ " });",
1132
+ ...armsStarted(" "),
1133
+ " await runtime.dispatch(handoff.event, { syncPolicyAlreadyApplied: handoff.syncPolicyAlreadyApplied === true, ignoreUnmatched: true });",
1134
+ "}"
1135
+ ].join("\n");
1136
+ const scalarOnlySpecialized = leanMode === "scalar" && scalarSpecializations.length > 0 && !needsFullResume && !servedOnly && allEventActionsHaveScalarPlan(runtimeDemandMap);
1137
+ const scalarDispatcher = scalarSpecializations.length > 0 ? emitSpecializedScalarDispatcher(scalarSpecializations, loadSymbolName, scalarOnlySpecialized ? "fail" : "full", scalarOnlySpecialized ? "static" : servedOnly ? "served-only" : "served", !scalarOnlySpecialized && routedClosures) : emitSpecializedScalarDispatcher([], loadSymbolName, "full", "static");
1138
+ const actionScopedLean = leanMode === "scalar" && scalarSpecializations.length > 0 && !prerenderDataId;
1139
+ if (needsFullResume && !actionScopedLean) return [
1140
+ fullResumeHandoff,
1141
+ "export async function resumeContainerEvent(input) {",
1142
+ " await marklessFullResumeHandoff({ ...input, document: input.root });",
1143
+ "}"
1144
+ ].join("\n");
1145
+ if (leanMode !== "none") {
1146
+ const row = [
1147
+ " const { resumeScalarRowEventFromPayloadDocument } = await import('@markless/web/event-only-lean/row');",
1148
+ " await resumeScalarRowEventFromPayloadDocument({",
1149
+ ...[
1150
+ " document: input.root,",
1151
+ " root: input.root,",
1152
+ " event: input.event,",
1153
+ " element: input.element,",
1154
+ " runtimeDemandMap: payloadRuntimeDemandMap,",
1155
+ " syncPolicyAlreadyApplied: input.syncPolicyAlreadyApplied === true,",
1156
+ ` loadSymbol: ${loadSymbolName},`,
1157
+ " });"
1158
+ ]
1159
+ ];
1160
+ if (leanMode === "scalar") return [
1161
+ scalarOnlySpecialized ? "" : fullResumeHandoff,
1162
+ scalarDispatcher,
1163
+ "export async function resumeContainerEvent(input) {",
1164
+ executionLogEnabled ? " const marklessLogBefore = globalThis.__mxLog && new Set(globalThis.__mxLog);" : "",
1165
+ " await marklessResumeSpecializedScalarEvent(input);",
1166
+ executionLogEnabled ? " if (marklessLogBefore) globalThis.__mxLoadLog().then(log => log.logMarklessSpecializedInteraction(input, marklessLogBefore));" : "",
1167
+ "}"
1168
+ ].join("\n");
1169
+ if (leanMode === "row") return [
1170
+ "export async function resumeContainerEvent(input) {",
1171
+ ...row,
1172
+ "}"
1173
+ ].join("\n");
1174
+ return [
1175
+ fullResumeHandoff,
1176
+ scalarDispatcher,
1177
+ "export async function resumeContainerEvent(input) {",
1178
+ " if (marklessScalarSpecializedAction(input)) {",
1179
+ " await marklessResumeSpecializedScalarEvent(input);",
1180
+ " return;",
1181
+ " }",
1182
+ ...row,
1183
+ "}"
1184
+ ].join("\n");
1185
+ }
1186
+ if (prerenderDataId) return "export async function resumeContainerEvent(_input) {}";
1187
+ return [
1188
+ fullResumeHandoff,
1189
+ "export async function resumeContainerEvent(input) {",
1190
+ " await marklessFullResumeHandoff({ ...input, document: input.root });",
1191
+ "}"
1192
+ ].join("\n");
1193
+ }
1194
+ function emitPrerenderTriggerGroupLoader(groups) {
1195
+ return [
1196
+ "function marklessPrerenderTriggerMatches(input, index, tagName, eventName) {",
1197
+ " if (input.event?.type !== eventName) return false;",
1198
+ " const host = marklessFindElementAtDomOrderIndex(input.root, index);",
1199
+ " if (!host || (tagName !== \"*\" && host.tagName.toLowerCase() !== tagName)) return false;",
1200
+ " const target = input.event?.target;",
1201
+ " return host === target || (!!target?.nodeType && typeof host.contains === \"function\" && host.contains(target));",
1202
+ "}",
1203
+ "function marklessPrerenderBranchTriggerMatches(input, startIndex, endIndex, hostPath, eventName) {",
1204
+ " if (input.event?.type !== eventName) return false;",
1205
+ " const comments = [];",
1206
+ " const collect = node => { for (const child of node.childNodes ?? []) { if (child.nodeType === 8) comments.push(child); collect(child); } };",
1207
+ " collect(input.root);",
1208
+ " const start = comments[startIndex], end = comments[endIndex], armNodes = [];",
1209
+ " let within = false, done = false;",
1210
+ " const between = node => { for (const child of node.childNodes ?? []) { if (child === start) { within = true; continue; } if (child === end) { done = true; return; } if (within) armNodes.push(child); else between(child); if (done) return; } };",
1211
+ " between(input.root);",
1212
+ " let host = armNodes[hostPath[0]];",
1213
+ " for (let index = 1; host && index < hostPath.length; index++) host = host.childNodes?.[hostPath[index]];",
1214
+ " const target = input.event?.target;",
1215
+ " return host?.nodeType === 1 && (host === target || (!!target?.nodeType && typeof host.contains === \"function\" && host.contains(target)));",
1216
+ "}",
1217
+ "function marklessLoadPrerenderTriggerGroup(input) {",
1218
+ ...groups.map((group) => {
1219
+ return `\tif (${group.eventName === "self-wake" ? "input.event === 0" : group.hostPath ? `marklessPrerenderBranchTriggerMatches(input, ${group.branchStartIndex}, ${group.branchEndIndex}, ${JSON.stringify(group.hostPath)}, ${JSON.stringify(group.eventName)})` : `marklessPrerenderTriggerMatches(input, ${group.hostIndex}, ${JSON.stringify(group.hostTagName.toLowerCase())}, ${JSON.stringify(group.eventName)})`}) return import(${JSON.stringify(group.moduleId)});`;
1220
+ }),
1221
+ " return Promise.resolve(null);",
1222
+ "}"
1223
+ ].join("\n");
1224
+ }
1225
+ function scalarDispatcherSpecializations(input) {
1226
+ const state = input.payloadState;
1227
+ const view = input.payloadView;
1228
+ const map = input.runtimeDemandMap;
1229
+ const cells = state?.cells ?? [];
1230
+ const locators = view?.locators ?? [];
1231
+ return (map?.actions ?? []).flatMap((action, index) => {
1232
+ const plan = action?.plan;
1233
+ if (action?.recordKind !== "event" || plan?.version !== 1) return [];
1234
+ if (plan.kind === "closure") return closureSpecialization(action, plan, index, view, input);
1235
+ if (plan.kind !== "scalar") return [];
1236
+ const cellIndex = cells.findIndex((cell) => cell?.graphNodeId === plan.cell);
1237
+ const initialCell = cells[cellIndex];
1238
+ const host = locators.find((locator) => locator?.hostNodeId === action.hostNodeId);
1239
+ const event = view?.events?.find((candidate) => candidate?.hostNodeId === action.hostNodeId && candidate?.eventName === action.eventName);
1240
+ const symbolId = scalarActionSymbolId(plan.symbolId, event, input.symbolRoutes ?? []);
1241
+ if (!symbolId) return [];
1242
+ if (cellIndex < 0 || !initialCell || !host || typeof host.index !== "number") return [];
1243
+ if (event && syncPolicyGraphNodeIds(event.syncPolicy).some((graphNodeId) => graphNodeId !== plan.cell)) return [];
1244
+ const textUpdates = (plan.textUpdates ?? []).flatMap((update) => {
1245
+ const locator = locators.find((candidate) => candidate?.hostNodeId === update.hostNodeId);
1246
+ return locator && typeof locator.index === "number" ? [{
1247
+ hostNodeId: update.hostNodeId,
1248
+ index: locator.index,
1249
+ tagName: String(locator.tagName ?? "*"),
1250
+ ...update.prefix ? { prefix: update.prefix } : {},
1251
+ ...update.suffix ? { suffix: update.suffix } : {}
1252
+ }] : [];
1253
+ });
1254
+ if (textUpdates.length !== (plan.textUpdates ?? []).length) return [];
1255
+ return [{
1256
+ kind: "scalar",
1257
+ name: `marklessRunScalar${index}`,
1258
+ hostNodeId: action.hostNodeId,
1259
+ eventName: action.eventName,
1260
+ symbolId,
1261
+ cell: plan.cell,
1262
+ cellIndex,
1263
+ initialCell,
1264
+ hostIndex: host.index,
1265
+ hostTagName: String(host.tagName ?? "*"),
1266
+ syncPolicy: event?.syncPolicy ?? null,
1267
+ write: plan.write,
1268
+ textUpdates
1269
+ }];
1270
+ });
1271
+ }
1272
+ function closureSpecialization(action, plan, index, view, input) {
1273
+ const host = view?.locators?.find((locator) => locator?.hostNodeId === action.hostNodeId);
1274
+ const event = view?.events?.find((candidate) => candidate?.hostNodeId === action.hostNodeId && candidate?.eventName === action.eventName);
1275
+ const symbolId = scalarActionSymbolId(plan.symbolId, event, input.symbolRoutes ?? []);
1276
+ if (symbolId === null || symbolId !== plan.symbolId || !host || typeof host.index !== "number" || !plan.cells || !plan.computed || !plan.updates) return [];
1277
+ return [{
1278
+ kind: "closure",
1279
+ name: `marklessRunClosure${index}`,
1280
+ hostNodeId: action.hostNodeId,
1281
+ eventName: action.eventName,
1282
+ symbolId,
1283
+ hostIndex: host.index,
1284
+ hostTagName: String(host.tagName ?? "*"),
1285
+ syncPolicy: event?.syncPolicy ?? null,
1286
+ plan: {
1287
+ cells: plan.cells,
1288
+ computed: plan.computed,
1289
+ updates: plan.updates
1290
+ }
1291
+ }];
1292
+ }
1293
+ function scalarActionSymbolId(plannedSymbolId, event, routes) {
1294
+ if (typeof plannedSymbolId !== "string") return null;
1295
+ const eventSymbolIds = Array.isArray(event?.symbolIds) ? event.symbolIds.filter((symbolId) => typeof symbolId === "string") : [];
1296
+ const routedSymbolId = eventSymbolIds.find((symbolId) => routes.some((route) => symbolId.startsWith(route.prefix)));
1297
+ if (routedSymbolId) return routedSymbolId;
1298
+ if (eventSymbolIds.some((symbolId) => /^[^:]+:symbol:/.test(symbolId))) return null;
1299
+ if (eventSymbolIds.length > 0 && !eventSymbolIds.includes(plannedSymbolId)) return null;
1300
+ return plannedSymbolId;
1301
+ }
1302
+ function allEventActionsHaveScalarPlan(runtimeDemandMap) {
1303
+ const eventActions = (runtimeDemandMap?.actions ?? []).filter((action) => action.recordKind === "event");
1304
+ return eventActions.length > 0 && eventActions.every((action) => action.plan?.kind === "scalar");
1305
+ }
1306
+ function emitSpecializedScalarDispatcher(actions, loadSymbolName, fallback, resolution, routedClosures = false) {
1307
+ const shapes = closureShapes(actions);
1308
+ const fallbackName = fallback === "fail" ? "marklessScalarSpecializedHostMiss" : "marklessScalarSpecializedFallback";
1309
+ const fallbackBody = fallback === "full" ? [
1310
+ "async function marklessScalarSpecializedFallback(input, site, syncPolicyAlreadyApplied = input.syncPolicyAlreadyApplied === true) {",
1311
+ " if (import.meta.env?.DEV) console.warn(Object.assign(new Error(\"MARKLESS_SCALAR_SPECIALIZED_FALLBACK\"), { code: \"MARKLESS_SCALAR_SPECIALIZED_FALLBACK\", site }));",
1312
+ " await marklessFullResumeHandoff({ ...input, document: input.root, syncPolicyAlreadyApplied });",
1313
+ "}"
1314
+ ] : [];
1315
+ return [
1316
+ "async function marklessResumeSpecializedScalarEvent(input) {",
1317
+ ...fallback === "full" ? [" if (input.root.__asyncResumeRuntimeStarted) return marklessFullResumeHandoff({ ...input, document: input.root });"] : [],
1318
+ " const action = marklessScalarSpecializedAction(input);",
1319
+ " if (action) {",
1320
+ " try {",
1321
+ " return await action(input);",
1322
+ " } catch (error) {",
1323
+ ` if (error?.code === "MARKLESS_SCALAR_SPECIALIZED_ESCALATE") return ${fallbackName}(input, error.site ?? "escalate", error.syncPolicyAlreadyApplied === true);`,
1324
+ " throw error;",
1325
+ " }",
1326
+ " }",
1327
+ ...fallback === "fail" ? [" return;"] : [" if (input.logOnly) return;", ` return ${fallbackName}(input, "event-match");`],
1328
+ "}",
1329
+ fallback === "fail" ? "function marklessScalarSpecializedHostMiss(_input, site) { return marklessScalarSpecializedError(\"MARKLESS_SCALAR_SPECIALIZED_HOST_MISS\", site); }" : "function marklessScalarSpecializedHostMiss(input, site) { return marklessScalarSpecializedFallback(input, site); }",
1330
+ ...resolution === "static" ? [
1331
+ "function marklessScalarSpecializedAction(input) {",
1332
+ ...emitStaticScalarMatches(actions),
1333
+ "}"
1334
+ ] : emitServedScalarMatches(actions, loadSymbolName, resolution, shapes, routedClosures),
1335
+ "function marklessScalarEventMatches(input, host, tagName, eventName, hostNodeId) {",
1336
+ " const eventTypeMatches = input.event?.type === eventName;",
1337
+ " if (!eventTypeMatches) return false;",
1338
+ " if (!host || (tagName !== \"*\" && host.tagName.toLowerCase() !== tagName)) return false;",
1339
+ " const eventTarget = input.event?.target;",
1340
+ " return host === eventTarget || (!!eventTarget?.nodeType && typeof host.contains === \"function\" && host.contains(eventTarget));",
1341
+ "}",
1342
+ ...shapes.length > 0 ? [`const marklessClosureShapes = [${shapes.join(", ")}];`] : [],
1343
+ ...actions.map((action) => action.kind === "closure" ? emitClosureAction(action, loadSymbolName, shapes) : emitScalarAction(action, loadSymbolName, resolution)),
1344
+ ...fallbackBody
1345
+ ].join("\n");
1346
+ }
1347
+ function emitStaticScalarMatches(actions) {
1348
+ return actions.filter((action) => action.kind === "scalar").map((action) => ` if (marklessScalarEventMatches(input, marklessFindElementAtDomOrderIndex(input.root, ${action.hostIndex}), ${JSON.stringify(action.hostTagName.toLowerCase())}, ${JSON.stringify(action.eventName)}, ${JSON.stringify(action.hostNodeId)})) return ${action.name};`);
1349
+ }
1350
+ function emitServedScalarMatches(actions, loadSymbolName, resolution, shapes, routedClosures) {
1351
+ const closures = routedClosures || actions.some((action) => action.kind === "closure");
1352
+ return [
1353
+ `const marklessScalarOwners = ${JSON.stringify(actions.map((action) => [
1354
+ action.hostNodeId,
1355
+ action.eventName,
1356
+ action.symbolId
1357
+ ]))};`,
1358
+ `const marklessScalarRuns = [${actions.map((action) => action.name).join(", ")}];`,
1359
+ ...closures ? [`const marklessScalarPrimes = [${actions.map((action) => action.kind === "closure" ? `() => marklessPrimeClosure(${emitClosurePlan(action, shapes)}, "", ${loadSymbolName})` : `() => ${loadSymbolName}(${JSON.stringify(action.symbolId)})`).join(", ")}];`] : [],
1360
+ "function marklessScalarSpecializedAction(input) {",
1361
+ " if (input.event === 0) {",
1362
+ ...closures ? [` const primed = marklessScalarServedPrime(input.root, input.element, marklessScalarOwners${routedClosures ? ", marklessClosureRouted" : ""});`, ` return primed && (() => Promise.all(primed.map((owner) => typeof owner === "number" ? marklessScalarPrimes[owner]() : marklessPrimeRoutedClosure(owner, marklessClosurePlanRoute, ${loadSymbolName}))).then(() => undefined));`] : [" const primed = marklessScalarServedPrime(input.root, input.element, marklessScalarOwners);", ` return primed && (() => Promise.all(primed.map((index) => ${loadSymbolName}(marklessScalarOwners[index][2]))).then(() => undefined));`],
1363
+ " }",
1364
+ " const owner = input.event && marklessScalarServedOwner(input.root, input.event, marklessScalarOwners);",
1365
+ ...routedClosures ? [
1366
+ " if (owner === -1) {",
1367
+ " const record = marklessScalarServedRecord(input.root, input.event);",
1368
+ ` if (record && record !== -1 && marklessClosureRouted(record)) return (input) => marklessRunRoutedClosure(input, record, marklessClosurePlanRoute, ${loadSymbolName});`,
1369
+ " }"
1370
+ ] : [],
1371
+ ...resolution === "served" ? [
1372
+ " if (owner === undefined) {",
1373
+ ...emitStaticScalarMatches(actions).map((line) => `\t${line}`),
1374
+ " return;",
1375
+ " }"
1376
+ ] : [],
1377
+ " return owner >= 0 ? marklessScalarRuns[owner] : undefined;",
1378
+ "}"
1379
+ ];
1380
+ }
1381
+ function emitScalarHostLookup(resolution, hostNodeId, index, tagName) {
1382
+ return resolution === "static" ? `marklessFindElementAtDomOrderIndex(input.root, ${index})` : `marklessScalarLocate(input.root, ${JSON.stringify(hostNodeId)}, ${resolution === "served" ? index : -1}, ${JSON.stringify(tagName.toLowerCase())})`;
1383
+ }
1384
+ function closureShapes(actions) {
1385
+ return [...new Set(actions.flatMap((action) => action.kind === "closure" ? [JSON.stringify(action.plan)] : []))];
1386
+ }
1387
+ function emitClosurePlan(action, shapes) {
1388
+ return `{ symbolId: ${JSON.stringify(action.symbolId)}, ...marklessClosureShapes[${shapes.indexOf(JSON.stringify(action.plan))}] }`;
1389
+ }
1390
+ function emitClosureAction(action, loadSymbolName, shapes) {
1391
+ return [
1392
+ `function ${action.name}(input) {`,
1393
+ ` return marklessRunClosureAction(input, ${emitClosurePlan(action, shapes)}, "", ${JSON.stringify(action.hostNodeId)}, ${loadSymbolName}${action.syncPolicy ? `, ${JSON.stringify(action.syncPolicy)}` : ""});`,
1394
+ "}"
1395
+ ].join("\n");
1396
+ }
1397
+ function emitScalarAction(action, loadSymbolName, resolution) {
1398
+ return [
1399
+ `async function ${action.name}(input) {`,
1400
+ " let syncPolicyAlreadyApplied = input.syncPolicyAlreadyApplied === true;",
1401
+ " const values = input.root.__marklessEventOnlyGraph || new Map();",
1402
+ " input.root.__marklessEventOnlyGraph = values;",
1403
+ ` if (!values.has(${JSON.stringify(action.cell)})) values.set(${JSON.stringify(action.cell)}, marklessDecodeScalarCell(marklessReadScalarCell(input.root, ${JSON.stringify(action.cell)})${resolution === "served-only" ? "" : ` ?? ${JSON.stringify(action.initialCell)}`}, ${JSON.stringify(action.cell)}, ${JSON.stringify(`markless/state cell ${action.cell}`)}));`,
1404
+ ` const state = { value: values.get(${JSON.stringify(action.cell)}), dirty: false };`,
1405
+ " try {",
1406
+ ` const host = ${emitScalarHostLookup(resolution, action.hostNodeId, action.hostIndex, action.hostTagName)};`,
1407
+ ` if (!host || (${JSON.stringify(action.hostTagName.toLowerCase())} !== "*" && host.tagName.toLowerCase() !== ${JSON.stringify(action.hostTagName.toLowerCase())})) return marklessScalarSpecializedHostMiss(input, "host");`,
1408
+ ...action.textUpdates.map((update, index) => ` const textTarget${index} = ${emitScalarHostLookup(resolution, update.hostNodeId, update.index, update.tagName)};`),
1409
+ ...action.textUpdates.map((update, index) => ` if (!textTarget${index} || (${JSON.stringify(update.tagName.toLowerCase())} !== "*" && textTarget${index}.tagName.toLowerCase() !== ${JSON.stringify(update.tagName.toLowerCase())})) return marklessScalarSpecializedHostMiss(input, "text-target");`),
1410
+ " const graph = {",
1411
+ ` hasCell(graphNodeId) { return graphNodeId === ${JSON.stringify(action.cell)}; },`,
1412
+ ` read(graphNodeId, path = []) { if (graphNodeId !== ${JSON.stringify(action.cell)} || path.length) return marklessScalarSpecializedError("MARKLESS_SCALAR_SPECIALIZED_ESCALATE", "read"); return state.value; },`,
1413
+ ` write(write) { if (write.graphNodeId !== ${JSON.stringify(action.cell)} || (write.path?.length ?? 0)) return marklessScalarSpecializedError("MARKLESS_SCALAR_SPECIALIZED_ESCALATE", "write"); if (!Object.is(state.value, write.value)) { state.value = write.value; values.set(${JSON.stringify(action.cell)}, state.value); state.dirty = true; } },`,
1414
+ ` update(update) { if (update.graphNodeId !== ${JSON.stringify(action.cell)} || (update.path?.length ?? 0)) return marklessScalarSpecializedError("MARKLESS_SCALAR_SPECIALIZED_ESCALATE", "update"); const previous = state.value; const next = update.update(previous); if (!Object.is(previous, next)) { state.value = next; values.set(${JSON.stringify(action.cell)}, state.value); state.dirty = true; } return update.returnValue === "previous" ? previous : update.returnValue === "next" ? next : undefined; },`,
1415
+ " call() { return marklessScalarSpecializedError(\"MARKLESS_SCALAR_SPECIALIZED_ESCALATE\", \"call\"); },",
1416
+ " async flush() {},",
1417
+ " };",
1418
+ ...action.syncPolicy ? [
1419
+ ` const syncPolicy = ${JSON.stringify(action.syncPolicy)};`,
1420
+ " if (syncPolicy && !syncPolicyAlreadyApplied) {",
1421
+ " const { runSyncPolicyActions } = await import('@markless/web/inline/sync-policy-core-lazy');",
1422
+ " runSyncPolicyActions(syncPolicy, graph, input.event);",
1423
+ " syncPolicyAlreadyApplied = true;",
1424
+ " }"
1425
+ ] : [],
1426
+ ...emitScalarWrite(action),
1427
+ ` const symbol = await Promise.resolve(${loadSymbolName}(${JSON.stringify(action.symbolId)}));`,
1428
+ " await Promise.resolve(symbol({ graph: { ...graph, write() {}, update(update) { const value = graph.read(update.graphNodeId, update.path ?? []); return update.returnValue === \"previous\" || update.returnValue === \"next\" ? value : undefined; } }, event: input.event, element: host, getElementHandle: () => undefined }));",
1429
+ " if (state.dirty) {",
1430
+ " state.dirty = false;",
1431
+ ...action.textUpdates.map((update, index) => ` textTarget${index}.textContent = marklessUpdateText({ domUpdate: { hostNodeId: ${JSON.stringify(update.hostNodeId)} }, value: ${JSON.stringify(update.prefix ?? "")} + (state.value == null ? '' : String(state.value))${update.suffix ? ` + ${JSON.stringify(update.suffix)}` : ""} }, ${JSON.stringify(update.hostNodeId)}).value;`),
1432
+ " }",
1433
+ " } catch (error) {",
1434
+ " if (error?.code === \"MARKLESS_SCALAR_SPECIALIZED_ESCALATE\") error.syncPolicyAlreadyApplied = syncPolicyAlreadyApplied;",
1435
+ " throw error;",
1436
+ " }",
1437
+ "}"
1438
+ ].join("\n");
1439
+ }
1440
+ function emitScalarWrite(action) {
1441
+ if (action.write.kind === "update") return [
1442
+ " marklessWriteScalar({ graph }, {",
1443
+ ` graphNodeId: ${JSON.stringify(action.cell)},`,
1444
+ " returnValue: \"next\",",
1445
+ " update(value) {",
1446
+ ` return typeof value === "bigint" ? value ${action.write.updateOperator === "--" ? "-" : "+"} BigInt(1) : Number(value) ${action.write.updateOperator === "--" ? "-" : "+"} 1;`,
1447
+ " },",
1448
+ " });"
1449
+ ];
1450
+ return [
1451
+ " marklessWriteScalar({ graph }, {",
1452
+ ` graphNodeId: ${JSON.stringify(action.cell)},`,
1453
+ ` value: ${action.write.valueKind === "undefined" ? "undefined" : JSON.stringify(action.write.value)},`,
1454
+ " });"
1455
+ ];
1456
+ }
1457
+ function syncPolicyGraphNodeIds(policy) {
1458
+ if (!policy || typeof policy !== "object") return [];
1459
+ const branches = Array.isArray(policy.branches) ? policy.branches : [policy];
1460
+ return [...new Set(branches.flatMap((branch) => conditionGraphNodeIds(branch.when)))].sort();
1461
+ }
1462
+ function conditionGraphNodeIds(condition) {
1463
+ if (!condition || typeof condition !== "object") return [];
1464
+ const typed = condition;
1465
+ if (typed.type === "graph-truthy" && typeof typed.graphNodeId === "string") return [typed.graphNodeId];
1466
+ if (typed.type === "not") return conditionGraphNodeIds(typed.condition);
1467
+ if ((typed.type === "and" || typed.type === "or") && Array.isArray(typed.conditions)) return typed.conditions.flatMap(conditionGraphNodeIds);
1468
+ return [];
1469
+ }
1470
+ function composedLeanMode(composed, mode) {
1471
+ return composed && mode !== "scalar" ? "none" : mode;
1472
+ }
1473
+ function leanResumeMode(runtimeDemandMap) {
1474
+ const recordKinds = runtimeDemandMap?.recordKinds;
1475
+ if (!recordKinds) return "none";
1476
+ const replaced = new Map(recordKinds.map((record) => [record.kind, record.replaced]));
1477
+ const scalar = replaced.get("event") === true && replaced.get("dom-update") === true;
1478
+ const row = replaced.get("keyed-repeat") === true && replaced.get("dom-update") === true;
1479
+ if (scalar && row) return "mixed";
1480
+ if (scalar) return "scalar";
1481
+ if (row) return "row";
1482
+ return "none";
1483
+ }
1484
+ function emitExecutionLogLoader() {
1485
+ return `globalThis.__mxLoadLog ||= () => import(${JSON.stringify(MARKLESS_EXECUTION_LOG_MODULE_ID)});`;
1486
+ }
1487
+ function emitLoadSymbol(input, sourceReaderName) {
1488
+ if (input.symbols.length > 0 && input.symbols.length <= 8) {
1489
+ const direct = emitDirectSourceSymbolLoader(input.symbols, sourceReaderName);
1490
+ if (!input.hasBoundSymbols) return direct;
1491
+ return [`const marklessSymbolResolverModule = () => import('${input.resolverId}');`, direct.replace(" return Promise.reject(new Error(`Unknown async symbol ${symbolId}`));", " return marklessSymbolResolverModule().then((mod) => mod.loadSymbol(symbolId));")].join("\n");
1492
+ }
1493
+ return [
1494
+ `const marklessSymbolResolverModule = () => import('${input.resolverId}');`,
1495
+ "function loadSymbol(symbolId) {",
1496
+ " return marklessSymbolResolverModule().then((mod) => mod.loadSymbol(symbolId));",
1497
+ "}"
1498
+ ].join("\n");
1499
+ }
1500
+ function emitDirectSourceSymbolLoader(symbols, readerName = "readMarklessSourceSymbol") {
1501
+ return [
1502
+ "function loadSymbol(symbolId) {",
1503
+ ...symbols.flatMap((symbol) => [` if (symbolId === ${JSON.stringify(symbol.id)}) return import('${symbol.lazyChunk ?? symbol.chunk}')`, ` .then((mod) => ${readerName}(mod, ${JSON.stringify(symbol.exportName)}));`]),
1504
+ " return Promise.reject(new Error(`Unknown async symbol ${symbolId}`));",
1505
+ "}",
1506
+ emitSourceSymbolExportReader(readerName)
1507
+ ].join("\n");
1508
+ }
1509
+ function emitSourceSymbolExportReader(name = "readMarklessSourceSymbol") {
1510
+ return [
1511
+ `function ${name}(mod, exportName) {`,
1512
+ " mod.init__virtual_markless_symbol?.();",
1513
+ " return mod[exportName];",
1514
+ "}"
1515
+ ].join("\n");
1516
+ }
1517
+ function stringHash(value) {
1518
+ let hash = 2166136261;
1519
+ for (let index = 0; index < value.length; index++) {
1520
+ hash ^= value.charCodeAt(index);
1521
+ hash = Math.imul(hash, 16777619);
1522
+ }
1523
+ return (hash >>> 0).toString(36);
1524
+ }
1525
+ const MARKLESS_BUILD_PREFIX = `build/`;
1526
+ const MARKLESS_BUNDLE_GRAPH = `${MARKLESS_BUILD_PREFIX}bundle-graph.json`;
1527
+ const MARKLESS_EXECUTION_SIZES = `${MARKLESS_BUILD_PREFIX}execution-sizes.json`;
1528
+ const MARKLESS_EXECUTION_DEMAND = `${MARKLESS_BUILD_PREFIX}execution-demand.json`;
1529
+ const MARKLESS_INTERACTION_CLOSURES = `${MARKLESS_BUILD_PREFIX}interaction-closures.json`;
1530
+ const MARKLESS_BYTE_ATTRIBUTION = `${MARKLESS_BUILD_PREFIX}byte-attribution.json`;
1531
+ const MARKLESS_BUILD_METADATA_FILES = [
1532
+ MARKLESS_BUNDLE_GRAPH,
1533
+ MARKLESS_EXECUTION_SIZES,
1534
+ MARKLESS_EXECUTION_DEMAND,
1535
+ MARKLESS_INTERACTION_CLOSURES,
1536
+ MARKLESS_BYTE_ATTRIBUTION
1537
+ ];
1538
+ const MARKLESS_PUBLIC_BUILD_METADATA_FILES = [MARKLESS_EXECUTION_SIZES];
1539
+ const WEB_RUNTIME_CAPABILITY_GROUPS = [
1540
+ {
1541
+ name: "markless-direct-renderer",
1542
+ test: fileBasenamePattern("direct")
1543
+ },
1544
+ {
1545
+ name: "markless-resume-branches",
1546
+ test: fileBasenamePattern("resume-branches", "resume-arm-records-lazy")
1547
+ },
1548
+ {
1549
+ name: "markless-resume-behaviors",
1550
+ test: fileBasenamePattern("resume-behaviors")
1551
+ },
1552
+ {
1553
+ name: "markless-resume-repeats",
1554
+ test: fileBasenamePattern("resume-keyed-repeats", "resume-keyed-repeats-lazy", "repeat-runtime")
1555
+ },
1556
+ {
1557
+ name: "markless-resume-async",
1558
+ test: fileBasenamePattern("resume-async-boundaries", "resume-async-wiring")
1559
+ },
1560
+ {
1561
+ name: "markless-resume-shared-patch",
1562
+ test: fileBasenamePattern("resume-shared-patch")
1563
+ },
1564
+ {
1565
+ name: "markless-resume-runtime",
1566
+ test: fileBasenamePattern("resume-runtime")
1567
+ },
1568
+ {
1569
+ name: "markless-resume-runtime-start",
1570
+ test: fileBasenamePattern("resume-runtime-start")
1571
+ },
1572
+ {
1573
+ name: "markless-resume-runtime-shared",
1574
+ test: fileBasenamePattern("resume-runtime-shared")
1575
+ },
1576
+ {
1577
+ name: "markless-resume-events",
1578
+ test: fileBasenamePattern("resume-events")
1579
+ },
1580
+ {
1581
+ name: "markless-resume-handoff",
1582
+ test: fileBasenamePattern("resume-handoff")
1583
+ },
1584
+ {
1585
+ name: "markless-resume-locators",
1586
+ test: fileBasenamePattern("resume-locators", "resume-census")
1587
+ },
1588
+ {
1589
+ name: "markless-resume-errors",
1590
+ test: fileBasenamePattern("resume-errors")
1591
+ },
1592
+ {
1593
+ name: "markless-resume-sync-computed",
1594
+ test: fileBasenamePattern("resume-sync-computed")
1595
+ },
1596
+ {
1597
+ name: "markless-resume-sync-demand",
1598
+ test: fileBasenamePattern("resume-sync-demand")
1599
+ },
1600
+ {
1601
+ name: "markless-payload-full",
1602
+ test: fileBasenamePattern("payload-full", "payload-full-storage-free")
1603
+ },
1604
+ {
1605
+ name: "markless-payload-resume",
1606
+ test: fileBasenamePattern("payload-resume", "payload-resume-lazy")
1607
+ },
1608
+ {
1609
+ name: "markless-inline-payload-document",
1610
+ test: /[/\\]web[/\\]src[/\\]inline[/\\]payload-document\.ts(?:[?#].*)?$/
1611
+ },
1612
+ {
1613
+ name: "markless-payload-document",
1614
+ test: fileBasenamePattern("payload-document", "payload-document-common", "payload-resume-registry")
1615
+ },
1616
+ {
1617
+ name: "markless-payload-graph-construct",
1618
+ test: fileBasenamePattern("payload-graph-construct")
1619
+ },
1620
+ {
1621
+ name: "markless-dom-journal",
1622
+ test: fileBasenamePattern("dom-journal")
1623
+ },
1624
+ {
1625
+ name: "markless-protocol-decode",
1626
+ test: fileBasenamePattern("protocol-client", "protocol-client-storage", "protocol-state", "storage-record-client")
1627
+ },
1628
+ {
1629
+ name: "markless-value-decode",
1630
+ test: fileBasenamePattern("value-decode-client", "value-decode-client-lazy", "value-decode-extensions")
1631
+ },
1632
+ {
1633
+ name: "markless-payload-leaves",
1634
+ test: fileBasenamePattern("payload", "payload-document")
1635
+ },
1636
+ {
1637
+ name: "markless-dev-log",
1638
+ test: EXECUTION_LOG_CHUNK_MODULE_PATTERN
1639
+ },
1640
+ {
1641
+ name: "markless-resume-core",
1642
+ test: fileBasenamePattern("resume")
1643
+ },
1644
+ {
1645
+ name: "markless-runtime-graph-core",
1646
+ test: fileBasenamePattern("graph-core")
1647
+ },
1648
+ {
1649
+ name: "markless-runtime-graph-collections",
1650
+ test: fileBasenamePattern("graph-collections")
1651
+ },
1652
+ {
1653
+ name: "markless-runtime-graph-computed",
1654
+ test: fileBasenamePattern("graph-computed")
1655
+ },
1656
+ {
1657
+ name: "markless-runtime-graph-async",
1658
+ test: fileBasenamePattern("graph-async")
1659
+ },
1660
+ {
1661
+ name: "markless-runtime-graph-scheduler",
1662
+ test: fileBasenamePattern("graph-scheduler")
1663
+ },
1664
+ {
1665
+ name: "markless-runtime-graph-shared",
1666
+ test: fileBasenamePattern("graph-shared")
1667
+ },
1668
+ {
1669
+ name: "markless-graph",
1670
+ test: /[/\\](?:runtime[/\\]src[/\\](?!graph-(?:core|collections|computed|async|scheduler|shared)\.ts)|core[/\\]src[/\\]runtime)[/\\]?/
1671
+ },
1672
+ {
1673
+ name: "markless-serializer",
1674
+ test: /[/\\]serializer[/\\]src[/\\](?!protocol-validation)/
1675
+ }
1676
+ ];
1677
+ function fileBasenamePattern(...names) {
1678
+ return new RegExp(`[/\\\\](?:${names.join("|")})\\.ts(?:[?#].*)?$`);
1679
+ }
1680
+ const MARKLESS_RUNTIME_GROUPS = [...WEB_RUNTIME_CAPABILITY_GROUPS, {
1681
+ name: "markless-runtime",
1682
+ test: /[/\\]@markless[/\\]runtime[/\\]/
1683
+ }];
1684
+ function outputDefaults(output, environment) {
1685
+ if (environment === "lib") return output;
1686
+ const next = {
1687
+ ...output,
1688
+ hoistTransitiveImports: false
1689
+ };
1690
+ if (environment === "server") {
1691
+ next.entryFileNames ??= "[name].js";
1692
+ next.chunkFileNames ??= "chunk-[hash].js";
1693
+ next.codeSplitting = marklessCodeSplitting(next.codeSplitting);
1694
+ return next;
1695
+ }
1696
+ next.entryFileNames ??= `${MARKLESS_BUILD_PREFIX}chunk-[hash].js`;
1697
+ next.chunkFileNames ??= `${MARKLESS_BUILD_PREFIX}chunk-[hash].js`;
1698
+ next.minifyInternalExports = true;
1699
+ next.strictExecutionOrder = true;
1700
+ next.codeSplitting = marklessCodeSplitting(next.codeSplitting);
1701
+ return next;
1702
+ }
1703
+ function marklessCodeSplitting(codeSplitting) {
1704
+ if (typeof codeSplitting === "boolean") throw new Error("@markless/bundler requires output.codeSplitting to be an object so runtime chunks can be grouped.");
1705
+ return {
1706
+ ...codeSplitting,
1707
+ groups: [...MARKLESS_RUNTIME_GROUPS, ...codeSplitting?.groups ?? []]
1708
+ };
1709
+ }
1710
+ //#endregion
1711
+ //#region src/bound-resolver.ts
1712
+ function adaptImportedCaptureResolver(source, hasImportedRows) {
1713
+ if (!hasImportedRows) return source;
1714
+ const original = " return (context) => base({ ...context, capture: createCaptureContext(context, bound) });";
1715
+ const replacement = [
1716
+ " return async (context) => {",
1717
+ " const pendingCallbacks = [];",
1718
+ " const capture = createCaptureContext(context, bound);",
1719
+ " const result = await base({ ...context, graph: createBoundGraph(context, bound, capture, pendingCallbacks), capture });",
1720
+ " await Promise.all(pendingCallbacks);",
1721
+ " return result;",
1722
+ " };"
1723
+ ].join("\n");
1724
+ const helper = [
1725
+ "function createBoundGraph(context, bound, capture, pendingCallbacks) {",
1726
+ " const legacySlots = new Map(bound.captureSlots.flatMap((slot) => slot.legacyGraphRead ? [[JSON.stringify([slot.legacyGraphRead.graphNodeId, slot.legacyGraphRead.path ?? []]), slot]] : []));",
1727
+ " let lastCallback = Promise.resolve();",
1728
+ " return {",
1729
+ " ...context.graph,",
1730
+ " read(graphNodeId, path = []) {",
1731
+ " const slot = legacySlots.get(JSON.stringify([graphNodeId, path]));",
1732
+ " if (!slot) return context.graph.read(graphNodeId, path);",
1733
+ " if (slot.route.kind === callbackRoute) return (...args) => {",
1734
+ " const pending = lastCallback.then(() => capture.invoke(slot.slotId, args));",
1735
+ " lastCallback = pending.catch(() => {});",
1736
+ " pendingCallbacks.push(pending);",
1737
+ " return pending;",
1738
+ " };",
1739
+ " return capture.read(slot.slotId);",
1740
+ " },",
1741
+ " };",
1742
+ "}",
1743
+ ""
1744
+ ].join("\n");
1745
+ return source.replace(original, replacement).replace("function createCaptureContext(context, bound) {", `${helper}function createCaptureContext(context, bound) {`);
1746
+ }
1747
+ //#endregion
1748
+ //#region src/trigger-groups.ts
1749
+ const EVENT_STAGES_BROWSER_TRIGGER = {
1750
+ [PROTOCOL_EVENT_ACTION_KIND.event]: true,
1751
+ [PROTOCOL_EVENT_ACTION_KIND.externalDelegate]: false
1752
+ };
1753
+ function triggerGroupVirtualModuleId(filename, index) {
1754
+ return `virtual:markless:trigger-group:${encodeURIComponent(filename)}:${index}`;
1755
+ }
1756
+ function triggerGroupVirtualModuleSourceFile(moduleId) {
1757
+ const bare = moduleId.startsWith("\0") ? moduleId.slice(1) : moduleId;
1758
+ const match = /^virtual:markless:trigger-group:([^:]+):\d+$/.exec(bare);
1759
+ if (!match?.[1]) return null;
1760
+ try {
1761
+ return decodeURIComponent(match[1]);
1762
+ } catch {
1763
+ return null;
1764
+ }
1765
+ }
1766
+ function emitPrerenderTriggerGroupModule(input) {
1767
+ const armRendererModuleId = input.armRendererModuleId ?? input.group.armRendererModuleId;
1768
+ const ids = new Set(input.group.symbolIds);
1769
+ const boundRows = input.boundRows.filter((row) => ids.has(row.id));
1770
+ let source = emitSymbolResolverModule({
1771
+ symbols: input.symbols.filter((symbol) => ids.has(symbol.id)),
1772
+ boundSymbols: boundRows,
1773
+ literalImports: input.literalImports,
1774
+ bundlerVisibleImports: input.literalImports
1775
+ });
1776
+ const routes = (input.symbolRoutes ?? []).map((route) => route.boundSymbols ? {
1777
+ ...route,
1778
+ boundSymbols: Object.fromEntries(Object.entries(route.boundSymbols).filter(([, rowId]) => ids.has(rowId)))
1779
+ } : route);
1780
+ if (routes.length > 0) {
1781
+ source = source.replaceAll("loadSymbol(", "marklessLoadLocalSymbol(");
1782
+ source += "\n" + emitSymbolRouteTable({
1783
+ routes: routes.map((route) => "importSource" in route ? {
1784
+ ...route,
1785
+ importSource: symbolRouteImportSource(route.importSource)
1786
+ } : route),
1787
+ functionName: "loadSymbol",
1788
+ fallbackName: "marklessLoadLocalSymbol",
1789
+ reboundName: "marklessLoadSymbolRebound",
1790
+ exported: true
1791
+ });
1792
+ }
1793
+ return [
1794
+ armRendererModuleId ? [
1795
+ `import { prepareBoundaryArm as marklessPrepareBoundaryArm, renderBoundaryArm as marklessRenderBoundaryArm } from ${JSON.stringify(armRendererModuleId)};`,
1796
+ "export function prepareBoundaryArm(boundaryId, status, graph) {",
1797
+ " return marklessPrepareBoundaryArm(boundaryId, status, graph, loadSymbol);",
1798
+ "}",
1799
+ "export function renderBoundaryArm(boundaryId, status, graph) {",
1800
+ " return marklessRenderBoundaryArm(boundaryId, status, graph, loadSymbol);",
1801
+ "}"
1802
+ ].join("\n") : "",
1803
+ adaptImportedCaptureResolver(source, boundRows.some((row) => row.loaderSymbolId !== void 0)),
1804
+ `export const groupId=${JSON.stringify(input.group.id)};`,
1805
+ `export const state=${JSON.stringify(input.group.state)};`,
1806
+ `export const view=${JSON.stringify(input.group.view)};`,
1807
+ `export const graphNodeIds=${JSON.stringify(input.group.graphNodeIds)};`
1808
+ ].join("\n");
1809
+ }
1810
+ function emitPrerenderBoundaryRendererModule(renderDataId) {
1811
+ return [
1812
+ `import { marklessPrerenderData } from ${JSON.stringify(renderDataId)};`,
1813
+ "import { renderPrerenderBoundary } from '@markless/web/fns/prerender-resume';",
1814
+ "const marklessPreparedBoundaryArms = new WeakMap();",
1815
+ "export async function prepareBoundaryArm(boundaryId, status, graph, loadSymbol) {",
1816
+ " const rendered = await renderPrerenderBoundary(marklessPrerenderData, boundaryId, status, graph, loadSymbol);",
1817
+ " if (!marklessPreparedBoundaryArms.has(graph)) marklessPreparedBoundaryArms.set(graph, new Map());",
1818
+ " marklessPreparedBoundaryArms.get(graph).set(`${boundaryId}:${status}`, rendered);",
1819
+ "}",
1820
+ "export function renderBoundaryArm(boundaryId, status, graph) {",
1821
+ " const key = `${boundaryId}:${status}`;",
1822
+ " const prepared = marklessPreparedBoundaryArms.get(graph);",
1823
+ " const rendered = prepared?.get(key);",
1824
+ " if (!rendered) throw new Error(`Markless prerender arm ${key} was not prepared.`);",
1825
+ " prepared.delete(key);",
1826
+ " return rendered;",
1827
+ "}"
1828
+ ].join("\n");
1829
+ }
1830
+ function symbolRouteImportSource(importSource) {
1831
+ return importSource.includes("?") ? `${importSource}&markless-symbols` : `${importSource}?markless-symbols`;
1832
+ }
1833
+ function planPrerenderTriggerGroups(input) {
1834
+ const symbols = new Map(input.symbolResolver.symbols.map((symbol) => [symbol.id, symbol]));
1835
+ const bounds = new Map(input.boundRows.map((row) => [row.id, row]));
1836
+ const completeView = input.completeView ?? input.view;
1837
+ const completeBoundaries = new Map(completeView.asyncBoundaries.map((boundary) => [boundary.id, boundary]));
1838
+ const selfWakeBoundaries = unsettledAsyncBoundaryIndexes(input.state, input.view);
1839
+ const groups = [
1840
+ ...selfWakeBoundaries.length > 0 ? [{
1841
+ event: {
1842
+ hostNodeId: "self-wake",
1843
+ eventName: "self-wake",
1844
+ symbolIds: []
1845
+ },
1846
+ selfWakeBoundaries
1847
+ }] : [],
1848
+ ...input.view.events.filter((event) => EVENT_STAGES_BROWSER_TRIGGER[protocolEventActionKind(event)]).map((event) => ({ event })),
1849
+ ...(input.view.branches ?? []).flatMap((branch, branchIndex) => {
1850
+ const events = /* @__PURE__ */ new Map();
1851
+ for (const arm of branch.armRecords ?? []) for (const event of arm.events) {
1852
+ const key = `${event.eventName}:${event.hostPath.join(".")}`;
1853
+ const route = events.get(key) ?? {
1854
+ eventName: event.eventName,
1855
+ hostPath: event.hostPath,
1856
+ symbolIds: /* @__PURE__ */ new Set()
1857
+ };
1858
+ for (const symbolId of event.symbolIds ?? []) route.symbolIds.add(symbolId);
1859
+ events.set(key, route);
1860
+ }
1861
+ return [...events.values()].map((route) => ({
1862
+ event: {
1863
+ hostNodeId: `branch:${branch.id}:${route.hostPath.join(".")}`,
1864
+ eventName: route.eventName,
1865
+ symbolIds: [...route.symbolIds]
1866
+ },
1867
+ branch,
1868
+ branchIndex,
1869
+ hostPath: route.hostPath
1870
+ }));
1871
+ })
1872
+ ].flatMap(({ event, branch, branchIndex, hostPath, selfWakeBoundaries }) => {
1873
+ const closureView = selfWakeBoundaries ? completeView : input.view;
1874
+ const host = branch ? void 0 : input.view.locators.find((locator) => locator.hostNodeId === event.hostNodeId);
1875
+ if (!host && !branch && !selfWakeBoundaries) return [];
1876
+ const compilerGroup = input.triggerGroups.groups.find((group) => group.hostNodeId === event.hostNodeId && group.eventName === event.eventName);
1877
+ const graphNodeIds = /* @__PURE__ */ new Set();
1878
+ const symbolIds = new Set(event.symbolIds ?? []);
1879
+ const selected = {
1880
+ domUpdates: /* @__PURE__ */ new Set(),
1881
+ behaviors: /* @__PURE__ */ new Set(),
1882
+ branches: /* @__PURE__ */ new Set(),
1883
+ boundaries: /* @__PURE__ */ new Set(),
1884
+ repeats: /* @__PURE__ */ new Set(),
1885
+ elementHandles: /* @__PURE__ */ new Set()
1886
+ };
1887
+ if (branch && branchIndex !== void 0) {
1888
+ selected.branches.add(branchIndex);
1889
+ if (branch.symbolId) symbolIds.add(branch.symbolId);
1890
+ for (const read of branch.testReads ?? []) graphNodeIds.add(read.graphNodeId);
1891
+ for (const arm of branch.armRecords ?? []) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
1892
+ }
1893
+ const adoptedBoundaryIds = /* @__PURE__ */ new Set();
1894
+ const escalatedHostNodeIds = /* @__PURE__ */ new Set();
1895
+ for (const boundaryIndex of selfWakeBoundaries ?? []) {
1896
+ const servedBoundary = input.view.asyncBoundaries[boundaryIndex];
1897
+ selected.boundaries.add(boundaryIndex);
1898
+ collectSettledBoundaryClosure(input, completeBoundaries.get(servedBoundary.id) ?? servedBoundary, graphNodeIds, symbolIds);
1899
+ }
1900
+ closureView.behaviors.forEach((behavior, index) => {
1901
+ if (selfWakeBoundaries) return;
1902
+ const recordId = `behavior:${behavior.hostNodeId}:${behavior.symbolId ?? ""}`;
1903
+ if ((behavior.inputGraphReads?.length ?? 0) > 0 && !compilerGroup?.payloadRecordIds.includes(recordId)) return;
1904
+ selected.behaviors.add(index);
1905
+ if (behavior.symbolId) symbolIds.add(behavior.symbolId);
1906
+ });
1907
+ let changed = true;
1908
+ while (changed) {
1909
+ const before = closureSize(graphNodeIds, symbolIds, selected);
1910
+ const currentSymbolIds = Array.from(symbolIds);
1911
+ for (const symbolId of currentSymbolIds) {
1912
+ const bound = bounds.get(symbolId);
1913
+ if (bound) {
1914
+ symbolIds.add(bound.loaderSymbolId ?? bound.baseSymbolId);
1915
+ for (const slot of bound.captureSlots) {
1916
+ if (slot.route.kind === "graph-reference") graphNodeIds.add(slot.route.graphNodeId);
1917
+ if (slot.route.kind === "callback-route") symbolIds.add(slot.route.callbackSymbolId);
1918
+ }
1919
+ }
1920
+ const symbol = symbols.get(symbolId);
1921
+ if (!symbol) continue;
1922
+ if ("reads" in symbol) for (const read of symbol.reads ?? []) graphNodeIds.add(read.graphNodeId);
1923
+ if ("writes" in symbol) for (const write of symbol.writes ?? []) graphNodeIds.add(write.graphNodeId);
1924
+ if (symbol.kind === "async-computed-runner" || symbol.kind === "sync-computed-derive") {
1925
+ graphNodeIds.add(symbol.graphNodeId);
1926
+ for (const dependency of symbol.dependencies ?? []) graphNodeIds.add(dependency.graphNodeId);
1927
+ }
1928
+ if ("elementHandleCalls" in symbol) for (const call of symbol.elementHandleCalls ?? []) closureView.elementHandles.forEach((handle, index) => {
1929
+ if (handle.name === call.handleName) selected.elementHandles.add(index);
1930
+ });
1931
+ if ("elementHandleReads" in symbol) for (const read of symbol.elementHandleReads ?? []) closureView.elementHandles.forEach((handle, index) => {
1932
+ if (handle.handleId === read.handleId || handle.name === read.handleName) selected.elementHandles.add(index);
1933
+ });
1934
+ }
1935
+ closeComputedGraph(graphNodeIds, input.state);
1936
+ for (const computed of input.state.computed) if (computed.deriveSymbolId && graphNodeIds.has(computed.graphNodeId)) symbolIds.add(computed.deriveSymbolId);
1937
+ for (const graphNodeId of graphNodeIds) {
1938
+ const runnerSymbolId = closureView.asyncRunners?.[graphNodeId];
1939
+ if (runnerSymbolId) symbolIds.add(runnerSymbolId);
1940
+ }
1941
+ selectViewSubscribers(closureView, graphNodeIds, symbolIds, selected);
1942
+ const escalatedBranchIds = /* @__PURE__ */ new Set();
1943
+ for (const index of selected.branches) {
1944
+ const record = closureView.branches?.[index];
1945
+ if (record?.escalates) escalatedBranchIds.add(record.id);
1946
+ }
1947
+ for (const index of selected.boundaries) {
1948
+ const served = closureView.asyncBoundaries[index];
1949
+ for (const arm of boundaryArmRecordSets(completeBoundaries.get(served.id) ?? served)) collectEscalatedArmBranchIds(arm, escalatedBranchIds);
1950
+ }
1951
+ for (const branchId of escalatedBranchIds) collectEscalatedBranchClosure(input, branchId, graphNodeIds, symbolIds, escalatedHostNodeIds);
1952
+ if (!selfWakeBoundaries) input.view.asyncBoundaries.forEach((servedBoundary, index) => {
1953
+ if (adoptedBoundaryIds.has(servedBoundary.id)) return;
1954
+ const boundary = completeBoundaries.get(servedBoundary.id) ?? servedBoundary;
1955
+ if (!settledArmReadGraphNodeIds(input, boundary).some((graphNodeId) => graphNodeIds.has(graphNodeId))) return;
1956
+ adoptedBoundaryIds.add(servedBoundary.id);
1957
+ selected.boundaries.add(index);
1958
+ collectSettledBoundaryClosure(input, boundary, graphNodeIds, symbolIds);
1959
+ collectSettledArmHostRecordClosure(completeView, boundary, graphNodeIds, symbolIds);
1960
+ });
1961
+ if (selfWakeBoundaries || adoptedBoundaryIds.size > 0) {
1962
+ for (const symbol of symbols.values()) if (symbol.kind === "state-initializer" && graphNodeIds.has(symbol.graphNodeId)) symbolIds.add(symbol.id);
1963
+ }
1964
+ changed = closureSize(graphNodeIds, symbolIds, selected) !== before;
1965
+ }
1966
+ dropEscalatedHostRecords(closureView, selected, escalatedHostNodeIds);
1967
+ const neededHosts = new Set(branch ? [] : [event.hostNodeId]);
1968
+ for (const index of selected.domUpdates) neededHosts.add(closureView.domUpdates[index].hostNodeId);
1969
+ for (const index of selected.behaviors) neededHosts.add(closureView.behaviors[index].hostNodeId);
1970
+ for (const index of selected.repeats) neededHosts.add(closureView.keyedRepeats[index].parentHostNodeId);
1971
+ for (const index of selected.elementHandles) neededHosts.add(closureView.elementHandles[index].hostNodeId);
1972
+ const selectedBoundaryIds = new Set([...selected.boundaries].map((index) => closureView.asyncBoundaries[index].id));
1973
+ const view = {
1974
+ ...input.view,
1975
+ locators: closureView.locators.filter((locator) => neededHosts.has(locator.hostNodeId)),
1976
+ events: branch || selfWakeBoundaries ? [] : [event],
1977
+ domUpdates: closureView.domUpdates.filter((_, index) => selected.domUpdates.has(index)),
1978
+ behaviors: closureView.behaviors.filter((_, index) => selected.behaviors.has(index)),
1979
+ elementHandles: closureView.elementHandles.filter((_, index) => selected.elementHandles.has(index)),
1980
+ keyedRepeats: closureView.keyedRepeats?.filter((_, index) => selected.repeats.has(index)),
1981
+ branches: closureView.branches?.filter((_, index) => selected.branches.has(index)),
1982
+ asyncBoundaries: closureView.asyncBoundaries.filter((boundary) => selectedBoundaryIds.has(boundary.id)).map((boundary) => adoptedBoundaryIds.has(boundary.id) ? completeBoundaries.get(boundary.id) ?? boundary : boundary),
1983
+ ...closureView.asyncRunners ? { asyncRunners: Object.fromEntries(Object.entries(closureView.asyncRunners).filter(([graphNodeId]) => graphNodeIds.has(graphNodeId))) } : {}
1984
+ };
1985
+ const graphIds = [...graphNodeIds].sort();
1986
+ return [{
1987
+ id: selfWakeBoundaries ? "self-wake" : branch ? `branch:${branch.id}:${event.eventName}:${hostPath.join(".")}` : `${event.hostNodeId}:${event.eventName}`,
1988
+ hostNodeId: event.hostNodeId,
1989
+ eventName: event.eventName,
1990
+ hostIndex: host?.index ?? -1,
1991
+ hostTagName: host?.tagName ?? "*",
1992
+ ...branch ? {
1993
+ branchStartIndex: branch.startAnchor.index,
1994
+ branchEndIndex: branch.endAnchor.index,
1995
+ hostPath
1996
+ } : {},
1997
+ graphNodeIds: graphIds,
1998
+ symbolIds: [...symbolIds].sort(),
1999
+ state: filterState(input.state, new Set(graphIds)),
2000
+ view,
2001
+ ...adoptedBoundaryIds.size > 0 ? { adoptsSettledArm: true } : {}
2002
+ }];
2003
+ });
2004
+ const armRendererModuleId = groups.some((group) => group.id === "self-wake") ? triggerGroupVirtualModuleId(input.filename, groups.length) : void 0;
2005
+ return groups.map(({ adoptsSettledArm, ...group }) => adoptsSettledArm && armRendererModuleId ? {
2006
+ ...group,
2007
+ armRendererModuleId
2008
+ } : group);
2009
+ }
2010
+ function settledArmReadGraphNodeIds(input, boundary) {
2011
+ const graphNodeIds = /* @__PURE__ */ new Set();
2012
+ for (const arm of boundaryArmRecordSets(boundary)) collectCompleteArmRecordClosure(arm, graphNodeIds, /* @__PURE__ */ new Set());
2013
+ for (const edge of input.componentEdges ?? []) if (edge.asyncBoundaryId === boundary.id) {
2014
+ for (const prop of edge.props) if (prop.kind === "graph-reference") graphNodeIds.add(prop.graphNodeId);
2015
+ }
2016
+ return [...graphNodeIds];
2017
+ }
2018
+ function collectSettledBoundaryClosure(input, boundary, graphNodeIds, symbolIds) {
2019
+ if (boundary.updateSymbolId) symbolIds.add(boundary.updateSymbolId);
2020
+ for (const read of boundary.asyncReads) {
2021
+ graphNodeIds.add(read.graphNodeId);
2022
+ if (read.runnerSymbolId) symbolIds.add(read.runnerSymbolId);
2023
+ }
2024
+ for (const arm of boundaryArmRecordSets(boundary)) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
2025
+ const settledEdgeIds = /* @__PURE__ */ new Set();
2026
+ for (const edge of input.componentEdges ?? []) {
2027
+ if (edge.asyncBoundaryId !== boundary.id) continue;
2028
+ settledEdgeIds.add(edge.id);
2029
+ for (const prop of edge.props) if (prop.kind === "graph-reference") graphNodeIds.add(prop.graphNodeId);
2030
+ }
2031
+ for (const row of input.boundRows) if (row.componentEdgePath.some((edgeId) => settledEdgeIds.has(edgeId))) symbolIds.add(row.id);
2032
+ }
2033
+ function collectSettledArmHostRecordClosure(completeView, boundary, graphNodeIds, symbolIds) {
2034
+ const armHosts = /* @__PURE__ */ new Set();
2035
+ for (const arm of boundaryArmRecordSets(boundary)) for (const locator of arm.locators ?? []) armHosts.add(locator.hostNodeId);
2036
+ if (armHosts.size === 0) return;
2037
+ for (const record of completeView.events) if (armHosts.has(record.hostNodeId)) for (const symbolId of record.symbolIds ?? []) symbolIds.add(symbolId);
2038
+ for (const record of completeView.domUpdates) if (armHosts.has(record.hostNodeId)) {
2039
+ graphNodeIds.add(record.graphNodeId);
2040
+ if (record.symbolId) symbolIds.add(record.symbolId);
2041
+ }
2042
+ for (const record of completeView.behaviors) if (armHosts.has(record.hostNodeId)) {
2043
+ for (const read of record.inputGraphReads ?? []) graphNodeIds.add(read.graphNodeId);
2044
+ if (record.symbolId) symbolIds.add(record.symbolId);
2045
+ }
2046
+ for (const record of completeView.keyedRepeats ?? []) if (armHosts.has(record.parentHostNodeId)) {
2047
+ if (record.collectionGraphNodeId) graphNodeIds.add(record.collectionGraphNodeId);
2048
+ for (const rowEvent of record.rowEvents) for (const symbolId of rowEvent.symbolIds ?? []) symbolIds.add(symbolId);
2049
+ }
2050
+ }
2051
+ function dropEscalatedHostRecords(view, selected, hostNodeIds) {
2052
+ if (hostNodeIds.size === 0) return;
2053
+ const drop = (indexes, hostOf) => {
2054
+ for (const index of indexes) if (hostNodeIds.has(hostOf(index) ?? "")) indexes.delete(index);
2055
+ };
2056
+ drop(selected.domUpdates, (index) => view.domUpdates[index]?.hostNodeId);
2057
+ drop(selected.behaviors, (index) => view.behaviors[index]?.hostNodeId);
2058
+ drop(selected.elementHandles, (index) => view.elementHandles[index]?.hostNodeId);
2059
+ drop(selected.repeats, (index) => view.keyedRepeats?.[index]?.parentHostNodeId);
2060
+ }
2061
+ function collectEscalatedArmBranchIds(arm, branchIds) {
2062
+ for (const branch of arm.branches ?? []) {
2063
+ if (!branch.symbolId && (branch.testReads?.length ?? 0) > 0) branchIds.add(branch.id);
2064
+ for (const nested of branch.armRecords ?? []) collectEscalatedArmBranchIds(nested, branchIds);
2065
+ }
2066
+ }
2067
+ function collectEscalatedBranchClosure(input, branchSiteId, graphNodeIds, symbolIds, hostNodeIds) {
2068
+ const renderData = input.renderData;
2069
+ const branch = renderData?.branches.find((candidate) => candidate.branchSiteId === branchSiteId);
2070
+ if (!renderData || !branch) return;
2071
+ const chunks = new Map(renderData.chunks.map((chunk) => [chunk.id, chunk]));
2072
+ const edgeIds = /* @__PURE__ */ new Set();
2073
+ const walked = /* @__PURE__ */ new Set();
2074
+ const walk = (chunkId) => {
2075
+ if (!chunkId || walked.has(chunkId)) return;
2076
+ walked.add(chunkId);
2077
+ const chunk = chunks.get(chunkId);
2078
+ if (!chunk) return;
2079
+ for (const host of chunk.hosts) hostNodeIds.add(host.hostNodeId);
2080
+ for (const slot of chunk.slots) if (slot.kind === "child-component") {
2081
+ edgeIds.add(slot.componentEdgeId);
2082
+ walk(slot.childTemplateId);
2083
+ walk(slot.projectionChunkId);
2084
+ } else if (slot.kind === "branch") for (const armId of slot.armTemplateIds) walk(armId);
2085
+ else if (slot.kind === "repeat") {
2086
+ walk(slot.rowTemplateId);
2087
+ walk(slot.emptyTemplateId);
2088
+ } else if (slot.kind === "async") {
2089
+ walk(slot.armTemplateIds.try);
2090
+ walk(slot.armTemplateIds.pending);
2091
+ walk(slot.armTemplateIds.catch);
2092
+ } else if (slot.kind === "dynamic-host") walk(slot.childChunkId);
2093
+ else if ("residue" in slot && slot.residue.kind === "graph-read") graphNodeIds.add(slot.residue.graphNodeId);
2094
+ };
2095
+ for (const armId of branch.armChunkIds) walk(armId);
2096
+ for (const symbol of input.symbolResolver.symbols) if (symbol.kind === "dom-update" && hostNodeIds.has(symbol.hostNodeId)) graphNodeIds.add(symbol.graphNodeId);
2097
+ for (const symbol of input.symbolResolver.symbols) if ("hostNodeId" in symbol && hostNodeIds.has(symbol.hostNodeId) || symbol.kind === "callback-prop" && edgeIds.has(symbol.componentEdgeId) || (symbol.kind === "state-initializer" || symbol.kind === "sync-computed-derive" || symbol.kind === "async-computed-runner") && graphNodeIds.has(symbol.graphNodeId)) symbolIds.add(symbol.id);
2098
+ for (const row of input.boundRows) if (row.componentEdgePath.some((edgeId) => edgeIds.has(edgeId))) symbolIds.add(row.id);
2099
+ }
2100
+ function boundaryArmRecordSets(boundary) {
2101
+ return Array.isArray(boundary.armRecords) ? boundary.armRecords : boundary.armRecords ? [boundary.armRecords] : [];
2102
+ }
2103
+ function unsettledAsyncBoundaryIndexes(state, view) {
2104
+ const computed = new Map(state.computed.map((record) => [record.graphNodeId, record]));
2105
+ const runners = { ...view.asyncRunners };
2106
+ for (const boundary of view.asyncBoundaries) for (const read of boundary.asyncReads) if (read.runnerSymbolId) runners[read.graphNodeId] ??= read.runnerSymbolId;
2107
+ return view.asyncBoundaries.flatMap((boundary, index) => {
2108
+ const reachable = new Set(boundary.asyncReads.map((read) => read.graphNodeId));
2109
+ for (const graphNodeId of reachable) {
2110
+ const record = computed.get(graphNodeId);
2111
+ if (!record) continue;
2112
+ if (runners[graphNodeId] && record.snapshot?.status !== "fulfilled" && record.snapshot?.status !== "rejected") return [index];
2113
+ for (const dependency of record.dependencies ?? []) reachable.add(dependency.graphNodeId);
2114
+ }
2115
+ return [];
2116
+ });
2117
+ }
2118
+ function selectViewSubscribers(view, graphNodeIds, symbolIds, selected) {
2119
+ view.domUpdates.forEach((record, index) => {
2120
+ if (!graphNodeIds.has(record.graphNodeId)) return;
2121
+ selected.domUpdates.add(index);
2122
+ if (record.symbolId) symbolIds.add(record.symbolId);
2123
+ });
2124
+ view.behaviors.forEach((record, index) => {
2125
+ if (!(record.inputGraphReads ?? []).some((read) => graphNodeIds.has(read.graphNodeId))) return;
2126
+ selected.behaviors.add(index);
2127
+ if (record.symbolId) symbolIds.add(record.symbolId);
2128
+ });
2129
+ (view.branches ?? []).forEach((record, index) => {
2130
+ if (!(record.testReads ?? []).some((read) => graphNodeIds.has(read.graphNodeId))) return;
2131
+ selected.branches.add(index);
2132
+ if (record.symbolId) symbolIds.add(record.symbolId);
2133
+ for (const arm of record.armRecords ?? []) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
2134
+ });
2135
+ view.asyncBoundaries.forEach((record, index) => {
2136
+ if (!record.asyncReads.some((read) => graphNodeIds.has(read.graphNodeId))) return;
2137
+ selected.boundaries.add(index);
2138
+ if (record.updateSymbolId) symbolIds.add(record.updateSymbolId);
2139
+ for (const read of record.asyncReads) if (read.runnerSymbolId) symbolIds.add(read.runnerSymbolId);
2140
+ const arms = Array.isArray(record.armRecords) ? record.armRecords : record.armRecords ? [record.armRecords] : [];
2141
+ for (const arm of arms) collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds);
2142
+ });
2143
+ (view.keyedRepeats ?? []).forEach((record, index) => {
2144
+ if (!record.collectionGraphNodeId || !graphNodeIds.has(record.collectionGraphNodeId)) return;
2145
+ selected.repeats.add(index);
2146
+ for (const rowEvent of record.rowEvents) for (const symbolId of rowEvent.symbolIds ?? []) symbolIds.add(symbolId);
2147
+ });
2148
+ }
2149
+ function collectCompleteArmRecordClosure(arm, graphNodeIds, symbolIds) {
2150
+ for (const event of arm.events ?? []) for (const symbolId of event.symbolIds ?? []) symbolIds.add(symbolId);
2151
+ for (const update of arm.domUpdates ?? []) {
2152
+ if (typeof update.graphNodeId === "string") graphNodeIds.add(update.graphNodeId);
2153
+ if (typeof update.symbolId === "string") symbolIds.add(update.symbolId);
2154
+ }
2155
+ for (const behavior of arm.behaviors ?? []) {
2156
+ for (const read of behavior.inputGraphReads ?? []) if (typeof read.graphNodeId === "string") graphNodeIds.add(read.graphNodeId);
2157
+ if (typeof behavior.symbolId === "string") symbolIds.add(behavior.symbolId);
2158
+ }
2159
+ for (const repeat of arm.keyedRepeats ?? []) {
2160
+ if (repeat.collectionGraphNodeId) graphNodeIds.add(repeat.collectionGraphNodeId);
2161
+ for (const event of repeat.rowEvents) for (const symbolId of event.symbolIds ?? []) symbolIds.add(symbolId);
2162
+ }
2163
+ for (const branch of arm.branches ?? []) {
2164
+ if (branch.symbolId) symbolIds.add(branch.symbolId);
2165
+ for (const read of branch.testReads ?? []) graphNodeIds.add(read.graphNodeId);
2166
+ for (const nested of branch.armRecords ?? []) collectCompleteArmRecordClosure(nested, graphNodeIds, symbolIds);
2167
+ }
2168
+ }
2169
+ function closeComputedGraph(graphNodeIds, state) {
2170
+ let changed = true;
2171
+ while (changed) {
2172
+ changed = false;
2173
+ for (const computed of state.computed) {
2174
+ const dependencies = computed.dependencies ?? [];
2175
+ if (!graphNodeIds.has(computed.graphNodeId) && !dependencies.some((dependency) => graphNodeIds.has(dependency.graphNodeId))) continue;
2176
+ if (!graphNodeIds.has(computed.graphNodeId)) {
2177
+ graphNodeIds.add(computed.graphNodeId);
2178
+ changed = true;
2179
+ }
2180
+ for (const dependency of dependencies) if (!graphNodeIds.has(dependency.graphNodeId)) {
2181
+ graphNodeIds.add(dependency.graphNodeId);
2182
+ changed = true;
2183
+ }
2184
+ }
2185
+ }
2186
+ }
2187
+ function filterState(state, graphNodeIds) {
2188
+ return {
2189
+ ...state,
2190
+ cells: state.cells.filter((cell) => graphNodeIds.has(cell.graphNodeId)),
2191
+ computed: state.computed.filter((computed) => graphNodeIds.has(computed.graphNodeId)),
2192
+ storage: state.storage?.filter((cell) => graphNodeIds.has(cell.graphNodeId)),
2193
+ sharedDefinitions: state.sharedDefinitions?.filter((definition) => definition.graphNodeIds.some((graphNodeId) => graphNodeIds.has(graphNodeId)))
2194
+ };
2195
+ }
2196
+ function closureSize(graphNodeIds, symbolIds, selected) {
2197
+ return graphNodeIds.size + symbolIds.size + Object.values(selected).reduce((total, records) => total + records.size, 0);
2198
+ }
2199
+ //#endregion
2200
+ //#region src/virtual-ids.ts
2201
+ const TSRX_SOURCE_FILE = /\.tsrx(?:[?#].*)?$/;
2202
+ const MARKLESS_SYMBOL_SOURCE_QUERY_RE = /[?&]markless-symbols(?:[&#]|$)/;
2203
+ const MARKLESS_RESUME_SOURCE_QUERY_RE = /[?&]markless-resume(?:[&#]|$)/;
2204
+ const MARKLESS_RENDER_DATA_SOURCE_QUERY_RE = /[?&]markless-render-data(?:[&#]|$)/;
2205
+ const MARKLESS_REACHED_FROM_SOURCE_QUERY = "markless-reached-from";
2206
+ const MARKLESS_REACHED_FROM_ROUTE = "route";
2207
+ const MARKLESS_PRERENDER_WAKE_SOURCE_QUERY_RE = /[?&]markless-prerender-wake(?:[&#]|$)/;
2208
+ const MARKLESS_ROUTE_SOURCE_QUERY_RE = /[?&]markless-route(?:[&#]|$)/;
2209
+ const RESUME_VIRTUAL_ID_RE = /^virtual:markless:resume:([^:]+)$/;
2210
+ const PRERENDER_WAKE_VIRTUAL_ID_RE = /^virtual:markless:prerender-wake:([^:]+)$/;
2211
+ const SETTLE_VIRTUAL_ID_RE = /^virtual:markless:settle:([^:]+)$/;
2212
+ const SYMBOL_VIRTUAL_STRING_RE = /(["'`])((?:virtual:markless:symbol:)[^"'`]+)\1/g;
2213
+ function stripBuildPrefix(fileName) {
2214
+ return fileName.startsWith(MARKLESS_BUILD_PREFIX) ? fileName.slice(MARKLESS_BUILD_PREFIX.length) : fileName;
2215
+ }
2216
+ function virtualModuleSourceForLoad(module, options) {
2217
+ if (!options.dev || module.type !== "resolver") return module.source;
2218
+ if (!module.source.includes("moduleUrls[row[0]]")) return module.source;
2219
+ return module.source.replace(SYMBOL_VIRTUAL_STRING_RE, (_match, _quote, virtualId) => JSON.stringify(devBrowserVirtualModuleUrl(virtualId, options.publicPath)));
2220
+ }
2221
+ function devBrowserSourceModuleUrl(source, _root, publicPath) {
2222
+ const path = withQuery(joinURL("@fs", withoutLeadingSlash(source)), { import: null });
2223
+ return publicPath ? publicPath(path) : joinURL("/", path);
2224
+ }
2225
+ function devBrowserVirtualModuleUrl(virtualId, publicPath) {
2226
+ const path = joinURL("@id", resolveVirtualId(virtualId).replace("\0", "__x00__"));
2227
+ return publicPath ? publicPath(path) : joinURL("/", path);
2228
+ }
2229
+ function clientSymbolEntries(input, root) {
2230
+ if (!input || typeof input !== "object" || Array.isArray(input)) return [];
2231
+ const sources = [];
2232
+ for (const [name, value] of Object.entries(input)) {
2233
+ if (!/symbol/i.test(name)) continue;
2234
+ for (const entry of inputEntryValues(value)) if (typeof entry === "string" && TSRX_SOURCE_FILE.test(entry)) sources.push(normalizeInputSource(entry, root));
2235
+ }
2236
+ return sources;
2237
+ }
2238
+ function inputEntryValues(value) {
2239
+ return Array.isArray(value) ? value.flatMap(inputEntryValues) : [value];
2240
+ }
2241
+ function normalizeInputSource(source, root) {
2242
+ const path = pathname(source);
2243
+ if (isAbsolute(path)) return path;
2244
+ return pathname(resolve(root ?? "", path));
2245
+ }
2246
+ function isSymbolOnlySourceRequest(id) {
2247
+ return MARKLESS_SYMBOL_SOURCE_QUERY_RE.test(id);
2248
+ }
2249
+ function isScalarPlanSourceRequest(id) {
2250
+ return isSymbolOnlySourceRequest(id) && new URLSearchParams(parsePath(id).search).has("markless-scalar-plans");
2251
+ }
2252
+ function isResumeSourceRequest(id) {
2253
+ return MARKLESS_RESUME_SOURCE_QUERY_RE.test(id);
2254
+ }
2255
+ function isRenderDataSourceRequest(id) {
2256
+ return MARKLESS_RENDER_DATA_SOURCE_QUERY_RE.test(id);
2257
+ }
2258
+ function renderDataReachedFromQuery(id) {
2259
+ return new URLSearchParams(parsePath(id).search).get(MARKLESS_REACHED_FROM_SOURCE_QUERY) ?? void 0;
2260
+ }
2261
+ function isRouteNavigationSourceRequest(id) {
2262
+ return MARKLESS_ROUTE_SOURCE_QUERY_RE.test(id) || isRenderDataSourceRequest(id) && renderDataReachedFromQuery(id) === void 0;
2263
+ }
2264
+ function materializedReachedRenderDataSource(source) {
2265
+ return withQuery(source, {
2266
+ "markless-render-data": null,
2267
+ [MARKLESS_REACHED_FROM_SOURCE_QUERY]: MARKLESS_REACHED_FROM_ROUTE
2268
+ });
2269
+ }
2270
+ function sharedReachedRenderDataRequest(id) {
2271
+ if (!isRenderDataSourceRequest(id)) return void 0;
2272
+ const reachedFrom = renderDataReachedFromQuery(id);
2273
+ return reachedFrom === void 0 || reachedFrom === MARKLESS_REACHED_FROM_ROUTE ? void 0 : withQuery(id, { [MARKLESS_REACHED_FROM_SOURCE_QUERY]: MARKLESS_REACHED_FROM_ROUTE });
2274
+ }
2275
+ function isPrerenderWakeSourceRequest(id) {
2276
+ return MARKLESS_PRERENDER_WAKE_SOURCE_QUERY_RE.test(id);
2277
+ }
2278
+ function isClientPrimarySourceRequest(id) {
2279
+ return !(MARKLESS_SYMBOL_SOURCE_QUERY_RE.test(id) || MARKLESS_RESUME_SOURCE_QUERY_RE.test(id) || MARKLESS_RENDER_DATA_SOURCE_QUERY_RE.test(id) || MARKLESS_PRERENDER_WAKE_SOURCE_QUERY_RE.test(id) || MARKLESS_ROUTE_SOURCE_QUERY_RE.test(id));
2280
+ }
2281
+ function clientRouteArtifactReference(source) {
2282
+ const symbolSource = source.includes("?") ? `${source}&markless-symbols` : `${source}?markless-symbols`;
2283
+ const renderDataSource = source.includes("?") ? `${source}&markless-render-data` : `${source}?markless-render-data`;
2284
+ return [
2285
+ `const [symbolModule, renderDataModule] = await Promise.all([import(${JSON.stringify(symbolSource)}), import(${JSON.stringify(renderDataSource)})]);`,
2286
+ "const marklessRouteArtifact = {",
2287
+ " renderData: renderDataModule.marklessPrerenderData,",
2288
+ " loadSymbol: symbolModule.loadSymbol,",
2289
+ "};",
2290
+ "export default marklessRouteArtifact;"
2291
+ ].join("\n");
2292
+ }
2293
+ function sourceForSymbolVirtualImporter(importer) {
2294
+ if (!importer) return null;
2295
+ return symbolVirtualModuleSourceFile(normalizeVirtualId(importer));
2296
+ }
2297
+ function sourceForResumeVirtualImporter(importer) {
2298
+ if (!importer) return null;
2299
+ const match = normalizeVirtualId(importer).match(RESUME_VIRTUAL_ID_RE);
2300
+ return match?.[1] ? decodeURIComponent(match[1]) : null;
2301
+ }
2302
+ function resolverVirtualModuleSourceFile(id) {
2303
+ const prefix = `${MARKLESS_VIRTUAL_PREFIX}resolver:`;
2304
+ return id.startsWith(prefix) ? decodeURIComponent(id.slice(prefix.length)) : null;
2305
+ }
2306
+ function sourceForTriggerGroupVirtualImporter(importer) {
2307
+ if (!importer) return null;
2308
+ return triggerGroupVirtualModuleSourceFile(normalizeVirtualId(importer));
2309
+ }
2310
+ function sourceForPrerenderWakeVirtualImporter(importer) {
2311
+ if (!importer) return null;
2312
+ const match = normalizeVirtualId(importer).match(PRERENDER_WAKE_VIRTUAL_ID_RE);
2313
+ return match?.[1] ? decodeURIComponent(match[1]) : null;
2314
+ }
2315
+ function sourceForSettleVirtualImporter(importer) {
2316
+ if (!importer) return null;
2317
+ const match = normalizeVirtualId(importer).match(SETTLE_VIRTUAL_ID_RE);
2318
+ return match?.[1] ? decodeURIComponent(match[1]) : null;
2319
+ }
2320
+ function isRelativeImport(source) {
2321
+ return source.startsWith("./") || source.startsWith("../");
2322
+ }
2323
+ function isMarklessRuntimeModule(id) {
2324
+ const path = pathname(id);
2325
+ return /[/\\](?:web|runtime|serializer)[/\\]src[/\\].+\.ts$/.test(path);
2326
+ }
2327
+ function executionLogRuntimeModuleId(id) {
2328
+ const path = pathname(id);
2329
+ const match = path.match(/[/\\](web|runtime|serializer)[/\\]src[/\\]([^?#]+)\.ts$/);
2330
+ return match ? `${match[1]}:${match[2].replace(/[/\\]/g, "/")}` : path;
2331
+ }
2332
+ function normalizeVirtualId(id) {
2333
+ const bare = id.startsWith("\0") ? id.slice(1) : id;
2334
+ if (!bare.startsWith("virtual:markless:")) return bare;
2335
+ const queryIndex = bare.indexOf("?");
2336
+ const segments = (queryIndex === -1 ? bare : bare.slice(0, queryIndex)).slice(17).split(":").map((segment) => {
2337
+ try {
2338
+ return encodeURIComponent(decodeURIComponent(segment));
2339
+ } catch {
2340
+ return segment;
2341
+ }
2342
+ });
2343
+ return `${MARKLESS_VIRTUAL_PREFIX}${segments.join(":")}`;
2344
+ }
2345
+ function emittedBundleModuleIds(bundle) {
2346
+ const ids = /* @__PURE__ */ new Set();
2347
+ for (const output of Object.values(bundle)) {
2348
+ if (!output || typeof output !== "object") continue;
2349
+ const chunk = output;
2350
+ if (chunk.type !== "chunk") continue;
2351
+ if (typeof chunk.facadeModuleId === "string") ids.add(normalizeVirtualId(chunk.facadeModuleId));
2352
+ if (Array.isArray(chunk.moduleIds)) {
2353
+ for (const id of chunk.moduleIds) if (typeof id === "string") ids.add(normalizeVirtualId(id));
2354
+ }
2355
+ }
2356
+ return ids;
2357
+ }
2358
+ function resolveVirtualId(id) {
2359
+ if (id.startsWith("\0")) return id;
2360
+ return `\0${id}`;
2361
+ }
2362
+ function pathname(id) {
2363
+ return parsePath(id).pathname;
2364
+ }
2365
+ const CLIENT_ONLY_SOURCE_QUERY_KEYS = /* @__PURE__ */ new Set([
2366
+ "markless-render-data",
2367
+ "markless-reached-from",
2368
+ "markless-symbols",
2369
+ "markless-scalar-plans"
2370
+ ]);
2371
+ function serverSharedSourceRequest(id, environment) {
2372
+ if (environment !== "server") return void 0;
2373
+ const { pathname: path, search } = parsePath(id);
2374
+ if (!search || !TSRX_SOURCE_FILE.test(path)) return void 0;
2375
+ const keys = [...new URLSearchParams(search).keys()];
2376
+ return keys.length > 0 && keys.every((key) => CLIENT_ONLY_SOURCE_QUERY_KEYS.has(key)) ? path : void 0;
2377
+ }
2378
+ //#endregion
2379
+ //#region src/build/planned-landing.ts
2380
+ const MARKLESS_INTERACTION_CLOSURES_ASSET = MARKLESS_INTERACTION_CLOSURES;
2381
+ function plannedLandingFiles(bundle) {
2382
+ const asset = bundle[MARKLESS_INTERACTION_CLOSURES_ASSET];
2383
+ if (asset?.type !== "asset" || asset.source === void 0) return void 0;
2384
+ const parsed = JSON.parse(typeof asset.source === "string" ? asset.source : new TextDecoder().decode(asset.source));
2385
+ const planned = /* @__PURE__ */ new Map();
2386
+ for (const route of parsed.routes) if (!route.fallback && route.files) planned.set(route.route, new Set(route.files.firstUse));
2387
+ return planned;
2388
+ }
2389
+ //#endregion
2390
+ //#region src/build/warm-packs.ts
2391
+ function warmPacksSuffix(specifiers) {
2392
+ return `setTimeout(()=>{for(const pack of[${specifiers.map((specifier) => `import(${JSON.stringify(specifier)})`).join(",")}])pack.catch(()=>{})});`;
2393
+ }
2394
+ const WARM_PACKS = /setTimeout\(\(\)=>\{for\((?:const|let|var) ([\w$]+) of\[((?:import\([^)]*\),?)+)\]\)\1\.catch\(\(\)=>\{\}\)\}\)/g;
2395
+ const IMPORT_SPECIFIER = /import\(\s*["'`]([^"'`]+)["'`]\s*\)/g;
2396
+ /** The packs a chunk evaluates a task after it runs, read from `warmPacksSuffix` before or after minifying. */
2397
+ function warmEvaluatedImports(code) {
2398
+ const specifiers = [];
2399
+ for (const warm of code.matchAll(WARM_PACKS)) for (const target of warm[2].matchAll(IMPORT_SPECIFIER)) specifiers.push(target[1]);
2400
+ return specifiers;
2401
+ }
2402
+ //#endregion
2403
+ //#region src/build/pack-cost-model.ts
2404
+ const PACK_COST_MODEL = {
2405
+ roundMs: 162,
2406
+ parallelRequestMs: 0,
2407
+ bootMsPerGzipKb: 2.8,
2408
+ interactionMsPerGzipKb: 1.5,
2409
+ decodedMsPerKb: 0,
2410
+ fileOverheadGzipKb: .5,
2411
+ lazySiblingOverheadGzipKb: 1,
2412
+ minDeferredGzipKb: 1,
2413
+ sourceGzipRatio: .25
2414
+ };
2415
+ function estimatedGzipKb(sourceLength, model = PACK_COST_MODEL) {
2416
+ return sourceLength * model.sourceGzipRatio / 1024;
2417
+ }
2418
+ function mergeIntoWiderPack(input, model = PACK_COST_MODEL) {
2419
+ return input.loadersNotNeeding * input.gzipKb * input.msPerGzipKb < input.loadersNeeding * (model.parallelRequestMs + model.fileOverheadGzipKb * input.msPerGzipKb);
2420
+ }
2421
+ function deferralPays(gzipKb, model = PACK_COST_MODEL) {
2422
+ return gzipKb >= model.minDeferredGzipKb;
2423
+ }
2424
+ function lazySiblingPays(input, model = PACK_COST_MODEL) {
2425
+ return deferralPays(input.gzipKb, model) && input.loadersSpedUp * input.gzipKb > input.loaders * model.lazySiblingOverheadGzipKb;
2426
+ }
2427
+ function frameworkSplitPays(input, model = PACK_COST_MODEL) {
2428
+ return deferralPays(input.appGzipKb, model) && deferralPays(input.frameworkGzipKb, model);
2429
+ }
2430
+ //#endregion
2431
+ //#region src/build/route-pack-groups.ts
2432
+ const MARKLESS_DEFERRED_PACK = "markless-deferred";
2433
+ const MARKLESS_NAVIGATION_PACK_PREFIX = "navigation:";
2434
+ function isMarklessDeferredPack(name) {
2435
+ return name === "markless-deferred" || !!name?.startsWith(`markless-deferred-`);
2436
+ }
2437
+ /** Deferred packs plus the module-free facade chunks Rolldown emits in front of their entries. */
2438
+ function marklessDeferredChunkFileNames(chunks) {
2439
+ const all = [...chunks];
2440
+ const deferred = new Set(all.filter((chunk) => isMarklessDeferredPack(chunk.name)).map((chunk) => chunk.fileName));
2441
+ for (let grew = deferred.size > 0; grew;) {
2442
+ grew = false;
2443
+ for (const chunk of all) if (!deferred.has(chunk.fileName) && chunk.moduleIds?.length === 0 && chunk.imports.length > 0 && chunk.imports.every((name) => deferred.has(name))) {
2444
+ deferred.add(chunk.fileName);
2445
+ grew = true;
2446
+ }
2447
+ }
2448
+ return deferred;
2449
+ }
2450
+ function isMarklessNavigationPack(name) {
2451
+ return !!name?.startsWith(MARKLESS_NAVIGATION_PACK_PREFIX);
2452
+ }
2453
+ function isStartupPack(group) {
2454
+ return !isMarklessDeferredPack(group) && !isMarklessNavigationPack(group);
2455
+ }
2456
+ function planRoutePackGroups(input) {
2457
+ const sources = /* @__PURE__ */ new Map();
2458
+ for (const [id, module] of input.modules) {
2459
+ if (!module.source || module.reachedFrom !== void 0) continue;
2460
+ push(sources, module.source, id);
2461
+ }
2462
+ const roots = /* @__PURE__ */ new Map();
2463
+ for (const [route, ids] of input.routes) for (const id of ids) {
2464
+ if (!input.modules.has(id)) throw new Error(`Markless route ${route} has missing root ${id}.`);
2465
+ roots.set(id, route);
2466
+ }
2467
+ const owners = /* @__PURE__ */ new Map();
2468
+ const walk = (route, start, visited) => {
2469
+ const reached = [];
2470
+ const pending = [...start];
2471
+ while (pending.length) {
2472
+ const id = pending.pop();
2473
+ if (visited.has(id)) continue;
2474
+ visited.add(id);
2475
+ if (roots.has(id) && roots.get(id) !== route) continue;
2476
+ const module = input.modules.get(id);
2477
+ if (!module) continue;
2478
+ add(owners, id, route);
2479
+ reached.push(id);
2480
+ pending.push(...module.dependencies, ...module.dynamicDependencies ?? []);
2481
+ }
2482
+ return reached;
2483
+ };
2484
+ const visitedByRoute = /* @__PURE__ */ new Map();
2485
+ for (const [route, ids] of input.routes) {
2486
+ const visited = /* @__PURE__ */ new Set();
2487
+ walk(route, ids, visited);
2488
+ visitedByRoute.set(route, visited);
2489
+ }
2490
+ const imported = new Set(owners.keys());
2491
+ for (const [route, visited] of visitedByRoute) {
2492
+ const expanded = /* @__PURE__ */ new Set();
2493
+ let frontier = [...visited].filter((id) => owners.get(id)?.has(route));
2494
+ while (frontier.length) {
2495
+ const next = [];
2496
+ for (const id of frontier) {
2497
+ const source = input.modules.get(id)?.source;
2498
+ if (!source || expanded.has(source)) continue;
2499
+ expanded.add(source);
2500
+ const siblings = (sources.get(source) ?? []).filter((sibling) => !imported.has(sibling));
2501
+ next.push(...walk(route, siblings, visited));
2502
+ }
2503
+ frontier = next;
2504
+ }
2505
+ }
2506
+ const reachedOutsideRoutes = /* @__PURE__ */ new Set();
2507
+ const outside = [...input.modules.keys()].filter((id) => !owners.has(id));
2508
+ while (outside.length) {
2509
+ const id = outside.pop();
2510
+ for (const dependency of input.modules.get(id)?.dependencies ?? []) {
2511
+ if (roots.has(dependency) || !owners.has(dependency)) continue;
2512
+ if (reachedOutsideRoutes.has(dependency)) continue;
2513
+ reachedOutsideRoutes.add(dependency);
2514
+ outside.push(dependency);
2515
+ }
2516
+ }
2517
+ const routeSpecific = (id) => owners.get(id).size < input.routes.size && (owners.get(id).size === 1 || input.modules.get(id)?.reachedFrom !== void 0);
2518
+ const rootedLandings = new Set([...roots].filter(([id]) => !input.modules.get(id).navigationOnly).map(([, route]) => route));
2519
+ const undemanded = input.undemandedDynamicTargets ?? /* @__PURE__ */ new Set();
2520
+ const reach = (landingOnly) => {
2521
+ const reached = /* @__PURE__ */ new Set();
2522
+ const pending = [...input.modules.keys()].filter((id) => roots.has(id) || !owners.has(id));
2523
+ while (pending.length) {
2524
+ const id = pending.pop();
2525
+ if (reached.has(id)) continue;
2526
+ const module = input.modules.get(id);
2527
+ if (landingOnly && module?.navigationOnly && roots.has(id)) continue;
2528
+ reached.add(id);
2529
+ if (!module) continue;
2530
+ pending.push(...module.dependencies);
2531
+ for (const target of module.dynamicDependencies ?? []) if (landingOnly || !undemanded.has(target)) pending.push(target);
2532
+ if (module.source) pending.push(...sources.get(module.source) ?? []);
2533
+ }
2534
+ return reached;
2535
+ };
2536
+ const eager = reach(false);
2537
+ const landing = reach(true);
2538
+ const firstUse = /* @__PURE__ */ new Map();
2539
+ const render = /* @__PURE__ */ new Map();
2540
+ const known = /* @__PURE__ */ new Set();
2541
+ for (const route of input.closures ?? []) {
2542
+ if (route.fallback) continue;
2543
+ known.add(route.route);
2544
+ for (const consumer of route.consumers) for (const id of consumer.modules) add(consumer.kind === "render" ? render : firstUse, id, route.route);
2545
+ }
2546
+ const planned = [...owners.keys()].filter((id) => eager.has(id) && !(reachedOutsideRoutes.has(id) && routeSpecific(id)));
2547
+ for (const id of planned) for (const route of owners.get(id)) if (!known.has(route)) add(landing.has(id) || !rootedLandings.has(route) ? firstUse : render, id, route);
2548
+ const gzipKb = (ids) => estimatedGzipKb(ids.reduce((sum, id) => sum + (input.modules.get(id)?.size ?? 0), 0));
2549
+ const renderIds = planned.filter((id) => !firstUse.has(id) && render.has(id));
2550
+ const deferRender = deferralPays(gzipKb(renderIds));
2551
+ if (!deferRender) for (const id of renderIds) firstUse.set(id, render.get(id));
2552
+ const idleIds = planned.filter((id) => !firstUse.has(id) && !render.has(id));
2553
+ const deferIdle = deferralPays(gzipKb(idleIds));
2554
+ if (!deferIdle) for (const id of idleIds) firstUse.set(id, owners.get(id));
2555
+ const groups = /* @__PURE__ */ new Map();
2556
+ for (const id of owners.keys()) if (!eager.has(id) && !(reachedOutsideRoutes.has(id) && routeSpecific(id))) groups.set(id, MARKLESS_DEFERRED_PACK);
2557
+ const critical = /* @__PURE__ */ new Map();
2558
+ for (const id of planned) {
2559
+ const routes = firstUse.get(id);
2560
+ if (!routes) continue;
2561
+ const foreign = [...owners.get(id)].some((route) => !routes.has(route));
2562
+ push(critical, `${routeKey(routes)}${foreign ? SHARED_MARK : ""}`, id);
2563
+ }
2564
+ const landingRoutes = new Set([...critical.keys()].flatMap(routesOf));
2565
+ for (const [marked, ids] of critical) {
2566
+ const key = marked.replace(SHARED_MARK, "");
2567
+ const routes = routesOf(key);
2568
+ const name = routes.length === 1 && key === marked ? `route:${routes[0]}` : routes.length === landingRoutes.size || !input.pagesLoadOneRoute || mergeIntoWiderPack({
2569
+ gzipKb: gzipKb(ids),
2570
+ loadersNeeding: routes.length,
2571
+ loadersNotNeeding: landingRoutes.size - routes.length,
2572
+ msPerGzipKb: PACK_COST_MODEL.bootMsPerGzipKb
2573
+ }) ? "shared" : `shared:${routeSetId(key)}`;
2574
+ if (name.startsWith("shared:")) input.routeSets?.set(name, routes);
2575
+ for (const id of ids) groups.set(id, name);
2576
+ }
2577
+ if (deferRender) {
2578
+ const rendered = /* @__PURE__ */ new Map();
2579
+ for (const id of renderIds) push(rendered, routeKey(render.get(id)), id);
2580
+ const renderRoutes = new Set([...rendered.keys()].flatMap(routesOf));
2581
+ for (const [key, ids] of rendered) {
2582
+ const routes = routesOf(key);
2583
+ const name = routes.length === 1 ? `${MARKLESS_NAVIGATION_PACK_PREFIX}${routes[0]}` : routes.length === renderRoutes.size || mergeIntoWiderPack({
2584
+ gzipKb: gzipKb(ids),
2585
+ loadersNeeding: routes.length,
2586
+ loadersNotNeeding: renderRoutes.size - routes.length,
2587
+ msPerGzipKb: PACK_COST_MODEL.interactionMsPerGzipKb
2588
+ }) ? `${MARKLESS_NAVIGATION_PACK_PREFIX}shared` : `${MARKLESS_NAVIGATION_PACK_PREFIX}shared:${routeSetId(key)}`;
2589
+ for (const id of ids) groups.set(id, name);
2590
+ }
2591
+ }
2592
+ if (deferIdle) {
2593
+ const deferred = /* @__PURE__ */ new Map();
2594
+ for (const id of idleIds) push(deferred, routeKey(owners.get(id)), id);
2595
+ const reachingRoutes = new Set([...deferred.keys()].flatMap(routesOf));
2596
+ for (const [key, ids] of deferred) {
2597
+ const routes = routesOf(key);
2598
+ const name = routes.length === reachingRoutes.size || mergeIntoWiderPack({
2599
+ gzipKb: gzipKb(ids),
2600
+ loadersNeeding: routes.length,
2601
+ loadersNotNeeding: reachingRoutes.size - routes.length,
2602
+ msPerGzipKb: PACK_COST_MODEL.interactionMsPerGzipKb
2603
+ }) ? MARKLESS_DEFERRED_PACK : `${MARKLESS_DEFERRED_PACK}-${routeSetId(key)}`;
2604
+ for (const id of ids) groups.set(id, name);
2605
+ }
2606
+ for (let moved = true; moved;) {
2607
+ moved = false;
2608
+ for (const id of idleIds) {
2609
+ const own = groups.get(id);
2610
+ if (!isMarklessDeferredPack(own)) continue;
2611
+ const target = input.modules.get(id).dependencies.map((dependency) => groups.get(dependency)).filter((name) => name !== void 0 && name !== own && (isMarklessNavigationPack(name) || isMarklessDeferredPack(name))).sort()[0];
2612
+ if (!target) continue;
2613
+ for (const other of idleIds) if (groups.get(other) === own) groups.set(other, target);
2614
+ moved = true;
2615
+ }
2616
+ }
2617
+ }
2618
+ return input.pagesLoadOneRoute ? splitFrameworkFromApp(splitStartupPacksByStaticReach(groups, roots, sources, owners, input), input) : groups;
2619
+ }
2620
+ function splitFrameworkFromApp(groups, input) {
2621
+ const halves = /* @__PURE__ */ new Map();
2622
+ for (const [id, group] of groups) {
2623
+ if (!isStartupPack(group)) continue;
2624
+ const half = halves.get(group) ?? {
2625
+ app: [],
2626
+ framework: []
2627
+ };
2628
+ halves.set(group, half);
2629
+ (input.modules.get(id)?.app ? half.app : half.framework).push(id);
2630
+ }
2631
+ const gzipKb = (ids) => estimatedGzipKb(ids.reduce((sum, id) => sum + (input.modules.get(id)?.size ?? 0), 0));
2632
+ for (const [group, half] of halves) {
2633
+ if (!frameworkSplitPays({
2634
+ appGzipKb: gzipKb(half.app),
2635
+ frameworkGzipKb: gzipKb(half.framework)
2636
+ })) continue;
2637
+ for (const id of half.framework) groups.set(id, `${group}${FRAMEWORK_PIECE}`);
2638
+ }
2639
+ return groups;
2640
+ }
2641
+ function splitStartupPacksByStaticReach(groups, roots, sources, owners, input) {
2642
+ const gzipKbOf = (ids) => estimatedGzipKb(ids.reduce((sum, id) => sum + (input.modules.get(id)?.size ?? 0), 0));
2643
+ const flagged = [...input.modules.values()].some((module) => module.firstEvent !== void 0);
2644
+ const seed = (id) => {
2645
+ const module = input.modules.get(id);
2646
+ return !!module && !module.navigationOnly && (!flagged || !!module.firstEvent);
2647
+ };
2648
+ const handler = (id) => !!input.modules.get(id)?.handler;
2649
+ const closure = (route, start, path) => {
2650
+ const reached = /* @__PURE__ */ new Set();
2651
+ const handlers = /* @__PURE__ */ new Set();
2652
+ const pending = [...start];
2653
+ while (pending.length) {
2654
+ const id = pending.pop();
2655
+ if (path.has(id) || reached.has(id) || roots.has(id) && roots.get(id) !== route) continue;
2656
+ const module = input.modules.get(id);
2657
+ if (!module) continue;
2658
+ reached.add(id);
2659
+ pending.push(...module.dependencies);
2660
+ for (const sibling of module.source ? sources.get(module.source) ?? [] : []) if (seed(sibling) && sibling !== id) if (handler(sibling)) handlers.add(sibling);
2661
+ else pending.push(sibling);
2662
+ }
2663
+ return {
2664
+ reached,
2665
+ handlers
2666
+ };
2667
+ };
2668
+ const staticReach = /* @__PURE__ */ new Set();
2669
+ for (const [route, ids] of input.routes) {
2670
+ const visited = /* @__PURE__ */ new Set();
2671
+ const first = closure(route, ids.filter((id) => seed(id) && !handler(id)), visited);
2672
+ for (const id of first.reached) visited.add(id);
2673
+ const candidates = [...first.handlers, ...[...owners].filter(([id, routes]) => routes.size === 1 && routes.has(route) && seed(id) && handler(id)).map(([id]) => id)];
2674
+ while (candidates.length) {
2675
+ const id = candidates.pop();
2676
+ if (visited.has(id)) continue;
2677
+ const extra = closure(route, [id], visited);
2678
+ if (deferralPays(gzipKbOf([...extra.reached].filter((reached) => reached !== id)))) continue;
2679
+ for (const reached of extra.reached) visited.add(reached);
2680
+ candidates.push(...extra.handlers);
2681
+ }
2682
+ for (const id of visited) staticReach.add(id);
2683
+ }
2684
+ const known = new Map((input.closures ?? []).filter((route) => !route.fallback).map((route) => [route.route, route]));
2685
+ const firstEventNeedsRuntime = (route) => !known.has(route) || known.get(route).consumers.some((consumer) => consumer.kind === "action" && !consumer.lean);
2686
+ const firstEventIsLean = (route) => !firstEventNeedsRuntime(route) && known.get(route).consumers.some((consumer) => consumer.kind === "action");
2687
+ const routePacks = new Set([...groups.values()].filter((group) => group.startsWith("route:")));
2688
+ const lazy = /* @__PURE__ */ new Map();
2689
+ const packSizes = /* @__PURE__ */ new Map();
2690
+ for (const [id, group] of groups) {
2691
+ if (!isStartupPack(group)) continue;
2692
+ packSizes.set(group, (packSizes.get(group) ?? 0) + 1);
2693
+ if (!staticReach.has(id)) push(lazy, group, id);
2694
+ }
2695
+ for (const [group, ids] of lazy) {
2696
+ if (ids.length === packSizes.get(group)) continue;
2697
+ const loaders = new Set(ids.flatMap((id) => [...owners.get(id) ?? []]));
2698
+ const eager = [...loaders].filter(firstEventNeedsRuntime);
2699
+ const loadersSpedUp = [...loaders].filter(firstEventIsLean).length;
2700
+ if (!lazySiblingPays({
2701
+ gzipKb: gzipKbOf(ids),
2702
+ loadersSpedUp,
2703
+ loaders: loaders.size
2704
+ })) continue;
2705
+ if (eager.some((route) => !routePacks.has(`route:${route}`))) continue;
2706
+ const name = lazyStartupPackName(group);
2707
+ for (const id of ids) groups.set(id, name);
2708
+ if (eager.length) input.eagerLazyRoutes?.set(name, eager.sort());
2709
+ }
2710
+ return groups;
2711
+ }
2712
+ function lazyStartupPackName(group) {
2713
+ return group.replace(/^(route|shared)/, `$1${LAZY_PACK_MARK}`);
2714
+ }
2715
+ function startupPackOfLazy(name) {
2716
+ return name.replace(new RegExp(`^(route|shared)${LAZY_PACK_MARK}`), "$1");
2717
+ }
2718
+ const LAZY_PACK_MARK = "-lazy";
2719
+ const FRAMEWORK_PIECE = "~1";
2720
+ const ROUTE_KEY_SEPARATOR = "\n";
2721
+ const SHARED_MARK = " ";
2722
+ function routeKey(routes) {
2723
+ return [...routes].sort().join(ROUTE_KEY_SEPARATOR);
2724
+ }
2725
+ function routeSetId(key) {
2726
+ let hash = 2166136261;
2727
+ for (let index = 0; index < key.length; index++) hash = Math.imul(hash ^ key.charCodeAt(index), 16777619) >>> 0;
2728
+ return hash.toString(36);
2729
+ }
2730
+ function routesOf(key) {
2731
+ return key.replace(SHARED_MARK, "").split(ROUTE_KEY_SEPARATOR);
2732
+ }
2733
+ function add(map, key, value) {
2734
+ const values = map.get(key);
2735
+ if (values) values.add(value);
2736
+ else map.set(key, /* @__PURE__ */ new Set([value]));
2737
+ }
2738
+ function push(map, key, value) {
2739
+ const values = map.get(key);
2740
+ if (values) values.push(value);
2741
+ else map.set(key, [value]);
2742
+ }
2743
+ //#endregion
2744
+ export { MARKLESS_BUNDLE_GRAPH as $, isSymbolOnlySourceRequest as A, executionLogVirtualModuleSource as At, sourceForResumeVirtualImporter as B, isMarklessRuntimeModule as C, symbolVirtualModuleId as Ct, isResumeSourceRequest as D, MARKLESS_EXECUTION_LOG_GLOBAL as Dt, isRenderDataSourceRequest as E, EXECUTION_LOG_DISPATCH_MODULE_IDS as Et, resolveVirtualId as F, requalifyExecutionLogModuleHook as Ft, virtualModuleSourceForLoad as G, sourceForSymbolVirtualImporter as H, resolverVirtualModuleSourceFile as I, planModulePreloadUrls as It, planPrerenderTriggerGroups as J, emitPrerenderBoundaryRendererModule as K, serverSharedSourceRequest as L, planModulePreloads as Lt, normalizeVirtualId as M, injectExecutionLogModuleHook as Mt, pathname as N, isExecutionLogChunk as Nt, isRouteNavigationSourceRequest as O, MARKLESS_EXECUTION_LOG_MODULE_ID as Ot, renderDataReachedFromQuery as P, normalizeExecutionLogMode as Pt, MARKLESS_BUILD_PREFIX as Q, sharedReachedRenderDataRequest as R, isClientPrimarySourceRequest as S, symbolEntryVirtualModuleId as St, isRelativeImport as T, withoutFirstUse as Tt, sourceForTriggerGroupVirtualImporter as U, sourceForSettleVirtualImporter as V, stripBuildPrefix as W, adaptImportedCaptureResolver as X, triggerGroupVirtualModuleId as Y, MARKLESS_BUILD_METADATA_FILES as Z, clientSymbolEntries as _, prerenderWakeVirtualModuleSourceFile as _t, isStartupPack as a, outputDefaults as at, emittedBundleModuleIds as b, scopedSymbolExportName as bt, planRoutePackGroups as c, STORAGE_FREE_RESUME_ENTRY_SPECIFIER as ct, warmPacksSuffix as d, emitResumeModule as dt, MARKLESS_BYTE_ATTRIBUTION as et, MARKLESS_INTERACTION_CLOSURES_ASSET as f, emitSettleModule as ft, clientRouteArtifactReference as g, prerenderWakeVirtualModuleId as gt, TSRX_SOURCE_FILE as h, payloadModule as ht, isMarklessNavigationPack as i, MARKLESS_PUBLIC_BUILD_METADATA_FILES as it, materializedReachedRenderDataSource as j, hasExecutionLogModuleHook as jt, isScalarPlanSourceRequest as k, executionLogActivationInjection as kt, startupPackOfLazy as l, demandsOverlay as lt, MARKLESS_ROUTE_SOURCE_QUERY_RE as m, encodedSymbolSource as mt, MARKLESS_NAVIGATION_PACK_PREFIX as n, MARKLESS_EXECUTION_SIZES as nt, lazyStartupPackName as o, MARKLESS_VIRTUAL_PREFIX as ot, plannedLandingFiles as p, emitSourceModule as pt, emitPrerenderTriggerGroupModule as q, isMarklessDeferredPack as r, MARKLESS_INTERACTION_CLOSURES as rt, marklessDeferredChunkFileNames as s, RESUME_ENTRY_SPECIFIER as st, MARKLESS_DEFERRED_PACK as t, MARKLESS_EXECUTION_DEMAND as tt, warmEvaluatedImports as u, emitOverlayLoaderInstall as ut, devBrowserSourceModuleUrl as v, resumeVirtualModuleId as vt, isPrerenderWakeSourceRequest as w, symbolVirtualModuleSourceFile as wt, executionLogRuntimeModuleId as x, settleVirtualModuleId as xt, devBrowserVirtualModuleUrl as y, rewriteSymbolModuleExport as yt, sourceForPrerenderWakeVirtualImporter as z };